text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { DescriptorSet } from '../base/descriptor-set'; import { DescriptorSetLayout } from '../base/descriptor-set-layout'; import { PipelineLayout } from '../base/pipeline-layout'; import { Buffer } from '../base/buffer'; import { CommandBuffer } from '../base/command-buffer'; import { Device } from '../base/device'; import { Framebuffer } from '../base/framebuffer'; import { InputAssembler } from '../base/input-assembler'; import { PipelineState, PipelineStateInfo } from '../base/pipeline-state'; import { Queue } from '../base/queue'; import { RenderPass } from '../base/render-pass'; import { Sampler } from '../base/states/sampler'; import { Shader } from '../base/shader'; import { Texture } from '../base/texture'; import { WebGLDescriptorSet } from './webgl-descriptor-set'; import { WebGLBuffer } from './webgl-buffer'; import { WebGLCommandBuffer } from './webgl-command-buffer'; import { WebGLFramebuffer } from './webgl-framebuffer'; import { WebGLInputAssembler } from './webgl-input-assembler'; import { WebGLDescriptorSetLayout } from './webgl-descriptor-set-layout'; import { WebGLPipelineLayout } from './webgl-pipeline-layout'; import { WebGLPipelineState } from './webgl-pipeline-state'; import { WebGLPrimaryCommandBuffer } from './webgl-primary-command-buffer'; import { WebGLQueue } from './webgl-queue'; import { WebGLRenderPass } from './webgl-render-pass'; import { WebGLSampler } from './states/webgl-sampler'; import { WebGLShader } from './webgl-shader'; import { getExtensions, WebGLSwapchain } from './webgl-swapchain'; import { WebGLTexture } from './webgl-texture'; import { CommandBufferType, ShaderInfo, QueueInfo, CommandBufferInfo, DescriptorSetInfo, DescriptorSetLayoutInfo, FramebufferInfo, InputAssemblerInfo, PipelineLayoutInfo, RenderPassInfo, SamplerInfo, TextureInfo, TextureViewInfo, BufferInfo, BufferViewInfo, DeviceInfo, TextureBarrierInfo, GlobalBarrierInfo, QueueType, API, Feature, BufferTextureCopy, SwapchainInfo, } from '../base/define'; import { WebGLCmdFuncCopyBuffersToTexture, WebGLCmdFuncCopyTextureToBuffers, WebGLCmdFuncCopyTexImagesToTexture } from './webgl-commands'; import { GlobalBarrier } from '../base/states/global-barrier'; import { TextureBarrier } from '../base/states/texture-barrier'; import { debug } from '../../platform/debug'; import { Swapchain } from '../base/swapchain'; import { WebGLDeviceManager } from './webgl-define'; export class WebGLDevice extends Device { get gl () { return this._swapchain!.gl; } get extensions () { return this._swapchain!.extensions; } get stateCache () { return this._swapchain!.stateCache; } get nullTex2D () { return this._swapchain!.nullTex2D; } get nullTexCube () { return this._swapchain!.nullTexCube; } private _swapchain: WebGLSwapchain | null = null; public initialize (info: DeviceInfo): boolean { WebGLDeviceManager.setInstance(this); this._gfxAPI = API.WEBGL; this._bindingMappingInfo = info.bindingMappingInfo; if (!this._bindingMappingInfo.bufferOffsets.length) this._bindingMappingInfo.bufferOffsets.push(0); if (!this._bindingMappingInfo.samplerOffsets.length) this._bindingMappingInfo.samplerOffsets.push(0); let gl: WebGLRenderingContext | null = null; try { gl = document.createElement('canvas').getContext('webgl'); } catch (err) { console.error(err); } if (!gl) { console.error('This device does not support WebGL.'); return false; } // create queue this._queue = this.createQueue(new QueueInfo(QueueType.GRAPHICS)); this._cmdBuff = this.createCommandBuffer(new CommandBufferInfo(this._queue)); this._caps.maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); this._caps.maxVertexUniformVectors = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS); this._caps.maxFragmentUniformVectors = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS); this._caps.maxTextureUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); this._caps.maxVertexTextureUnits = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); this._caps.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); this._caps.maxCubeMapTextureSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE); const extensions = gl.getSupportedExtensions(); let extStr = ''; if (extensions) { for (const ext of extensions) { extStr += `${ext} `; } } const exts = getExtensions(gl); if (exts.WEBGL_debug_renderer_info) { this._renderer = gl.getParameter(exts.WEBGL_debug_renderer_info.UNMASKED_RENDERER_WEBGL); this._vendor = gl.getParameter(exts.WEBGL_debug_renderer_info.UNMASKED_VENDOR_WEBGL); } else { this._renderer = gl.getParameter(gl.RENDERER); this._vendor = gl.getParameter(gl.VENDOR); } const version: string = gl.getParameter(gl.VERSION); this._features.fill(false); if (exts.EXT_sRGB) { this._features[Feature.FORMAT_SRGB] = true; } if (exts.EXT_blend_minmax) { this._features[Feature.BLEND_MINMAX] = true; } if (exts.WEBGL_color_buffer_float) { this._features[Feature.COLOR_FLOAT] = true; } if (exts.EXT_color_buffer_half_float) { this._features[Feature.COLOR_HALF_FLOAT] = true; } if (exts.OES_texture_float) { this._features[Feature.TEXTURE_FLOAT] = true; } if (exts.OES_texture_half_float) { this._features[Feature.TEXTURE_HALF_FLOAT] = true; } if (exts.OES_texture_float_linear) { this._features[Feature.TEXTURE_FLOAT_LINEAR] = true; } if (exts.OES_texture_half_float_linear) { this._features[Feature.TEXTURE_HALF_FLOAT_LINEAR] = true; } this._features[Feature.FORMAT_RGB8] = true; if (exts.OES_element_index_uint) { this._features[Feature.ELEMENT_INDEX_UINT] = true; } if (exts.ANGLE_instanced_arrays) { this._features[Feature.INSTANCED_ARRAYS] = true; } if (exts.WEBGL_draw_buffers) { this._features[Feature.MULTIPLE_RENDER_TARGETS] = true; } let compressedFormat = ''; if (exts.WEBGL_compressed_texture_etc1) { this._features[Feature.FORMAT_ETC1] = true; compressedFormat += 'etc1 '; } if (exts.WEBGL_compressed_texture_etc) { this._features[Feature.FORMAT_ETC2] = true; compressedFormat += 'etc2 '; } if (exts.WEBGL_compressed_texture_s3tc) { this._features[Feature.FORMAT_DXT] = true; compressedFormat += 'dxt '; } if (exts.WEBGL_compressed_texture_pvrtc) { this._features[Feature.FORMAT_PVRTC] = true; compressedFormat += 'pvrtc '; } if (exts.WEBGL_compressed_texture_astc) { this._features[Feature.FORMAT_ASTC] = true; compressedFormat += 'astc '; } debug('WebGL device initialized.'); debug(`RENDERER: ${this._renderer}`); debug(`VENDOR: ${this._vendor}`); debug(`VERSION: ${version}`); debug(`COMPRESSED_FORMAT: ${compressedFormat}`); debug(`EXTENSIONS: ${extStr}`); return true; } public destroy (): void { if (this._queue) { this._queue.destroy(); this._queue = null; } if (this._cmdBuff) { this._cmdBuff.destroy(); this._cmdBuff = null; } } public flushCommands (cmdBuffs: CommandBuffer[]) {} public acquire (swapchains: Swapchain[]) {} public present () { const queue = (this._queue as WebGLQueue); this._numDrawCalls = queue.numDrawCalls; this._numInstances = queue.numInstances; this._numTris = queue.numTris; queue.clear(); } public createCommandBuffer (info: CommandBufferInfo): CommandBuffer { // const Ctor = WebGLCommandBuffer; // opt to instant invocation const Ctor = info.type === CommandBufferType.PRIMARY ? WebGLPrimaryCommandBuffer : WebGLCommandBuffer; const cmdBuff = new Ctor(); cmdBuff.initialize(info); return cmdBuff; } public createSwapchain (info: SwapchainInfo): Swapchain { const swapchain = new WebGLSwapchain(); this._swapchain = swapchain; swapchain.initialize(info); return swapchain; } public createBuffer (info: BufferInfo | BufferViewInfo): Buffer { const buffer = new WebGLBuffer(); buffer.initialize(info); return buffer; } public createTexture (info: TextureInfo | TextureViewInfo): Texture { const texture = new WebGLTexture(); texture.initialize(info); return texture; } public createDescriptorSet (info: DescriptorSetInfo): DescriptorSet { const descriptorSet = new WebGLDescriptorSet(); descriptorSet.initialize(info); return descriptorSet; } public createShader (info: ShaderInfo): Shader { const shader = new WebGLShader(); shader.initialize(info); return shader; } public createInputAssembler (info: InputAssemblerInfo): InputAssembler { const inputAssembler = new WebGLInputAssembler(); inputAssembler.initialize(info); return inputAssembler; } public createRenderPass (info: RenderPassInfo): RenderPass { const renderPass = new WebGLRenderPass(); renderPass.initialize(info); return renderPass; } public createFramebuffer (info: FramebufferInfo): Framebuffer { const framebuffer = new WebGLFramebuffer(); framebuffer.initialize(info); return framebuffer; } public createDescriptorSetLayout (info: DescriptorSetLayoutInfo): DescriptorSetLayout { const descriptorSetLayout = new WebGLDescriptorSetLayout(); descriptorSetLayout.initialize(info); return descriptorSetLayout; } public createPipelineLayout (info: PipelineLayoutInfo): PipelineLayout { const pipelineLayout = new WebGLPipelineLayout(); pipelineLayout.initialize(info); return pipelineLayout; } public createPipelineState (info: PipelineStateInfo): PipelineState { const pipelineState = new WebGLPipelineState(); pipelineState.initialize(info); return pipelineState; } public createQueue (info: QueueInfo): Queue { const queue = new WebGLQueue(); queue.initialize(info); return queue; } public getSampler (info: SamplerInfo): Sampler { const hash = Sampler.computeHash(info); if (!this._samplers.has(hash)) { this._samplers.set(hash, new WebGLSampler(info, hash)); } return this._samplers.get(hash)!; } public getGlobalBarrier (info: GlobalBarrierInfo) { const hash = GlobalBarrier.computeHash(info); if (!this._globalBarriers.has(hash)) { this._globalBarriers.set(hash, new GlobalBarrier(info, hash)); } return this._globalBarriers.get(hash)!; } public getTextureBarrier (info: TextureBarrierInfo) { const hash = TextureBarrier.computeHash(info); if (!this._textureBarriers.has(hash)) { this._textureBarriers.set(hash, new TextureBarrier(info, hash)); } return this._textureBarriers.get(hash)!; } public copyBuffersToTexture (buffers: ArrayBufferView[], texture: Texture, regions: BufferTextureCopy[]) { WebGLCmdFuncCopyBuffersToTexture( this, buffers, (texture as WebGLTexture).gpuTexture, regions, ); } public copyTextureToBuffers (texture: Texture, buffers: ArrayBufferView[], regions: BufferTextureCopy[]) { WebGLCmdFuncCopyTextureToBuffers( this, (texture as WebGLTexture).gpuTexture, buffers, regions, ); } public copyTexImagesToTexture ( texImages: TexImageSource[], texture: Texture, regions: BufferTextureCopy[], ) { WebGLCmdFuncCopyTexImagesToTexture( this, texImages, (texture as WebGLTexture).gpuTexture, regions, ); } }
the_stack
import * as moment from "moment"; import * as Web3 from "web3"; // utils import { BigNumber } from "utils/bignumber"; import * as Units from "utils/units"; import { Web3Utils } from "utils/web3_utils"; import { ACCOUNTS } from "../../accounts"; // wrappers import { DebtKernelContract, ERC20Contract, RepaymentRouterContract, SimpleInterestTermsContractContract, } from "src/wrappers"; // types import { DEBT_ORDER_DATA_DEFAULTS, DebtRegistryEntry } from "src/types"; // adapters import { AmortizationUnit, SimpleInterestAdapterErrors, SimpleInterestLoanAdapter, SimpleInterestLoanOrder, } from "src/adapters/simple_interest_loan_adapter"; import { ContractsAPI, ContractsError } from "src/apis/contracts_api"; import { SimpleInterestLoanTerms } from "../../../src/adapters/simple_interest_loan_terms"; const provider = new Web3.providers.HttpProvider("http://localhost:8545"); const web3 = new Web3(provider); const web3Utils = new Web3Utils(web3); const contracts = new ContractsAPI(web3); const simpleInterestLoanAdapter = new SimpleInterestLoanAdapter(web3, contracts); const simpleInterestLoanTerms = new SimpleInterestLoanTerms(web3, contracts); const TX_DEFAULTS = { from: ACCOUNTS[0].address, gas: 4712388 }; // Given that we rely on having access to the deployed Dharma smart contracts, // we unmock the Dharma smart contracts artifacts package to pull the most recently // deployed contracts on the current network. jest.unmock("@dharmaprotocol/contracts"); // Unmock the "fs-extra" package in order to give us // access to the deployed TokenRegistry on the // test chain. jest.unmock("fs-extra"); describe("Simple Interest Terms Contract Interface (Unit Tests)", () => { let snapshotId: number; beforeEach(async () => { snapshotId = await web3Utils.saveTestSnapshot(); }); afterEach(async () => { await web3Utils.revertToSnapshot(snapshotId); }); const defaultLoanParams = { principalTokenIndex: new BigNumber(0), // REP's index in the Token Registry is 0 principalAmount: new BigNumber(3.456 * 10 ** 18), // Principal Amount: 3.456e18 interestRate: new BigNumber(14.36), // Interest Rate: 14.36% amortizationUnit: SimpleInterestLoanAdapter.Installments.DAILY, // Daily installments termLength: new BigNumber(7), // 7 day term }; describe("#packParameters", () => { describe("...with invalid principal token index", () => { // 300 is an invalid principal token index, given that we cannot encode // values greater than 255 in the terms contract parameters const invalidPrincipalTokenIndex = new BigNumber(300); test("should throw INVALID_TOKEN_INDEX error", () => { expect(() => { simpleInterestLoanTerms.packParameters({ ...defaultLoanParams, principalTokenIndex: invalidPrincipalTokenIndex, }); }).toThrow( SimpleInterestAdapterErrors.INVALID_TOKEN_INDEX(invalidPrincipalTokenIndex), ); }); }); describe("...with principal amount > 2^96 - 1", () => { test("should throw INVALID_PRINCIPAL_AMOUNT error", () => { expect(() => { simpleInterestLoanTerms.packParameters({ ...defaultLoanParams, principalAmount: new BigNumber(3.5 * 10 ** 38), }); }).toThrow(SimpleInterestAdapterErrors.INVALID_PRINCIPAL_AMOUNT()); }); }); describe("...with principal amount < 0", () => { test("should throw INVALID_PRINCIPAL_AMOUNT error", () => { expect(() => { simpleInterestLoanTerms.packParameters({ ...defaultLoanParams, principalAmount: new BigNumber(-1), }); }).toThrowError(SimpleInterestAdapterErrors.INVALID_PRINCIPAL_AMOUNT()); }); }); describe("...with interest rate > 1677.7216%", () => { test("should throw INVALID_INTEREST_RATE error", () => { expect(() => { simpleInterestLoanTerms.packParameters({ ...defaultLoanParams, interestRate: new BigNumber(1677.7217), }); }).toThrowError(SimpleInterestAdapterErrors.INVALID_INTEREST_RATE()); }); }); describe("...with interest rate < 0", () => { test("should throw INVALID_INTEREST_RATE error", () => { expect(() => { simpleInterestLoanTerms.packParameters({ ...defaultLoanParams, interestRate: new BigNumber(-1), }); }).toThrowError(SimpleInterestAdapterErrors.INVALID_INTEREST_RATE()); }); }); describe("...where interest rate has more than 4 decimal places", () => { test("should throw INVALID_INTEREST_RATE error", () => { expect(() => { simpleInterestLoanTerms.packParameters({ ...defaultLoanParams, interestRate: new BigNumber(5.20035), }); }).toThrowError(SimpleInterestAdapterErrors.INVALID_INTEREST_RATE()); }); }); describe("...with non-existent amortization unit", () => { test("should throw INVALID_AMORTIZATION_UNIT_TYPE error", () => { expect(() => { simpleInterestLoanTerms.packParameters({ ...defaultLoanParams, amortizationUnit: "every decade" as AmortizationUnit, }); }).toThrowError(SimpleInterestAdapterErrors.INVALID_AMORTIZATION_UNIT_TYPE()); }); }); describe("...with term length > 2^120 - 1", () => { test("should throw INVALID_TERM_LENGTH error", () => { expect(() => { simpleInterestLoanTerms.packParameters({ ...defaultLoanParams, termLength: new BigNumber(3.5 * 10 ** 38), }); }).toThrowError(SimpleInterestAdapterErrors.INVALID_TERM_LENGTH()); }); }); describe("...with term length < 0", () => { test("should throw INVALID_TERM_LENGTH error", () => { expect(() => { simpleInterestLoanTerms.packParameters({ ...defaultLoanParams, termLength: new BigNumber(-1), }); }).toThrowError(SimpleInterestAdapterErrors.INVALID_TERM_LENGTH()); }); }); describe("...with term length not specified in whole numbers", () => { test("should throw INVALID_TERM_LENGTH error", () => { expect(() => { simpleInterestLoanTerms.packParameters({ ...defaultLoanParams, termLength: new BigNumber(1.3), }); }).toThrowError(/Expected termLength to conform to schema \/WholeNumber/); }); }); describe("...with valid principal amount, interest rate, amortization, and term length", () => { describe("Scenario #1", () => { test("should return correctly packed parameters", () => { expect(simpleInterestLoanTerms.packParameters(defaultLoanParams)).toEqual( "0x00000000002ff62db077c000000230f010007000000000000000000000000000", ); }); }); describe("Scenario #2", () => { const principalTokenIndex = new BigNumber(1); const principalAmount = new BigNumber(723489020 * 10 ** 18); const interestRate = new BigNumber(0.012); const amortizationUnit = SimpleInterestLoanAdapter.Installments.YEARLY; const termLength = new BigNumber(4); test("should return correctly packed parameters", () => { expect( simpleInterestLoanTerms.packParameters({ principalTokenIndex, principalAmount, interestRate, amortizationUnit, termLength, }), ).toEqual("0x01025674c25cd7f81d0670000000007840004000000000000000000000000000"); }); }); describe("Scenario #3", () => { const principalTokenIndex = new BigNumber(2); const principalAmount = new BigNumber(0.0000023232312 * 10 ** 18); const interestRate = new BigNumber(90.2321); const amortizationUnit = SimpleInterestLoanAdapter.Installments.MONTHLY; const termLength = new BigNumber(12); test("should return correctly packed parameters", () => { expect( simpleInterestLoanTerms.packParameters({ principalTokenIndex, principalAmount, interestRate, amortizationUnit, termLength, }), ).toEqual("0x02000000000000021ceb5ed3000dc4b13000c000000000000000000000000000"); }); }); }); }); describe("#unpackParameters", () => { describe("...with amortization unit > 4", () => { const termsContractParameters = "0x0000000025674c25cd7f81d06700000050004000000000000000000000000000"; test("should throw INVALID_AMORTIZATION_UNIT_TYPE error", () => { expect(() => { simpleInterestLoanTerms.unpackParameters(termsContractParameters); }).toThrowError(SimpleInterestAdapterErrors.INVALID_AMORTIZATION_UNIT_TYPE()); }); }); describe("...with value that has too few bytes", () => { const termsContractParameters = "0x00000000025674c25cd7f81d067000000500000000000004"; test("should throw INVALID_PACKED_PARAMETERS error", () => { expect(() => { simpleInterestLoanTerms.unpackParameters(termsContractParameters); }).toThrowError( /Expected termsContractParametersPacked to conform to schema \/Bytes32/, ); }); }); describe("...with value that has too many bytes", () => { const termsContractParameters = "0x00000000000000002ff62db077c000000100000000000000000000000000000007"; test("should throw INVALID_PACKED_PARAMETERS error", () => { expect(() => { simpleInterestLoanTerms.unpackParameters(termsContractParameters); }).toThrowError( /Expected termsContractParametersPacked to conform to schema \/Bytes32/, ); }); }); describe("...with value that includes non-hexadecimal characters", () => { const termsContractParameters = "0x00000000000000002ff62db077c0000001000000000000z00000000000000007"; test("should throw INVALID_PACKED_PARAMETERS error", () => { expect(() => { simpleInterestLoanTerms.unpackParameters(termsContractParameters); }).toThrowError( /Expected termsContractParametersPacked to conform to schema \/Bytes32/, ); }); }); describe("...with termsContractParameters string", () => { describe("Scenario #1", () => { const parameters = "0x00000000002ff62db077c000000230f010007000000000000000000000000000"; test("should return correctly unpacked parameters", () => { expect(simpleInterestLoanTerms.unpackParameters(parameters)).toEqual( defaultLoanParams, ); }); }); describe("Scenario #2", () => { const parameters = "0x01025674c25cd7f81d0670000000007840004000000000000000000000000000"; const unpackedParameters = { principalTokenIndex: new BigNumber(1), principalAmount: new BigNumber(723489020 * 10 ** 18), interestRate: new BigNumber(0.012), amortizationUnit: SimpleInterestLoanAdapter.Installments.YEARLY, termLength: new BigNumber(4), }; test("should return correctly unpacked parameters", () => { expect(simpleInterestLoanTerms.unpackParameters(parameters)).toEqual( unpackedParameters, ); }); }); describe("Scenario #3", () => { const parameters = "0x05000000000000021ceb5ed3000dc4b13000c000000000000000000000000000"; const unpackedParameters = { principalTokenIndex: new BigNumber(5), principalAmount: new BigNumber(0.0000023232312 * 10 ** 18), interestRate: new BigNumber(90.2321), amortizationUnit: SimpleInterestLoanAdapter.Installments.MONTHLY, termLength: new BigNumber(12), }; test("should return correctly unpacked parameters", () => { expect(simpleInterestLoanTerms.unpackParameters(parameters)).toEqual( unpackedParameters, ); }); }); }); }); }); describe("Simple Interest Loan Adapter (Unit Tests)", async () => { let debtKernelAddress: string; let repaymentRouterAddress: string; let defaultLoanOrder: SimpleInterestLoanOrder; beforeAll(async () => { const debtKernel = await DebtKernelContract.deployed(web3, TX_DEFAULTS); const repaymentRouter = await RepaymentRouterContract.deployed(web3, TX_DEFAULTS); debtKernelAddress = debtKernel.address; repaymentRouterAddress = repaymentRouter.address; defaultLoanOrder = { principalAmount: Units.ether(1), principalTokenSymbol: "REP", interestRate: new BigNumber(0.14), amortizationUnit: SimpleInterestLoanAdapter.Installments.WEEKLY, termLength: new BigNumber(2), }; }); describe("#toDebtOrder", () => { describe("simple interest loan's required parameter is missing or malformed", () => { describe("principalTokenSymbol missing", () => { it("should throw DOES_NOT_CONFORM_TO_SCHEMA", async () => { await expect( simpleInterestLoanAdapter.toDebtOrder({ ...defaultLoanOrder, principalTokenSymbol: undefined, }), ).rejects.toThrow('instance requires property "principalTokenSymbol"'); }); }); describe("principalTokenSymbol is not tracked by Token Registry", () => { it("should throw PRINCIPAL_TOKEN_NOT_SUPPORTED", async () => { await expect( simpleInterestLoanAdapter.toDebtOrder({ ...defaultLoanOrder, principalTokenSymbol: "XXX", // XXX is not tracked in our test env's registry }), ).rejects.toThrow(ContractsError.CANNOT_FIND_TOKEN_WITH_SYMBOL("XXX")); }); }); describe("principalAmount missing", async () => { it("should throw DOES_NOT_CONFORM_TO_SCHEMA", async () => { await expect( simpleInterestLoanAdapter.toDebtOrder({ ...defaultLoanOrder, principalAmount: undefined, }), ).rejects.toThrow('instance requires property "principalAmount"'); }); }); describe("interestRate missing", async () => { it("should throw DOES_NOT_CONFORM_TO_SCHEMA", async () => { await expect( simpleInterestLoanAdapter.toDebtOrder({ ...defaultLoanOrder, interestRate: undefined, }), ).rejects.toThrow('instance requires property "interestRate"'); }); }); describe("amortizationUnit missing", async () => { it("should throw DOES_NOT_CONFORM_TO_SCHEMA", async () => { await expect( simpleInterestLoanAdapter.toDebtOrder({ ...defaultLoanOrder, amortizationUnit: undefined, }), ).rejects.toThrow('instance requires property "amortizationUnit"'); }); }); describe("amortizationUnit not one of hours|days|months|years", async () => { it("should throw DOES_NOT_CONFORM_TO_SCHEMA", async () => { await expect( simpleInterestLoanAdapter.toDebtOrder({ ...defaultLoanOrder, amortizationUnit: "decades" as AmortizationUnit, }), ).rejects.toThrow("instance.amortizationUnit does not match pattern"); }); }); describe("termLength missing", async () => { it("should throw DOES_NOT_CONFORM_TO_SCHEMA", async () => { await expect( simpleInterestLoanAdapter.toDebtOrder({ ...defaultLoanOrder, termLength: undefined, }), ).rejects.toThrow('instance requires property "termLength"'); }); }); }); describe("simple interest loan's required parameters are present and well formed ", () => { let simpleInterestTermsContract: SimpleInterestTermsContractContract; let principalToken: ERC20Contract; let principalTokenIndex: BigNumber; beforeAll(async () => { simpleInterestTermsContract = await contracts.loadSimpleInterestTermsContract( TX_DEFAULTS, ); }); describe("Scenario #1", () => { const principalAmount = Units.ether(1); const interestRate = new BigNumber(0.14); const amortizationUnit = SimpleInterestLoanAdapter.Installments.WEEKLY; const termLength = new BigNumber(2); beforeAll(async () => { principalToken = await contracts.loadTokenBySymbolAsync("REP", TX_DEFAULTS); principalTokenIndex = await contracts.getTokenIndexBySymbolAsync("REP"); }); it("should return debt order with correctly packed values", async () => { const encodedIndex = principalTokenIndex.toString().padStart(2, "0"); const termsContractParameters = `0x${encodedIndex}000000000de0b6b3a764000000057820002000000000000000000000000000`; await expect( simpleInterestLoanAdapter.toDebtOrder({ principalAmount, principalTokenSymbol: "REP", interestRate, amortizationUnit, termLength, }), ).resolves.toEqual({ ...DEBT_ORDER_DATA_DEFAULTS, kernelVersion: debtKernelAddress, issuanceVersion: repaymentRouterAddress, principalAmount, principalToken: principalToken.address, termsContract: simpleInterestTermsContract.address, termsContractParameters, }); }); }); describe("Scenario #2", () => { const principalAmount = Units.ether(0.3); const interestRate = new BigNumber(1.678); const amortizationUnit = SimpleInterestLoanAdapter.Installments.YEARLY; const termLength = new BigNumber(1); beforeAll(async () => { principalToken = await contracts.loadTokenBySymbolAsync("MKR", TX_DEFAULTS); principalTokenIndex = await contracts.getTokenIndexBySymbolAsync("MKR"); }); it("should return debt order with correctly packed values", async () => { const encodedIndex = principalTokenIndex.toString().padStart(2, "0"); const termsContractParameters = `0x${encodedIndex}000000000429d069189e000000418c40001000000000000000000000000000`; await expect( simpleInterestLoanAdapter.toDebtOrder({ principalAmount, principalTokenSymbol: "MKR", interestRate, amortizationUnit, termLength, }), ).resolves.toEqual({ ...DEBT_ORDER_DATA_DEFAULTS, kernelVersion: debtKernelAddress, issuanceVersion: repaymentRouterAddress, principalAmount, principalToken: principalToken.address, termsContract: simpleInterestTermsContract.address, termsContractParameters, }); }); }); describe("Scenario #3", () => { const principalAmount = Units.ether(200000); const interestRate = new BigNumber(0.0001); const amortizationUnit = SimpleInterestLoanAdapter.Installments.MONTHLY; const termLength = new BigNumber(12); beforeAll(async () => { principalToken = await contracts.loadTokenBySymbolAsync("ZRX", TX_DEFAULTS); principalTokenIndex = await contracts.getTokenIndexBySymbolAsync("ZRX"); }); it("should return debt order with correctly packed values", async () => { const encodedIndex = principalTokenIndex.toString().padStart(2, "0"); const termsContractParameters = `0x${encodedIndex}00002a5a058fc295ed0000000000013000c000000000000000000000000000`; await expect( simpleInterestLoanAdapter.toDebtOrder({ principalAmount, principalTokenSymbol: "ZRX", interestRate, amortizationUnit, termLength, }), ).resolves.toEqual({ ...DEBT_ORDER_DATA_DEFAULTS, kernelVersion: debtKernelAddress, issuanceVersion: repaymentRouterAddress, principalAmount, principalToken: principalToken.address, termsContract: simpleInterestTermsContract.address, termsContractParameters, }); }); }); }); }); describe("#getRepaymentSchedule", () => { let simpleInterestTermsContractAddress: string; let termsContract; beforeAll(async () => { const simpleInterestTermsContract = await contracts.loadSimpleInterestTermsContract(); simpleInterestTermsContractAddress = simpleInterestTermsContract.address; termsContract = simpleInterestTermsContractAddress; }); describe("when the schedule is across 2 weeks", () => { test("it returns a list of 2 unix timestamps 1 week apart", async () => { const principalTokenIndex = new BigNumber(0); const principalAmount = new BigNumber(1); const interestRate = new BigNumber(1.23); const amortizationUnit = SimpleInterestLoanAdapter.Installments.WEEKLY; const termLength = new BigNumber(2); const contractTermsParameters = simpleInterestLoanTerms.packParameters({ principalTokenIndex, principalAmount, interestRate, amortizationUnit, termLength, }); const issuanceTime = moment().unix(); // Mock a debt registry entry that has some issuance time and the terms parameters. const debtRegistryEntry = { version: "0", beneficiary: "0", underwriter: "0", underwriterRiskRating: new BigNumber(0), termsContract, termsContractParameters: contractTermsParameters, issuanceBlockTimestamp: new BigNumber(issuanceTime), }; const scheduleList = simpleInterestLoanAdapter.getRepaymentSchedule( debtRegistryEntry, ); expect(scheduleList).toEqual([ moment .unix(issuanceTime) .add(1, "week") .unix(), moment .unix(issuanceTime) .add(2, "weeks") .unix(), ]); }); }); }); describe("#fromDebtOrder()", () => { let simpleInterestTermsContractAddress: string; let principalTokenAddress: string; beforeAll(async () => { const simpleInterestTermsContract = await contracts.loadSimpleInterestTermsContract(); simpleInterestTermsContractAddress = simpleInterestTermsContract.address; principalTokenAddress = await contracts.getTokenAddressBySymbolAsync("REP"); }); describe("argument does not conform to the DebtOrderWithTermsSpecified schema", () => { describe("malformed terms contract / terms contract parameters", () => { it("should throw DOES_NOT_CONFORM_TO_SCHEMA", async () => { await expect( simpleInterestLoanAdapter.fromDebtOrder({ principalAmount: Units.ether(1), principalToken: principalTokenAddress, termsContract: "invalid terms contract", termsContractParameters: "invalid terms contract parameters", }), ).rejects.toThrow("instance.termsContract does not match pattern"); }); }); describe("missing termsContract", () => { it("should throw DOES_NOT_CONFORM_TO_SCHEMA", async () => { await expect( simpleInterestLoanAdapter.fromDebtOrder({ principalAmount: Units.ether(1), principalToken: principalTokenAddress, termsContractParameters: "0x0000000000002a5b1b1e089f00d000000300000000000000000000000000000c", }), ).rejects.toThrow('instance requires property "termsContract"'); }); }); describe("missing termsContractParameters", () => { it("should throw DOES_NOT_CONFORM_TO_SCHEMA", async () => { await expect( simpleInterestLoanAdapter.fromDebtOrder({ principalAmount: Units.ether(1), principalToken: principalTokenAddress, termsContract: ACCOUNTS[0].address, }), ).rejects.toThrow('instance requires property "termsContractParameters"'); }); }); describe("missing principalAmount", async () => { await expect( simpleInterestLoanAdapter.fromDebtOrder({ principalToken: principalTokenAddress, termsContract: ACCOUNTS[0].address, termsContractParameters: "0x0000000000002a5b1b1e089f00d000000300000000000000000000000000000c", }), ).rejects.toThrow('instance requires property "principalAmount"'); }); describe("missing principalToken", async () => { await expect( simpleInterestLoanAdapter.fromDebtOrder({ principalAmount: Units.ether(1), termsContract: ACCOUNTS[0].address, termsContractParameters: "0x0000000000002a5b1b1e089f00d000000300000000000000000000000000000c", }), ).rejects.toThrow('instance requires property "principalToken"'); }); }); describe("amortization specified in termsContractParameters is of invalid type", () => { it("should throw INVALID_AMORTIZATION_UNIT_TYPE", async () => { await expect( simpleInterestLoanAdapter.fromDebtOrder({ principalToken: principalTokenAddress, principalAmount: Units.ether(1), termsContract: simpleInterestTermsContractAddress, termsContractParameters: "0x0000000000002a5b1b1e089f00d000006000c000000000000000000000000000", }), ).rejects.toThrow(SimpleInterestAdapterErrors.INVALID_AMORTIZATION_UNIT_TYPE()); }); }); describe("debt order is valid and well-formed", () => { let principalTokenSymbol; let principalToken; let termsContract; beforeAll(() => { termsContract = simpleInterestTermsContractAddress; }); describe("Scenario #1", () => { const principalAmount = Units.ether(1); const interestRate = new BigNumber(0.14); const amortizationUnit = SimpleInterestLoanAdapter.Installments.WEEKLY; const termLength = new BigNumber(2); const termsContractParameters = "0x00000000000de0b6b3a764000000057820002000000000000000000000000000"; beforeAll(async () => { const principalTokenIndex = new BigNumber(termsContractParameters.substr(2, 2)); principalTokenSymbol = await contracts.getTokenSymbolByIndexAsync( principalTokenIndex, ); principalToken = await contracts.getTokenAddressBySymbolAsync( principalTokenSymbol, ); }); it("should return SimpleInterestLoanOrder with correctly unpacked values", async () => { await expect( simpleInterestLoanAdapter.fromDebtOrder({ principalAmount, principalToken, termsContract, termsContractParameters, }), ).resolves.toEqual({ principalAmount, principalToken, principalTokenSymbol, termsContract, termsContractParameters, interestRate, amortizationUnit, termLength, }); }); }); describe("Scenario #2", () => { const principalAmount = Units.ether(0.3); const interestRate = new BigNumber(1.678); const amortizationUnit = SimpleInterestLoanAdapter.Installments.YEARLY; const termLength = new BigNumber(1); const termsContractParameters = "0x01000000000429d069189e000000418c40001000000000000000000000000000"; beforeAll(async () => { const principalTokenIndex = new BigNumber(termsContractParameters.substr(2, 2)); principalTokenSymbol = await contracts.getTokenSymbolByIndexAsync( principalTokenIndex, ); principalToken = await contracts.getTokenAddressBySymbolAsync( principalTokenSymbol, ); }); it("should return SimpleInterestLoanOrder with correctly unpacked values", async () => { await expect( simpleInterestLoanAdapter.fromDebtOrder({ principalAmount, principalToken, termsContract, termsContractParameters, }), ).resolves.toEqual({ principalAmount, principalToken, principalTokenSymbol, termsContract, termsContractParameters, interestRate, amortizationUnit, termLength, }); }); }); describe("Scenario #3", () => { const principalAmount = Units.ether(200000); const interestRate = new BigNumber(0.0001); const amortizationUnit = SimpleInterestLoanAdapter.Installments.MONTHLY; const termLength = new BigNumber(12); const termsContractParameters = "0x0200002a5a058fc295ed0000000000013000c000000000000000000000000000"; beforeAll(async () => { const principalTokenIndex = new BigNumber(termsContractParameters.substr(2, 2)); principalTokenSymbol = await contracts.getTokenSymbolByIndexAsync( principalTokenIndex, ); principalToken = await contracts.getTokenAddressBySymbolAsync( principalTokenSymbol, ); }); it("should return SimpleInterestLoanOrder with correctly unpacked values", async () => { await expect( simpleInterestLoanAdapter.fromDebtOrder({ principalAmount, principalToken, termsContract, termsContractParameters, }), ).resolves.toEqual({ principalAmount, principalToken, principalTokenSymbol, termsContract, termsContractParameters, interestRate, amortizationUnit, termLength, }); }); }); }); }); describe("#fromDebtRegistryEntry", () => { let termsContract: SimpleInterestTermsContractContract; let defaultDebtRegistryEntry: DebtRegistryEntry; beforeAll(async () => { termsContract = await contracts.loadSimpleInterestTermsContract(); defaultDebtRegistryEntry = { version: repaymentRouterAddress, issuanceBlockTimestamp: new BigNumber(moment().unix()), beneficiary: ACCOUNTS[0].address, underwriter: ACCOUNTS[1].address, underwriterRiskRating: Units.percent(0.1), termsContract: termsContract.address, termsContractParameters: "0x00000000000de0b6b3a764000000057820002000000000000000000000000000", }; }); describe("no principal token tracked at that index", () => { it("should throw CANNOT_FIND_TOKEN_WITH_INDEX", async () => { await expect( simpleInterestLoanAdapter.fromDebtRegistryEntry({ ...defaultDebtRegistryEntry, // Our test environment does not track a token at index 5 (which is packed // into the first byte of the parameters) termsContractParameters: "0xff000000000de0b6b3a764000000057820002000000000000000000000000000", }), ).rejects.toThrow(ContractsError.CANNOT_FIND_TOKEN_WITH_INDEX(255)); }); }); describe("refers to incorrect terms contract", () => { it("should throw MISMATCHED_TERMS_CONTRACT", async () => { // We choose an arbitrary address to represent // a different terms contract's address. const nonSimpleInterestTermsContract = ACCOUNTS[3].address; await expect( simpleInterestLoanAdapter.fromDebtRegistryEntry({ ...defaultDebtRegistryEntry, termsContract: nonSimpleInterestTermsContract, }), ).rejects.toThrow( SimpleInterestAdapterErrors.MISMATCHED_TERMS_CONTRACT( nonSimpleInterestTermsContract, ), ); }); }); describe("invalid amorization unit type", () => { it("should throw INVALID_AMORTIZATION_UNIT_TYPE", async () => { await expect( simpleInterestLoanAdapter.fromDebtRegistryEntry({ ...defaultDebtRegistryEntry, termsContractParameters: "0x00000000000de0b6b3a764000000057850002000000000000000000000000000", }), ).rejects.toThrow(SimpleInterestAdapterErrors.INVALID_AMORTIZATION_UNIT_TYPE()); }); }); describe("entry parameters are valid", () => { describe("Scenario #1:", () => { let expectedLoanOrder: SimpleInterestLoanOrder; beforeAll(async () => { const { termsContractParameters } = defaultDebtRegistryEntry; const principalTokenIndex = new BigNumber(termsContractParameters.substr(2, 2)); const principalTokenSymbol = await contracts.getTokenSymbolByIndexAsync( principalTokenIndex, ); expectedLoanOrder = { principalAmount: Units.ether(1), principalTokenSymbol, interestRate: new BigNumber(0.14), amortizationUnit: SimpleInterestLoanAdapter.Installments.WEEKLY, termLength: new BigNumber(2), }; }); it("should return correct simple interest loan order", async () => { await expect( simpleInterestLoanAdapter.fromDebtRegistryEntry(defaultDebtRegistryEntry), ).resolves.toEqual(expectedLoanOrder); }); }); describe("Scenario #2:", () => { let expectedLoanOrder: SimpleInterestLoanOrder; const termsContractParameters = "0x01000000000429d069189e000000418c40001000000000000000000000000000"; beforeAll(async () => { const principalTokenIndex = new BigNumber(termsContractParameters.substr(2, 2)); const principalTokenSymbol = await contracts.getTokenSymbolByIndexAsync( principalTokenIndex, ); expectedLoanOrder = { principalAmount: Units.ether(0.3), principalTokenSymbol, interestRate: new BigNumber(1.678), amortizationUnit: SimpleInterestLoanAdapter.Installments.YEARLY, termLength: new BigNumber(1), }; }); it("should return correct simple interest loan order", async () => { await expect( simpleInterestLoanAdapter.fromDebtRegistryEntry({ ...defaultDebtRegistryEntry, termsContractParameters, }), ).resolves.toEqual(expectedLoanOrder); }); }); describe("Scenario #3:", () => { let expectedLoanOrder: SimpleInterestLoanOrder; const termsContractParameters = "0x0200002a5a058fc295ed0000000000013000c000000000000000000000000000"; beforeAll(async () => { const principalTokenIndex = new BigNumber(termsContractParameters.substr(2, 2)); const principalTokenSymbol = await contracts.getTokenSymbolByIndexAsync( principalTokenIndex, ); expectedLoanOrder = { principalAmount: Units.ether(200000), principalTokenSymbol, interestRate: new BigNumber(0.0001), amortizationUnit: SimpleInterestLoanAdapter.Installments.MONTHLY, termLength: new BigNumber(12), }; }); it("should return correct simple interest loan order", async () => { await expect( simpleInterestLoanAdapter.fromDebtRegistryEntry({ ...defaultDebtRegistryEntry, termsContractParameters, }), ).resolves.toEqual(expectedLoanOrder); }); }); }); }); });
the_stack
import { parse, parseFromClause, SelectStatement, FromTableNode, ColumnRefNode, IncompleteSubqueryNode, FromClauseParserResult, DeleteStatement, NodeRange } from '@joe-re/sql-parser' import log4js from 'log4js' import { Schema, Table, DbFunction } from './database_libs/AbstractClient' import { CompletionItem, CompletionItemKind } from 'vscode-languageserver-types'; type Pos = { line: number, column: number } const logger = log4js.getLogger() export const KEYWORD_ICON = CompletionItemKind.Text export const COLUMN_ICON = CompletionItemKind.Interface export const TABLE_ICON = CompletionItemKind.Field export const FUNCTION_ICON = CompletionItemKind.Property export const ALIAS_ICON = CompletionItemKind.Variable export const UTILITY_ICON = CompletionItemKind.Event const CLAUSES: string[] = [ 'SELECT', 'WHERE', 'ORDER BY', 'GROUP BY', 'LIMIT', '--', '/*', '(' ] const UNDESIRED_LITERAL = [ '+', '-', '*', '$', ':', 'COUNT', 'AVG', 'SUM', 'MIN', 'MAX', '`', '"', "'", ] export class Identifier { lastToken: string identifier: string detail: string kind: CompletionItemKind constructor(lastToken: string, identifier: string, detail: string, kind: CompletionItemKind) { this.lastToken = lastToken this.identifier = identifier this.detail = detail || '' this.kind = kind } matchesLastToken(): boolean { if (this.identifier.startsWith(this.lastToken)) { // prevent suggesting the lastToken itself, there is nothing to complete in that case if (this.identifier !== this.lastToken) { return true; } } return false; } toCompletionItem(): CompletionItem { const idx = this.lastToken.lastIndexOf('.') const label = this.identifier.substr(idx + 1) let kindName: string let tableAlias: string = '' if (this.kind === TABLE_ICON) { let tableName = label const i = tableName.lastIndexOf('.') if (i > 0) { tableName = label.substr(i + 1) } tableAlias = makeTableAlias(tableName) kindName = 'table' } else { kindName = 'column' } const item: CompletionItem = { label: label, detail: `${kindName} ${this.detail}`, kind: this.kind, } if (this.kind == TABLE_ICON) { item.insertText = `${label} AS ${tableAlias}` } return item } } // Gets the last token from the given string considering that tokens can contain dots. export function getLastToken(sql: string): string { const match = sql.match(/^(?:.|\s)*[^A-z0-9\.:'](.*?)$/) if (match) { let prevToken = ''; let currentToken = match[1]; while (currentToken != prevToken) { prevToken = currentToken; currentToken = prevToken.replace(/\[.*?\]/, ''); } return currentToken; } return sql; } function getFromNodesFromClause(sql: string): FromClauseParserResult | null { try { return parseFromClause(sql) as any } catch (_e) { // no-op return null } } function makeTableAlias(tableName: string): string { if (tableName.length > 3) { return tableName.substr(0, 3) } return tableName } function makeTableName(table: Table): string { if (table.catalog) { return table.catalog + '.' + table.database + '.' + table.tableName } else if (table.database) { return table.database + '.' + table.tableName } return table.tableName } class Completer { lastToken: string = '' candidates: CompletionItem[] = [] schema: Schema error: any = '' sql: string pos: Pos isSpaceTriggerCharacter: boolean = false; isDotTriggerCharacter: boolean = false; jupyterLabMode: boolean; constructor(schema: Schema, sql: string, pos: Pos, jupyterLabMode: boolean) { this.schema = schema this.sql = sql this.pos = pos this.jupyterLabMode = jupyterLabMode } complete() { const target = this.getRidOfAfterCursorString() logger.debug(`target: ${target}`) this.lastToken = getLastToken(target) const idx = this.lastToken.lastIndexOf('.') this.isSpaceTriggerCharacter = this.lastToken === '' this.isDotTriggerCharacter = !this.isSpaceTriggerCharacter && (idx == (this.lastToken.length - 1)) try { const ast = parse(target); this.addCandidatesForParsedStatement(ast) } catch (e: any) { logger.debug('error') logger.debug(e) if (e.name !== 'SyntaxError') { throw e } const parsedFromClause = getFromNodesFromClause(this.sql) if (parsedFromClause) { const fromNodes = this.getAllNestedFromNodes(parsedFromClause?.from?.tables || []) const fromNodeOnCursor = this.getFromNodeByPos(fromNodes) if (fromNodeOnCursor && fromNodeOnCursor.type === 'incomplete_subquery') { // Incomplete sub query 'SELECT sub FROM (SELECT e. FROM employees e) sub' this.addCandidatesForIncompleteSubquery(fromNodeOnCursor) } else { this.addCandidatesForSelectQuery(e, fromNodes) this.addCandidatesForJoins(e.expected || [], fromNodes) } } else if (e.message === 'EXPECTED COLUMN NAME') { this.addCandidatesForInsert() } else { this.addCandidatesForError(e) } this.error = { label: e.name, detail: e.message, line: e.line, offset: e.offset } } return this.candidates } toCompletionItemForFunction(f: DbFunction): CompletionItem { const item: CompletionItem = { label: f.name, detail: 'function', kind: FUNCTION_ICON, documentation: f.description, } return item } toCompletionItemForAlias(alias: string): CompletionItem { const item: CompletionItem = { label: alias, detail: 'alias', kind: ALIAS_ICON, } return item } toCompletionItemForKeyword(name: string): CompletionItem { const item: CompletionItem = { label: name, kind: KEYWORD_ICON, detail: 'keyword', } return item } addCandidatesForBasicKeyword() { CLAUSES .map(v => this.toCompletionItemForKeyword(v)) .forEach(v => this.addCandidateIfStartsWithLastToken(v)) } // Check if parser expects us to terminate a single quote value or double quoted column name // SELECT TABLE1.COLUMN1 FROM TABLE1 WHERE TABLE1.COLUMN1 = "hoge. // We don't offer the ', the ", the ` as suggestions addCandidatesForExpectedLiterals(expected: { type: string, text: string }[]) { const literals = expected.filter(v => v.type === 'literal').map(v => v.text) const uniqueLiterals = [...new Set(literals)]; uniqueLiterals .filter(v => !UNDESIRED_LITERAL.includes(v)) .map(v => { switch (v) { case 'ORDER': return 'ORDER BY' case 'GROUP': return 'GROUP BY' case 'LEFT': return 'LEFT JOIN' case 'RIGHT': return 'RIGHT JOIN' case 'INNER': return 'INNER JOIN' default: return v } }) .map(v => this.toCompletionItemForKeyword(v)) .forEach(v => this.addCandidateIfStartsWithLastToken(v)) } getColumnRefByPos(columns: ColumnRefNode[]) { return columns.find(v => // guard against ColumnRefNode that don't have a location, // for example sql functions that are not known to the parser v.location && (v.location.start.line === this.pos.line + 1 && v.location.start.column <= this.pos.column) && (v.location.end.line === this.pos.line + 1 && v.location.end.column >= this.pos.column) ) } isPosInLocation(location: NodeRange) { return (location.start.line === this.pos.line + 1 && location.start.column <= this.pos.column) && (location.end.line === this.pos.line + 1 && location.end.column >= this.pos.column) } /** * Finds the most deeply nested FROM node that have a range encompasing the position. * In cases such as SELECT * FROM T1 JOIN (SELECT * FROM (SELECT * FROM T2 <pos>)) * We will get a list of nodes like this * SELECT * FROM T1 * (SELECT * FROM * (SELECT * FROM T2)) * The idea is to reverse the list so that the most nested queries come first. Then * apply a filter to keep only the FROM nodes which encompass the position and take * the first one from that resulting list. * @param fromNodes * @param pos * @returns */ getFromNodeByPos(fromNodes: FromTableNode[]) { return fromNodes .reverse() .filter(tableNode => this.isPosInLocation(tableNode.location)) .shift() } /** * Given a table returns all possible ways to refer to it. * That is by table name only, using the database scope, * using the catalog and database scopes. * @param table * @returns */ allTableNameCombinations(table: Table): string[] { const names = [table.tableName]; if (table.database) names.push(table.database + '.' + table.tableName) if (table.catalog) names.push(table.catalog + '.' + table.database + '.' + table.tableName) return names; } addCandidatesForTables(tables: Table[]) { tables .flatMap(table => this.allTableNameCombinations(table)) .map(aTableNameVariant => { return new Identifier( this.lastToken, aTableNameVariant, '', TABLE_ICON ) }) .filter(item => item.matchesLastToken()) .map(item => item.toCompletionItem()) .forEach(item => this.addCandidate(item)) } addCandidatesForColumnsOfAnyTable(tables: Table[]) { tables .flatMap(table => table.columns) .map(column => { return new Identifier( this.lastToken, column.columnName, column.description, COLUMN_ICON ) }) .filter(item => item.matchesLastToken()) .map(item => item.toCompletionItem()) .forEach(item => this.addCandidate(item)) } addCandidate(item: CompletionItem) { // JupyterLab requires the dot or space character preceeding the <tab> key pressed // If the dot or space character are not added to the label then searching // in the list of suggestion does not work. // Here we fix this issue by adding the dot or space character // to the filterText and insertText. // TODO: report this issue to JupyterLab-LSP project. if (this.jupyterLabMode) { const text = item.insertText || item.label if (this.isSpaceTriggerCharacter) { item.insertText = ' ' + text item.filterText = ' ' + text } else if (this.isDotTriggerCharacter) { item.insertText = '.' + text item.filterText = '.' + text } } this.candidates.push(item) } addCandidateIfStartsWithLastToken(item: CompletionItem) { if (item.label.startsWith(this.lastToken)) { this.addCandidate(item) } } addCandidatesForIncompleteSubquery(incompleteSubquery: IncompleteSubqueryNode) { const parsedFromClause = getFromNodesFromClause(incompleteSubquery.text) try { parse(incompleteSubquery.text); } catch (e: any) { if (e.name !== 'SyntaxError') { throw e } const fromText = incompleteSubquery.text const newPos = parsedFromClause ? { line: this.pos.line - (incompleteSubquery.location.start.line - 1), column: this.pos.column - incompleteSubquery.location.start.column + 1 } : { line: 0, column: 0 } const completer = new Completer(this.schema, fromText, newPos, this.jupyterLabMode) completer.complete().forEach(item => this.addCandidate(item)) } } createTablesFromFromNodes(fromNodes: FromTableNode[]): Table[] { return fromNodes.reduce((p: any, c) => { if (c.type !== 'subquery') { return p } if (!Array.isArray(c.subquery.columns)) { return p } const columns = c.subquery.columns.map(v => { if (typeof v === 'string') { return null } return { columnName: v.as || (v.expr.type === 'column_ref' && v.expr.column) || '', description: 'alias' } }) return p.concat({ database: null, columns, tableName: c.as }) }, []) } /** * INSERT INTO TABLE1 (C */ addCandidatesForInsert() { this.addCandidatesForColumnsOfAnyTable(this.schema.tables) } addCandidatesForError(e: any) { this.addCandidatesForExpectedLiterals(e.expected || []) this.addCandidatesForFunctions() this.addCandidatesForTables(this.schema.tables) } addCandidatesForSelectQuery(e: any, fromNodes: FromTableNode[]) { const subqueryTables = this.createTablesFromFromNodes(fromNodes) const schemaAndSubqueries = this.schema.tables.concat(subqueryTables) this.addCandidatesForSelectStar(fromNodes, schemaAndSubqueries) this.addCandidatesForExpectedLiterals(e.expected || []) this.addCandidatesForFunctions() this.addCandidatesForScopedColumns(fromNodes, schemaAndSubqueries) this.addCandidatesForAliases(fromNodes) this.addCandidatesForTables(schemaAndSubqueries) if (logger.isDebugEnabled()) logger.debug(`candidates for error returns: ${JSON.stringify(this.candidates)}`) } addCandidatesForJoins(expected: { type: string, text: string }[], fromNodes: FromTableNode[]) { let joinType: string = '' if ('INNER'.startsWith(this.lastToken)) joinType = 'INNER' if ('LEFT'.startsWith(this.lastToken)) joinType = 'LEFT' if ('RIGH'.startsWith(this.lastToken)) joinType = 'RIGHT' if (joinType && (expected.map(v => v.text).find(v => v === 'JOIN'))) { if (fromNodes && fromNodes.length > 0) { const fromNode: any = fromNodes[0] const fromAlias = fromNode.as || fromNode.table const fromTable = this.schema.tables.find(table => this.tableMatch(fromNode, table)) this.schema.tables .filter(table => table != fromTable) .forEach(table => { table.columns .filter(column => fromTable?.columns .map(col => col.columnName).includes(column.columnName)) .map(column => { return { tableName: makeTableName(table), alias: makeTableAlias(table.tableName), columnName: column.columnName } }) .map(match => { const label = `${joinType} JOIN ${match.tableName} AS ${match.alias} ON ${match.alias}.${match.columnName} = ${fromAlias}.${match.columnName}` return { label: label, detail: 'utility', kind: UTILITY_ICON, } }) .forEach(item => this.addCandidate(item)) }) } } } getRidOfAfterCursorString() { return this.sql.split('\n').filter((_v, idx) => this.pos.line >= idx).map((v, idx) => idx === this.pos.line ? v.slice(0, this.pos.column) : v).join('\n') } addCandidatesForParsedDeleteStatement(ast: DeleteStatement) { if (this.isPosInLocation(ast.table.location)) { this.addCandidatesForTables(this.schema.tables) } else if (ast.where && this.isPosInLocation(ast.where.expression.location)) { const expr = ast.where.expression if (expr.type === 'column_ref') { this.addCandidatesForColumnsOfAnyTable(this.schema.tables) } } } completeSelectStatement(ast: SelectStatement) { if (Array.isArray(ast.columns)) { this.addCandidateIfStartsWithLastToken(this.toCompletionItemForKeyword('FROM')) this.addCandidateIfStartsWithLastToken(this.toCompletionItemForKeyword('AS')) } } /** * Recursively pull out the FROM nodes (including sub-queries) * @param tableNodes * @returns */ getAllNestedFromNodes(tableNodes: FromTableNode[]): FromTableNode[] { return tableNodes.flatMap(tableNode => { let result = [tableNode] if (tableNode.type == 'subquery') { const subTableNodes = tableNode.subquery.from?.tables || [] result = result.concat(this.getAllNestedFromNodes(subTableNodes)) } return result }) } addCandidatesForParsedSelectQuery(ast: any) { this.addCandidatesForBasicKeyword() this.completeSelectStatement(ast) if (!ast.distinct) { this.addCandidateIfStartsWithLastToken(this.toCompletionItemForKeyword('DISTINCT')) } const columnRef = this.findColumnAtPosition(ast) if (!columnRef) { this.addJoinCondidates(ast) } else { const parsedFromClause = getFromNodesFromClause(this.sql) const fromNodes = parsedFromClause?.from?.tables || [] const subqueryTables = this.createTablesFromFromNodes(fromNodes) const schemaAndSubqueries = this.schema.tables.concat(subqueryTables) if (columnRef.table) { // We know what table/alias this column belongs to // Find the corresponding table and suggest it's columns this.addCandidatesForScopedColumns(fromNodes, schemaAndSubqueries) } else { // Column is not scoped to a table/alias yet // Could be an alias, a talbe or a function this.addCandidatesForAliases(fromNodes) this.addCandidatesForTables(schemaAndSubqueries) this.addCandidatesForFunctions() } } if (logger.isDebugEnabled()) logger.debug(`parse query returns: ${JSON.stringify(this.candidates)}`) } addCandidatesForParsedStatement(ast: any) { if (logger.isDebugEnabled()) logger.debug(`getting candidates for parse query ast: ${JSON.stringify(ast)}`) if (!ast.type) { this.addCandidatesForBasicKeyword() } else if (ast.type === 'delete') { this.addCandidatesForParsedDeleteStatement(ast) } else if (ast.type === 'select') { this.addCandidatesForParsedSelectQuery(ast) } else { console.log(`AST type not supported yet: ${ast.type}`) } } addJoinCondidates(ast: any) { // from clause: complete 'ON' keyword on 'INNER JOIN' if (ast.type === 'select' && Array.isArray(ast.from?.tables)) { const fromTable = this.getFromNodeByPos(ast.from?.tables || []) if (fromTable && fromTable.type === 'table') { this.addCandidatesForTables(this.schema.tables) this.addCandidateIfStartsWithLastToken(this.toCompletionItemForKeyword('INNER JOIN')) this.addCandidateIfStartsWithLastToken(this.toCompletionItemForKeyword('LEFT JOIN')) if (fromTable.join && !fromTable.on) { this.addCandidateIfStartsWithLastToken(this.toCompletionItemForKeyword('ON')) } } } } findColumnAtPosition(ast: any): ColumnRefNode | undefined { const columns = ast.columns if (Array.isArray(columns)) { // columns in select clause const columnRefs = (columns as any).map((col: any) => col.expr).filter((expr: any) => !!expr) if (ast.type === 'select' && ast.where?.expression) { // columns in where clause columnRefs.push(ast.where.expression) } // column at position const columnRef = this.getColumnRefByPos(columnRefs) if (logger.isDebugEnabled()) logger.debug(JSON.stringify(columnRef)) return columnRef } return undefined } addCandidatesForFunctions() { console.time('addCandidatesForFunctions') if (!this.lastToken) { // Nothing was typed, return all lowercase functions this.schema.functions .map(func => this.toCompletionItemForFunction(func)) .forEach(item => this.addCandidate(item)) } else { // If user typed the start of the function const lower = this.lastToken.toLowerCase() const isTypedUpper = (this.lastToken != lower) this.schema.functions // Search using lowercase prefix .filter(v => v.name.startsWith(lower)) // If typed string is in upper case, then return upper case suggestions .map(v => { if (isTypedUpper) v.name = v.name.toUpperCase() return v }) .map(v => this.toCompletionItemForFunction(v)) .forEach(item => this.addCandidate(item)) } console.timeEnd('addCandidatesForFunctions') } makeColumnName(alias: string, columnName: string) { return alias ? alias + '.' + columnName : columnName; } addCandidatesForSelectStar(fromNodes: FromTableNode[], tables: Table[]) { console.time('addCandidatesForSelectStar') tables.flatMap(table => { return fromNodes.filter((fromNode: any) => this.tableMatch(fromNode, table)) .map((fromNode: any) => fromNode.as || fromNode.table) .filter(_alias => this.lastToken.toUpperCase() === 'SELECT' // complete SELECT keyword || this.lastToken === '') // complete at space after SELECT .map(alias => { const columnNames = table.columns .map(col => this.makeColumnName(alias, col.columnName)) .join(',\n') const label = `Select all columns from ${alias}` let prefix: string = '' if (this.lastToken) { prefix = this.lastToken + '\n' } return { label: label, insertText: prefix + columnNames, filterText: prefix + label, detail: 'utility', kind: UTILITY_ICON, } }) }).forEach(item => this.addCandidate(item)) console.timeEnd('addCandidatesForSelectStar') } addCandidatesForScopedColumns(fromNodes: FromTableNode[], tables: Table[]) { console.time('addCandidatesForScopedColumns') tables.flatMap(table => { return fromNodes.filter((fromNode: any) => this.tableMatch(fromNode, table)) .map((fromNode: any) => fromNode.as || fromNode.table) .filter(alias => this.lastToken.startsWith(alias + '.')) .flatMap(alias => table.columns.map(col => { return new Identifier( this.lastToken, this.makeColumnName(alias, col.columnName), col.description, COLUMN_ICON ) }) ) }) .filter(item => item.matchesLastToken()) .map(item => item.toCompletionItem()) .forEach(item => this.addCandidate(item)) console.timeEnd('addCandidatesForScopedColumns') } /** * Test if the given table matches the fromNode. * @param fromNode * @param table * @returns */ tableMatch(fromNode: any, table: Table) { // Assume table matches from node and disprove let matchingTable = true if (fromNode.type == 'subquery') { // If we have an alias it should match the subquery table name if (fromNode.as && fromNode.as != table.tableName) { matchingTable = false; } } // Regular tables // If we have a from node with a table name // and it does not match the table, we know it's not a match else { if (fromNode.table && fromNode.table != table.tableName) { matchingTable = false; } else if (fromNode.db && fromNode.db != table.database) { matchingTable = false; } else if (fromNode.catalog && fromNode.catalog != table.catalog) { matchingTable = false; } } return matchingTable; } addCandidatesForAliases(fromNodes: FromTableNode[]) { fromNodes .map((fromNode: any) => fromNode.as) .filter(aliasName => aliasName && aliasName.startsWith(this.lastToken)) .map(aliasName => this.toCompletionItemForAlias(aliasName)) .forEach(item => this.addCandidate(item)) } } export function complete(sql: string, pos: Pos, schema: Schema = { tables: [], functions: [] }, jupyterLabMode: boolean = false) { console.time('complete') if (logger.isDebugEnabled()) logger.debug(`complete: ${sql}, ${JSON.stringify(pos)}`) const completer = new Completer(schema, sql, pos, jupyterLabMode) const candidates = completer.complete() console.timeEnd('complete') return { candidates: candidates, error: completer.error } }
the_stack
import * as React from 'react'; import { NotificationContext, Severity } from '@lunchpad/contexts' import lodash from 'lodash'; import OBSWebSocket, { SceneItem } from 'obs-websocket-js'; import { StartOrStop } from '../../actions/obs-studio/togglestreaming'; import { SourcesOptions } from 'electron'; import { useLocalStorage } from '@lunchpad/hooks'; import { settingsLabels } from '@lunchpad/types'; import { settings } from 'cluster'; import { useEvent } from 'react-use'; const obs = new OBSWebSocket(); export type Source = { name: string, type: string, typeId: string } export type Filter = { enabled: boolean, name: string, settings: any, type: string } export interface IOBSStudioContext { isConnected: boolean hasError: unknown connect: () => void scenes: string[] currentScene: string sources: Source[] switchActiveScene: (name: string) => Promise<unknown> sceneItems: SceneItem[] collections: string[] currentCollection: string switchActiveSceneCollection: (name: string) => Promise<unknown> toggleStreaming: (mode: StartOrStop) => Promise<void> toggleRecording: (mode: StartOrStop) => Promise<void> toggleReplay: (mode: StartOrStop) => Promise<void> setMute: (source: string, mute: boolean) => Promise<void> setVolume: (source: string, volume: number) => Promise<void> getSourceFilters: (source: string) => Promise<Filter[]> saveReplay: () => Promise<void> setItemVisiblity: (name: string, scene: string, visible: boolean) => Promise<void> setFilterVisibility: (sourceName: string, filterName: string, filterEnabled: boolean) => Promise<void> } const obsContext = React.createContext<Partial<IOBSStudioContext>>({}) const { Provider } = obsContext; const OBSStudioProvider = (props) => { const obs = React.useRef(new OBSWebSocket()); const [ enabled, setEnabled ] = useLocalStorage<boolean>(settingsLabels.connections.obsStudio.enabled, false); const [ address ] = useLocalStorage<string>(settingsLabels.connections.obsStudio.address, "localhost:4444"); const [ autoConnect ] = useLocalStorage<boolean>(settingsLabels.connections.obsStudio.autoConnect, false); const [ password ] = useLocalStorage<string>(settingsLabels.connections.obsStudio.password, ""); const [ showErrorMessage ] = NotificationContext.useNotification(); const [ showSuccessMessage ] = NotificationContext.useNotification(); const [ isConnected, _setConnected ] = React.useState<boolean>(false); const [ hasError, setError ] = React.useState<Error>(); const [ collections, setCollections ] = React.useState<Array<string>>([]); const [ scenes, setScenes ] = React.useState<Array<string>>([]) const [ sceneItems, setSceneItems ] = React.useState<SceneItem[]>([]); const [ sources, setSources ] = React.useState<Source[]>([]); const [ currentScene, setCurrentScene ] = React.useState<string>(); const [ currentCollection, setCurrentCollection ] = React.useState<string>(); const setConnected = (val) => { _setConnected(val) } const onConnected = () => { setConnected(true); } const onDisconnected = () => { setConnected(false); } const onAuthenticationFailure = () => { setEnabled(false); setConnected(false); } obs.current.removeAllListeners('AuthenticationSuccess') obs.current.removeAllListeners('AuthenticationFailure') obs.current.removeAllListeners('ConnectionClosed') obs.current.addListener('AuthenticationSuccess', onConnected); obs.current.addListener('ConnectionClosed', onDisconnected); obs.current.addListener('AuthenticationFailure', onAuthenticationFailure); const OBSError = (error: any) => { if ('error' in error) { console.error(error) if (error.error === "Authentication Failed.") showErrorMessage("Authentication with OBS-Websocket failed.", 2500, Severity.error); else if ('code' in error && error.code === "CONNECTION_ERROR") { showErrorMessage("Cannot connect to OBS-Websocket. Is OBS Studio running and the OBS-Websocket plugin enabled? Disabling OBS-Studio integration.", 5000, Severity.error); setEnabled(false); } } else { console.error(error) } } const connect = () => { if (enabled) { obs.current.connect({ address, password }).then(() => { obs.current.send('GetVersion').then((result) => { const [ major, minor, fix] = result["obs-websocket-version"].split("."); if (parseInt(major) <= 4) { if (parseInt(minor) < 8) { setEnabled(false) return showErrorMessage("Please upgrade your obs-websocket plugin version to 4.8.0+", 5000, Severity.error); } } showSuccessMessage("OBS-Websocket connection established", 2500, Severity.info) }) }).catch(OBSError) } } React.useEffect(() => { if (autoConnect && enabled) { connect(); } return () => { if (enabled) { obs.current.disconnect(); } } }, [ autoConnect, enabled, password ]) const fetchSceneCollections = () => obs.current.send('ListSceneCollections').then(result => setCollections(result["scene-collections"].map(sc => lodash.get(sc, 'sc-name')))).catch(OBSError) const fetchScenes = () => obs.current.send('GetSceneList').then(result => setScenes([...result.scenes.map(scene => scene.name)])).catch(OBSError); const fetchCurrentCollection = () => obs.current.send('GetCurrentSceneCollection').then(result => setCurrentCollection(result["sc-name"])).catch(OBSError); const fetchCurrentScene = () => obs.current.send('GetCurrentScene').then(result => { setCurrentScene(result.name); setSceneItems(result.sources); }).catch(OBSError); const fetchSources = () => obs.current.send('GetSourcesList').then(result => { //@ts-ignore type def is wrong setSources(result.sources); }).catch(OBSError) React.useEffect(() => { if (enabled && isConnected) { fetchSceneCollections(); fetchCurrentCollection(); fetchScenes(); fetchCurrentScene(); fetchSources(); } }, [ isConnected, enabled ]) React.useEffect(() => { obs.current.on('SceneCollectionListChanged', fetchSceneCollections); obs.current.on('SceneCollectionChanged', () => { fetchCurrentCollection(); fetchCurrentScene(); }); obs.current.on('SourceCreated', fetchSources); obs.current.on('SourceDestroyed', fetchSources); obs.current.on('SourceRenamed', fetchSources); obs.current.on('SourceFilterAdded', fetchSources); obs.current.on('SourceFilterRemoved', fetchSources); obs.current.on('ScenesChanged', fetchScenes); obs.current.on('SwitchScenes', result => { setCurrentScene(result["scene-name"]); setSceneItems(result.sources); }); return () => { obs.current.removeAllListeners('SceneCollectionListChanged') obs.current.removeAllListeners('SceneCollectionChanged') obs.current.removeAllListeners('SourceCreated') obs.current.removeAllListeners('SourceDestroyed') obs.current.removeAllListeners('SourceRenamed') obs.current.removeAllListeners('SourceFilterAdded') obs.current.removeAllListeners('SourceFilterRemoved') obs.current.removeAllListeners('ScenesChanged') obs.current.removeAllListeners('SwitchScenes') } }, [ isConnected ]) const switchActiveScene = React.useCallback((name: string): Promise<void> => { if (!isConnected) return; return obs.current.send('SetCurrentScene', { "scene-name": name}) }, [ isConnected ]); const switchActiveSceneCollection = React.useCallback((name: string): Promise<void> => { if (!isConnected) return; return obs.current.send('SetCurrentSceneCollection', { "sc-name": name }) }, [ isConnected ]); const setItemVisiblity = React.useCallback((name: string, scene: string, visible: boolean): Promise<void> => { if (!isConnected) return; //@ts-ignore - buggy types return obs.current.send('SetSceneItemProperties', { "scene-name": scene, item: name, visible }) }, [ isConnected ]) const toggleStreaming = React.useCallback((mode: StartOrStop): Promise<void> => { if (!isConnected) return; if (mode === StartOrStop.Start) return obs.current.send('StartStreaming', {}) if (mode === StartOrStop.Stop) return obs.current.send('StopStreaming') if (mode === StartOrStop.Toggle) return obs.current.send('StartStopStreaming') }, [ isConnected ]) const toggleRecording = React.useCallback((mode: StartOrStop): Promise<void> => { console.log(mode) if (!isConnected) return; if (mode === StartOrStop.Start) return obs.current.send('StartRecording'); if (mode === StartOrStop.Stop) return obs.current.send('StopRecording') if (mode === StartOrStop.Toggle) return obs.current.send('StartStopRecording') }, [ isConnected ]) const toggleReplay = React.useCallback((mode: StartOrStop): Promise<void> => { if (!isConnected) return; if (mode === StartOrStop.Start) return obs.current.send('StartReplayBuffer') if (mode === StartOrStop.Stop) return obs.current.send('StopReplayBuffer') if (mode === StartOrStop.Toggle) return obs.current.send('StartStopReplayBuffer') }, [ isConnected ]) const getSourceFilters = React.useCallback(async (source: string): Promise<Filter[]> => { if (!isConnected) return; const result = await obs.current.send('GetSourceFilters', { sourceName: source }) //@ts-ignore wrong type defs return result.filters; }, [ isConnected ]) const setFilterVisibility = React.useCallback((sourceName: string, filterName: string, filterEnabled: boolean): Promise<void> => { if (!isConnected) return; //@ts-ignore wrong type defs return obs.current.send("SetSourceFilterVisibility", { sourceName, filterName, filterEnabled }) }, [ isConnected ]); const saveReplay = React.useCallback((): Promise<void> => { if (!isConnected) return; return obs.current.send("SaveReplayBuffer") }, [ isConnected ]) const setMute = React.useCallback((source: string, mute: boolean): Promise<void> => { if (!isConnected) return; return obs.current.send("SetMute", { source, mute }); }, [ isConnected ]) const setVolume = React.useCallback((source: string, volume: number): Promise<void> => { if (!isConnected) return; //@ts-ignore return obs.current.send("SetVolume", { source, volume, useDecibel: true }); }, [ isConnected ]) const value = React.useMemo(() => ({ isConnected, hasError, connect, scenes, collections, sources, currentCollection, currentScene, switchActiveScene, switchActiveSceneCollection, sceneItems, setItemVisiblity, toggleStreaming, toggleRecording, toggleReplay, saveReplay, getSourceFilters, setFilterVisibility, setMute, setVolume, }), [ setMute, setVolume, connect, getSourceFilters, setFilterVisibility, isConnected, hasError, scenes, collections, currentCollection, currentScene, switchActiveScene, switchActiveSceneCollection, sceneItems, setItemVisiblity, toggleStreaming, toggleRecording, toggleReplay, saveReplay, sources ]) return ( <Provider value={value}> {props.children} </Provider> ) } export const OBSStudioContext = { Provider: OBSStudioProvider, Context: obsContext, }
the_stack
// A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies. export enum __DirectiveLocation { QUERY = "QUERY", // Location adjacent to a query operation. MUTATION = "MUTATION", // Location adjacent to a mutation operation. SUBSCRIPTION = "SUBSCRIPTION", // Location adjacent to a subscription operation. FIELD = "FIELD", // Location adjacent to a field. FRAGMENT_DEFINITION = "FRAGMENT_DEFINITION", // Location adjacent to a fragment definition. FRAGMENT_SPREAD = "FRAGMENT_SPREAD", // Location adjacent to a fragment spread. INLINE_FRAGMENT = "INLINE_FRAGMENT", // Location adjacent to an inline fragment. SCHEMA = "SCHEMA", // Location adjacent to a schema definition. SCALAR = "SCALAR", // Location adjacent to a scalar definition. OBJECT = "OBJECT", // Location adjacent to an object type definition. FIELD_DEFINITION = "FIELD_DEFINITION", // Location adjacent to a field definition. ARGUMENT_DEFINITION = "ARGUMENT_DEFINITION", // Location adjacent to an argument definition. INTERFACE = "INTERFACE", // Location adjacent to an interface definition. UNION = "UNION", // Location adjacent to a union definition. ENUM = "ENUM", // Location adjacent to an enum definition. ENUM_VALUE = "ENUM_VALUE", // Location adjacent to an enum value definition. INPUT_OBJECT = "INPUT_OBJECT", // Location adjacent to an input object type definition. INPUT_FIELD_DEFINITION = "INPUT_FIELD_DEFINITION" // Location adjacent to an input object field definition. } // An enum describing what kind of type a given `__Type` is. export enum TypeKind { SCALAR = "SCALAR", // Indicates this type is a scalar. OBJECT = "OBJECT", // Indicates this type is an object. `fields` and `interfaces` are valid fields. INTERFACE = "INTERFACE", // Indicates this type is an interface. `fields` and `possibleTypes` are valid fields. UNION = "UNION", // Indicates this type is a union. `possibleTypes` is a valid field. ENUM = "ENUM", // Indicates this type is an enum. `enumValues` is a valid field. INPUT_OBJECT = "INPUT_OBJECT", // Indicates this type is an input object. `inputFields` is a valid field. LIST = "LIST", // Indicates this type is a list. `ofType` is a valid field. NON_NULL = "NON_NULL" // Indicates this type is a non-null. `ofType` is a valid field. } export type GraphQLSchema = { __schema: { __typename: "__Schema"; // The type that query operations will be rooted at. queryType: { __typename: "__Type"; name: string | null; }; // If this server supports mutation, the type that mutation operations will be rooted at. mutationType: { __typename: "__Type"; name: string | null; } | null; // If this server support subscription, the type that subscription operations will be rooted at. subscriptionType: { __typename: "__Type"; name: string | null; } | null; // A list of all types supported by this server. types: Array<{ __typename: "__Type"; kind: TypeKind; name: string | null; description: string | null; fields: Array<{ __typename: "__Field"; name: string; description: string | null; args: Array<{ __typename: "__InputValue"; name: string; description: string | null; type: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; } | null; } | null; } | null; } | null; } | null; } | null; } | null; }; // A GraphQL-formatted string representing the default value for this input value. defaultValue: string | null; }>; type: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; } | null; } | null; } | null; } | null; } | null; } | null; } | null; }; isDeprecated: boolean; deprecationReason: string | null; }> | null; inputFields: Array<{ __typename: "__InputValue"; name: string; description: string | null; type: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; } | null; } | null; } | null; } | null; } | null; } | null; } | null; }; // A GraphQL-formatted string representing the default value for this input value. defaultValue: string | null; }> | null; interfaces: Array<{ __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; } | null; } | null; } | null; } | null; } | null; } | null; } | null; }> | null; enumValues: Array<{ __typename: "__EnumValue"; name: string; description: string | null; }> | null; possibleTypes: Array<{ __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; } | null; } | null; } | null; } | null; } | null; } | null; } | null; }> | null; }>; // A list of all directives supported by this server. directives: Array<{ __typename: "__Directive"; name: string; description: string | null; locations: Array<__DirectiveLocation>; args: Array<{ __typename: "__InputValue"; name: string; description: string | null; type: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: "__Type"; kind: TypeKind; name: string | null; } | null; } | null; } | null; } | null; } | null; } | null; } | null; }; // A GraphQL-formatted string representing the default value for this input value. defaultValue: string | null; }>; }>; }; }; export type FullTypeFragment = { __typename: "__Type"; kind: TypeKind; name: string | null; description: string | null; fields: Array<{ __typename: string; name: string; description: string | null; args: Array<{ __typename: string; name: string; description: string | null; type: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; } | null; } | null; } | null; } | null; } | null; } | null; } | null; }; // A GraphQL-formatted string representing the default value for this input value. defaultValue: string | null; }>; type: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; } | null; } | null; } | null; } | null; } | null; } | null; } | null; }; isDeprecated: boolean; deprecationReason: string | null; }> | null; inputFields: Array<{ __typename: string; name: string; description: string | null; type: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; } | null; } | null; } | null; } | null; } | null; } | null; } | null; }; // A GraphQL-formatted string representing the default value for this input value. defaultValue: string | null; }> | null; interfaces: Array<{ __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; } | null; } | null; } | null; } | null; } | null; } | null; } | null; }> | null; enumValues: Array<{ __typename: string; name: string; description: string | null; }> | null; possibleTypes: Array<{ __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; } | null; } | null; } | null; } | null; } | null; } | null; } | null; }> | null; }; export type InputValueFragment = { __typename: "__InputValue"; name: string; description: string | null; type: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; } | null; } | null; } | null; } | null; } | null; } | null; } | null; }; // A GraphQL-formatted string representing the default value for this input value. defaultValue: string | null; }; export type TypeRefFragment = { __typename: "__Type"; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; ofType: { __typename: string; kind: TypeKind; name: string | null; } | null; } | null; } | null; } | null; } | null; } | null; } | null; };
the_stack
// global['window'] = win; // Object.defineProperty(win.document.body.style, 'transform', { // value: () => { // return { // enumerable: true, // configurable: true, // }; // }, // }); // global['document'] = win.document; // global['CSS'] = null; // global['Prism'] = null; // tslint:disable: ordered-imports import 'zone.js/dist/zone-node'; import 'reflect-metadata'; // tslint:disable-next-line: ordered-imports import { readFileSync, writeFile, writeFileSync, existsSync, mkdirSync } from 'fs'; import { join } from 'path'; // * NOTE :: leave this as require() since this file is built Dynamically from webpack // tslint:disable-next-line: no-var-requires const { AppServerModuleNgFactory, LAZY_MODULE_MAP, provideModuleMap, renderModuleFactory } = require('./dist/server/main'); import routeData from './static.paths'; const BROWSER_FOLDER = join(process.cwd(), 'dist', 'browser'); // Load the index.html file containing references to your application bundle. const index = readFileSync(join(BROWSER_FOLDER, 'index.html'), 'utf8'); let previousRender = Promise.resolve(); // Iterate each route path routeData.routes.forEach(route => { const fullPath = join(BROWSER_FOLDER, route); // Make sure the directory structure is there if (!existsSync(fullPath)) { mkdirSync(fullPath); } // Writes rendered HTML to index.html, replacing the file if it already exists. previousRender = previousRender .then(_ => renderModuleFactory(AppServerModuleNgFactory, { document: index, url: route, extraProviders: [provideModuleMap(LAZY_MODULE_MAP)], }), ) .then(html => writeFileSync(join(fullPath, 'index.html'), html)); }); const siteMap = `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"> ${routeData.routes.map(route => `<url><loc>${routeData.hostname ? routeData.hostname : ''}${route}</loc></url>`)} </urlset>`; writeFile(join(BROWSER_FOLDER, 'sitemap.xml'), siteMap, 'utf8', err => { if (err) { throw err; } // tslint:disable-next-line: no-console console.log('Sitemap has been created.'); }); /** * This section provides the logic to auto-import routes for an already existing app, * so the user does not have to add them manually on the static.paths file. */ // tslint:disable: no-implicit-dependencies no-console import ts from 'typescript'; import { Route, Routes } from '@angular/router'; import { WorkspaceSchema, Builders, WorkspaceTargets } from '@schematics/angular/utility/workspace-models'; import { getProjectTargets } from '@schematics/angular/utility/project-targets'; import { REQUEST, RESPONSE } from '@nguniversal/express-engine/tokens'; interface IRouteIdentifiers { identifiers: any[]; routes: any[]; } interface IRoutingMapper { path: string; visit: boolean; children?: any; } // Store our Angular configuration file. const angularConfiguration: WorkspaceSchema = JSON.parse(readFileSync('./angular.json').toString()); // Initialize our universal entry file variable to store later. let universalProjectEntryFile: string; // Loop on each project defined on Angular Configuration file. for (const project in angularConfiguration.projects) { // For each project, get workspace targets (build, server, lint, ...) if (angularConfiguration.projects.hasOwnProperty(project)) { const workspaceTargets: WorkspaceTargets = getProjectTargets(angularConfiguration.projects[project]); // Loop over each workspace target and check if it exists (just in case). for (const targetKey in workspaceTargets) { if (workspaceTargets.hasOwnProperty(targetKey)) { const target = workspaceTargets[targetKey]; // If the architect builder setting is equal to `build-angular:server`, assign it to our universal entry file. if (target.builder === Builders.Server) { universalProjectEntryFile = target.options.main; } } } } } console.log('------- Universal Project Entry File -------'); console.log(universalProjectEntryFile); // Extract the source directory from the universal entry file (usually src). const sourceDir: string = universalProjectEntryFile.substring(0, universalProjectEntryFile.lastIndexOf('/') + 1); // Create a temporal source file from the entry file string. const entryFileSource: ts.SourceFile = ts.createSourceFile( 'temp', readFileSync(universalProjectEntryFile).toString(), ts.ScriptTarget.Latest, ); // Initialize entry module path variable to store later. let entryModulePath: string; // Read the temporal source file and navigate into each export declaration to extract entry module path (app.server.module in this case). entryFileSource.forEachChild((parentNode: ts.Node) => { if (ts.isExportDeclaration(parentNode)) { parentNode.forEachChild((childNode: ts.Node) => { if (ts.isStringLiteral(childNode)) { const moduleDir: string = childNode.text.substring(childNode.text.lastIndexOf('/') + 1, childNode.text.length); if (moduleDir === 'app.server.module') { entryModulePath = sourceDir + childNode.text + '.ts'; } } }); } }); console.log('------- Entry Module Path -------'); console.log(entryModulePath); // Find all app routes. const routesList: Routes = findRoutes(readFileSync(entryModulePath).toString(), entryModulePath).routes; // Map the route list in order to const mappedRoutes: IRoutingMapper[] = routesList.map(routingMapper); // Load existing routes from the `static.paths` file. let allRoutes = routeData.routes; // Print the entire static routes along with the ones found at the app. console.log('-------- Static Routes Found --------'); allRoutes.forEach((route, idx) => console.log(`Route ${idx}: ${route}`)); // After mapping, add those to allRoutes array by using addToRoutes function. addToRoutes(mappedRoutes, '/'); // If the routes array is empty, push the base route. if (allRoutes.length === 0) { allRoutes.push('/'); } // Print the app routes. console.log('---------- App Routes Found ---------'); allRoutes.forEach((route, idx) => console.log(`Route ${idx}: ${route}`)); // Iterate each route path allRoutes.forEach(route => { const fullPath = join(BROWSER_FOLDER, route); // Make sure the directory structure is there if (!existsSync(fullPath)) { let syncpath = BROWSER_FOLDER; route.split('/').forEach(element => { syncpath = syncpath + '/' + element; if (!existsSync(syncpath)) { mkdirSync(syncpath); } }); } // Writes rendered HTML to index.html, replacing the file if it already exists. previousRender = previousRender .then(_ => renderModuleFactory(AppServerModuleNgFactory, { document: index, url: route, extraProviders: [ provideModuleMap(LAZY_MODULE_MAP), { provide: REQUEST, useValue: { cookie: '', headers: {} }, }, { provide: RESPONSE, useValue: {}, }, ], }), ) .then(html => writeFileSync(join(fullPath, 'index.html'), html)) .finally(() => console.log('🚀 Pre-rendering Finished!')); }); function routingMapper(entry: Route): IRoutingMapper { if (entry.children) { return { path: entry.path, children: entry.children.map(routingMapper), visit: !!entry.component || !!entry.redirectTo }; } else { return { path: entry.path, visit: !!entry.component || !!entry.redirectTo }; } } function addToRoutes(routing: IRoutingMapper[], basePath: string): void { routing.forEach(element => { if (element.visit && element.path.indexOf(':') === -1) { if (allRoutes.indexOf(basePath + element.path) === -1) { allRoutes = allRoutes.concat(basePath + element.path); } if (element.children) { basePath += element.path !== '' ? element.path + '/' : element.path; addToRoutes(element.children, basePath); } } }); } function findRoutes(sourceCode: string, path: string): IRouteIdentifiers { let identifiers = []; let routes = []; const SourceCodeObj = ts.createSourceFile('temp', sourceCode, ts.ScriptTarget.Latest); SourceCodeObj.getChildren().forEach(nodes => { nodes .getChildren() .filter(node => ts.isClassDeclaration(node)) .forEach((node: ts.Node) => { if (node.decorators) { node.forEachChild(subNode => subNode.forEachChild(decoratorNode => { if ( ts.isCallExpression(decoratorNode) && ts.isIdentifier(decoratorNode.expression) && decoratorNode.expression.escapedText === 'NgModule' ) { decoratorNode.arguments.forEach((argumentNode: ts.Expression) => { if (ts.isObjectLiteralExpression(argumentNode)) { const importsNode = argumentNode.properties.find((propertyNode: ts.ObjectLiteralElementLike) => { return (propertyNode.name as ts.Identifier).escapedText === 'imports'; }); if (!!importsNode) { const identifierNodes = ((importsNode as ts.PropertyAssignment) .initializer as ts.ArrayLiteralExpression).elements.filter(initNode => { return ts.isIdentifier(initNode) || ts.isCallExpression(initNode); }); identifierNodes.forEach((identifierNode: ts.Expression) => { if (ts.isCallExpression(identifierNode)) { if ( ((identifierNode.expression as ts.PropertyAccessExpression) .expression as ts.Identifier).escapedText === 'RouterModule' ) { // RouterModule Found! const argument = identifierNode.arguments[0]; let subRoutes: any; if (ts.isIdentifier(argument)) { // variable const varName = argument.escapedText; SourceCodeObj.forEachChild((sourceNode: ts.Node) => { if ( ts.isVariableStatement(sourceNode) && (sourceNode.declarationList.declarations[0].name as ts.Identifier) .escapedText === varName ) { const initializer = sourceNode.declarationList.declarations[0].initializer; subRoutes = sourceCode.substring(initializer.pos, initializer.end); } }); } else { // array subRoutes = sourceCode.substring( identifierNode.arguments.pos, identifierNode.arguments.end, ); } routes = subRoutes.replace( /(.*?:\s)([^'"`].*?[^'"`])((\s*?),|(\s*?)})/g, "$1'$2'$3", ); // tslint:disable-next-line: no-eval eval('routes = ' + routes); // console.log(routes); } node = (identifierNode.expression as ts.PropertyAccessExpression).expression; } if ((identifierNode as ts.Identifier).escapedText) { identifiers.push((identifierNode as ts.Identifier).escapedText); } }); } } }); } }), ); } }); }); SourceCodeObj.forEachChild(node => { if (ts.isImportDeclaration(node)) { node.importClause.namedBindings.forEachChild(name => { const identifierIndex = identifiers.indexOf((name as ts.ImportSpecifier).name.escapedText); if (identifierIndex > -1 && (node.moduleSpecifier as ts.StringLiteral).text.indexOf('.') === 0) { identifiers[identifierIndex] = { module: identifiers[identifierIndex], path: path.substring(0, entryModulePath.lastIndexOf('/') + 1) + (node.moduleSpecifier as ts.StringLiteral).text + '.ts', }; } }); } }); identifiers = identifiers .filter(element => element.hasOwnProperty('module')) .map(entry => { return { path: entry.path, importedIn: path }; }); if (routes.length === 0) { identifiers.forEach(identifier => { const nested = findRoutes(readFileSync(identifier.path).toString(), identifier.path); // if (nested.length >= 1) { identifiers = identifiers.concat(nested.identifiers); routes = routes.concat(nested.routes); // } }); } return { identifiers, routes } as IRouteIdentifiers; }
the_stack
import { LiveAnnouncer } from '@angular/cdk/a11y'; import { ConnectedPosition, ScrollStrategy, ScrollStrategyOptions, } from '@angular/cdk/overlay'; import { AfterViewInit, Component, EventEmitter, Injectable, OnInit, Output, QueryList, ViewChild, ViewChildren, } from '@angular/core'; import { MatCheckbox } from '@angular/material/checkbox'; import { MatDialog } from '@angular/material/dialog'; import { MatPaginator, MatPaginatorIntl, PageEvent, } from '@angular/material/paginator'; import { ActivatedRoute, NavigationEnd, Router } from '@angular/router'; import { take } from 'rxjs/operators'; import { ScoredItem, SelectableItem, SocialMediaItem, } from '../../common-types'; import { Attributes } from '../../perspectiveapi-types'; import { CommentInfoComponent } from '../comment-info/comment-info.component'; import { isSameDay } from '../common/date_utils'; import { getInfluenceScore } from '../common/social_media_item_utils'; import { DateFilterService } from '../date-filter.service'; import { DatePickerDialogComponent } from '../date-picker-dialog/date-picker-dialog.component'; import { DropdownOption, FilterDropdownComponent, } from '../filter-dropdown/filter-dropdown.component'; import { applyCommentFilters, buildDateFilterForNDays, DateFilter, ToxicityRangeFilter, } from '../filter_utils'; import { EventAction, EventCategory, GoogleAnalyticsService, } from '../google_analytics.service'; import { OnboardingService } from '../onboarding.service'; import { RecommendedReportTemplate, TOXICITY_RANGE_TEMPLATES, } from '../recommended-report-card/recommended-report-card.component'; import { RegexFilter } from '../regular-expression-filter/regular-expression-filter.component'; import { ReportService } from '../report.service'; import { SearchBoxComponent } from '../search-box/search-box.component'; import { SocialMediaItemService } from '../social-media-item.service'; import { ToxicityRangeSelectorDialogComponent } from '../toxicity-range-selector-dialog/toxicity-range-selector-dialog.component'; enum DateFilterName { YESTERDAY = 'Since yesterday', LAST_TWO_DAYS = 'Last two days', LAST_WEEK = 'Last week', LAST_MONTH = 'Last month', CUSTOM = 'Custom range', } enum OnboardingStep { NONE, HIGHLIGHT_BLUR_TOGGLE, HIGHLIGHT_FILTERS, HIGHLIGHT_PAGINATION, HIGHLIGHT_COMMENT_CARD, } interface DateFilterDropdownOption extends DropdownOption { numDays?: number; } export interface ToxicityRangeFilterDropdownOption extends DropdownOption { toxicityRangeFilter?: ToxicityRangeFilter; name: string; } interface MetadataFilterDropdownOption extends DropdownOption { hasImage?: boolean; verified?: boolean; } export enum SortOption { PRIORITY = 'Highest priority', TIME = 'Most recent', POPULARITY = 'Most popular', } export const TOXICITY_FILTER_NAME_QUERY_PARAM = 'toxicityFilterName'; const PAGE_SIZE = 8; // Represents the empty comment data for a loading comment card. const LOADING_COMMENT = { selected: false, disabled: true, item: null, scores: {}, }; function getRangeLabel(page: number, pageSize: number, length: number) { if (length <= pageSize) { return `Showing ${length} of ${length} comments`; } length = Math.max(length, 0); const startIndex = page * pageSize; // This ternary handles the condition in which the user changes the page // size. We don't currently allow that in the app, but we keep the logic // just in case. const endIndex = startIndex < length ? Math.min(startIndex + pageSize, length) : startIndex + pageSize; return `Showing ${startIndex + 1} – ${endIndex} of ${length} comments`; } @Injectable() export class PaginatorIntl extends MatPaginatorIntl { getRangeLabel = getRangeLabel; } @Component({ selector: 'app-create-report', templateUrl: './create-report.component.html', styleUrls: ['./create-report.component.scss'], providers: [{ provide: MatPaginatorIntl, useClass: PaginatorIntl }], }) export class CreateReportComponent implements OnInit, AfterViewInit { // Copy of enum for use in the template. readonly OnboardingStep = OnboardingStep; currentOnboardingStep = OnboardingStep.NONE; overlayScrollStrategy: ScrollStrategy; // This describes how the overlay should be connected to the origin element. highlightViewSettingsConnectedOverlayPositions: ConnectedPosition[] = [ { originX: 'end', originY: 'center', overlayX: 'start', overlayY: 'center', offsetX: 24, }, ]; centerBottomConnectedOverlayPositions: ConnectedPosition[] = [ { originX: 'center', originY: 'bottom', overlayX: 'center', overlayY: 'top', }, // Use center top if center bottom doesn't fit onscreen { originX: 'center', originY: 'top', overlayX: 'center', overlayY: 'bottom', offsetY: -24, }, ]; leftBottomConnectedOverlayPositions: ConnectedPosition[] = [ { originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'top', offsetY: 24, }, // Use left top if left bottom doesn't fit onscreen. { originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'bottom', offsetY: -24, }, ]; @Output() triggerHighlightReviewReportButtonOnboardingStep = new EventEmitter< void >(); @ViewChildren(CommentInfoComponent) itemList!: QueryList< CommentInfoComponent >; @ViewChild('dateFilterDropdown') dateFilterDropdown!: FilterDropdownComponent; @ViewChild('moreFiltersDropdown') moreFiltersDropdown!: FilterDropdownComponent; @ViewChild('toxicityRangeDropdown') toxicityRangeDropdown!: FilterDropdownComponent; @ViewChild('selectAllCheckbox') selectAllCheckbox!: MatCheckbox; @ViewChild(MatPaginator) paginator!: MatPaginator; @ViewChild(SearchBoxComponent) searchBoxComponent!: SearchBoxComponent; private pageIndex = 0; private numPages = 0; private now: Date; comments: Array<SelectableItem<SocialMediaItem>> = []; error: string | null = null; loading = false; lastLoadedDate = ''; commentsLoaded = 0; initialToxicityFilterNames: string[] = ['']; // A subset of comments that meet the user-selected filters, sorted based on // the selectedSortOption. filteredComments: Array<SelectableItem<SocialMediaItem>> = []; includeRegexFilters: RegexFilter[] = []; excludeRegexFilters: RegexFilter[] = []; toxicityRangeFilters: ToxicityRangeFilter[] = []; hasImageFilter = false; shouldBlur = true; verifiedFilter = false; pageSize = PAGE_SIZE; dateDropdownOptions: DateFilterDropdownOption[] = [ { displayText: DateFilterName.YESTERDAY, numDays: 1 }, { displayText: DateFilterName.LAST_TWO_DAYS, numDays: 2 }, { displayText: DateFilterName.LAST_WEEK, numDays: 7 }, { displayText: DateFilterName.LAST_MONTH, numDays: 31 }, { displayText: DateFilterName.CUSTOM, customOption: true }, ]; dateFilter: DateFilter; recommendedDropdownOptions = [ { displayText: 'Severe' }, { displayText: 'High' }, ]; toxicityRangeDropdownOptions: ToxicityRangeFilterDropdownOption[] = TOXICITY_RANGE_TEMPLATES.map( template => { const rangeFilter = template.toxicityRangeFilter; const minPercent = Math.round(rangeFilter.minScore * 100); const maxPercent = rangeFilter.maxScore === 1 ? 100 : Math.round(rangeFilter.maxScore * 100) - 1; const scoreRange = template.name === 'Unable to score' ? '(-)' : '(' + minPercent + ' - ' + maxPercent + '%)'; return { name: template.name, displayText: `${template.description} ${scoreRange}`, toxicityRangeFilter: template.toxicityRangeFilter, } as ToxicityRangeFilterDropdownOption; } ).concat([ { name: 'Custom range', displayText: 'Custom range', customOption: true, }, ]); moreDropdownOptions: MetadataFilterDropdownOption[] = [ { displayText: 'Verified accounts only', verified: true }, { displayText: 'Comment includes images', hasImage: true }, ]; sortOptions = [SortOption.PRIORITY, SortOption.TIME, SortOption.POPULARITY]; selectedSortOption = this.sortOptions[0]; private datePickerDialogOpen = false; private toxicityRangeDialogOpen = false; // Max visible page buttons to be displayed in the bottom pagination. readonly maxBottomPaginationPages = 6; selectedItemsForPage: Array<SelectableItem<SocialMediaItem>> = []; constructor( public dialog: MatDialog, private dateFilterService: DateFilterService, private reportService: ReportService, private router: Router, private route: ActivatedRoute, private socialMediaItemsService: SocialMediaItemService, private readonly scrollStrategyOptions: ScrollStrategyOptions, private onboardingService: OnboardingService, private googleAnalyticsService: GoogleAnalyticsService, private liveAnnouncer: LiveAnnouncer ) { this.overlayScrollStrategy = this.scrollStrategyOptions.block(); this.router.events.subscribe(event => { if (event instanceof NavigationEnd) { this.initialToxicityFilterNames = this.getInitialToxicityFilterNames(); this.setInitialToxicityFilterOptions(); } }); this.now = new Date(this.dateFilterService.getStartTimeMs()); this.dateFilter = buildDateFilterForNDays( this.now, this.dateDropdownOptions[0].numDays! ); this.dateFilterService.getFilter().subscribe((newFilter: DateFilter) => { const previousFilter = this.dateFilter; this.dateFilter = newFilter; if (dateFilterWithinRange(previousFilter, newFilter)) { this.applyFilters(); } else { this.commentsLoaded = 0; this.getComments(); } }); this.reportService.reportCommentsChanged.subscribe(() => { this.toggleItemsInReport(); }); this.reportService.reportCleared.subscribe(() => { // Reset the UI. // Reset sorting this.selectedSortOption = this.sortOptions[0]; // Reset search box if (this.searchBoxComponent) { this.searchBoxComponent.resetFilters(); } // Reset toxicity options. if (this.toxicityRangeDropdown) { this.initialToxicityFilterNames = TOXICITY_RANGE_TEMPLATES.map( template => template.name ); this.setInitialToxicityFilterOptions(); } // Reset date filter option. if (this.dateFilterDropdown) { this.dateFilterDropdown.setSelectedOption(this.dateDropdownOptions[0]); } // Reset more filters options. if (this.moreFiltersDropdown) { this.moreFiltersDropdown.setSelectedOptions([]); } // Get latest data. this.refresh(); }); this.socialMediaItemsService.onSocialMediaItemsLoaded.subscribe( (newCount: number) => { this.commentsLoaded = newCount; } ); } ngOnInit() { this.initialToxicityFilterNames = this.getInitialToxicityFilterNames(); this.getComments(); } ngAfterViewInit() { // When first creating the component, check if a recommended report was used // to navigate here, and set the filter accordingly. // Wrap in a Promise.resolve() to avoid an // ExpressionChangedAfterItHasBeenChecked error. Promise.resolve().then(() => { this.setInitialToxicityFilterOptions(); // We have to wait for the ViewChild to load to start onboarding, so we do // this in ngAfterViewInit. this.onboardingService .getCreateReportPageOnboardingComplete() .subscribe((onboarded: boolean) => { if (!onboarded) { this.nextOnboardingStep(); } }); }); } private getInitialToxicityFilterNames(): string[] { const names = this.route.snapshot.queryParamMap.getAll( TOXICITY_FILTER_NAME_QUERY_PARAM ); return names.length ? names : ['']; } nextOnboardingStep() { this.liveAnnouncer.announce('Opened next walkthrough dialog'); if (this.currentOnboardingStep === OnboardingStep.NONE) { this.currentOnboardingStep = OnboardingStep.HIGHLIGHT_BLUR_TOGGLE; } else if ( this.currentOnboardingStep === OnboardingStep.HIGHLIGHT_BLUR_TOGGLE ) { this.currentOnboardingStep = OnboardingStep.HIGHLIGHT_FILTERS; } else if ( this.currentOnboardingStep === OnboardingStep.HIGHLIGHT_FILTERS ) { this.currentOnboardingStep = OnboardingStep.HIGHLIGHT_PAGINATION; } else if ( this.currentOnboardingStep === OnboardingStep.HIGHLIGHT_PAGINATION ) { this.currentOnboardingStep = OnboardingStep.HIGHLIGHT_COMMENT_CARD; } else if ( this.currentOnboardingStep === OnboardingStep.HIGHLIGHT_COMMENT_CARD ) { // The next onboarding step is highlighting the review report button, // which needs to be done in the toolbar component, so we use a service. this.onboardingService.triggerHighlightReviewReportButton(); this.currentOnboardingStep = OnboardingStep.NONE; } } // Given a ISO 8601 date (like '2020-11-10T17:44:51.000Z') format it // as 'Month Day Time Timezone' like 'Jan 8 12:42 EST' private formatLastLoadedDate(date: Date): string { return `${date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', timeZoneName: 'short', })}`; } private getComments() { this.loading = true; this.error = null; this.socialMediaItemsService .fetchItems( this.dateFilter.startDateTimeMs, this.dateFilter.endDateTimeMs ) .pipe(take(1)) .subscribe( (items: Array<ScoredItem<SocialMediaItem>>) => { this.comments = items.map( (item): SelectableItem<SocialMediaItem> => { return { item: item.item, scores: item.scores, selected: false, }; } ); this.toggleItemsInReport(); this.applyFilters(); this.loading = false; this.lastLoadedDate = this.formatLastLoadedDate(new Date()); }, error => { this.error = error; this.comments = []; this.loading = false; this.googleAnalyticsService.emitEvent( EventCategory.ERROR, EventAction.LOAD_COMMENTS_ERROR, error ); } ); } private shouldSelectOption( option: ToxicityRangeFilterDropdownOption ): boolean { return ( this.initialToxicityFilterNames[0] === 'All' || this.initialToxicityFilterNames.includes(option.name) ); } private setInitialToxicityFilterOptions() { if (this.initialToxicityFilterNames.length && this.toxicityRangeDropdown) { const optionsToSelect: ToxicityRangeFilterDropdownOption[] = []; // Add the options from the initialToxicityFilterNames. The 'Customize // Range' option should never be added, so it is omitted. for (const option of this.toxicityRangeDropdownOptions.slice(0, -1)) { if (this.shouldSelectOption(option)) { optionsToSelect.push(option); } } if (optionsToSelect.length) { this.toxicityRangeDropdown.setSelectedOptions(optionsToSelect); } this.applyFilters(); } } getDatePickerDialogOpen() { return this.datePickerDialogOpen; } getToxicityRangeDialogOpen() { return this.toxicityRangeDialogOpen; } applySortOption() { // Make a copy of comments, since js sort methods sort in place. const commentsCopy = this.filteredComments.slice(); switch (this.selectedSortOption) { case SortOption.PRIORITY: // Based on the ordering of TOXICITY_RANGE_TEMPLATES, unscored // comments can have a greater priority than other comments with // toxicity scores. The unscoredValue is the minimum toxicity score of // a comment with greater priority than an unscored comment. // Note: This assumes that the order of templates in the // TOXICITY_RANGE_TEMPLATES is the intended filter ordering. const indexUnscored = TOXICITY_RANGE_TEMPLATES.findIndex( (template: RecommendedReportTemplate) => template.name === 'Unable to score' ); const unscoredValue = TOXICITY_RANGE_TEMPLATES[indexUnscored - 1].toxicityRangeFilter .minScore; this.filteredComments = commentsCopy.sort((a, b) => { const aScore = a.scores[Attributes.TOXICITY]; const bScore = b.scores[Attributes.TOXICITY]; if (aScore === bScore) { return 0; } else if (aScore && bScore) { // both are numbers return this.toNumberOrZero(aScore) > this.toNumberOrZero(bScore) ? -1 : 1; } else if (aScore) { // aScore is a number, bScore is undefined return this.toNumberOrZero(aScore) >= unscoredValue ? -1 : 1; } else { // bScore is a number, aScore is undefined return this.toNumberOrZero(bScore) >= unscoredValue ? 1 : -1; } }); break; case SortOption.TIME: this.filteredComments = commentsCopy.sort((a, b) => { if (a.item.date === b.item.date) { return 0; } else { return a.item.date > b.item.date ? -1 : 1; } }); break; case SortOption.POPULARITY: this.filteredComments = commentsCopy.sort((a, b) => { const aPopularity = getInfluenceScore(a.item); const bPopularity = getInfluenceScore(b.item); if (aPopularity === bPopularity) { return 0; } else { return aPopularity > bPopularity ? -1 : 1; } }); break; default: break; } } // Used for testing getSelectedComments() { return this.filteredComments.filter(c => c.selected); } private updateSelectedItemsForPage() { this.selectedItemsForPage = this.itemList .filter(item => item.selected && item.comment !== undefined) .map(item => item.comment!); } updateSelectedComment(comment: SelectableItem<SocialMediaItem>) { if (comment.selected) { this.reportService.addCommentsToReport([comment]); } else { this.reportService.removeCommentFromReport(comment); } this.updateSelectedItemsForPage(); } private updateSelectedComments( comments: Array<SelectableItem<SocialMediaItem>> ) { const allSelected = comments.every(c => c.selected); if (allSelected) { // If all are selected, add them to the report in batch. this.reportService.addCommentsToReport(comments); this.updateSelectedItemsForPage(); } else { for (const comment of comments) { this.updateSelectedComment(comment); } } } selectAll() { const commentsToUpdate = []; for (const item of this.itemList) { if (item.comment && !item.comment.disabled) { item.selected = true; commentsToUpdate.push(item.comment); } } this.updateSelectedComments(commentsToUpdate); } deselectAll() { const commentsToUpdate = []; for (const item of this.itemList) { if (item.comment && !item.comment.disabled) { item.selected = false; commentsToUpdate.push(item.comment); } } this.updateSelectedComments(commentsToUpdate); } /** * Applies toxicity range, date, and keyword filters. * * Note that this updates automatically when filters are updated, which will * result in hiding any selected items that don't fall within filter * parameters. */ applyFilters(): void { const regexFilters = this.includeRegexFilters.concat( this.excludeRegexFilters ); this.filteredComments = applyCommentFilters< SelectableItem<SocialMediaItem> >(this.comments, { toxicityRangeFilters: this.toxicityRangeFilters, regexFilters, dateFilter: this.dateFilter, imageFilter: this.hasImageFilter, verifiedFilter: this.verifiedFilter, }); this.applySortOption(); if (this.pageIndex * this.pageSize > this.filteredComments.length) { // The current page index is higher than the total number of pages, so // reset to the first page. this.paginator.firstPage(); } this.numPages = Math.ceil(this.filteredComments.length / this.pageSize); } formatScore(score: number): number { return Math.round(score * 100) / 100; } getFormattedDate(timeMs: number): string { return new Date(timeMs).toLocaleString('en-US', { timeZone: 'UTC' }); } getIncludeKeywordsFilterActive(): boolean { return this.includeRegexFilters.length > 0; } getExcludeKeywordsFilterActive(): boolean { return this.excludeRegexFilters.length > 0; } getIncludeKeywordsDisplayString(): string { return this.includeRegexFilters.map(item => item.regex).join(); } getExcludeKeywordsDisplayString(): string { return this.excludeRegexFilters.map(item => item.regex).join(); } dateFilterSelectionChanged(selection: DateFilterDropdownOption) { if (!selection) { return; } if (selection.customOption) { this.getCustomDateFilter(); } else if (selection.numDays) { this.dateFilterService.updateFilter( buildDateFilterForNDays(this.now, selection.numDays) ); } } /** Opens a dialogue to select a custom date range. */ getCustomDateFilter() { if (this.datePickerDialogOpen) { return; } const dialogRef = this.dialog.open(DatePickerDialogComponent); this.datePickerDialogOpen = true; dialogRef.afterClosed().subscribe(result => { this.datePickerDialogOpen = false; if (result) { this.dateFilterService.updateFilter(result); } }); } toxicityRangeSelectionChanged( selection: ToxicityRangeFilterDropdownOption[] ) { const toxicityRangeFilters: ToxicityRangeFilter[] = []; for (const item of selection) { if (item.toxicityRangeFilter) { toxicityRangeFilters.push(item.toxicityRangeFilter); } } this.toxicityRangeFilters = toxicityRangeFilters; this.applyFilters(); } metadataFilterSelectionChanged(selection: MetadataFilterDropdownOption[]) { this.hasImageFilter = false; this.verifiedFilter = false; for (const option of selection) { if (option.hasImage) { this.hasImageFilter = true; } if (option.verified) { this.verifiedFilter = true; } } this.applyFilters(); } /** Opens a dialogue to select a toxicity range. */ getCustomToxicityRange() { if (this.toxicityRangeDialogOpen) { return; } const dialogRef = this.dialog.open(ToxicityRangeSelectorDialogComponent); this.toxicityRangeDialogOpen = true; dialogRef.afterClosed().subscribe(result => { this.toxicityRangeDialogOpen = false; if (result) { this.toxicityRangeFilters = [result]; this.applyFilters(); } else { this.toxicityRangeDropdown.setToPreviousSelectedValue(); } }); } getPaginatedItems(): | Array<SelectableItem<SocialMediaItem>> | Array<SelectableItem<null>> { if (this.loading) { const loadingComments = []; for (let i = 0; i < PAGE_SIZE; i++) { loadingComments.push(LOADING_COMMENT); } return loadingComments; } const startIndex = this.pageIndex * this.pageSize; const endIndex = startIndex + this.pageSize; return this.filteredComments.slice(startIndex, endIndex); } page(pageEvent: Partial<PageEvent>): void { if (pageEvent.pageIndex !== undefined) { this.pageIndex = pageEvent.pageIndex; } // Unchecks the select all checkbox so the user can select all on the next // page if they want to. this.selectAllCheckbox.checked = false; } /** Gets a list of pages for pagination in the template. */ getAllPages(): number[] { const pages: number[] = []; for (let i = 1; i <= this.numPages; i++) { pages.push(i); } return pages; } /** Gets a list of pages for pagination before the ellipsis. */ getStartAbbreviatedPages(): number[] { const startPages: number[] = []; if (this.pageIndex >= this.numPages - (this.maxBottomPaginationPages - 1)) { // If we're at the end, we want to show 1 ... n-2 n-1 n so // we just return 1 here. startPages.push(1); } else { // Otherwise show something like c c+1 c+2 c+3 c+4 ... n where // c = current page, so we return c c+1 c+2 c+3 c+4 here. const start = this.pageIndex + 1; const end = Math.min( this.pageIndex + this.maxBottomPaginationPages - 1, this.numPages - 2 ); for (let i = start; i <= end; i++) { startPages.push(i); } } return startPages; } /** Gets a list of pages for pagination after the ellipsis. */ getEndAbbreviatedPages(): number[] { const startPages = this.getStartAbbreviatedPages(); const endPages: number[] = []; if (startPages.length === 1 && startPages[0] === 1) { // If we're at the end, we want to show 1 ... n-2 n-1 n so // startAbbreviatedPages will just be 1 and we want to return // n-4 n-3 n-2 n-1 n here. const start = this.numPages - (this.maxBottomPaginationPages - 2); const end = this.numPages; for (let i = start; i <= end; i++) { endPages.push(i); } } else { // Otherwise just return the last number. endPages.push(this.numPages); } return endPages; } toNumberOrZero(input: string | number | undefined): number { return Number(input) || 0; } handleRegexFiltersChanged(filters: RegexFilter[]) { this.includeRegexFilters = filters; this.applyFilters(); } refresh() { const endDate = new Date(this.dateFilter.endDateTimeMs); // Avoid refetching data if a user has selected a custom date range with a // end date != today. if (!isSameDay(endDate, this.now)) { return; } // Update the end date time to "now" so we refetch data. this.now = new Date(); this.dateFilterService.updateFilter({ startDateTimeMs: this.dateFilter.startDateTimeMs, endDateTimeMs: this.now.getTime(), }); } setPageSize(pageSize: number) { this.pageSize = pageSize; this.numPages = Math.ceil(this.filteredComments.length / this.pageSize); } // Only used for testing. getPageIndex() { return this.pageIndex; } getRangeLabel(page: number, pageSize: number, length: number) { return getRangeLabel(page, pageSize, length); } private toggleItemsInReport() { const reportItemIds = this.reportService .getCommentsForReport() .map(item => item.item.id_str); for (const comment of this.comments) { // We check the comment if it's in the report, otherwise uncheck it. comment.selected = reportItemIds.includes(comment.item.id_str); } } } function dateFilterWithinRange( filter1: DateFilter, filter2: DateFilter ): boolean { return ( filter2.startDateTimeMs >= filter1.startDateTimeMs && filter2.endDateTimeMs <= filter1.endDateTimeMs ); }
the_stack
import { MirrorEffectFunction, MirrorFetchManyFunction, MirrorOptions, MirrorPurgeScheduler, NamespacedMirror, } from './Mirror' import { MirrorDocumentHandle, MirrorDocumentListHandle } from './MirrorHandles' import { MirrorSnapshot, MirrorPrimedSnapshot, MirrorDocumentSnapshot, MirrorPrimedDocumentSnapshot, } from './MirrorSnapshots' interface ScheduledPurge { canceller?: () => void } interface Subscription<Data, Key> { hashes: string[] callback: (snapshots: MirrorDocumentSnapshot<Data, Key>[]) => void } export default class NamespacedMirrorImplementation< Data, Key, Context extends object > implements NamespacedMirror<Data, Key, Context> { readonly context: Context _config: { computeHashForKey: (key: Key) => string effect?: MirrorEffectFunction<Data, Key, Context> fetchMany: MirrorFetchManyFunction<Data, Key, Context> schedulePurge: MirrorPurgeScheduler<Data, Key, Context> } _effectCleanups: { [hash: string]: () => void } _fetches: { [hash: string]: Promise<any> } _holds: { [hash: string]: number } _scheduledPurges: { [hash: string]: ScheduledPurge } _subscriptions: { [hash: string]: Subscription<Data, Key>[] } _snapshots: { [hash: string]: MirrorDocumentSnapshot<Data, Key> } constructor(options: MirrorOptions<Data, Key, Context>, context: Context) { this.context = context let fetchMany: MirrorFetchManyFunction<Data, Key, Context> if (options.fetchMany) { fetchMany = options.fetchMany } else if (options.fetch) { // When not using nested collections, it's okay to fetchMany using // fetch. const fetch = options.fetch fetchMany = (keys: Key[]) => Promise.all(keys.map(key => fetch(key, context, this))) } else { fetchMany = async (keys: Key[]) => { // Wait for a small delay, then if the snapshot is still pending, // assume that the data ain't coming and throw an error. await new Promise(resolve => setTimeout(resolve)) const datas: Data[] = [] for (let snapshot of this._get(keys)) { if (snapshot === null || !snapshot.primed) { throw new Error(`Unable to fetch`) } else { datas.push(snapshot.data!) } } return datas } } this._config = { computeHashForKey: options.computeHashForKey, effect: options.effect, fetchMany, schedulePurge: typeof options.schedulePurge === 'number' ? createTimeoutPurgeScheduler(options.schedulePurge) : options.schedulePurge, } this._effectCleanups = {} this._fetches = {} this._holds = {} this._scheduledPurges = {} this._subscriptions = {} this._snapshots = {} } hydrateFromState(snapshots: any) { // TODO: can't just set state; need to actually update any subscriptions // on hydration. throw new Error('Unimplemented') } key(key: Key) { return new MirrorKeyHandle(this, key) } keys(keys: Key[]) { return new MirrorKeyListHandle(this, keys) } knownKeys() { return Object.values(this._snapshots).map(snapshot => snapshot.key) } purge() { // TODO: can't just clear state; need to actually update any subscriptions // on hydration. throw new Error('Unimplemented') } extractState(): any { return this._snapshots } _cancelScheduledPurge(hash: string) { const scheduledPurge = this._scheduledPurges[hash] if (scheduledPurge) { if (scheduledPurge.canceller) { scheduledPurge.canceller() } delete this._scheduledPurges[hash] } } _computeHashes(keys: Key[]) { return keys.map(this._config.computeHashForKey) } async _fetch(keys: Key[], hashes: string[]) { const pendingSnapshotsToStore: MirrorDocumentSnapshot<Data, Key>[] = [] const keysToFetch: Key[] = [] const hashesToFetch: string[] = [] // Hold the pending snapshots while fetching const unhold = this._hold(hashes) for (let i = 0; i < keys.length; i++) { const key = keys[i] const hash = hashes[i] // If there's already a fetch for this key, then don't interrupt it. if (this._fetches[hash]) { continue } keysToFetch.push(key) hashesToFetch.push(hash) // Fetching will change `pending` to true, if it isn't already so. let snapshot = this._snapshots[hash] if (!snapshot || !snapshot.pending) { snapshot = getPendingSnapshot(key, snapshot) pendingSnapshotsToStore.push(snapshot) } } // Store any pending statuses this._store(pendingSnapshotsToStore) if (keysToFetch.length > 0) { let updatedSnapshots: MirrorDocumentSnapshot<Data, Key>[] = [] try { const promise = this._config.fetchMany(keysToFetch, this.context, this) for (let i = 0; i < hashesToFetch.length; i++) { this._fetches[hashesToFetch[i]] = promise } // Careful, this could fail -- and the fetches need to be cleaned up in either case. const datas = await promise const updatedAt = Date.now() for (let i = 0; i < hashesToFetch.length; i++) { delete this._fetches[hashesToFetch[i]] updatedSnapshots.push( getUpdatedSnapshot(keysToFetch[i], datas[i], false, updatedAt), ) } } catch (reason) { const failedAt = Date.now() for (let i = 0; i < hashesToFetch.length; i++) { const hash = hashesToFetch[i] delete this._fetches[hash] updatedSnapshots.push( getFailureSnapshot(this._snapshots[hash], reason, failedAt), ) } } this._store(updatedSnapshots) } unhold() } _get(keys: Key[]): (MirrorDocumentSnapshot<Data, Key> | null)[] { return keys.map( key => this._snapshots[this._config.computeHashForKey(key)] || null, ) } _hold(hashes: string[]): () => void { for (let i = 0; i < hashes.length; i++) { // Cancel any scheduled purges of the given keys. const hash = hashes[i] this._cancelScheduledPurge(hash) // Update hold count let currentHoldCount = this._holds[hash] || 0 this._holds[hash] = currentHoldCount + 1 } return () => { const hashesToSchedulePurge: string[] = [] for (let i = 0; i < hashes.length; i++) { const hash = hashes![i] const currentHoldCount = this._holds[hash] if (currentHoldCount > 1) { this._holds[hash] = currentHoldCount - 1 } else { delete this._holds[hash] hashesToSchedulePurge.push(hash) } } this._schedulePurge(hashesToSchedulePurge) } } _invalidate(keys: Key[]): void { const hashes = this._computeHashes(keys) const snapshotsToStore: MirrorDocumentSnapshot<Data, Key>[] = [] const keysToFetch: Key[] = [] const hashesToFetch: string[] = [] for (let i = 0; i < hashes.length; i++) { const key = keys[i] const hash = hashes[i] const snapshot = this._snapshots[hash] // If the has doesn't exist or is already invalid, then there's no need // to touch it. if (!snapshot || snapshot.invalidated) { continue } snapshotsToStore.push({ ...snapshot, invalidated: true, }) // If the hash has an active subscription, then we'll want to initiate a // fetch. We don't worry about held-but-not-subscribed keys, as if a // subscription is made, then invalidated snapshots will be fetched then. if (this._subscriptions[hash]) { keysToFetch.push(key) hashesToFetch.push(hash) } } // TODO: This can result in a double update. this._store(snapshotsToStore) if (keysToFetch.length) { this._fetch(keysToFetch, hashesToFetch) } } _performScheduledPurge(hash: string) { // Wait a tick to avoid purging something that gets held again in the // next tick. Promise.resolve().then(() => { const scheduledPurge = this._scheduledPurges[hash] if (scheduledPurge) { // Clean up effects const effectCleanup = this._effectCleanups[hash] if (effectCleanup) { effectCleanup() delete this._effectCleanups[hash] } // Remove stored snapshot data, and remove the scheduled purge delete this._snapshots[hash] delete this._scheduledPurges[hash] } }) } _schedulePurge(hashes: string[]) { // Schedule purges individually, as purging, scheduling purges and // cancelling scheduled purges will never result in UI updates, and thus // they don't need batching -- but there *are* situations where we'll need // to cancel individual purges from the group. for (let i = 0; i < hashes.length; i++) { const hash = hashes[i] const snapshot = this._snapshots[hash] if (this._scheduledPurges[hash] || !snapshot) { continue } const scheduledPurge: ScheduledPurge = {} const purge = this._performScheduledPurge.bind(this, hash) this._scheduledPurges[hash] = scheduledPurge scheduledPurge.canceller = this._config.schedulePurge( purge, snapshot, this.context, ) } } _store(snapshots: MirrorDocumentSnapshot<Data, Key>[]): void { const hashes: string[] = [] const hashesToSchedulePurge: string[] = [] const updatedSubscriptions: Set<Subscription<Data, Key>> = new Set() for (let i = 0; i < snapshots.length; i++) { const snapshot = snapshots[i] const hash = this._config.computeHashForKey(snapshot.key) hashes.push(hash) // Update the stored snapshot this._snapshots[hash] = snapshot // Mark down any subscriptions which need to be run, to run them // all in a single update let subscriptions = this._subscriptions[hash] if (subscriptions) { subscriptions.forEach(subscription => updatedSubscriptions.add(subscription), ) } // If this snapshot isn't held, schedule a purge if (!this._holds[hash]) { hashesToSchedulePurge.push(hash) } } // Notify subscribers in a single update let subscriptions = Array.from(updatedSubscriptions.values()) for (let i = 0; i < subscriptions.length; i++) { const { hashes, callback } = subscriptions[i] callback(hashes.map(hash => this._snapshots[hash])) } // Run effects, and clean up any previously run effects const effect = this._config.effect if (effect) { for (let i = 0; i < hashes.length; i++) { const hash = hashes[i] // Get latest snapshot values in case they've changed within the // subscription callbacks const snapshot = this._snapshots[hash] const previousCleanup = this._effectCleanups[hash] this._effectCleanups[hash] = effect(snapshot, this.context) previousCleanup() } } if (hashesToSchedulePurge.length) { this._schedulePurge(hashesToSchedulePurge) } } _subscribe( keys: Key[], callback: (snapshots: MirrorDocumentSnapshot<Data, Key>[]) => void, ): () => void { const keysToFetch: Key[] = [] const hashes: string[] = this._computeHashes(keys) const hashesToFetch: string[] = [] const unhold = this._hold(hashes) const subscription = { hashes, callback, } for (let i = 0; i < keys.length; i++) { const key = keys[i] const hash = hashes[i] // Add the same subscription object for every key's hash. This will create // duplicates, but they can be easily deduped when changes actually occur. let subscriptions = this._subscriptions[hash] if (!subscriptions) { this._subscriptions[hash] = subscriptions = [] } subscriptions.push(subscription) // If there's no snapshot, or a pending snapshot with no fetch, then // add this id to the list of ids to fetch. if (!this._fetches[hash]) { const snapshot = this._snapshots[hash] if (!snapshot || snapshot.pending || snapshot.invalidated) { keysToFetch.push(key) hashesToFetch.push(hash) } } } if (keysToFetch.length) { this._fetch(keysToFetch, hashesToFetch) } return () => { // Remove subscriptions for (let i = 0; i < hashes.length; i++) { const hash = hashes[i] const subscriptions = this._subscriptions[hash] if (subscriptions.length === 1) { delete this._subscriptions[hash] } else { subscriptions.splice(subscriptions.indexOf(subscription), 1) } } unhold() } } } class MirrorKeyHandle<Data, Key> implements MirrorDocumentHandle<Data, Key> { readonly key: Key readonly impl: NamespacedMirrorImplementation<Data, Key, any> constructor(impl: NamespacedMirrorImplementation<Data, Key, any>, key: Key) { this.key = key this.impl = impl } getLatest() { let snapshot = this.impl._get([this.key])[0] if (snapshot === null) { snapshot = getInitialSnapshot(this.key) this.impl._store([snapshot]) } return snapshot } get(): Promise<MirrorPrimedDocumentSnapshot<Data, Key>> { const currentSnapshot = this.impl._get([this.key])[0] if (currentSnapshot && currentSnapshot.primed) { return Promise.resolve(currentSnapshot as MirrorPrimedDocumentSnapshot< Data, Key >) } else { return new Promise<MirrorPrimedDocumentSnapshot<Data, Key>>( (resolve, reject) => { const unsubscribe = this.impl._subscribe([this.key], ([snapshot]) => { if (!snapshot.pending) { unsubscribe() if (snapshot.primed) { resolve(snapshot as MirrorPrimedDocumentSnapshot<Data, Key>) } else { reject(snapshot.failure && snapshot.failure.reason) } } }) }, ) } } hold() { return this.impl._hold(this.impl._computeHashes([this.key])) } invalidate() { this.impl._invalidate([this.key]) } async predictUpdate(dataOrUpdater) { // TODO: // - should be possible to store predicted state for a short period of // time, setting a flag noting that the state is just a prediction. throw new Error('Unimplemented') } subscribe(callback) { return this.impl._subscribe([this.key], ([snapshot]) => { callback(snapshot) }) } update(dataOrUpdater) { let data: Data let [currentSnapshot] = this.impl._get([this.key]) if (typeof dataOrUpdater === 'function') { if (!currentSnapshot || !currentSnapshot.primed) { throw new MissingDataError() } data = dataOrUpdater(currentSnapshot.data!) } else { data = dataOrUpdater } this.impl._store([ getUpdatedSnapshot( this.key, data, currentSnapshot ? currentSnapshot.pending : false, Date.now(), ), ]) } } class MirrorKeyListHandle<Data, Key> implements MirrorDocumentListHandle<Data, Key> { readonly key: Key[] readonly impl: NamespacedMirrorImplementation<Data, Key, any> constructor( impl: NamespacedMirrorImplementation<Data, Key, any>, key: Key[], ) { this.key = key this.impl = impl } getLatest() { const snapshotsToStore: MirrorDocumentSnapshot<Data, Key>[] = [] const maybeSnapshots = this.impl._get(this.key) const snapshots: MirrorDocumentSnapshot<Data, Key>[] = [] let primed = true for (let i = 0; i < maybeSnapshots.length; i++) { const key = this.key[i] let snapshot = maybeSnapshots[i] if (snapshot === null) { snapshot = getInitialSnapshot(key) snapshotsToStore.push(snapshot) primed = false } else if (!snapshot.primed) { primed = false } snapshots.push(snapshot!) } if (snapshotsToStore.length) { this.impl._store(snapshotsToStore) } return getListSnapshot(this.key, snapshots, primed) } get(): Promise< MirrorPrimedSnapshot<MirrorDocumentSnapshot<Data, Key>[], Key[]> > { const maybeSnapshots = this.impl._get(this.key) const primed = maybeSnapshots.every(snapshot => snapshot && snapshot.primed) if (primed) { return Promise.resolve(getListSnapshot( this.key, maybeSnapshots as MirrorDocumentSnapshot<Data, Key>[], true, ) as MirrorPrimedSnapshot<MirrorDocumentSnapshot<Data, Key>[], Key[]>) } else { return new Promise< MirrorPrimedSnapshot<MirrorDocumentSnapshot<Data, Key>[], Key[]> >((resolve, reject) => { const unsubscribe = this.impl._subscribe(this.key, snapshots => { const pending = snapshots.some(snapshot => snapshot.pending) if (!pending) { const primed = snapshots.every( snapshot => snapshot && snapshot.primed, ) const listSnapshot = getListSnapshot(this.key, snapshots, primed) unsubscribe() if (primed) { resolve(listSnapshot as MirrorPrimedSnapshot< MirrorDocumentSnapshot<Data, Key>[], Key[] >) } else { reject(listSnapshot.failure && listSnapshot.failure.reason) } } }) }) } } hold() { return this.impl._hold(this.impl._computeHashes(this.key)) } invalidate() { this.impl._invalidate(this.key) } async predictUpdate(dataOrUpdater) { // TODO: // - should be possible to store predicted state for a short period of // time, setting a flag noting that the state is just a prediction. throw new Error('Unimplemented') } subscribe(callback) { return this.impl._subscribe(this.key, snapshots => { callback( getListSnapshot( this.key, snapshots, snapshots.every(snapshot => snapshot.primed), ), ) }) } update(dataOrUpdater) { let data: Data[] let maybeSnapshots = this.impl._get(this.key) if (typeof dataOrUpdater === 'function') { if (maybeSnapshots.some(snapshot => !snapshot || !snapshot.primed)) { throw new MissingDataError() } data = dataOrUpdater(maybeSnapshots.map(snapshot => snapshot!.data)) } else { data = dataOrUpdater } const updateTime = Date.now() this.impl._store( maybeSnapshots.map((snapshot, i) => getUpdatedSnapshot( this.key[i], data[i], snapshot ? snapshot.pending : false, updateTime, ), ), ) } } function getListSnapshot<Data, Key>( key: Key[], snapshots: MirrorDocumentSnapshot<Data, Key>[], primed: boolean, ): MirrorSnapshot<MirrorDocumentSnapshot<Data, Key>[], Key[]> { const failedSnapshot = snapshots.find(snapshot => snapshot.failure) return { data: snapshots, key, primed, failure: failedSnapshot ? failedSnapshot.failure : null, } } function getFailureSnapshot<Data, Key>( currentSnapshot: MirrorDocumentSnapshot<Data, Key>, reason: any, failedAt: number, ): MirrorDocumentSnapshot<Data, Key> { return { ...currentSnapshot, failure: { reason, at: failedAt, }, pending: false, } } function getInitialSnapshot<Key>(key: Key): MirrorDocumentSnapshot<any, Key> { return { data: undefined, failure: null, key, invalidated: false, pending: true, primed: false, updatedAt: null, } } function getPendingSnapshot<Data, Key>( key: Key, currentSnapshot: null | MirrorDocumentSnapshot<Data, Key>, ): MirrorDocumentSnapshot<Data, Key> { if (!currentSnapshot) { return getInitialSnapshot(key) } else if (!currentSnapshot.pending) { return { ...currentSnapshot, pending: true, } } return currentSnapshot } function getUpdatedSnapshot<Data, Key>( key: Key, data: Data, pending: boolean, updatedAt: number, ): MirrorDocumentSnapshot<Data, Key> { return { data, failure: null, key, invalidated: false, pending, primed: true, updatedAt, } } function createTimeoutPurgeScheduler<Data, Key, Context extends object>( milliseconds: number, ): MirrorPurgeScheduler<Data, Key, Context> { return (purge: () => void) => { const timeout = setTimeout(purge, milliseconds) return () => { clearTimeout(timeout) } } } class MissingDataError extends Error {}
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * Namespaces * __NOTE__: An instance of this class is automatically created for an * instance of the NotificationHubsManagementClient. */ export interface Namespaces { /** * 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 {object} parameters The namespace name. * * @param {string} parameters.name Resource name * * @param {string} parameters.location Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [parameters.sku] The sku of the created namespace * * @param {string} parameters.sku.name Name of the notification hub sku. * Possible values include: 'Free', 'Basic', 'Standard' * * @param {string} [parameters.sku.tier] The tier of particular sku * * @param {string} [parameters.sku.size] The Sku size * * @param {string} [parameters.sku.family] The Sku Family * * @param {number} [parameters.sku.capacity] The capacity of the resource * * @param {boolean} [parameters.isAvailiable] True if the name is available and * can be used to create new Namespace/NotificationHub. Otherwise false. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<CheckAvailabilityResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ checkAvailabilityWithHttpOperationResponse(parameters: models.CheckAvailabilityParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.CheckAvailabilityResult>>; /** * 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 {object} parameters The namespace name. * * @param {string} parameters.name Resource name * * @param {string} parameters.location Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [parameters.sku] The sku of the created namespace * * @param {string} parameters.sku.name Name of the notification hub sku. * Possible values include: 'Free', 'Basic', 'Standard' * * @param {string} [parameters.sku.tier] The tier of particular sku * * @param {string} [parameters.sku.size] The Sku size * * @param {string} [parameters.sku.family] The Sku Family * * @param {number} [parameters.sku.capacity] The capacity of the resource * * @param {boolean} [parameters.isAvailiable] True if the name is available and * can be used to create new Namespace/NotificationHub. Otherwise false. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {CheckAvailabilityResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {CheckAvailabilityResult} [result] - The deserialized result object if an error did not occur. * See {@link CheckAvailabilityResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ checkAvailability(parameters: models.CheckAvailabilityParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.CheckAvailabilityResult>; checkAvailability(parameters: models.CheckAvailabilityParameters, callback: ServiceCallback<models.CheckAvailabilityResult>): void; checkAvailability(parameters: models.CheckAvailabilityParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.CheckAvailabilityResult>): void; /** * Creates/Updates a service namespace. Once created, this namespace's resource * manifest is immutable. This operation is idempotent. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {object} parameters Parameters supplied to create a Namespace * Resource. * * @param {string} [parameters.namespaceCreateOrUpdateParametersName] The name * of the namespace. * * @param {string} [parameters.provisioningState] Provisioning state of the * Namespace. * * @param {string} [parameters.region] Specifies the targeted region in which * the namespace should be created. It can be any of the following values: * Australia EastAustralia SoutheastCentral USEast USEast US 2West USNorth * Central USSouth Central USEast AsiaSoutheast AsiaBrazil SouthJapan EastJapan * WestNorth EuropeWest Europe * * @param {string} [parameters.status] Status of the namespace. It can be any * of these values:1 = Created/Active2 = Creating3 = Suspended4 = Deleting * * @param {date} [parameters.createdAt] The time the namespace was created. * * @param {string} [parameters.serviceBusEndpoint] Endpoint you can use to * perform NotificationHub operations. * * @param {string} [parameters.subscriptionId] The Id of the Azure subscription * associated with the namespace. * * @param {string} [parameters.scaleUnit] ScaleUnit where the namespace gets * created * * @param {boolean} [parameters.enabled] Whether or not the namespace is * currently enabled. * * @param {boolean} [parameters.critical] Whether or not the namespace is set * as Critical. * * @param {string} [parameters.namespaceType] The namespace type. Possible * values include: 'Messaging', 'NotificationHub' * * @param {string} parameters.location Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [parameters.sku] The sku of the created namespace * * @param {string} parameters.sku.name Name of the notification hub sku. * Possible values include: 'Free', 'Basic', 'Standard' * * @param {string} [parameters.sku.tier] The tier of particular sku * * @param {string} [parameters.sku.size] The Sku size * * @param {string} [parameters.sku.family] The Sku Family * * @param {number} [parameters.sku.capacity] The capacity of the resource * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NamespaceResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, parameters: models.NamespaceCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NamespaceResource>>; /** * Creates/Updates a service namespace. Once created, this namespace's resource * manifest is immutable. This operation is idempotent. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {object} parameters Parameters supplied to create a Namespace * Resource. * * @param {string} [parameters.namespaceCreateOrUpdateParametersName] The name * of the namespace. * * @param {string} [parameters.provisioningState] Provisioning state of the * Namespace. * * @param {string} [parameters.region] Specifies the targeted region in which * the namespace should be created. It can be any of the following values: * Australia EastAustralia SoutheastCentral USEast USEast US 2West USNorth * Central USSouth Central USEast AsiaSoutheast AsiaBrazil SouthJapan EastJapan * WestNorth EuropeWest Europe * * @param {string} [parameters.status] Status of the namespace. It can be any * of these values:1 = Created/Active2 = Creating3 = Suspended4 = Deleting * * @param {date} [parameters.createdAt] The time the namespace was created. * * @param {string} [parameters.serviceBusEndpoint] Endpoint you can use to * perform NotificationHub operations. * * @param {string} [parameters.subscriptionId] The Id of the Azure subscription * associated with the namespace. * * @param {string} [parameters.scaleUnit] ScaleUnit where the namespace gets * created * * @param {boolean} [parameters.enabled] Whether or not the namespace is * currently enabled. * * @param {boolean} [parameters.critical] Whether or not the namespace is set * as Critical. * * @param {string} [parameters.namespaceType] The namespace type. Possible * values include: 'Messaging', 'NotificationHub' * * @param {string} parameters.location Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [parameters.sku] The sku of the created namespace * * @param {string} parameters.sku.name Name of the notification hub sku. * Possible values include: 'Free', 'Basic', 'Standard' * * @param {string} [parameters.sku.tier] The tier of particular sku * * @param {string} [parameters.sku.size] The Sku size * * @param {string} [parameters.sku.family] The Sku Family * * @param {number} [parameters.sku.capacity] The capacity of the resource * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NamespaceResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NamespaceResource} [result] - The deserialized result object if an error did not occur. * See {@link NamespaceResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, namespaceName: string, parameters: models.NamespaceCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NamespaceResource>; createOrUpdate(resourceGroupName: string, namespaceName: string, parameters: models.NamespaceCreateOrUpdateParameters, callback: ServiceCallback<models.NamespaceResource>): void; createOrUpdate(resourceGroupName: string, namespaceName: string, parameters: models.NamespaceCreateOrUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NamespaceResource>): void; /** * Patches the existing namespace * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {object} parameters Parameters supplied to patch a Namespace * Resource. * * @param {object} [parameters.tags] Resource tags * * @param {object} [parameters.sku] The sku of the created namespace * * @param {string} parameters.sku.name Name of the notification hub sku. * Possible values include: 'Free', 'Basic', 'Standard' * * @param {string} [parameters.sku.tier] The tier of particular sku * * @param {string} [parameters.sku.size] The Sku size * * @param {string} [parameters.sku.family] The Sku Family * * @param {number} [parameters.sku.capacity] The capacity of the resource * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NamespaceResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ patchWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, parameters: models.NamespacePatchParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NamespaceResource>>; /** * Patches the existing namespace * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {object} parameters Parameters supplied to patch a Namespace * Resource. * * @param {object} [parameters.tags] Resource tags * * @param {object} [parameters.sku] The sku of the created namespace * * @param {string} parameters.sku.name Name of the notification hub sku. * Possible values include: 'Free', 'Basic', 'Standard' * * @param {string} [parameters.sku.tier] The tier of particular sku * * @param {string} [parameters.sku.size] The Sku size * * @param {string} [parameters.sku.family] The Sku Family * * @param {number} [parameters.sku.capacity] The capacity of the resource * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NamespaceResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NamespaceResource} [result] - The deserialized result object if an error did not occur. * See {@link NamespaceResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ patch(resourceGroupName: string, namespaceName: string, parameters: models.NamespacePatchParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NamespaceResource>; patch(resourceGroupName: string, namespaceName: string, parameters: models.NamespacePatchParameters, callback: ServiceCallback<models.NamespaceResource>): void; patch(resourceGroupName: string, namespaceName: string, parameters: models.NamespacePatchParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NamespaceResource>): void; /** * Deletes an existing namespace. This operation also removes all associated * notificationHubs under the namespace. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes an existing namespace. This operation also removes all associated * notificationHubs under the namespace. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, namespaceName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, namespaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Returns the description for the specified namespace. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NamespaceResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NamespaceResource>>; /** * Returns the description for the specified namespace. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NamespaceResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NamespaceResource} [result] - The deserialized result object if an error did not occur. * See {@link NamespaceResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NamespaceResource>; get(resourceGroupName: string, namespaceName: string, callback: ServiceCallback<models.NamespaceResource>): void; get(resourceGroupName: string, namespaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NamespaceResource>): void; /** * Creates an authorization rule for a namespace * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} authorizationRuleName Aauthorization Rule Name. * * @param {object} parameters The shared access authorization rule. * * @param {object} parameters.properties Properties of the Namespace * AuthorizationRules. * * @param {array} [parameters.properties.rights] The rights associated with the * rule. * * @param {string} parameters.location Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [parameters.sku] The sku of the created namespace * * @param {string} parameters.sku.name Name of the notification hub sku. * Possible values include: 'Free', 'Basic', 'Standard' * * @param {string} [parameters.sku.tier] The tier of particular sku * * @param {string} [parameters.sku.size] The Sku size * * @param {string} [parameters.sku.family] The Sku Family * * @param {number} [parameters.sku.capacity] The capacity of the resource * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SharedAccessAuthorizationRuleResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateAuthorizationRuleWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, parameters: models.SharedAccessAuthorizationRuleCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SharedAccessAuthorizationRuleResource>>; /** * Creates an authorization rule for a namespace * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} authorizationRuleName Aauthorization Rule Name. * * @param {object} parameters The shared access authorization rule. * * @param {object} parameters.properties Properties of the Namespace * AuthorizationRules. * * @param {array} [parameters.properties.rights] The rights associated with the * rule. * * @param {string} parameters.location Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [parameters.sku] The sku of the created namespace * * @param {string} parameters.sku.name Name of the notification hub sku. * Possible values include: 'Free', 'Basic', 'Standard' * * @param {string} [parameters.sku.tier] The tier of particular sku * * @param {string} [parameters.sku.size] The Sku size * * @param {string} [parameters.sku.family] The Sku Family * * @param {number} [parameters.sku.capacity] The capacity of the resource * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SharedAccessAuthorizationRuleResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SharedAccessAuthorizationRuleResource} [result] - The deserialized result object if an error did not occur. * See {@link SharedAccessAuthorizationRuleResource} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdateAuthorizationRule(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, parameters: models.SharedAccessAuthorizationRuleCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SharedAccessAuthorizationRuleResource>; createOrUpdateAuthorizationRule(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, parameters: models.SharedAccessAuthorizationRuleCreateOrUpdateParameters, callback: ServiceCallback<models.SharedAccessAuthorizationRuleResource>): void; createOrUpdateAuthorizationRule(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, parameters: models.SharedAccessAuthorizationRuleCreateOrUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SharedAccessAuthorizationRuleResource>): void; /** * Deletes a namespace authorization rule * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} authorizationRuleName Authorization Rule Name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteAuthorizationRuleWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a namespace authorization rule * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} authorizationRuleName Authorization Rule Name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteAuthorizationRule(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteAuthorizationRule(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, callback: ServiceCallback<void>): void; deleteAuthorizationRule(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets an authorization rule for a namespace by name. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name * * @param {string} authorizationRuleName Authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SharedAccessAuthorizationRuleResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getAuthorizationRuleWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SharedAccessAuthorizationRuleResource>>; /** * Gets an authorization rule for a namespace by name. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name * * @param {string} authorizationRuleName Authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SharedAccessAuthorizationRuleResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SharedAccessAuthorizationRuleResource} [result] - The deserialized result object if an error did not occur. * See {@link SharedAccessAuthorizationRuleResource} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getAuthorizationRule(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SharedAccessAuthorizationRuleResource>; getAuthorizationRule(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, callback: ServiceCallback<models.SharedAccessAuthorizationRuleResource>): void; getAuthorizationRule(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SharedAccessAuthorizationRuleResource>): void; /** * Lists the available namespaces within a resourceGroup. * * @param {string} resourceGroupName The name of the resource group. If * resourceGroupName value is null the method lists all the namespaces within * subscription * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NamespaceListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NamespaceListResult>>; /** * Lists the available namespaces within a resourceGroup. * * @param {string} resourceGroupName The name of the resource group. If * resourceGroupName value is null the method lists all the namespaces within * subscription * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NamespaceListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NamespaceListResult} [result] - The deserialized result object if an error did not occur. * See {@link NamespaceListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NamespaceListResult>; list(resourceGroupName: string, callback: ServiceCallback<models.NamespaceListResult>): void; list(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NamespaceListResult>): void; /** * Lists all the available namespaces within the subscription irrespective of * the resourceGroups. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NamespaceListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listAllWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NamespaceListResult>>; /** * Lists all the available namespaces within the subscription irrespective of * the resourceGroups. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NamespaceListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NamespaceListResult} [result] - The deserialized result object if an error did not occur. * See {@link NamespaceListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listAll(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NamespaceListResult>; listAll(callback: ServiceCallback<models.NamespaceListResult>): void; listAll(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NamespaceListResult>): void; /** * Gets the authorization rules for a namespace. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SharedAccessAuthorizationRuleListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listAuthorizationRulesWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SharedAccessAuthorizationRuleListResult>>; /** * Gets the authorization rules for a namespace. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SharedAccessAuthorizationRuleListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SharedAccessAuthorizationRuleListResult} [result] - The deserialized result object if an error did not occur. * See {@link SharedAccessAuthorizationRuleListResult} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listAuthorizationRules(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SharedAccessAuthorizationRuleListResult>; listAuthorizationRules(resourceGroupName: string, namespaceName: string, callback: ServiceCallback<models.SharedAccessAuthorizationRuleListResult>): void; listAuthorizationRules(resourceGroupName: string, namespaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SharedAccessAuthorizationRuleListResult>): void; /** * Gets the Primary and Secondary ConnectionStrings to the namespace * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} authorizationRuleName The connection string of the namespace * for the specified authorizationRule. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResourceListKeys>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listKeysWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResourceListKeys>>; /** * Gets the Primary and Secondary ConnectionStrings to the namespace * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} authorizationRuleName The connection string of the namespace * for the specified authorizationRule. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResourceListKeys} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResourceListKeys} [result] - The deserialized result object if an error did not occur. * See {@link ResourceListKeys} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listKeys(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ResourceListKeys>; listKeys(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, callback: ServiceCallback<models.ResourceListKeys>): void; listKeys(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResourceListKeys>): void; /** * Regenerates the Primary/Secondary Keys to the Namespace Authorization Rule * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} authorizationRuleName The connection string of the namespace * for the specified authorizationRule. * * @param {object} parameters Parameters supplied to regenerate the Namespace * Authorization Rule Key. * * @param {string} [parameters.policyKey] Name of the key that has to be * regenerated for the Namespace/Notification Hub Authorization Rule. The value * can be Primary Key/Secondary Key. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResourceListKeys>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ regenerateKeysWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, parameters: models.PolicykeyResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResourceListKeys>>; /** * Regenerates the Primary/Secondary Keys to the Namespace Authorization Rule * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} authorizationRuleName The connection string of the namespace * for the specified authorizationRule. * * @param {object} parameters Parameters supplied to regenerate the Namespace * Authorization Rule Key. * * @param {string} [parameters.policyKey] Name of the key that has to be * regenerated for the Namespace/Notification Hub Authorization Rule. The value * can be Primary Key/Secondary Key. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResourceListKeys} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResourceListKeys} [result] - The deserialized result object if an error did not occur. * See {@link ResourceListKeys} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ regenerateKeys(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, parameters: models.PolicykeyResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ResourceListKeys>; regenerateKeys(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, parameters: models.PolicykeyResource, callback: ServiceCallback<models.ResourceListKeys>): void; regenerateKeys(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, parameters: models.PolicykeyResource, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResourceListKeys>): void; /** * Deletes an existing namespace. This operation also removes all associated * notificationHubs under the namespace. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes an existing namespace. This operation also removes all associated * notificationHubs under the namespace. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(resourceGroupName: string, namespaceName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(resourceGroupName: string, namespaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Lists the available namespaces within a resourceGroup. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NamespaceListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NamespaceListResult>>; /** * Lists the available namespaces within a resourceGroup. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NamespaceListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NamespaceListResult} [result] - The deserialized result object if an error did not occur. * See {@link NamespaceListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NamespaceListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.NamespaceListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NamespaceListResult>): void; /** * Lists all the available namespaces within the subscription irrespective of * the resourceGroups. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NamespaceListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listAllNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NamespaceListResult>>; /** * Lists all the available namespaces within the subscription irrespective of * the resourceGroups. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NamespaceListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NamespaceListResult} [result] - The deserialized result object if an error did not occur. * See {@link NamespaceListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listAllNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NamespaceListResult>; listAllNext(nextPageLink: string, callback: ServiceCallback<models.NamespaceListResult>): void; listAllNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NamespaceListResult>): void; /** * Gets the authorization rules for a namespace. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SharedAccessAuthorizationRuleListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listAuthorizationRulesNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SharedAccessAuthorizationRuleListResult>>; /** * Gets the authorization rules for a namespace. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SharedAccessAuthorizationRuleListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SharedAccessAuthorizationRuleListResult} [result] - The deserialized result object if an error did not occur. * See {@link SharedAccessAuthorizationRuleListResult} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listAuthorizationRulesNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SharedAccessAuthorizationRuleListResult>; listAuthorizationRulesNext(nextPageLink: string, callback: ServiceCallback<models.SharedAccessAuthorizationRuleListResult>): void; listAuthorizationRulesNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SharedAccessAuthorizationRuleListResult>): void; } /** * @class * Name * __NOTE__: An instance of this class is automatically created for an * instance of the NotificationHubsManagementClient. */ export interface Name { /** * 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 {object} parameters The namespace name. * * @param {string} parameters.name Resource name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<CheckNameAvailabilityResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ checkAvailabilityWithHttpOperationResponse(parameters: models.CheckNameAvailabilityRequestParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.CheckNameAvailabilityResponse>>; /** * 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 {object} parameters The namespace name. * * @param {string} parameters.name Resource name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {CheckNameAvailabilityResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {CheckNameAvailabilityResponse} [result] - The deserialized result object if an error did not occur. * See {@link CheckNameAvailabilityResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ checkAvailability(parameters: models.CheckNameAvailabilityRequestParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.CheckNameAvailabilityResponse>; checkAvailability(parameters: models.CheckNameAvailabilityRequestParameters, callback: ServiceCallback<models.CheckNameAvailabilityResponse>): void; checkAvailability(parameters: models.CheckNameAvailabilityRequestParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.CheckNameAvailabilityResponse>): void; } /** * @class * NotificationHubs * __NOTE__: An instance of this class is automatically created for an * instance of the NotificationHubsManagementClient. */ export interface NotificationHubs { /** * Checks the availability of the given notificationHub in a namespace. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {object} parameters The notificationHub name. * * @param {string} parameters.name Resource name * * @param {string} parameters.location Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [parameters.sku] The sku of the created namespace * * @param {string} parameters.sku.name Name of the notification hub sku. * Possible values include: 'Free', 'Basic', 'Standard' * * @param {string} [parameters.sku.tier] The tier of particular sku * * @param {string} [parameters.sku.size] The Sku size * * @param {string} [parameters.sku.family] The Sku Family * * @param {number} [parameters.sku.capacity] The capacity of the resource * * @param {boolean} [parameters.isAvailiable] True if the name is available and * can be used to create new Namespace/NotificationHub. Otherwise false. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<CheckAvailabilityResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ checkAvailabilityWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, parameters: models.CheckAvailabilityParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.CheckAvailabilityResult>>; /** * Checks the availability of the given notificationHub in a namespace. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {object} parameters The notificationHub name. * * @param {string} parameters.name Resource name * * @param {string} parameters.location Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [parameters.sku] The sku of the created namespace * * @param {string} parameters.sku.name Name of the notification hub sku. * Possible values include: 'Free', 'Basic', 'Standard' * * @param {string} [parameters.sku.tier] The tier of particular sku * * @param {string} [parameters.sku.size] The Sku size * * @param {string} [parameters.sku.family] The Sku Family * * @param {number} [parameters.sku.capacity] The capacity of the resource * * @param {boolean} [parameters.isAvailiable] True if the name is available and * can be used to create new Namespace/NotificationHub. Otherwise false. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {CheckAvailabilityResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {CheckAvailabilityResult} [result] - The deserialized result object if an error did not occur. * See {@link CheckAvailabilityResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ checkAvailability(resourceGroupName: string, namespaceName: string, parameters: models.CheckAvailabilityParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.CheckAvailabilityResult>; checkAvailability(resourceGroupName: string, namespaceName: string, parameters: models.CheckAvailabilityParameters, callback: ServiceCallback<models.CheckAvailabilityResult>): void; checkAvailability(resourceGroupName: string, namespaceName: string, parameters: models.CheckAvailabilityParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.CheckAvailabilityResult>): void; /** * Creates/Update a NotificationHub in a namespace. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} notificationHubName The notification hub name. * * @param {object} parameters Parameters supplied to the create/update a * NotificationHub Resource. * * @param {string} [parameters.notificationHubCreateOrUpdateParametersName] The * NotificationHub name. * * @param {string} [parameters.registrationTtl] The RegistrationTtl of the * created NotificationHub * * @param {array} [parameters.authorizationRules] The AuthorizationRules of the * created NotificationHub * * @param {object} [parameters.apnsCredential] The ApnsCredential of the * created NotificationHub * * @param {string} [parameters.apnsCredential.apnsCertificate] The APNS * certificate. * * @param {string} [parameters.apnsCredential.certificateKey] The certificate * key. * * @param {string} [parameters.apnsCredential.endpoint] The endpoint of this * credential. * * @param {string} [parameters.apnsCredential.thumbprint] The Apns certificate * Thumbprint * * @param {string} [parameters.apnsCredential.keyId] A 10-character key * identifier (kid) key, obtained from your developer account * * @param {string} [parameters.apnsCredential.appName] The name of the * application * * @param {string} [parameters.apnsCredential.appId] The issuer (iss) * registered claim key, whose value is your 10-character Team ID, obtained * from your developer account * * @param {string} [parameters.apnsCredential.token] Provider Authentication * Token, obtained through your developer account * * @param {object} [parameters.wnsCredential] The WnsCredential of the created * NotificationHub * * @param {string} [parameters.wnsCredential.packageSid] The package ID for * this credential. * * @param {string} [parameters.wnsCredential.secretKey] The secret key. * * @param {string} [parameters.wnsCredential.windowsLiveEndpoint] The Windows * Live endpoint. * * @param {object} [parameters.gcmCredential] The GcmCredential of the created * NotificationHub * * @param {string} [parameters.gcmCredential.gcmEndpoint] The GCM endpoint. * * @param {string} [parameters.gcmCredential.googleApiKey] The Google API key. * * @param {object} [parameters.mpnsCredential] The MpnsCredential of the * created NotificationHub * * @param {string} [parameters.mpnsCredential.mpnsCertificate] The MPNS * certificate. * * @param {string} [parameters.mpnsCredential.certificateKey] The certificate * key for this credential. * * @param {string} [parameters.mpnsCredential.thumbprint] The Mpns certificate * Thumbprint * * @param {object} [parameters.admCredential] The AdmCredential of the created * NotificationHub * * @param {string} [parameters.admCredential.clientId] The client identifier. * * @param {string} [parameters.admCredential.clientSecret] The credential * secret access key. * * @param {string} [parameters.admCredential.authTokenUrl] The URL of the * authorization token. * * @param {object} [parameters.baiduCredential] The BaiduCredential of the * created NotificationHub * * @param {string} [parameters.baiduCredential.baiduApiKey] Baidu Api Key. * * @param {string} [parameters.baiduCredential.baiduEndPoint] Baidu Endpoint. * * @param {string} [parameters.baiduCredential.baiduSecretKey] Baidu Secret Key * * @param {string} parameters.location Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [parameters.sku] The sku of the created namespace * * @param {string} parameters.sku.name Name of the notification hub sku. * Possible values include: 'Free', 'Basic', 'Standard' * * @param {string} [parameters.sku.tier] The tier of particular sku * * @param {string} [parameters.sku.size] The Sku size * * @param {string} [parameters.sku.family] The Sku Family * * @param {number} [parameters.sku.capacity] The capacity of the resource * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NotificationHubResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, notificationHubName: string, parameters: models.NotificationHubCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NotificationHubResource>>; /** * Creates/Update a NotificationHub in a namespace. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} notificationHubName The notification hub name. * * @param {object} parameters Parameters supplied to the create/update a * NotificationHub Resource. * * @param {string} [parameters.notificationHubCreateOrUpdateParametersName] The * NotificationHub name. * * @param {string} [parameters.registrationTtl] The RegistrationTtl of the * created NotificationHub * * @param {array} [parameters.authorizationRules] The AuthorizationRules of the * created NotificationHub * * @param {object} [parameters.apnsCredential] The ApnsCredential of the * created NotificationHub * * @param {string} [parameters.apnsCredential.apnsCertificate] The APNS * certificate. * * @param {string} [parameters.apnsCredential.certificateKey] The certificate * key. * * @param {string} [parameters.apnsCredential.endpoint] The endpoint of this * credential. * * @param {string} [parameters.apnsCredential.thumbprint] The Apns certificate * Thumbprint * * @param {string} [parameters.apnsCredential.keyId] A 10-character key * identifier (kid) key, obtained from your developer account * * @param {string} [parameters.apnsCredential.appName] The name of the * application * * @param {string} [parameters.apnsCredential.appId] The issuer (iss) * registered claim key, whose value is your 10-character Team ID, obtained * from your developer account * * @param {string} [parameters.apnsCredential.token] Provider Authentication * Token, obtained through your developer account * * @param {object} [parameters.wnsCredential] The WnsCredential of the created * NotificationHub * * @param {string} [parameters.wnsCredential.packageSid] The package ID for * this credential. * * @param {string} [parameters.wnsCredential.secretKey] The secret key. * * @param {string} [parameters.wnsCredential.windowsLiveEndpoint] The Windows * Live endpoint. * * @param {object} [parameters.gcmCredential] The GcmCredential of the created * NotificationHub * * @param {string} [parameters.gcmCredential.gcmEndpoint] The GCM endpoint. * * @param {string} [parameters.gcmCredential.googleApiKey] The Google API key. * * @param {object} [parameters.mpnsCredential] The MpnsCredential of the * created NotificationHub * * @param {string} [parameters.mpnsCredential.mpnsCertificate] The MPNS * certificate. * * @param {string} [parameters.mpnsCredential.certificateKey] The certificate * key for this credential. * * @param {string} [parameters.mpnsCredential.thumbprint] The Mpns certificate * Thumbprint * * @param {object} [parameters.admCredential] The AdmCredential of the created * NotificationHub * * @param {string} [parameters.admCredential.clientId] The client identifier. * * @param {string} [parameters.admCredential.clientSecret] The credential * secret access key. * * @param {string} [parameters.admCredential.authTokenUrl] The URL of the * authorization token. * * @param {object} [parameters.baiduCredential] The BaiduCredential of the * created NotificationHub * * @param {string} [parameters.baiduCredential.baiduApiKey] Baidu Api Key. * * @param {string} [parameters.baiduCredential.baiduEndPoint] Baidu Endpoint. * * @param {string} [parameters.baiduCredential.baiduSecretKey] Baidu Secret Key * * @param {string} parameters.location Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [parameters.sku] The sku of the created namespace * * @param {string} parameters.sku.name Name of the notification hub sku. * Possible values include: 'Free', 'Basic', 'Standard' * * @param {string} [parameters.sku.tier] The tier of particular sku * * @param {string} [parameters.sku.size] The Sku size * * @param {string} [parameters.sku.family] The Sku Family * * @param {number} [parameters.sku.capacity] The capacity of the resource * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NotificationHubResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NotificationHubResource} [result] - The deserialized result object if an error did not occur. * See {@link NotificationHubResource} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, namespaceName: string, notificationHubName: string, parameters: models.NotificationHubCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NotificationHubResource>; createOrUpdate(resourceGroupName: string, namespaceName: string, notificationHubName: string, parameters: models.NotificationHubCreateOrUpdateParameters, callback: ServiceCallback<models.NotificationHubResource>): void; createOrUpdate(resourceGroupName: string, namespaceName: string, notificationHubName: string, parameters: models.NotificationHubCreateOrUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NotificationHubResource>): void; /** * Deletes a notification hub associated with a namespace. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} notificationHubName The notification hub name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, notificationHubName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a notification hub associated with a namespace. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} notificationHubName The notification hub name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, namespaceName: string, notificationHubName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, namespaceName: string, notificationHubName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, namespaceName: string, notificationHubName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Lists the notification hubs associated with a namespace. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} notificationHubName The notification hub name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NotificationHubResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, notificationHubName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NotificationHubResource>>; /** * Lists the notification hubs associated with a namespace. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} notificationHubName The notification hub name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NotificationHubResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NotificationHubResource} [result] - The deserialized result object if an error did not occur. * See {@link NotificationHubResource} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, namespaceName: string, notificationHubName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NotificationHubResource>; get(resourceGroupName: string, namespaceName: string, notificationHubName: string, callback: ServiceCallback<models.NotificationHubResource>): void; get(resourceGroupName: string, namespaceName: string, notificationHubName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NotificationHubResource>): void; /** * Creates/Updates an authorization rule for a NotificationHub * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} notificationHubName The notification hub name. * * @param {string} authorizationRuleName Authorization Rule Name. * * @param {object} parameters The shared access authorization rule. * * @param {object} parameters.properties Properties of the Namespace * AuthorizationRules. * * @param {array} [parameters.properties.rights] The rights associated with the * rule. * * @param {string} parameters.location Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [parameters.sku] The sku of the created namespace * * @param {string} parameters.sku.name Name of the notification hub sku. * Possible values include: 'Free', 'Basic', 'Standard' * * @param {string} [parameters.sku.tier] The tier of particular sku * * @param {string} [parameters.sku.size] The Sku size * * @param {string} [parameters.sku.family] The Sku Family * * @param {number} [parameters.sku.capacity] The capacity of the resource * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SharedAccessAuthorizationRuleResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateAuthorizationRuleWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, parameters: models.SharedAccessAuthorizationRuleCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SharedAccessAuthorizationRuleResource>>; /** * Creates/Updates an authorization rule for a NotificationHub * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} notificationHubName The notification hub name. * * @param {string} authorizationRuleName Authorization Rule Name. * * @param {object} parameters The shared access authorization rule. * * @param {object} parameters.properties Properties of the Namespace * AuthorizationRules. * * @param {array} [parameters.properties.rights] The rights associated with the * rule. * * @param {string} parameters.location Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [parameters.sku] The sku of the created namespace * * @param {string} parameters.sku.name Name of the notification hub sku. * Possible values include: 'Free', 'Basic', 'Standard' * * @param {string} [parameters.sku.tier] The tier of particular sku * * @param {string} [parameters.sku.size] The Sku size * * @param {string} [parameters.sku.family] The Sku Family * * @param {number} [parameters.sku.capacity] The capacity of the resource * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SharedAccessAuthorizationRuleResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SharedAccessAuthorizationRuleResource} [result] - The deserialized result object if an error did not occur. * See {@link SharedAccessAuthorizationRuleResource} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdateAuthorizationRule(resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, parameters: models.SharedAccessAuthorizationRuleCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SharedAccessAuthorizationRuleResource>; createOrUpdateAuthorizationRule(resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, parameters: models.SharedAccessAuthorizationRuleCreateOrUpdateParameters, callback: ServiceCallback<models.SharedAccessAuthorizationRuleResource>): void; createOrUpdateAuthorizationRule(resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, parameters: models.SharedAccessAuthorizationRuleCreateOrUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SharedAccessAuthorizationRuleResource>): void; /** * Deletes a notificationHub authorization rule * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} notificationHubName The notification hub name. * * @param {string} authorizationRuleName Authorization Rule Name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteAuthorizationRuleWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a notificationHub authorization rule * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} notificationHubName The notification hub name. * * @param {string} authorizationRuleName Authorization Rule Name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteAuthorizationRule(resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteAuthorizationRule(resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, callback: ServiceCallback<void>): void; deleteAuthorizationRule(resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets an authorization rule for a NotificationHub by name. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name * * @param {string} notificationHubName The notification hub name. * * @param {string} authorizationRuleName authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SharedAccessAuthorizationRuleResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getAuthorizationRuleWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SharedAccessAuthorizationRuleResource>>; /** * Gets an authorization rule for a NotificationHub by name. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name * * @param {string} notificationHubName The notification hub name. * * @param {string} authorizationRuleName authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SharedAccessAuthorizationRuleResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SharedAccessAuthorizationRuleResource} [result] - The deserialized result object if an error did not occur. * See {@link SharedAccessAuthorizationRuleResource} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getAuthorizationRule(resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SharedAccessAuthorizationRuleResource>; getAuthorizationRule(resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, callback: ServiceCallback<models.SharedAccessAuthorizationRuleResource>): void; getAuthorizationRule(resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SharedAccessAuthorizationRuleResource>): void; /** * Lists the notification hubs associated with a namespace. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NotificationHubListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NotificationHubListResult>>; /** * Lists the notification hubs associated with a namespace. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NotificationHubListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NotificationHubListResult} [result] - The deserialized result object if an error did not occur. * See {@link NotificationHubListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NotificationHubListResult>; list(resourceGroupName: string, namespaceName: string, callback: ServiceCallback<models.NotificationHubListResult>): void; list(resourceGroupName: string, namespaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NotificationHubListResult>): void; /** * Gets the authorization rules for a NotificationHub. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name * * @param {string} notificationHubName The notification hub name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SharedAccessAuthorizationRuleListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listAuthorizationRulesWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, notificationHubName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SharedAccessAuthorizationRuleListResult>>; /** * Gets the authorization rules for a NotificationHub. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name * * @param {string} notificationHubName The notification hub name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SharedAccessAuthorizationRuleListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SharedAccessAuthorizationRuleListResult} [result] - The deserialized result object if an error did not occur. * See {@link SharedAccessAuthorizationRuleListResult} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listAuthorizationRules(resourceGroupName: string, namespaceName: string, notificationHubName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SharedAccessAuthorizationRuleListResult>; listAuthorizationRules(resourceGroupName: string, namespaceName: string, notificationHubName: string, callback: ServiceCallback<models.SharedAccessAuthorizationRuleListResult>): void; listAuthorizationRules(resourceGroupName: string, namespaceName: string, notificationHubName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SharedAccessAuthorizationRuleListResult>): void; /** * Gets the Primary and Secondary ConnectionStrings to the NotificationHub * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} notificationHubName The notification hub name. * * @param {string} authorizationRuleName The connection string of the * NotificationHub for the specified authorizationRule. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResourceListKeys>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listKeysWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResourceListKeys>>; /** * Gets the Primary and Secondary ConnectionStrings to the NotificationHub * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} notificationHubName The notification hub name. * * @param {string} authorizationRuleName The connection string of the * NotificationHub for the specified authorizationRule. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResourceListKeys} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResourceListKeys} [result] - The deserialized result object if an error did not occur. * See {@link ResourceListKeys} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listKeys(resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ResourceListKeys>; listKeys(resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, callback: ServiceCallback<models.ResourceListKeys>): void; listKeys(resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResourceListKeys>): void; /** * Regenerates the Primary/Secondary Keys to the NotificationHub Authorization * Rule * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} notificationHubName The notification hub name. * * @param {string} authorizationRuleName The connection string of the * NotificationHub for the specified authorizationRule. * * @param {object} parameters Parameters supplied to regenerate the * NotificationHub Authorization Rule Key. * * @param {string} [parameters.policyKey] Name of the key that has to be * regenerated for the Namespace/Notification Hub Authorization Rule. The value * can be Primary Key/Secondary Key. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResourceListKeys>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ regenerateKeysWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, parameters: models.PolicykeyResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResourceListKeys>>; /** * Regenerates the Primary/Secondary Keys to the NotificationHub Authorization * Rule * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} notificationHubName The notification hub name. * * @param {string} authorizationRuleName The connection string of the * NotificationHub for the specified authorizationRule. * * @param {object} parameters Parameters supplied to regenerate the * NotificationHub Authorization Rule Key. * * @param {string} [parameters.policyKey] Name of the key that has to be * regenerated for the Namespace/Notification Hub Authorization Rule. The value * can be Primary Key/Secondary Key. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResourceListKeys} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResourceListKeys} [result] - The deserialized result object if an error did not occur. * See {@link ResourceListKeys} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ regenerateKeys(resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, parameters: models.PolicykeyResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ResourceListKeys>; regenerateKeys(resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, parameters: models.PolicykeyResource, callback: ServiceCallback<models.ResourceListKeys>): void; regenerateKeys(resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, parameters: models.PolicykeyResource, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResourceListKeys>): void; /** * Lists the PNS Credentials associated with a notification hub . * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} notificationHubName The notification hub name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PnsCredentialsResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getPnsCredentialsWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, notificationHubName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PnsCredentialsResource>>; /** * Lists the PNS Credentials associated with a notification hub . * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {string} notificationHubName The notification hub name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PnsCredentialsResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PnsCredentialsResource} [result] - The deserialized result object if an error did not occur. * See {@link PnsCredentialsResource} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getPnsCredentials(resourceGroupName: string, namespaceName: string, notificationHubName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PnsCredentialsResource>; getPnsCredentials(resourceGroupName: string, namespaceName: string, notificationHubName: string, callback: ServiceCallback<models.PnsCredentialsResource>): void; getPnsCredentials(resourceGroupName: string, namespaceName: string, notificationHubName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PnsCredentialsResource>): void; /** * Lists the notification hubs associated with a namespace. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NotificationHubListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NotificationHubListResult>>; /** * Lists the notification hubs associated with a namespace. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NotificationHubListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NotificationHubListResult} [result] - The deserialized result object if an error did not occur. * See {@link NotificationHubListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NotificationHubListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.NotificationHubListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NotificationHubListResult>): void; /** * Gets the authorization rules for a NotificationHub. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SharedAccessAuthorizationRuleListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listAuthorizationRulesNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SharedAccessAuthorizationRuleListResult>>; /** * Gets the authorization rules for a NotificationHub. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SharedAccessAuthorizationRuleListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SharedAccessAuthorizationRuleListResult} [result] - The deserialized result object if an error did not occur. * See {@link SharedAccessAuthorizationRuleListResult} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listAuthorizationRulesNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SharedAccessAuthorizationRuleListResult>; listAuthorizationRulesNext(nextPageLink: string, callback: ServiceCallback<models.SharedAccessAuthorizationRuleListResult>): void; listAuthorizationRulesNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SharedAccessAuthorizationRuleListResult>): void; } /** * @class * Hubs * __NOTE__: An instance of this class is automatically created for an * instance of the NotificationHubsManagementClient. */ export interface Hubs { /** * Checks the availability of the given notificationHub in a namespace. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {object} parameters The notificationHub name. * * @param {string} parameters.name Resource name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<CheckNameAvailabilityResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ checkAvailabilityWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, parameters: models.CheckNameAvailabilityRequestParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.CheckNameAvailabilityResponse>>; /** * Checks the availability of the given notificationHub in a namespace. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} namespaceName The namespace name. * * @param {object} parameters The notificationHub name. * * @param {string} parameters.name Resource name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {CheckNameAvailabilityResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {CheckNameAvailabilityResponse} [result] - The deserialized result object if an error did not occur. * See {@link CheckNameAvailabilityResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ checkAvailability(resourceGroupName: string, namespaceName: string, parameters: models.CheckNameAvailabilityRequestParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.CheckNameAvailabilityResponse>; checkAvailability(resourceGroupName: string, namespaceName: string, parameters: models.CheckNameAvailabilityRequestParameters, callback: ServiceCallback<models.CheckNameAvailabilityResponse>): void; checkAvailability(resourceGroupName: string, namespaceName: string, parameters: models.CheckNameAvailabilityRequestParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.CheckNameAvailabilityResponse>): void; }
the_stack
import * as utils from '../../src/common/utils'; import { Vector3 } from 'three'; describe('utils', function() { it('getExtension', () => { expect( () => { expect(utils.getExtension('test')); } ).toThrow(new Error(`Invalid filename: test, or no extension present.`)); expect(utils.getExtension('test.tom')).toBe('tom'); expect(utils.getExtension('pathTo/test.vol')).toBe('vol'); const filename = 'pathTo with/ Spaces.andDots/test.vol'; expect(utils.getExtension(filename)).toBe('vol'); // No mutations. expect(filename).toEqual('pathTo with/ Spaces.andDots/test.vol'); }); it('removeExtension', () => { expect( () => { expect(utils.removeExtension('test')); } ).toThrow(new Error(`Invalid filename: test, or no extension present.`)); expect(utils.removeExtension('test.tom')).toBe('test'); expect(utils.removeExtension('pathTo/test.vol')).toBe('pathTo/test'); const filename = 'pathTo with/ Spaces.andDots/te.st.vol'; expect(utils.removeExtension(filename)).toBe('pathTo with/ Spaces.andDots/te.st'); // No mutations. expect(filename).toEqual('pathTo with/ Spaces.andDots/te.st.vol'); }); it('isInteger', () => { expect(utils.isInteger(NaN)).toEqual(false); expect(utils.isInteger(Infinity)).toEqual(false); expect(utils.isInteger(-Infinity)).toEqual(false); expect(utils.isInteger(4.7)).toEqual(false); expect(utils.isInteger(0)).toEqual(true); expect(utils.isInteger(3)).toEqual(true); expect(utils.isInteger(-45)).toEqual(true); }); it('isPositiveInteger', () => { expect(utils.isPositiveInteger(NaN)).toEqual(false); expect(utils.isPositiveInteger(Infinity)).toEqual(false); expect(utils.isPositiveInteger(-Infinity)).toEqual(false); expect(utils.isPositiveInteger(4.7)).toEqual(false); expect(utils.isPositiveInteger(0)).toEqual(false); expect(utils.isPositiveInteger(3)).toEqual(true); expect(utils.isPositiveInteger(-45)).toEqual(false); }); it('isNonNegativeInteger', () => { expect(utils.isNonNegativeInteger(NaN)).toEqual(false); expect(utils.isNonNegativeInteger(Infinity)).toEqual(false); expect(utils.isNonNegativeInteger(-Infinity)).toEqual(false); expect(utils.isNonNegativeInteger(4.7)).toEqual(false); expect(utils.isNonNegativeInteger(0)).toEqual(true); expect(utils.isNonNegativeInteger(3)).toEqual(true); expect(utils.isNonNegativeInteger(-45)).toEqual(false); }); it('isUint8', () => { expect(utils.isUint8(NaN)).toEqual(false); expect(utils.isUint8(Infinity)).toEqual(false); expect(utils.isUint8(-Infinity)).toEqual(false); expect(utils.isUint8(4.7)).toEqual(false); expect(utils.isUint8(0)).toEqual(true); expect(utils.isUint8(3)).toEqual(true); expect(utils.isUint8(200)).toEqual(true); expect(utils.isUint8(32948700)).toEqual(false); expect(utils.isUint8(-45)).toEqual(false); }); it('isUint32', () => { expect(utils.isUint32(NaN)).toEqual(false); expect(utils.isUint32(Infinity)).toEqual(false); expect(utils.isUint32(-Infinity)).toEqual(false); expect(utils.isUint32(4.7)).toEqual(false); expect(utils.isUint32(0)).toEqual(true); expect(utils.isUint32(3)).toEqual(true); expect(utils.isUint32(200)).toEqual(true); expect(utils.isUint32(32948700)).toEqual(true); expect(utils.isUint32(-45)).toEqual(false); }); it('isInt32', () => { expect(utils.isInt32(NaN)).toEqual(false); expect(utils.isInt32(Infinity)).toEqual(false); expect(utils.isInt32(-Infinity)).toEqual(false); expect(utils.isInt32(4.7)).toEqual(false); expect(utils.isInt32(0)).toEqual(true); expect(utils.isInt32(3)).toEqual(true); expect(utils.isInt32(200)).toEqual(true); expect(utils.isInt32(32948700)).toEqual(true); expect(utils.isInt32(-45)).toEqual(true); }); it('isFloat32', () => { expect(utils.isFloat32(NaN)).toEqual(false); expect(utils.isFloat32(Infinity)).toEqual(false); expect(utils.isFloat32(-Infinity)).toEqual(false); expect(utils.isFloat32(4.7)).toEqual(true); expect(utils.isFloat32(0)).toEqual(true); expect(utils.isFloat32(3)).toEqual(true); expect(utils.isFloat32(200)).toEqual(true); expect(utils.isFloat32(32948700)).toEqual(true); expect(utils.isFloat32(-45)).toEqual(true); }); it('isArray', () => { expect(utils.isArray(undefined)).toEqual(false); expect(utils.isArray(null)).toEqual(false); expect(utils.isArray(NaN)).toEqual(false); expect(utils.isArray(-45)).toEqual(false); expect(utils.isArray([])).toEqual(true); expect(utils.isArray(new Uint8Array(10))).toEqual(true); expect(utils.isArray([1, 2, 3, -4])).toEqual(true); expect(utils.isArray({})).toEqual(false); }); it('isTypedArray', () => { expect(utils.isTypedArray(undefined)).toEqual(false); expect(utils.isTypedArray(null)).toEqual(false); expect(utils.isTypedArray(NaN)).toEqual(false); expect(utils.isTypedArray([])).toEqual(false); expect(utils.isTypedArray(new Uint8Array(10))).toEqual(true); expect(utils.isTypedArray(new Int32Array(10))).toEqual(true); expect(utils.isTypedArray(new Uint32Array(10))).toEqual(true); expect(utils.isTypedArray(new Float32Array(10))).toEqual(true); expect(utils.isTypedArray(new Float64Array(10))).toEqual(true); }); it('index3Dto1D', () => { const dim = new Vector3(24, 46, 21); const dimCopy = dim.clone(); // Check for errors. // Bad index. const vector = new Vector3(2, 5, 12); vector.x = NaN; expect( () => { utils.index3Dto1D(vector, dim) } ).toThrow(new Error('Invalid index3D: [ NaN, 5, 12 ].')); vector.x = 2; vector.y = NaN; expect( () => { utils.index3Dto1D(vector, dim) } ).toThrow(new Error('Invalid index3D: [ 2, NaN, 12 ].')); vector.y = 5; vector.z = NaN; expect( () => { utils.index3Dto1D(vector, dim) } ).toThrow(new Error('Invalid index3D: [ 2, 5, NaN ].')); // Index is float. expect( () => { utils.index3Dto1D(new Vector3(2.3, 5, 12), dim) } ).toThrow(new Error('Invalid index3D: [ 2.3, 5, 12 ].')); expect( () => { utils.index3Dto1D(new Vector3(2, 5.1, 12), dim) } ).toThrow(new Error('Invalid index3D: [ 2, 5.1, 12 ].')); expect( () => { utils.index3Dto1D(new Vector3(2, 5, 12.4), dim) } ).toThrow(new Error('Invalid index3D: [ 2, 5, 12.4 ].')); // Index out of bounds. expect( () => { utils.index3Dto1D(new Vector3(-2, 5, 12), dim) } ).toThrow(new Error('Invalid index3D: [ -2, 5, 12 ] for buffer dimensions: [ 24, 46, 21 ].')); expect( () => { utils.index3Dto1D(new Vector3(24, 5, 12), dim) } ).toThrow(new Error('Invalid index3D: [ 24, 5, 12 ] for buffer dimensions: [ 24, 46, 21 ].')); expect( () => { utils.index3Dto1D(new Vector3(2, -5, 12), dim) } ).toThrow(new Error('Invalid index3D: [ 2, -5, 12 ] for buffer dimensions: [ 24, 46, 21 ].')); expect( () => { utils.index3Dto1D(new Vector3(2, 46, 12), dim) } ).toThrow(new Error('Invalid index3D: [ 2, 46, 12 ] for buffer dimensions: [ 24, 46, 21 ].')); expect( () => { utils.index3Dto1D(new Vector3(2, 5, -12), dim) } ).toThrow(new Error('Invalid index3D: [ 2, 5, -12 ] for buffer dimensions: [ 24, 46, 21 ].')); expect( () => { utils.index3Dto1D(new Vector3(2, 5, 21), dim) } ).toThrow(new Error('Invalid index3D: [ 2, 5, 21 ] for buffer dimensions: [ 24, 46, 21 ].')); // Positive cases. expect(utils.index3Dto1D(new Vector3(0, 0, 0), dim)).toEqual(0); expect(utils.index3Dto1D(new Vector3(2, 5, 12), dim)).toEqual(13370); // No mutations. expect(dim).toEqual(dimCopy); }); it('index1Dto3D', () => { const dim = new Vector3(24, 46, 21); const dimCopy = dim.clone(); const output = new Vector3(); // Check for errors. // Dimension is float. expect( () => { utils.index1Dto3D(2, new Vector3(24.2, 46, 21), output) } ).toThrow(new Error('Invalid dimension parameter: [ 24.2, 46, 21 ].')); expect( () => { utils.index1Dto3D(2, new Vector3(24, 46.3, 21), output) } ).toThrow(new Error('Invalid dimension parameter: [ 24, 46.3, 21 ].')); expect( () => { utils.index1Dto3D(2, new Vector3(24, 46, 21.7), output) } ).toThrow(new Error('Invalid dimension parameter: [ 24, 46, 21.7 ].')); // Bad index. expect( () => { utils.index1Dto3D(NaN, dim, output) } ).toThrow(new Error('Invalid index parameter: NaN.')); // Index is float. expect( () => { utils.index1Dto3D(4.3, dim, output) } ).toThrow(new Error('Invalid index parameter: 4.3.')); // Index out of range. expect( () => { utils.index1Dto3D(-2, dim, output) } ).toThrow(new Error('Attempting to access out of bounds index: -2 for dimensions: [ 24, 46, 21 ].')); expect( () => { utils.index1Dto3D(dim.x * dim.y * dim.z, dim, output) } ).toThrow(new Error('Attempting to access out of bounds index: 23184 for dimensions: [ 24, 46, 21 ].')); // Positive cases. expect(utils.index1Dto3D(0, dim, output)).toEqual(new Vector3(0, 0, 0)); expect(utils.index1Dto3D(13370, dim, output)).toEqual(new Vector3(2, 5, 12)); // No mutations. expect(dim).toEqual(dimCopy); }); it('positionToIndex3D', () => { const dim = new Vector3(4, 5, 7); const dimCopy = dim.clone(); expect(utils.positionToIndex3D(new Vector3(3.0, 4.52, -2.4), new Vector3(), dim)).toEqual(null); expect(utils.positionToIndex3D(new Vector3(3.0, 4.52, 2.4), new Vector3(), dim)).toEqual(new Vector3(3, 4, 2)); const position = new Vector3(3.0, 4.52, 8.1); const positionClone = position.clone(); expect(utils.positionToIndex3D(position, new Vector3(), dim)).toEqual(null); // No mutations. expect(dim).toEqual(dimCopy); expect(position).toEqual(positionClone); }); it('index3DInBounds', () => { const dim = new Vector3(24, 46, 21); const dimCopy = dim.clone(); const index = new Vector3(23, 4, 5); const indexCopy = index.clone(); expect(utils.index3DInBounds(index, dim)).toBe(true); expect(utils.index3DInBounds(new Vector3(24, 4, 5), dim)).toBe(false); expect(utils.index3DInBounds(new Vector3(23, 46, 5), dim)).toBe(false); expect(utils.index3DInBounds(new Vector3(23, 4, 21), dim)).toBe(false); expect(utils.index3DInBounds(new Vector3(-1, 4, 5), dim)).toBe(false); expect(utils.index3DInBounds(new Vector3(23, -1, 5), dim)).toBe(false); expect(utils.index3DInBounds(new Vector3(23, 4, -1), dim)).toBe(false); // No mutations. expect(dim).toEqual(dimCopy); expect(index).toEqual(indexCopy); }); // it('vector3ForIndex', () => { // const data = Float32Array.from([3.5, 2.3, 0, -10000, -10000, -10000, -3.4, 23.5, -10]); // const dataCopy = data.slice(); // expect(utils.vector3ForIndex(0, data)).toEqual(new Vector3(data[0], data[1], data[2])); // expect(utils.vector3ForIndex(1, data)).toEqual(null); // expect(utils.vector3ForIndex(2, data)).toEqual(new Vector3(data[6], data[7], data[8])); // expect( () => { utils.vector3ForIndex(3, data) } ).toThrow(new Error('Index out of range: 3.')); // expect( () => { utils.vector3ForIndex(-1, data) } ).toThrow(new Error('Index out of range: -1.')); // // no mutations // expect(data).toEqual(dataCopy); // }); // it('convertNeighborsToEdges', () => { // }); it('clamp', () => { expect(utils.clamp(0, 3, 4)).toBe(3); expect(utils.clamp(0, -3, 4)).toBe(0); expect(utils.clamp(-10, -3, 4)).toBe(-3); expect(utils.clamp(4.3, 3, 4)).toBe(4); expect( () => { utils.clamp(4.3, 4, 3) } ).toThrow(new Error('Invalid range for clamp: min 4, max 3.')); }); });
the_stack
'use strict'; const { debug, info, warn, error } = require('portal-env').Logger('portal-auth:app'); const prometheusMiddleware = require('portal-env').PrometheusMiddleware; const express = require('express'); const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser'); const path = require('path'); const logger = require('morgan'); import * as wicked from 'wicked-sdk'; import * as nocache from 'nocache'; const passport = require('passport'); const session = require('express-session'); // const FileStore = require('session-file-store')(session); import { redisConnection } from './common/redis-connection'; import { LocalIdP } from './providers/local'; import { DummyIdP } from './providers/dummy'; import { GithubIdP } from './providers/github'; import { GoogleIdP } from './providers/google'; import { TwitterIdP } from './providers/twitter'; import { OAuth2IdP } from './providers/oauth2'; // import { FacebookIdP } from './providers/facebook'; import { SamlIdP } from './providers/saml'; import { ExternalIdP } from './providers/external'; import { LdapIdP } from './providers/ldap'; import { StatusError } from './common/utils-fail'; import { SimpleCallback } from './common/types'; import { WickedAuthServer } from 'wicked-sdk'; import { utils } from './common/utils'; import { utilsOAuth2 } from './common/utils-oauth2'; // Use default options, see https://www.npmjs.com/package/session-file-store const sessionStoreOptions = {}; const SECRET = 'ThisIsASecret'; let sessionMinutes = 60; if (process.env.AUTH_SERVER_SESSION_MINUTES) { info('Using session duration specified in env var AUTH_SERVER_SESSION_MINUTES.'); sessionMinutes = Number(process.env.AUTH_SERVER_SESSION_MINUTES); } debug('Session duration: ' + sessionMinutes + ' minutes.'); export const app: any = express(); function rejectFromKong(req, res, next) { const via = req.get('via'); if (via && via.toLowerCase().indexOf('kong') > 0) { res.status(403).json({ code: 403, message: 'Not allowed from outside network.' }); return; } return next(); } app.initApp = function (authServerConfig: WickedAuthServer, callback: SimpleCallback) { // Store auth Config with application app.authConfig = authServerConfig; app.initialized = true; if (!wicked.isDevelopmentMode()) { app.set('trust proxy', 1); // TODO: This is not deal-breaking, as we're in a quite secure surrounding anyway, // but currently Kong sends 'X-Forwarded-Proto: http', which is plain wrong. And that // prevents the securing of the cookies. We know it's okay right now, so we do it // anyway - the Auth Server is SSL terminated at HAproxy, and the rest is http but // in the internal network of Docker. //sessionArgs.cookie.secure = true; info("Running in PRODUCTION MODE."); } else { warn("============================="); warn(" Running in DEVELOPMENT MODE"); warn("============================="); warn("If you see this in your production logs, you're doing something wrong."); } const basePath = app.get('base_path'); app._startupSeconds = utils.getUtc(); app.use(prometheusMiddleware.middleware('wicked_auth')); function answerPing(req, res, next) { debug('/ping'); const health = { name: 'auth', message: 'Up and running', uptime: (utils.getUtc() - app._startupSeconds), healthy: 1, pingUrl: '/ping', version: utils.getVersion(), error: null, gitLastCommit: utils.getGitLastCommit(), gitBranch: utils.getGitBranch(), buildDate: utils.getBuildDate() }; if (!app.initialized) { health.healthy = 2; health.message = 'Initializing - Waiting for API'; res.status(503); } else if (app.lastErr) { health.healthy = 0; health.message = app.lastErr.message; health.error = JSON.stringify(app.lastErr, null, 2); res.status(500); } res.json(health); } app.use(basePath + '/bootstrap', express.static(path.join(__dirname, 'assets/bootstrap/dist'))); app.use(basePath + '/jquery', express.static(path.join(__dirname, 'assets/jquery/dist'))); const serveStaticContent = express.Router(); serveStaticContent.get('/*', function (req, res, next) { debug('serveStaticContent ' + req.path); if (utils.isPublic(req.path)) { return utils.pipe(req, res, 'content' + req.path); } res.status(404).json({ message: 'Not found.' }); }); app.use(basePath + '/content', serveStaticContent); app.use(wicked.correlationIdHandler()); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); logger.token('correlation-id', function (req, res) { return req.correlationId; }); app.use(logger('{"date":":date[clf]","method":":method","url":":url","remote-addr":":remote-addr","version":":http-version","status":":status","content-length":":res[content-length]","referrer":":referrer","response-time":":response-time","correlation-id":":correlation-id"}')); app.get('/metrics', rejectFromKong, prometheusMiddleware.metrics); app.get('/ping', answerPing); app.get(basePath + '/ping', answerPing); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // Set up the cookie parser app.use(cookieParser(SECRET)); // Specify the session arguments. Used for configuring the session component. var sessionArgs = { name: 'portal-auth.cookie.sid', store: redisConnection.createSessionStore(session), secret: SECRET, saveUninitialized: true, resave: false, cookie: { maxAge: sessionMinutes * 60 * 1000 } }; // And session management app.use(session(sessionArgs)); // Initialize Passport app.use(passport.initialize()); app.use(passport.session()); // ======================= // Actual implementation // ======================= app.idpMap = {}; // Here: Read from Auth Methods configuration in default.json for (let i = 0; i < authServerConfig.authMethods.length; ++i) { const authMethod = authServerConfig.authMethods[i]; const authUri = `${basePath}/${authMethod.name}`; let enabled = true; if (authMethod.hasOwnProperty("enabled")) enabled = utils.parseBool(authMethod.enabled); if (!enabled) { info(`Skipping disabled auth method ${authMethod.name}.`); continue; } const options = { externalUrlBase: app.get('external_url'), basePath: app.get('base_path') }; debug(`options: ${JSON.stringify(options)}`) info(`Activating auth method ${authMethod.name} with type ${authMethod.type}, at ${authUri}.`); let idp = null; switch (authMethod.type) { case "local": idp = new LocalIdP(basePath, authMethod.name, authMethod.config, options); break; case "external": idp = new ExternalIdP(basePath, authMethod.name, authMethod.config, options); break; case "dummy": idp = new DummyIdP(basePath, authMethod.name, authMethod.config, options); break; case "github": idp = new GithubIdP(basePath, authMethod.name, authMethod.config, options); break; case "google": idp = new GoogleIdP(basePath, authMethod.name, authMethod.config, options); break; case "twitter": idp = new TwitterIdP(basePath, authMethod.name, authMethod.config, options); break; case "oauth2": idp = new OAuth2IdP(basePath, authMethod.name, authMethod.config, options); break; case "adfs": idp = new OAuth2IdP(basePath, authMethod.name, authMethod.config, options); break; case "saml": idp = new SamlIdP(basePath, authMethod.name, authMethod.config, options); break; case "ldap": idp = new LdapIdP(basePath, authMethod.name, authMethod.config, options); break; default: error('ERROR: Unknown authMethod type ' + authMethod.type); break; } if (idp) { app.idpMap[authMethod.name] = idp; app.use(authUri, idp.getRouter()); } } app.get(basePath + '/profile', nocache(), utilsOAuth2.getProfile); app.get(basePath + '/userinfo', nocache(), utilsOAuth2.getProfile); app.post(basePath + '/userinfo', nocache(), utilsOAuth2.getProfile); app.get(basePath + '/logout', nocache(), function (req, res, next) { debug(basePath + '/logout'); const redirect_uri = req.query && req.query.redirect_uri ? req.query.redirect_uri : null; // Iterate over the IdPs and see if they need to do a logout hook for (let authMethodId in app.idpMap) { const idp = app.idpMap[authMethodId]; if (idp.logoutHook) { const hasHandledRequest = idp.logoutHook(req, res, next, redirect_uri); if (!hasHandledRequest) { // Then just delete the session data for this auth Method utils.deleteSession(req, authMethodId); } else { // One IDP has taken over; let's quit here. The IdP must make // sure that this end point is called again after it is done // with whatever it does when logging out. Plus it must delete // its own session state. The reason why it's not done here yet // is that the IdP may need the session data to be able to correctly // log the user out (e.g. user_id and session_index for SAML). debug(`IdP ${authMethodId} has taken over, quitting /logout`); return; } } } // Successfully logged out. info('Successfully logged a user out.'); req.session.destroy(); if (redirect_uri) return res.redirect(req.query.redirect_uri); utils.render(req, res, 'logout', { title: 'Logged out', portalUrl: wicked.getExternalPortalUrl(), baseUrl: req.app.get('base_path'), correlationId: req.correlationId, }); }); app.get(basePath + '/failure', nocache(), function (req, res, next) { debug(basePath + '/failure'); let redirectUri = null; if (req.session && req.session.redirectUri) redirectUri = req.session.redirectUri; utils.render(req, res, 'failure', { title: 'Failure', portalUrl: wicked.getExternalPortalUrl(), baseUrl: req.app.get('base_path'), correlationId: req.correlationId, returnUrl: redirectUri }); }); // ======================= // catch 404 and forward to error handler app.use(function (req, res, next) { const err = new StatusError(404, 'Not Found'); next(err); }); // production error handler // no stacktraces leaked to user app.use(function (err, req, res, next) { if (err.status !== 404) { error(err); } if (err.status === 302) { // Issue as redirect res.redirect(`${err.redirectUri}?error=${err.oauthError}&error_description=${err.message}`); return; } res.status(err.status || 500); // From failJson? if (err.issueAsJson) { res.json({ status: err.status || 500, message: err.message, internal_error: err.internalError }); } else if (err.oauthError) { // From failOAuth // RFC 6749 compatible JSON error res.json({ error: err.oauthError, error_description: err.message }); } else { utils.render(req, res, 'error', { title: 'Error', portalUrl: wicked.getExternalPortalUrl(), baseUrl: req.app.get('base_path'), correlationId: req.correlationId, message: err.message, status: err.status, errorLink: err.errorLink, errorLinkDescription: err.errorLinkDescription }); } }); callback(null); };
the_stack
import { Pos, NoPos } from "./pos" import { strings } from "./bytestr" import { PathMap } from "./pathmap" import * as utf8 from "./utf8" import * as ast from "./ast" import { Node, Template, TemplateInvocation, TemplateVar } from "./ast" import { debuglog as dlog } from "./util" const DEBUG_EXPANSION = false // DEBUG let ind = "" let dbg = DEBUG_EXPANSION ? (...args :any[]) :void => { print(ind + args.map(v => typeof v == "string" ? v.replace(/\n/m, "\n" + ind) : v ).join(" ")) } : (...args :any[]) :void => {} export type ErrorCallback = (message :string, pos :Pos) => any class CacheEnt { key :Node[] value :Node|null constructor(key :Node[], value: Node|null) { this.key = key this.value = value } } const instanceCache = new class { tmap = new Map<Template<Node>,CacheEnt[]>() get(t :Template<Node>, args :Node[]) :Node|null { let entries = this.tmap.get(t) if (!entries) { return null } // TODO: replace this with something more efficient, like a trie. let nargs = args.length ent_loop: for (let ent of entries) { if (ent.key.length == nargs) { for (let i = 0; i < nargs; i++) { let arg = args[i] if (!this.equals(args[i], ent.key[i])) { continue ent_loop } } return ent.value } } return null } set(t :Template<Node>, args :Node[], value :Node) { let ent = new CacheEnt(args, value) let v = this.tmap.get(t) if (!v) { this.tmap.set(t, [ent]) } else { v.push(ent) } } equals(a :Node, b :Node) :bool { if (a === b) { return true } if (a.isType() && b.isType()) { return a.equals(b) } if (a.isIdent() && b.isIdent()) { return a.ent === b.ent } return false } } // expand a template, possibly returning a partially expanded template. // // restype is a Node constructor representing the expected result type. // For instance, for a template used as a type, restype==ast.Type. // // Note on type arguments for this function: // restype R can be a supertype or same type as the template type T. // The reason for this is that a template must always produce a type // compatible with the expected result type R. // // env, if provided, describes the outer/parent envionment in which // tvar lookups can be resolved. // // onerr, if provided, is invoked when an error occurs. The causing node // is the first argument and the error message the second argument. // For example, used for failing constraints. // export function expand<R extends Node, T extends R>( restype :Constructor<R>, ti :TemplateInvocation<T>, env :Env|null, onerr :ErrorCallback|null, ) :T|Template<T> { // TODO: instance cache. // e.g. instanceCache.get([ti.template, ti.args]) // We can use PathMap for this. let cached = instanceCache.get(ti.template, ti.args) if (cached) { return cached as T|Template<T> } let tp = ti.template // expansion state let hasUnresolvedTvars = false let lookupCache = new Map<TemplateVar,Node>() env = new Env(env, ti) if (DEBUG_EXPANSION) { if (ind == "") { ast.print(ti) } dbg(`expand ${tp} as ${restype.name}`) tp.aliases().forEach(t => dbg(` alias for ${t}`)) dbg(`env:\n` + Array.from(env.bindings).map(p => ` ${p[0].name} => ${p[1]}`).join("\n")) } function expandVar(tvar :TemplateVar, visitChildren :ast.Visitor) :Node { let tvar2 :TemplateVar = visitChildren(tvar) // lookup tvar in environment let val :Node|null = lookupCache.get(tvar) as Node|null if (val) { dbg(`lookup cache hit for ${tvar} -> ${val}`) return val } val = env!.lookup(tvar) // unwind tvar->tvar chains if (!DEBUG_EXPANSION) { while (val instanceof TemplateVar) { val = env!.lookup(val) } } else { let prevtvar :TemplateVar = tvar // only for debug print while (val instanceof TemplateVar) { // unwind tvar->tvar chains dbg(`○ RESOLVE ${prevtvar} -> ${val}`); prevtvar = val val = env!.lookup(val) } dbg(`● RESOLVE ${tvar} -> ${val}`) } if (!val) { hasUnresolvedTvars = true val = tvar2 } else { let pos = val.pos if (val.isIdent() && val.ent && val.ent.value.isType()) { // val is a name of a type val = val.ent.value } // check constraint on tvar assert(!tvar2.constraint == !tvar.constraint) if (tvar2.constraint && onerr) { let constraint :Node = tvar2.constraint dbg(`check constraint ${constraint} <- ${val}`) let msg = validateConstraint(constraint, val) if (msg) { if (tvar.constraint && tvar.constraint.isTemplateVar()) { // The constraint is based on another tvar. e.g. // type Point<T int|i32|i64, Y T> {} // x Point<int,i64> msg += ` (inferred from ${tvar.constraint.name})` } onerr(msg, pos) } } } lookupCache.set(tvar, val) return val } // hide template vars during transformation to avoid unnecessary substitution let vars = tp.vars // save vars tp.vars = [] // clear vars // apply transformation to expand template let expanded :Template<Node> = ast.transform(tp, (n, visitChildren) => { // Pipe through nodes which can never contain a TemplateVar if (n instanceof ast.LiteralExpr || n instanceof ast.PrimType || n instanceof ast.Atom) { return n } let dbgexit :<T>(v:T)=>T = DEBUG_EXPANSION ? ( dbg(`enter ${n.constructor.name} (${n})`), ind += " ", v => { ind = ind.substr(0, ind.length-2) dbg(`exit ${n.constructor.name} (${n})`) return v }) : function<T>(v:T):T{return v} if (n instanceof TemplateInvocation) { return dbgexit(expand(Node, n, env, onerr)) // FIXME restype (Node for now to allow any) } else if (n instanceof TemplateVar) { return dbgexit(expandVar(n, visitChildren)) } return dbgexit(visitChildren(n)) }) // unhide vars tp.vars = vars // template was either not expanded at all, or partially expanded, where the latter // produces a new derivative template, which is what we test for. if (hasUnresolvedTvars) { if (expanded !== tp) { // partially expanded dbg(`partially expanded`) // patch newly-created template to only define unexpanded tvars. // copy & filter scope to only include unexpanded vars expanded.vars = [] expanded._scope = expanded._scope.filter((name, ent) => { let tvar = ent.value as TemplateVar assert(tvar.isTemplateVar(), `non-tvar in template scope: ${tvar}`) if (lookupCache.get(tvar) === tvar) { expanded.vars.push(tvar) return true } return false }) } else { // not expanded at all dbg(`not expanded at all`) } // TODO: consider if it makes sense to allow/support zero expansion. // i.e. TemplateInvocation without args. It may not make sense and we // might be able to simplify some of this code. However, at the moment // we essentially get it for free (no special logic). // return visitChildren(expanded) // maybe we need a second pass..? instanceCache.set(ti.template, ti.args, expanded) return expanded as Template<T> } // if we get here, the template was fully expanded (all tvars were resolved). // this does NOT mean that the expansion result is not a template -- it may very well // be a template, i.e. for templates of templates. assert(expanded !== tp, `${tp} not expanded even though args were provided`) dbg(`fully expanded`) let n = expanded.base as T // check expanded vs restype if (onerr && !(n instanceof restype)) { onerr(`expected ${ti} to expand to ${restype.name} but got ${n.constructor.name}`, ti.pos) } // if we get a struct back, rename it to e.g. "Foo<A,B>". if (n.isStructType()) { let base = tp.bottomBase() if (base !== tp) { // TODO: efficiency of string creation let str = strings.get(utf8.encodeString(`${base}<${ti.args.join(",")}>`)) n.name = new ast.Ident(base.pos, ti._scope, str) } else { // TODO: efficiency of string creation let str = strings.get(utf8.encodeString(`<${ti.args.join(",")}>`)) n.name = new ast.Ident(ti.pos, ti._scope, str) } } // if (n.isType()) { // // erase own type // n.type = null // } instanceCache.set(ti.template, ti.args, n) if (DEBUG_EXPANSION) { ast.print(n) if (ind == "") { process.exit(0) } } return n } // Env holds bindings for a template expansion. // Envs can be nested. // export class Env { outer :Env|null bindings = new Map<TemplateVar,Node>() constructor(outer :Env|null, ti :TemplateInvocation) { this.outer = outer let vars = ti.template.vars let i = 0 for (let z = Math.min(vars.length, ti.args.length); i < z; i++) { let arg :Node = ti.args[i] if (arg.isIdent() && arg.type && arg.type.isTemplateVar()) { arg = arg.type } this.bindings.set(vars[i], arg) } // append default vars after we finish adding explicit args for (; i < vars.length; i++) { let v = vars[i] if (!v.def) { break } this.bindings.set(vars[i], v.def) } } lookup(tv :TemplateVar) :Node|null { let n = this.bindings.get(tv) return n || (this.outer ? this.outer.lookup(tv) : null) } } function validateConstraint(constraint :Node, n :Node) :string|null { // TODO: expand this if (constraint.isType()) { if (n.isType()) { if (!constraint.accepts(n)) { return `Type ${n} does not satisfy the constraint ${constraint}` } } else if (n.isExpr()) { return `${n} (expression of type ${n.type}) does not satisfy the constraint ${constraint}` } else { return `${n} does not satisfy the constraint ${constraint}` } } else { dlog(`TODO: add support for non-type constraints`) } return null } // // IDEA: use memoization when visiting the AST. // // Do some testing to see if this would provide any significant // // performance upside. // // // // This function acts as a substitute for visitChildren: // // visitChildren(n) == memoizedVisit(n, visitChildren) // // // let memo = new Map<Node,Node>() // function memoizedVisit<T extends Node>(n :T, visitChildren :ast.Visitor) :T { // let mn = memo.get(n) // if (mn) { // print(`memo hit ${n.constructor.name}(${n}) -> ${mn.constructor.name}(${mn})`) // return mn as T // } // let n2 = visitChildren(n) // memo.set(n, n2) // if (n !== n2) { // memo.set(n2, n2) // } // return n2 // }
the_stack
// clang-format off import 'chrome://resources/cr_elements/cr_checkbox/cr_checkbox.m.js'; import {AnchorAlignment, CrActionMenuElement} from 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js'; import {CrCheckboxElement} from 'chrome://resources/cr_elements/cr_checkbox/cr_checkbox.m.js'; import {isMac, isWindows} from 'chrome://resources/js/cr.m.js'; import {FocusOutlineManager} from 'chrome://resources/js/cr/ui/focus_outline_manager.m.js'; import {getDeepActiveElement} from 'chrome://resources/js/util.m.js'; import {keyDownOn} from 'chrome://resources/polymer/v3_0/iron-test-helpers/mock-interactions.js'; import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {assertEquals, assertFalse, assertNotEquals, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {eventToPromise, flushTasks} from 'chrome://webui-test/test_util.js'; // clang-format on /** * @fileoverview Tests for cr-action-menu element. Runs as an interactive UI * test, since many of these tests check focus behavior. */ suite('CrActionMenu', function() { let menu: CrActionMenuElement; let dialog: HTMLDialogElement; let items: NodeListOf<HTMLElement>; let dots: HTMLElement; let container: HTMLElement; let checkboxFocusableElement: Element|null = null; setup(function() { FocusOutlineManager.forDocument(document).visible = false; document.body.innerHTML = ` <button id="dots">...</button> <cr-action-menu> <button class="dropdown-item">Un</button> <hr> <button class="dropdown-item">Dos</button> <cr-checkbox class="dropdown-item">Tres</cr-checkbox> </cr-action-menu> `; menu = document.querySelector('cr-action-menu')!; dialog = menu.getDialog(); items = menu.querySelectorAll('.dropdown-item'); checkboxFocusableElement = (items[2] as CrCheckboxElement).getFocusableElement(); dots = document.querySelector('#dots')!; assertEquals(3, items.length); }); teardown(function() { document.body.style.direction = 'ltr'; if (dialog.open) { menu.close(); } }); function down() { keyDownOn(menu, 0, [], 'ArrowDown'); } function up() { keyDownOn(menu, 0, [], 'ArrowUp'); } function enter() { keyDownOn(menu, 0, [], 'Enter'); } test('open-changed event fires', async function() { let whenFired = eventToPromise('open-changed', menu); menu.showAt(dots); let event = await whenFired; assertTrue(event.detail.value); whenFired = eventToPromise('open-changed', menu); menu.close(); event = await whenFired; assertFalse(event.detail.value); }); test('close event bubbles', function() { menu.showAt(dots); const whenFired = eventToPromise('close', menu); menu.close(); return whenFired; }); test('hidden or disabled items', function() { menu.showAt(dots); down(); assertEquals(items[0], getDeepActiveElement()); menu.close(); items[0]!.hidden = true; menu.showAt(dots); down(); assertEquals(items[1], getDeepActiveElement()); menu.close(); (items[1] as HTMLButtonElement).disabled = true; menu.showAt(dots); down(); assertEquals(checkboxFocusableElement, getDeepActiveElement()); }); test('focus after down/up arrow', function() { menu.showAt(dots); // The menu should be focused when shown, but not on any of the items. assertEquals(menu, document.activeElement); assertNotEquals(items[0], getDeepActiveElement()); assertNotEquals(items[1], getDeepActiveElement()); assertNotEquals(checkboxFocusableElement, getDeepActiveElement()); down(); assertEquals(items[0], getDeepActiveElement()); down(); assertEquals(items[1], getDeepActiveElement()); down(); assertEquals(checkboxFocusableElement, getDeepActiveElement()); down(); assertEquals(items[0], getDeepActiveElement()); up(); assertEquals(checkboxFocusableElement, getDeepActiveElement()); up(); assertEquals(items[1], getDeepActiveElement()); up(); assertEquals(items[0], getDeepActiveElement()); up(); assertEquals(checkboxFocusableElement, getDeepActiveElement()); (items[1] as HTMLButtonElement).disabled = true; up(); assertEquals(items[0], getDeepActiveElement()); }); test('focus skips cr-checkbox when disabled or hidden', () => { menu.showAt(dots); const crCheckbox = document.querySelector('cr-checkbox')!; assertEquals(items[2], crCheckbox); // Check checkbox is focusable when not disabled or hidden. down(); assertEquals(items[0], getDeepActiveElement()); down(); assertEquals(items[1], getDeepActiveElement()); down(); assertEquals(checkboxFocusableElement, getDeepActiveElement()); // Check checkbox is not focusable when either disabled or hidden. ([ [false, true], [true, false], [true, true], ] as [boolean, boolean][]) .forEach(([disabled, hidden]) => { crCheckbox.disabled = disabled; crCheckbox.hidden = hidden; (getDeepActiveElement() as HTMLElement).blur(); down(); assertEquals(items[0], getDeepActiveElement()); down(); assertEquals(items[1], getDeepActiveElement()); down(); assertEquals(items[0], getDeepActiveElement()); }); }); test('pressing up arrow when no focus will focus last item', function() { menu.showAt(dots); assertEquals(menu, document.activeElement); up(); assertEquals(checkboxFocusableElement, getDeepActiveElement()); }); test('pressing enter when no focus', function() { if (isWindows || isMac) { return testFocusAfterClosing('Enter'); } // First item is selected menu.showAt(dots); assertEquals(menu, document.activeElement); enter(); assertEquals(items[0], getDeepActiveElement()); return; }); test('pressing enter when when item has focus', function() { menu.showAt(dots); down(); enter(); assertEquals(items[0], getDeepActiveElement()); }); test('can navigate to dynamically added items', async function() { // Can modify children after attached() and before showAt(). const item = document.createElement('button'); item.classList.add('dropdown-item'); menu.insertBefore(item, items[0]!); menu.showAt(dots); await flushTasks(); down(); assertEquals(item, getDeepActiveElement()); down(); assertEquals(items[0], getDeepActiveElement()); // Can modify children while menu is open. menu.removeChild(item); up(); // Focus should have wrapped around to final item. assertEquals(checkboxFocusableElement, getDeepActiveElement()); }); test('close on click away', function() { menu.showAt(dots); assertTrue(dialog.open); menu.click(); assertFalse(dialog.open); }); test('close on resize', function() { menu.showAt(dots); assertTrue(dialog.open); window.dispatchEvent(new CustomEvent('resize')); assertFalse(dialog.open); }); test('close on popstate', function() { menu.showAt(dots); assertTrue(dialog.open); window.dispatchEvent(new CustomEvent('popstate')); assertFalse(dialog.open); }); /** @param key The key to use for closing. */ function testFocusAfterClosing(key: string): Promise<void> { return new Promise<void>(function(resolve) { menu.showAt(dots); assertTrue(dialog.open); let anchorHasFocus = false; let tabkeyCloseEventFired = false; const checkTestDone = () => { assertFalse(dialog.open); if (key !== 'Tab') { resolve(); } else if (anchorHasFocus && tabkeyCloseEventFired) { resolve(); } }; // Check that focus returns to the anchor element. dots.addEventListener('focus', () => { anchorHasFocus = true; checkTestDone(); }); // Check that a Tab key close fires a custom event. menu.addEventListener('tabkeyclose', () => { tabkeyCloseEventFired = true; checkTestDone(); }); keyDownOn(menu, 0, [], key); }); } test('close on Tab', () => testFocusAfterClosing('Tab')); test('close on Escape', () => testFocusAfterClosing('Escape')); function dispatchMouseoverEvent(eventTarget: EventTarget) { eventTarget.dispatchEvent(new MouseEvent('mouseover', {bubbles: true})); } test('moving mouse on option 1 should focus it', () => { menu.showAt(dots); assertNotEquals(items[0], getDeepActiveElement()); dispatchMouseoverEvent(items[0]!); assertEquals(items[0], getDeepActiveElement()); }); test('moving mouse on the menu (not on option) should focus the menu', () => { menu.showAt(dots); items[0]!.focus(); dispatchMouseoverEvent(menu); assertEquals(dialog.querySelector('[role="menu"]'), getDeepActiveElement()); }); test('moving mouse on a disabled item should focus the menu', () => { menu.showAt(dots); items[2]!.toggleAttribute('disabled', true); items[0]!.focus(); dispatchMouseoverEvent(items[2]!); assertEquals(dialog.querySelector('[role="menu"]'), getDeepActiveElement()); }); test('mouse movements should override keyboard focus', () => { menu.showAt(dots); items[0]!.focus(); down(); assertEquals(items[1], getDeepActiveElement()); dispatchMouseoverEvent(items[0]!); assertEquals(items[0], getDeepActiveElement()); }); test('items automatically given accessibility role', async function() { const newItem = document.createElement('button'); newItem.classList.add('dropdown-item'); items[1]!.setAttribute('role', 'checkbox'); menu.showAt(dots); await flushTasks(); assertEquals('menuitem', items[0]!.getAttribute('role')); assertEquals('checkbox', items[1]!.getAttribute('role')); menu.insertBefore(newItem, items[0]!); await flushTasks(); assertEquals('menuitem', newItem.getAttribute('role')); }); test('positioning', function() { // A 40x10 box at (100, 250). const config = { left: 100, top: 250, width: 40, height: 10, maxX: 1000, maxY: 2000, }; // Show right and bottom aligned by default. menu.showAtPosition(config); assertTrue(dialog.open); assertEquals('100px', dialog.style.left); assertEquals('250px', dialog.style.top); menu.close(); // Center the menu horizontally. menu.showAtPosition(Object.assign({}, config, { anchorAlignmentX: AnchorAlignment.CENTER, })); const menuWidth = dialog.offsetWidth; const menuHeight = dialog.offsetHeight; assertEquals(`${120 - menuWidth / 2}px`, dialog.style.left); assertEquals('250px', dialog.style.top); menu.close(); // Center the menu in both axes. menu.showAtPosition(Object.assign({}, config, { anchorAlignmentX: AnchorAlignment.CENTER, anchorAlignmentY: AnchorAlignment.CENTER, })); assertEquals(`${120 - menuWidth / 2}px`, dialog.style.left); assertEquals(`${255 - menuHeight / 2}px`, dialog.style.top); menu.close(); // Left and top align the menu. menu.showAtPosition(Object.assign({}, config, { anchorAlignmentX: AnchorAlignment.BEFORE_END, anchorAlignmentY: AnchorAlignment.BEFORE_END, })); assertEquals(`${140 - menuWidth}px`, dialog.style.left); assertEquals(`${260 - menuHeight}px`, dialog.style.top); menu.close(); // Being left and top aligned at (0, 0) should anchor to the bottom right. menu.showAtPosition(Object.assign({}, config, { anchorAlignmentX: AnchorAlignment.BEFORE_END, anchorAlignmentY: AnchorAlignment.BEFORE_END, left: 0, top: 0, })); assertEquals(`0px`, dialog.style.left); assertEquals(`0px`, dialog.style.top); menu.close(); // Being aligned to a point in the bottom right should anchor to the top // left. menu.showAtPosition({ left: 1000, top: 2000, maxX: 1000, maxY: 2000, }); assertEquals(`${1000 - menuWidth}px`, dialog.style.left); assertEquals(`${2000 - menuHeight}px`, dialog.style.top); menu.close(); // If the viewport can't fit the menu, align the menu to the viewport. menu.showAtPosition({ left: menuWidth - 5, top: 0, width: 0, height: 0, maxX: menuWidth * 2 - 10, }); assertEquals(`${menuWidth - 10}px`, dialog.style.left); assertEquals(`0px`, dialog.style.top); menu.close(); // Alignment is reversed in RTL. document.body.style.direction = 'rtl'; menu.showAtPosition(config); assertTrue(dialog.open); assertEquals(140 - menuWidth, dialog.offsetLeft); assertEquals('250px', dialog.style.top); menu.close(); }); (function() { // TODO(dpapad): fix flakiness and re-enable this test. test.skip( '[auto-reposition] enables repositioning if content changes', function(done) { menu.autoReposition = true; dots.style.marginLeft = '800px'; const dotsRect = dots.getBoundingClientRect(); // Anchored at right-top by default. menu.showAt(dots); assertTrue(dialog.open); let menuRect = menu.getBoundingClientRect(); assertEquals( Math.round(dotsRect.left + dotsRect.width), Math.round(menuRect.left + menuRect.width)); assertEquals(dotsRect.top, menuRect.top); const lastMenuLeft = menuRect.left; const lastMenuWidth = menuRect.width; menu.addEventListener('cr-action-menu-repositioned', () => { assertTrue(dialog.open); menuRect = menu.getBoundingClientRect(); // Test that menu width got larger. assertTrue(menuRect.width > lastMenuWidth); // Test that menu upper-left moved further left. assertTrue(menuRect.left < lastMenuLeft); // Test that right and top did not move since it is anchored there. assertEquals( Math.round(dotsRect.left + dotsRect.width), Math.round(menuRect.left + menuRect.width)); assertEquals(dotsRect.top, menuRect.top); done(); }); // Still anchored at the right place after content size changes. items[0]!.textContent = 'this is a long string to make menu wide'; }); })(); suite('offscreen scroll positioning', function() { const bodyHeight = 10000; const bodyWidth = 20000; const containerLeft = 5000; const containerTop = 10000; const containerWidth = 500; suiteSetup(function() { Polymer({ is: 'test-element', _template: html` <style> #container { overflow: auto; position: absolute; top: 10000px; /* containerTop */ left: 5000px; /* containerLeft */ right: 5000px; /* containerLeft */ height: 500px; /* containerWidth */ width: 500px; /* containerWidth */ } #inner-container { height: 1000px; width: 1000px; } </style> <div id="container"> <div id="inner-container"> <button id="dots">...</button> <cr-action-menu> <button class="dropdown-item">Un</button> <hr> <button class="dropdown-item">Dos</button> <button class="dropdown-item">Tres</button> </cr-action-menu> </div> </div> `, }); }); setup(function() { document.body.scrollTop = 0; document.body.scrollLeft = 0; document.body.innerHTML = ` <style> test-element { height: ${bodyHeight}px; width: ${bodyWidth}px; } </style> <test-element></test-element>`; const testElement = document.querySelector('test-element')!; menu = testElement.shadowRoot!.querySelector('cr-action-menu')!; dialog = menu.getDialog(); dots = testElement.shadowRoot!.querySelector('#dots')!; container = testElement.shadowRoot!.querySelector('#container')!; }); // Show the menu, scrolling the body to the button. test('simple offscreen', function() { menu.showAt(dots, {anchorAlignmentX: AnchorAlignment.AFTER_START}); assertEquals(`${containerLeft}px`, dialog.style.left); assertEquals(`${containerTop}px`, dialog.style.top); menu.close(); }); // Show the menu, scrolling the container to the button, and the body to the // button. test('offscreen and out of scroll container viewport', function() { document.body.scrollLeft = bodyWidth; document.body.scrollTop = bodyHeight; container.scrollLeft = containerLeft; container.scrollTop = containerTop; menu.showAt(dots, {anchorAlignmentX: AnchorAlignment.AFTER_START}); assertEquals(`${containerLeft}px`, dialog.style.left); assertEquals(`${containerTop}px`, dialog.style.top); menu.close(); }); // Show the menu for an already onscreen button. The anchor should be // overridden so that no scrolling happens. test('onscreen forces anchor change', function() { const rect = dots.getBoundingClientRect(); document.documentElement.scrollLeft = rect.right - document.documentElement.clientWidth + 10; document.documentElement.scrollTop = rect.bottom - document.documentElement.clientHeight + 10; menu.showAt(dots, {anchorAlignmentX: AnchorAlignment.AFTER_START}); const buttonWidth = dots.offsetWidth; const buttonHeight = dots.offsetHeight; const menuWidth = dialog.offsetWidth; const menuHeight = dialog.offsetHeight; assertEquals(containerLeft - menuWidth + buttonWidth, dialog.offsetLeft); assertEquals(containerTop - menuHeight + buttonHeight, dialog.offsetTop); menu.close(); }); test('scroll position maintained for showAtPosition', function() { document.documentElement.scrollLeft = 500; document.documentElement.scrollTop = 1000; menu.showAtPosition({top: 50, left: 50}); assertEquals(550, dialog.offsetLeft); assertEquals(1050, dialog.offsetTop); menu.close(); }); test('rtl', function() { // Anchor to an item in RTL. document.body.style.direction = 'rtl'; menu.showAt(dots, {anchorAlignmentX: AnchorAlignment.AFTER_START}); const menuWidth = dialog.offsetWidth; assertEquals( container.offsetLeft + containerWidth - menuWidth, dialog.offsetLeft); assertEquals(containerTop, dialog.offsetTop); menu.close(); }); test('FocusFirstItemWhenOpenedWithKeyboard', async () => { FocusOutlineManager.forDocument(document).visible = true; menu.showAtPosition({top: 50, left: 50}); await new Promise(resolve => requestAnimationFrame(resolve)); assertEquals( menu.querySelector('.dropdown-item'), getDeepActiveElement()); }); }); });
the_stack
import 'chrome://print/print_preview.js'; import {PagesValue, PrintPreviewPagesSettingsElement, Range} from 'chrome://print/print_preview.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {keyEventOn} from 'chrome://resources/polymer/v3_0/iron-test-helpers/mock-interactions.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {eventToPromise, fakeDataBind} from 'chrome://webui-test/test_util.js'; import {selectOption, triggerInputEvent} from './print_preview_test_utils.js'; const pages_settings_test = { suiteName: 'PagesSettingsTest', TestNames: { PagesDropdown: 'pages dropdown', NoParityOptions: 'no parity options', ParitySelectionMemorized: 'parity selection memorized', ValidPageRanges: 'valid page ranges', InvalidPageRanges: 'invalid page ranges', NupChangesPages: 'nup changes pages', ClearInput: 'clear input', InputNotDisabledOnValidityChange: 'input not disabled on validity change', EnterOnInputTriggersPrint: 'enter on input triggers print', }, }; Object.assign(window, {pages_settings_test: pages_settings_test}); suite(pages_settings_test.suiteName, function() { let pagesSection: PrintPreviewPagesSettingsElement; const oneToHundred: number[] = Array.from({length: 100}, (_x, i) => i + 1); const limitError: string = 'Out of bounds page reference, limit is '; setup(function() { document.body.innerHTML = ''; const model = document.createElement('print-preview-model'); document.body.appendChild(model); pagesSection = document.createElement('print-preview-pages-settings'); pagesSection.settings = model.settings; pagesSection.disabled = false; fakeDataBind(model, pagesSection, 'settings'); document.body.appendChild(pagesSection); }); /** * @param inputString The input value to set. * @return Promise that resolves when the input has been set and * the input-change event has fired. */ function setCustomInput(inputString: string): Promise<void> { const pagesInput = pagesSection.$.pageSettingsCustomInput.inputElement; return triggerInputEvent(pagesInput, inputString, pagesSection); } /** * @param expectedPages The expected pages value. * @param expectedPages The expected pages value. * @param expectedError The expected error message. * @param invalid Whether the pages setting should be invalid. */ function validateState( expectedPages: number[], expectedRanges: Range[], expectedError: string, invalid: boolean) { const pagesValue = pagesSection.getSettingValue('pages'); assertEquals(expectedPages.length, pagesValue.length); expectedPages.forEach((page: number, index: number) => { assertEquals(page, pagesValue[index]); }); const rangesValue = pagesSection.getSettingValue('ranges'); assertEquals(expectedRanges.length, rangesValue.length); expectedRanges.forEach((range: Range, index: number) => { assertEquals(range.to, rangesValue[index].to); assertEquals(range.from, rangesValue[index].from); }); assertEquals(!invalid, pagesSection.getSetting('pages').valid); assertEquals( expectedError !== '', pagesSection.shadowRoot!.querySelector('cr-input')!.invalid); assertEquals( expectedError, pagesSection.shadowRoot!.querySelector('cr-input')!.errorMessage); } // Verifies that the pages setting updates correctly when the dropdown // changes. test(assert(pages_settings_test.TestNames.PagesDropdown), async () => { pagesSection.pageCount = 5; // Default value is all pages. const customInputCollapse = pagesSection.shadowRoot!.querySelector('iron-collapse')!; assertFalse(pagesSection.getSetting('ranges').setFromUi); validateState([1, 2, 3, 4, 5], [], '', false); assertFalse(customInputCollapse.opened); // Set selection to odd pages. await selectOption(pagesSection, PagesValue.ODDS.toString()); assertFalse(customInputCollapse.opened); validateState( [1, 3, 5], [{from: 1, to: 1}, {from: 3, to: 3}, {from: 5, to: 5}], '', false); // Set selection to even pages. await selectOption(pagesSection, PagesValue.EVENS.toString()); assertFalse(customInputCollapse.opened); validateState([2, 4], [{from: 2, to: 2}, {from: 4, to: 4}], '', false); // Set selection of pages 1 and 2. await selectOption(pagesSection, PagesValue.CUSTOM.toString()); assertTrue(customInputCollapse.opened); await setCustomInput('1-2'); validateState([1, 2], [{from: 1, to: 2}], '', false); assertTrue(pagesSection.getSetting('ranges').setFromUi); // Re-select "all". await selectOption(pagesSection, PagesValue.ALL.toString()); assertFalse(customInputCollapse.opened); validateState([1, 2, 3, 4, 5], [], '', false); // Re-select custom. The previously entered value should be // restored. await selectOption(pagesSection, PagesValue.CUSTOM.toString()); assertTrue(customInputCollapse.opened); validateState([1, 2], [{from: 1, to: 2}], '', false); // Set a selection equal to the full page range. This should set ranges to // empty, so that reselecting "all" does not regenerate the preview. await setCustomInput('1-5'); validateState([1, 2, 3, 4, 5], [], '', false); }); // Tests that the odd-only and even-only options are hidden when the document // has only one page. test(assert(pages_settings_test.TestNames.NoParityOptions), async () => { pagesSection.pageCount = 1; const oddOption = pagesSection.shadowRoot!.querySelector<HTMLOptionElement>( `[value="${PagesValue.ODDS}"]`)!; assertTrue(oddOption.hidden); const evenOption = pagesSection.shadowRoot!.querySelector<HTMLOptionElement>( `[value="${PagesValue.EVENS}"]`)!; assertTrue(evenOption.hidden); }); // Tests that the odd-only and even-only selections are preserved when the // page counts change. test( assert(pages_settings_test.TestNames.ParitySelectionMemorized), async () => { const select = pagesSection.shadowRoot!.querySelector('select')!; pagesSection.pageCount = 2; assertEquals(PagesValue.ALL.toString(), select.value); await selectOption(pagesSection, PagesValue.ODDS.toString()); assertEquals(PagesValue.ODDS.toString(), select.value); let whenValueChanged = eventToPromise('process-select-change', pagesSection); pagesSection.pageCount = 1; await whenValueChanged; assertEquals(PagesValue.ALL.toString(), select.value); whenValueChanged = eventToPromise('process-select-change', pagesSection); pagesSection.pageCount = 2; await whenValueChanged; assertEquals(PagesValue.ODDS.toString(), select.value); }); // Tests that the page ranges set are valid for different user inputs. test(assert(pages_settings_test.TestNames.ValidPageRanges), async () => { pagesSection.pageCount = 100; const tenToHundred = Array.from({length: 91}, (_x, i) => i + 10); await selectOption(pagesSection, PagesValue.CUSTOM.toString()); await setCustomInput('1, 2, 3, 1, 56'); validateState( [1, 2, 3, 56], [{from: 1, to: 3}, {from: 56, to: 56}], '', false); await setCustomInput('1-3, 6-9, 6-10'); validateState( [1, 2, 3, 6, 7, 8, 9, 10], [{from: 1, to: 3}, {from: 6, to: 10}], '', false); await setCustomInput('10-'); validateState(tenToHundred, [{from: 10, to: 100}], '', false); await setCustomInput('10-100'); validateState(tenToHundred, [{from: 10, to: 100}], '', false); await setCustomInput('-'); validateState(oneToHundred, [], '', false); // https://crbug.com/806165 await setCustomInput('1\u30012\u30013\u30011\u300156'); validateState( [1, 2, 3, 56], [{from: 1, to: 3}, {from: 56, to: 56}], '', false); await setCustomInput('1,2,3\u30011\u300156'); validateState( [1, 2, 3, 56], [{from: 1, to: 3}, {from: 56, to: 56}], '', false); // https://crbug.com/1015145 // Tests that the pages gets sorted for an unsorted input. await setCustomInput('89-91, 3, 6, 46, 1, 4, 2-3'); validateState( [1, 2, 3, 4, 6, 46, 89, 90, 91], [ {from: 1, to: 4}, {from: 6, to: 6}, {from: 46, to: 46}, {from: 89, to: 91} ], '', false); }); // Tests that the correct error messages are shown for different user // inputs. test(assert(pages_settings_test.TestNames.InvalidPageRanges), async () => { pagesSection.pageCount = 100; const syntaxError = 'Invalid page range, use e.g. 1-5, 8, 11-13'; await selectOption(pagesSection, PagesValue.CUSTOM.toString()); await setCustomInput('10-100000'); validateState(oneToHundred, [], limitError + '100', true); await setCustomInput('1, 2, 0, 56'); validateState(oneToHundred, [], syntaxError, true); await setCustomInput('-1, 1, 2,, 56'); validateState(oneToHundred, [], syntaxError, true); await setCustomInput('1,2,56-40'); validateState(oneToHundred, [], syntaxError, true); await setCustomInput('101-110'); validateState(oneToHundred, [], limitError + '100', true); await setCustomInput('1\u30012\u30010\u300156'); validateState(oneToHundred, [], syntaxError, true); await setCustomInput('-1,1,2\u3001\u300156'); validateState(oneToHundred, [], syntaxError, true); await setCustomInput('--'); validateState(oneToHundred, [], syntaxError, true); await setCustomInput(' 1 1 '); validateState(oneToHundred, [], syntaxError, true); }); // Tests that the pages are set correctly for different values of pages per // sheet, and that ranges remain fixed (since they are used for generating // the print preview ticket). test(assert(pages_settings_test.TestNames.NupChangesPages), async () => { pagesSection.pageCount = 100; await selectOption(pagesSection, PagesValue.CUSTOM.toString()); await setCustomInput('1, 2, 3, 1, 56'); let expectedRanges = [{from: 1, to: 3}, {from: 56, to: 56}]; validateState([1, 2, 3, 56], expectedRanges, '', false); pagesSection.setSetting('pagesPerSheet', 2); validateState([1, 2], expectedRanges, '', false); pagesSection.setSetting('pagesPerSheet', 4); validateState([1], expectedRanges, '', false); pagesSection.setSetting('pagesPerSheet', 1); await setCustomInput('1-3, 6-9, 6-10'); expectedRanges = [{from: 1, to: 3}, {from: 6, to: 10}]; validateState([1, 2, 3, 6, 7, 8, 9, 10], expectedRanges, '', false); pagesSection.setSetting('pagesPerSheet', 2); validateState([1, 2, 3, 4], expectedRanges, '', false); pagesSection.setSetting('pagesPerSheet', 3); validateState([1, 2, 3], expectedRanges, '', false); await setCustomInput('1-3'); expectedRanges = [{from: 1, to: 3}]; validateState([1], expectedRanges, '', false); pagesSection.setSetting('pagesPerSheet', 1); validateState([1, 2, 3], expectedRanges, '', false); }); // Note: Remaining tests in this file are interactive_ui_tests, and validate // some focus related behavior. // Tests that the clearing a valid input has no effect, clearing an invalid // input does not show an error message but does not reset the preview, and // changing focus from an empty input in either case fills in the dropdown // with the full page range. test(assert(pages_settings_test.TestNames.ClearInput), async () => { pagesSection.pageCount = 3; const input = pagesSection.$.pageSettingsCustomInput.inputElement; const select = pagesSection.shadowRoot!.querySelector('select')!; const allValue = PagesValue.ALL.toString(); const customValue = PagesValue.CUSTOM.toString(); assertEquals(allValue, select.value); // Selecting custom focuses the input. await Promise.all([ selectOption(pagesSection, customValue), eventToPromise('focus', input) ]); input.focus(); await setCustomInput('1-2'); assertEquals(customValue, select.value); validateState([1, 2], [{from: 1, to: 2}], '', false); await setCustomInput(''); assertEquals(customValue, select.value); validateState([1, 2], [{from: 1, to: 2}], '', false); let whenBlurred = eventToPromise('blur', input); input.blur(); await whenBlurred; // Blurring a blank field sets the full page range. assertEquals(customValue, select.value); validateState([1, 2, 3], [], '', false); assertEquals('1-3', input.value); input.focus(); await setCustomInput('5'); assertEquals(customValue, select.value); // Invalid input doesn't change the preview. validateState([1, 2, 3], [], limitError + '3', true); await setCustomInput(''); assertEquals(customValue, select.value); validateState([1, 2, 3], [], '', false); whenBlurred = eventToPromise('blur', input); input.blur(); // Blurring an invalid value that has been cleared should reset the // value to all pages. await whenBlurred; assertEquals(customValue, select.value); validateState([1, 2, 3], [], '', false); assertEquals('1-3', input.value); // Re-focus and clear the input and then select "All" in the // dropdown. input.focus(); await setCustomInput(''); select.focus(); await selectOption(pagesSection, allValue); flush(); assertEquals(allValue, select.value); validateState([1, 2, 3], [], '', false); // Reselect custom. This should focus the input. await Promise.all([ selectOption(pagesSection, customValue), eventToPromise('focus', input), ]); // Input has been cleared. assertEquals('', input.value); validateState([1, 2, 3], [], '', false); whenBlurred = eventToPromise('blur', input); input.blur(); await whenBlurred; assertEquals('1-3', input.value); // Change the page count. Since the range was set automatically, this // should reset it to the new set of all pages. pagesSection.pageCount = 2; validateState([1, 2], [], '', false); assertEquals('1-2', input.value); }); // Verifies that the input is never disabled when the validity of the // setting changes. test( assert(pages_settings_test.TestNames.InputNotDisabledOnValidityChange), async () => { pagesSection.pageCount = 3; // In the real UI, the print preview app listens for this event from // this section and others and sets disabled to true if any change from // true to false is detected. Imitate this here. Since we are only // interacting with the pages input, at no point should the input be // disabled, as it will lose focus. pagesSection.addEventListener('setting-valid-changed', function(e) { assertFalse(pagesSection.$.pageSettingsCustomInput.disabled); pagesSection.set('disabled', !(e as CustomEvent<boolean>).detail); assertFalse(pagesSection.$.pageSettingsCustomInput.disabled); }); await selectOption(pagesSection, PagesValue.CUSTOM.toString()); await setCustomInput('1'); validateState([1], [{from: 1, to: 1}], '', false); await setCustomInput('12'); validateState([1], [{from: 1, to: 1}], limitError + '3', true); // Restore valid input await setCustomInput('1'); validateState([1], [{from: 1, to: 1}], '', false); // Invalid input again await setCustomInput('8'); validateState([1], [{from: 1, to: 1}], limitError + '3', true); // Clear input await setCustomInput(''); validateState([1], [{from: 1, to: 1}], '', false); // Set valid input await setCustomInput('2'); validateState([2], [{from: 2, to: 2}], '', false); }); // Verifies that the enter key event is bubbled to the pages settings // element, so that it will be bubbled to the print preview app to trigger a // print. test( assert(pages_settings_test.TestNames.EnterOnInputTriggersPrint), async () => { pagesSection.pageCount = 3; const input = pagesSection.$.pageSettingsCustomInput.inputElement; const whenPrintReceived = eventToPromise('keydown', pagesSection); // Setup an empty input by selecting custom.. const customValue = PagesValue.CUSTOM.toString(); const pagesSelect = pagesSection.shadowRoot!.querySelector('select')!; await Promise.all([ selectOption(pagesSection, customValue), eventToPromise('focus', input) ]); assertEquals(customValue, pagesSelect.value); keyEventOn(input, 'keydown', 0, [], 'Enter'); await whenPrintReceived; // Keep custom selected, but pages to print should still be all. assertEquals(customValue, pagesSelect.value); validateState([1, 2, 3], [], '', false); // Select a custom input of 1. await setCustomInput('1'); assertEquals(customValue, pagesSelect.value); const whenSecondPrintReceived = eventToPromise('keydown', pagesSection); keyEventOn(input, 'keydown', 0, [], 'Enter'); await whenSecondPrintReceived; assertEquals(customValue, pagesSelect.value); validateState([1], [{from: 1, to: 1}], '', false); }); });
the_stack
module android.text { import Paint = android.graphics.Paint; import UpdateLayout = android.text.style.UpdateLayout; import WrapTogetherSpan = android.text.style.WrapTogetherSpan; import WeakReference = java.lang.ref.WeakReference; import System = java.lang.System; import Layout = android.text.Layout; import PackedIntVector = android.text.PackedIntVector; import PackedObjectVector = android.text.PackedObjectVector; import Spannable = android.text.Spannable; import Spanned = android.text.Spanned; import StaticLayout = android.text.StaticLayout; import TextDirectionHeuristic = android.text.TextDirectionHeuristic; import TextDirectionHeuristics = android.text.TextDirectionHeuristics; import TextPaint = android.text.TextPaint; import TextUtils = android.text.TextUtils; import TextWatcher = android.text.TextWatcher; /** * DynamicLayout is a text layout that updates itself as the text is edited. * <p>This is used by widgets to control text layout. You should not need * to use this class directly unless you are implementing your own widget * or custom display object, or need to call * {@link android.graphics.Canvas#drawText(java.lang.CharSequence, int, int, float, float, android.graphics.Paint) * Canvas.drawText()} directly.</p> */ export class DynamicLayout extends Layout { private static PRIORITY:number = 128; private static BLOCK_MINIMUM_CHARACTER_LENGTH:number = 400; /** * Make a layout for the transformed text (password transformation * being the primary example of a transformation) * that will be updated as the base text is changed. * If ellipsize is non-null, the Layout will ellipsize the text * down to ellipsizedWidth. * * * *@hide */ constructor( base:String, display:String, paint:TextPaint, width:number, align:Layout.Alignment, textDir:TextDirectionHeuristic, spacingmult:number, spacingadd:number, includepad:boolean, ellipsize:TextUtils.TruncateAt=null, ellipsizedWidth=0) { super((ellipsize == null) ? display : (Spanned.isImplements(display)) ? new Layout.SpannedEllipsizer(display) : new Layout.Ellipsizer(display), paint, width, align, textDir, spacingmult, spacingadd); this.mBase = base; this.mDisplay = display; if (ellipsize != null) { this.mInts = new PackedIntVector(DynamicLayout.COLUMNS_ELLIPSIZE); this.mEllipsizedWidth = ellipsizedWidth; this.mEllipsizeAt = ellipsize; } else { this.mInts = new PackedIntVector(DynamicLayout.COLUMNS_NORMAL); this.mEllipsizedWidth = width; this.mEllipsizeAt = null; } this.mObjects = new PackedObjectVector<Layout.Directions>(1); this.mIncludePad = includepad; /* * This is annoying, but we can't refer to the layout until * superclass construction is finished, and the superclass * constructor wants the reference to the display text. * * This will break if the superclass constructor ever actually * cares about the content instead of just holding the reference. */ if (ellipsize != null) { let e:Layout.Ellipsizer = <Layout.Ellipsizer> this.getText(); e.mLayout = this; e.mWidth = ellipsizedWidth; e.mMethod = ellipsize; this.mEllipsize = true; } // Initial state is a single line with 0 characters (0 to 0), // with top at 0 and bottom at whatever is natural, and // undefined ellipsis. let start:number[]; if (ellipsize != null) { start = androidui.util.ArrayCreator.newNumberArray(DynamicLayout.COLUMNS_ELLIPSIZE); start[DynamicLayout.ELLIPSIS_START] = DynamicLayout.ELLIPSIS_UNDEFINED; } else { start = androidui.util.ArrayCreator.newNumberArray(DynamicLayout.COLUMNS_NORMAL); } let dirs:Layout.Directions[] = [ DynamicLayout.DIRS_ALL_LEFT_TO_RIGHT ]; let fm = new Paint.FontMetricsInt(); paint.getFontMetricsInt(fm); let asc:number = fm.ascent; let desc:number = fm.descent; start[DynamicLayout.DIR] = DynamicLayout.DIR_LEFT_TO_RIGHT << DynamicLayout.DIR_SHIFT; start[DynamicLayout.TOP] = 0; start[DynamicLayout.DESCENT] = desc; this.mInts.insertAt(0, start); start[DynamicLayout.TOP] = desc - asc; this.mInts.insertAt(1, start); this.mObjects.insertAt(0, dirs); // Update from 0 characters to whatever the real text is this.reflow(base, 0, 0, base.length); //if (base instanceof Spannable) { // if (this.mWatcher == null) // this.mWatcher = new DynamicLayout.ChangeWatcher(this); // // Strip out any watchers for other DynamicLayouts. // let sp:Spannable = <Spannable> base; // let spans:DynamicLayout.ChangeWatcher[] = sp.getSpans(0, sp.length(), DynamicLayout.ChangeWatcher.class); // for (let i:number = 0; i < spans.length; i++) sp.removeSpan(spans[i]); // sp.setSpan(this.mWatcher, 0, base.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE | (DynamicLayout.PRIORITY << Spannable.SPAN_PRIORITY_SHIFT)); //} } private reflow(s:String, where:number, before:number, after:number):void { if (s != this.mBase) return; let text:String = this.mDisplay; let len:number = text.length; // seek back to the start of the paragraph let find:number = text.lastIndexOf('\n', where - 1); if (find < 0) find = 0; else find = find + 1; { let diff:number = where - find; before += diff; after += diff; where -= diff; } // seek forward to the end of the paragraph let look:number = text.indexOf('\n', where + after); if (look < 0) look = len; else // we want the index after the \n look++; let change:number = look - (where + after); before += change; after += change; //if (Spanned.isImplements(text)) { // let sp:Spanned = <Spanned> text; // let again:boolean; // do { // again = false; // let force:any[] = sp.getSpans(where, where + after, WrapTogetherSpan.class); // for (let i:number = 0; i < force.length; i++) { // let st:number = sp.getSpanStart(force[i]); // let en:number = sp.getSpanEnd(force[i]); // if (st < where) { // again = true; // let diff:number = where - st; // before += diff; // after += diff; // where -= diff; // } // if (en > where + after) { // again = true; // let diff:number = en - (where + after); // before += diff; // after += diff; // } // } // } while (again); //} // find affected region of old layout let startline:number = this.getLineForOffset(where); let startv:number = this.getLineTop(startline); let endline:number = this.getLineForOffset(where + before); if (where + after == len) endline = this.getLineCount(); let endv:number = this.getLineTop(endline); let islast:boolean = (endline == this.getLineCount()); // generate new layout for affected text let reflowed:StaticLayout; { reflowed = DynamicLayout.sStaticLayout; DynamicLayout.sStaticLayout = null; } if (reflowed == null) { reflowed = new StaticLayout(null, 0, 0, null, 0, null, null, 0, 1, true); } else { reflowed.prepare(); } reflowed.generate(text, where, where + after, this.getPaint(), this.getWidth(), this.getTextDirectionHeuristic(), this.getSpacingMultiplier(), this.getSpacingAdd(), false, true, this.mEllipsizedWidth, this.mEllipsizeAt); let n:number = reflowed.getLineCount(); if (where + after != len && reflowed.getLineStart(n - 1) == where + after) n--; // remove affected lines from old layout this.mInts.deleteAt(startline, endline - startline); this.mObjects.deleteAt(startline, endline - startline); // adjust offsets in layout for new height and offsets let ht:number = reflowed.getLineTop(n); let toppad:number = 0, botpad:number = 0; if (this.mIncludePad && startline == 0) { toppad = reflowed.getTopPadding(); this.mTopPadding = toppad; ht -= toppad; } if (this.mIncludePad && islast) { botpad = reflowed.getBottomPadding(); this.mBottomPadding = botpad; ht += botpad; } this.mInts.adjustValuesBelow(startline, DynamicLayout.START, after - before); this.mInts.adjustValuesBelow(startline, DynamicLayout.TOP, startv - endv + ht); // insert new layout let ints:number[]; if (this.mEllipsize) { ints = androidui.util.ArrayCreator.newNumberArray(DynamicLayout.COLUMNS_ELLIPSIZE); ints[DynamicLayout.ELLIPSIS_START] = DynamicLayout.ELLIPSIS_UNDEFINED; } else { ints = androidui.util.ArrayCreator.newNumberArray(DynamicLayout.COLUMNS_NORMAL); } let objects:Layout.Directions[] = new Array<Layout.Directions>(1); for (let i:number = 0; i < n; i++) { ints[DynamicLayout.START] = reflowed.getLineStart(i) | (reflowed.getParagraphDirection(i) << DynamicLayout.DIR_SHIFT) | (reflowed.getLineContainsTab(i) ? DynamicLayout.TAB_MASK : 0); let top:number = reflowed.getLineTop(i) + startv; if (i > 0) top -= toppad; ints[DynamicLayout.TOP] = top; let desc:number = reflowed.getLineDescent(i); if (i == n - 1) desc += botpad; ints[DynamicLayout.DESCENT] = desc; objects[0] = reflowed.getLineDirections(i); if (this.mEllipsize) { ints[DynamicLayout.ELLIPSIS_START] = reflowed.getEllipsisStart(i); ints[DynamicLayout.ELLIPSIS_COUNT] = reflowed.getEllipsisCount(i); } this.mInts.insertAt(startline + i, ints); this.mObjects.insertAt(startline + i, objects); } this.updateBlocks(startline, endline - 1, n); { DynamicLayout.sStaticLayout = reflowed; reflowed.finish(); } } /** * Create the initial block structure, cutting the text into blocks of at least * BLOCK_MINIMUM_CHARACTER_SIZE characters, aligned on the ends of paragraphs. */ private createBlocks():void { let offset:number = DynamicLayout.BLOCK_MINIMUM_CHARACTER_LENGTH; this.mNumberOfBlocks = 0; const text:String = this.mDisplay; while (true) { offset = text.indexOf('\n', offset); if (offset < 0) { this.addBlockAtOffset(text.length); break; } else { this.addBlockAtOffset(offset); offset += DynamicLayout.BLOCK_MINIMUM_CHARACTER_LENGTH; } } // mBlockIndices and mBlockEndLines should have the same length this.mBlockIndices = androidui.util.ArrayCreator.newNumberArray(this.mBlockEndLines.length); for (let i:number = 0; i < this.mBlockEndLines.length; i++) { this.mBlockIndices[i] = DynamicLayout.INVALID_BLOCK_INDEX; } } /** * Create a new block, ending at the specified character offset. * A block will actually be created only if has at least one line, i.e. this offset is * not on the end line of the previous block. */ private addBlockAtOffset(offset:number):void { const line:number = this.getLineForOffset(offset); if (this.mBlockEndLines == null) { // Initial creation of the array, no test on previous block ending line this.mBlockEndLines = androidui.util.ArrayCreator.newNumberArray((1)); this.mBlockEndLines[this.mNumberOfBlocks] = line; this.mNumberOfBlocks++; return; } const previousBlockEndLine:number = this.mBlockEndLines[this.mNumberOfBlocks - 1]; if (line > previousBlockEndLine) { if (this.mNumberOfBlocks == this.mBlockEndLines.length) { // Grow the array if needed let blockEndLines:number[] = androidui.util.ArrayCreator.newNumberArray((this.mNumberOfBlocks + 1)); System.arraycopy(this.mBlockEndLines, 0, blockEndLines, 0, this.mNumberOfBlocks); this.mBlockEndLines = blockEndLines; } this.mBlockEndLines[this.mNumberOfBlocks] = line; this.mNumberOfBlocks++; } } /** * This method is called every time the layout is reflowed after an edition. * It updates the internal block data structure. The text is split in blocks * of contiguous lines, with at least one block for the entire text. * When a range of lines is edited, new blocks (from 0 to 3 depending on the * overlap structure) will replace the set of overlapping blocks. * Blocks are listed in order and are represented by their ending line number. * An index is associated to each block (which will be used by display lists), * this class simply invalidates the index of blocks overlapping a modification. * * This method is package private and not private so that it can be tested. * * @param startLine the first line of the range of modified lines * @param endLine the last line of the range, possibly equal to startLine, lower * than getLineCount() * @param newLineCount the number of lines that will replace the range, possibly 0 * * @hide */ updateBlocks(startLine:number, endLine:number, newLineCount:number):void { if (this.mBlockEndLines == null) { this.createBlocks(); return; } let firstBlock:number = -1; let lastBlock:number = -1; for (let i:number = 0; i < this.mNumberOfBlocks; i++) { if (this.mBlockEndLines[i] >= startLine) { firstBlock = i; break; } } for (let i:number = firstBlock; i < this.mNumberOfBlocks; i++) { if (this.mBlockEndLines[i] >= endLine) { lastBlock = i; break; } } const lastBlockEndLine:number = this.mBlockEndLines[lastBlock]; let createBlockBefore:boolean = startLine > (firstBlock == 0 ? 0 : this.mBlockEndLines[firstBlock - 1] + 1); let createBlock:boolean = newLineCount > 0; let createBlockAfter:boolean = endLine < this.mBlockEndLines[lastBlock]; let numAddedBlocks:number = 0; if (createBlockBefore) numAddedBlocks++; if (createBlock) numAddedBlocks++; if (createBlockAfter) numAddedBlocks++; const numRemovedBlocks:number = lastBlock - firstBlock + 1; const newNumberOfBlocks:number = this.mNumberOfBlocks + numAddedBlocks - numRemovedBlocks; if (newNumberOfBlocks == 0) { // Even when text is empty, there is actually one line and hence one block this.mBlockEndLines[0] = 0; this.mBlockIndices[0] = DynamicLayout.INVALID_BLOCK_INDEX; this.mNumberOfBlocks = 1; return; } if (newNumberOfBlocks > this.mBlockEndLines.length) { const newSize:number = (newNumberOfBlocks); let blockEndLines:number[] = androidui.util.ArrayCreator.newNumberArray(newSize); let blockIndices:number[] = androidui.util.ArrayCreator.newNumberArray(newSize); System.arraycopy(this.mBlockEndLines, 0, blockEndLines, 0, firstBlock); System.arraycopy(this.mBlockIndices, 0, blockIndices, 0, firstBlock); System.arraycopy(this.mBlockEndLines, lastBlock + 1, blockEndLines, firstBlock + numAddedBlocks, this.mNumberOfBlocks - lastBlock - 1); System.arraycopy(this.mBlockIndices, lastBlock + 1, blockIndices, firstBlock + numAddedBlocks, this.mNumberOfBlocks - lastBlock - 1); this.mBlockEndLines = blockEndLines; this.mBlockIndices = blockIndices; } else { System.arraycopy(this.mBlockEndLines, lastBlock + 1, this.mBlockEndLines, firstBlock + numAddedBlocks, this.mNumberOfBlocks - lastBlock - 1); System.arraycopy(this.mBlockIndices, lastBlock + 1, this.mBlockIndices, firstBlock + numAddedBlocks, this.mNumberOfBlocks - lastBlock - 1); } this.mNumberOfBlocks = newNumberOfBlocks; let newFirstChangedBlock:number; const deltaLines:number = newLineCount - (endLine - startLine + 1); if (deltaLines != 0) { // Display list whose index is >= mIndexFirstChangedBlock is valid // but it needs to update its drawing location. newFirstChangedBlock = firstBlock + numAddedBlocks; for (let i:number = newFirstChangedBlock; i < this.mNumberOfBlocks; i++) { this.mBlockEndLines[i] += deltaLines; } } else { newFirstChangedBlock = this.mNumberOfBlocks; } this.mIndexFirstChangedBlock = Math.min(this.mIndexFirstChangedBlock, newFirstChangedBlock); let blockIndex:number = firstBlock; if (createBlockBefore) { this.mBlockEndLines[blockIndex] = startLine - 1; this.mBlockIndices[blockIndex] = DynamicLayout.INVALID_BLOCK_INDEX; blockIndex++; } if (createBlock) { this.mBlockEndLines[blockIndex] = startLine + newLineCount - 1; this.mBlockIndices[blockIndex] = DynamicLayout.INVALID_BLOCK_INDEX; blockIndex++; } if (createBlockAfter) { this.mBlockEndLines[blockIndex] = lastBlockEndLine + deltaLines; this.mBlockIndices[blockIndex] = DynamicLayout.INVALID_BLOCK_INDEX; } } /** * This package private method is used for test purposes only * @hide */ setBlocksDataForTest(blockEndLines:number[], blockIndices:number[], numberOfBlocks:number):void { this.mBlockEndLines = androidui.util.ArrayCreator.newNumberArray(blockEndLines.length); this.mBlockIndices = androidui.util.ArrayCreator.newNumberArray(blockIndices.length); System.arraycopy(blockEndLines, 0, this.mBlockEndLines, 0, blockEndLines.length); System.arraycopy(blockIndices, 0, this.mBlockIndices, 0, blockIndices.length); this.mNumberOfBlocks = numberOfBlocks; } /** * @hide */ getBlockEndLines():number[] { return this.mBlockEndLines; } /** * @hide */ getBlockIndices():number[] { return this.mBlockIndices; } /** * @hide */ getNumberOfBlocks():number { return this.mNumberOfBlocks; } /** * @hide */ getIndexFirstChangedBlock():number { return this.mIndexFirstChangedBlock; } /** * @hide */ setIndexFirstChangedBlock(i:number):void { this.mIndexFirstChangedBlock = i; } getLineCount():number { return this.mInts.size() - 1; } getLineTop(line:number):number { return this.mInts.getValue(line, DynamicLayout.TOP); } getLineDescent(line:number):number { return this.mInts.getValue(line, DynamicLayout.DESCENT); } getLineStart(line:number):number { return this.mInts.getValue(line, DynamicLayout.START) & DynamicLayout.START_MASK; } getLineContainsTab(line:number):boolean { return (this.mInts.getValue(line, DynamicLayout.TAB) & DynamicLayout.TAB_MASK) != 0; } getParagraphDirection(line:number):number { return this.mInts.getValue(line, DynamicLayout.DIR) >> DynamicLayout.DIR_SHIFT; } getLineDirections(line:number):Layout.Directions { return this.mObjects.getValue(line, 0); } getTopPadding():number { return this.mTopPadding; } getBottomPadding():number { return this.mBottomPadding; } getEllipsizedWidth():number { return this.mEllipsizedWidth; } getEllipsisStart(line:number):number { if (this.mEllipsizeAt == null) { return 0; } return this.mInts.getValue(line, DynamicLayout.ELLIPSIS_START); } getEllipsisCount(line:number):number { if (this.mEllipsizeAt == null) { return 0; } return this.mInts.getValue(line, DynamicLayout.ELLIPSIS_COUNT); } private mBase:String; private mDisplay:String; private mWatcher;//:DynamicLayout.ChangeWatcher; private mIncludePad:boolean; private mEllipsize:boolean; private mEllipsizedWidth:number = 0; private mEllipsizeAt:TextUtils.TruncateAt; private mInts:PackedIntVector; private mObjects:PackedObjectVector<Layout.Directions>; /** * Value used in mBlockIndices when a block has been created or recycled and indicating that its * display list needs to be re-created. * @hide */ static INVALID_BLOCK_INDEX:number = -1; // Stores the line numbers of the last line of each block (inclusive) private mBlockEndLines:number[]; // The indices of this block's display list in TextView's internal display list array or // INVALID_BLOCK_INDEX if this block has been invalidated during an edition private mBlockIndices:number[]; // Number of items actually currently being used in the above 2 arrays private mNumberOfBlocks:number = 0; // The first index of the blocks whose locations are changed private mIndexFirstChangedBlock:number = 0; private mTopPadding:number = 0 private mBottomPadding:number = 0; private static sStaticLayout:StaticLayout = new StaticLayout(null, 0, 0, null, 0, null, null, 1, 0, true); private static sLock:any[] = new Array<any>(0); private static START:number = 0; private static DIR:number = DynamicLayout.START; private static TAB:number = DynamicLayout.START; private static TOP:number = 1; private static DESCENT:number = 2; private static COLUMNS_NORMAL:number = 3; private static ELLIPSIS_START:number = 3; private static ELLIPSIS_COUNT:number = 4; private static COLUMNS_ELLIPSIZE:number = 5; private static START_MASK:number = 0x1FFFFFFF; private static DIR_SHIFT:number = 30; private static TAB_MASK:number = 0x20000000; private static ELLIPSIS_UNDEFINED:number = 0x80000000; } export module DynamicLayout{ //export class ChangeWatcher implements TextWatcher, SpanWatcher { // // constructor( layout:DynamicLayout) { // this.mLayout = new WeakReference<DynamicLayout>(layout); // } // // private reflow(s:CharSequence, where:number, before:number, after:number):void { // let ml:DynamicLayout = this.mLayout.get(); // if (ml != null) // ml.reflow(s, where, before, after); // else if (s instanceof Spannable) // (<Spannable> s).removeSpan(this); // } // // beforeTextChanged(s:CharSequence, where:number, before:number, after:number):void { // // Intentionally empty // } // // onTextChanged(s:CharSequence, where:number, before:number, after:number):void { // this.reflow(s, where, before, after); // } // // afterTextChanged(s:Editable):void { // // Intentionally empty // } // // onSpanAdded(s:Spannable, o:any, start:number, end:number):void { // if (o instanceof UpdateLayout) // this.reflow(s, start, end - start, end - start); // } // // onSpanRemoved(s:Spannable, o:any, start:number, end:number):void { // if (o instanceof UpdateLayout) // this.reflow(s, start, end - start, end - start); // } // // onSpanChanged(s:Spannable, o:any, start:number, end:number, nstart:number, nend:number):void { // if (o instanceof UpdateLayout) { // this.reflow(s, start, end - start, end - start); // this.reflow(s, nstart, nend - nstart, nend - nstart); // } // } // // private mLayout:WeakReference<DynamicLayout>; //} } }
the_stack
import util = require('util'); import Promise = require('bluebird'); import _ = require('lodash'); import should = require('should'); import request = require('request'); import TestHelper = require('./lib/test-helper'); should(true).ok; // Added so ts won't get rid of should module var HOST = 'http://localhost:3000'; describe('Request/Response', (): void => { var ipc: TestHelper.IOurSocket; // Create test server // Use function instead of lambda to avoid ts capturing "this" in a variable before(function(done: Function): void { this.timeout(0); // Turn off timeout for before all hook TestHelper.startServer() .then((s: TestHelper.IOurSocket): void => { ipc = s; done(); }); }); // Shut-down server after((): Promise<any> => { return TestHelper.stopServer(); }); describe('blpSession cannot be started', (): void => { // Set instructions before((): Promise<void> => { return ipc.emitAcknowledge('set-instructions', { start: false }); }); // Clear instructions after((): Promise<void> => { return ipc.emitAcknowledge('clear-instructions'); }); it('should fail with 500 if blpSession cannot be started', (done: Function): void => { var opt = { url: HOST + '/request?ns=blp&service=refdata&type=HistoricalDataRequest', body: {}, json: true }; request.post(opt, (error: Error, response: any, body: any): void => { should.ifError(error); response.statusCode.should.be.a.Number.and.equal(500); done(); }); }); }); describe('blpSession start successfully', (): void => { // Set instructions before((): Promise<void> => { return ipc.emitAcknowledge('set-instructions', { start: true }); }); // Clear instructions after((): Promise<void> => { return ipc.emitAcknowledge('clear-instructions'); }); describe('service open failure', (): void => { before((): void => { ipc.on('wait-to-openService', (data: any): void => { ipc.emit(util.format('openService-%d-fail', data.cid)); }); }); after((): void => { ipc.off('wait-to-openService'); }); it('should fail with 500 if service cannot be opened', (done: Function): void => { var opt = { url: HOST + '/request?ns=blpp&service=refdata&type=HistoricalDataRequest', body: {}, json: true }; request.post(opt, (error: Error, response: any, body: any): void => { should.ifError(error); response.statusCode.should.be.a.Number.and.equal(500); done(); }); }); }); describe('service open successfully', (): void => { before((): void => { ipc.on('wait-to-openService', (data: any): void => { ipc.emit(util.format('openService-%d-success', data.cid)); }); }); after((): void => { ipc.off('wait-to-openService'); }); describe('request data arrives in 1 chunk', (): void => { beforeEach((): void => { ipc.once('wait-to-request', (data: any): void => { ipc.emit(util.format('request-%d-final', data.cid)); }); }); it('should fail with 406 if accept header is not json', (done: Function): void => { var opt: request.Options = { url: HOST + '/requests', body: {}, json: true, headers: { 'accept': 'application/xml' } }; request.post(opt, (error: Error, response: any, body: any): void => { should.ifError(error); response.statusCode.should.be.a.Number.and.equal(406); done(); }); }); it('should fail with 413 if body exceeds 1024 byte', (done: Function): void => { var s: String; for (var i = 0; i < 1025; i++) { s += 'x'; } var opt = { url: HOST + '/request?ns=blp&service=refdata&type=HistoricalDataRequest', body: {test: s}, json: true }; request.post(opt, (error: Error, response: any, body: any): void => { should.ifError(error); response.statusCode.should.be.a.Number.and.equal(413); done(); }); }); it('should gzip compress response data', (done: Function): void => { var opt = { url: HOST + '/request?ns=blp&service=refdata&type=HistoricalDataRequest', body: {}, json: true, gzip: true }; request.post(opt, (error: Error, response: any, body: any): void => { should.ifError(error); response.statusCode.should.be.a.Number.and.equal(200); response.headers.should.have.property('content-type') .equal('application/json'); response.headers.should.have.property('content-encoding').equal('gzip'); done(); }); }); it('should fail with 404 if url resource is wrong', (done: Function): void => { var opt = { url: HOST + '/requests', body: {}, json: true }; request.post(opt, (error: Error, response: any, body: any): void => { should.ifError(error); response.statusCode.should.be.a.Number.and.equal(404); done(); }); }); it('should fail with 400 if query params are missing', (done: Function): void => { var opt = { url: HOST + '/request', body: {}, json: true }; request.post(opt, (error: Error, response: any, body: any): void => { should.ifError(error); response.statusCode.should.be.a.Number.and.equal(400); done(); }); }); it('should fail with 400 if param "ns" is missing', (done: Function): void => { var opt = { url: HOST + '/request?service=refdata&type=HistoricalDataRequest', body: {}, json: true }; request.post(opt, (error: Error, response: any, body: any): void => { should.ifError(error); response.statusCode.should.be.a.Number.and.equal(400); done(); }); }); it('should fail with 400 if param "service" missing', (done: Function): void => { var opt = { url: HOST + '/request?ns=blp&type=HistoricalDataRequest', body: {}, json: true }; request.post(opt, (error: Error, response: any, body: any): void => { should.ifError(error); response.statusCode.should.be.a.Number.and.equal(400); done(); }); }); it('should fail with 400 if param "type" is missing', (done: Function): void => { var opt = { url: HOST + '/request?ns=blp&service=refdata', body: {}, json: true }; request.post(opt, (error: Error, response: any, body: any): void => { should.ifError(error); response.statusCode.should.be.a.Number.and.equal(400); done(); }); }); it('should succeed with 200 and expected response', (done: Function): void => { var opt = { url: HOST + '/request?ns=blp&service=refdata&type=HistoricalDataRequest', body: {}, json: true }; request.post(opt, (error: Error, response: any, body: any): void => { should.ifError(error); response.statusCode.should.be.a.Number.and.equal(200); response.headers.should.have.property('content-type') .equal('application/json'); body.status.should.be.a.Number.and.equal(0); body.message.should.be.a.String.and.equal('OK'); body.data.should.be.an.Array.and.have.length(1); body.data.should.eql(['FinalTestData']); done(); }); }); }); describe('request data arrives in 3 chunk', (): void => { beforeEach((): void => { ipc.once('wait-to-request', (data: any): void => { ipc.emit(util.format('request-%d-partial', data.cid)); ipc.emit(util.format('request-%d-partial', data.cid)); ipc.emit(util.format('request-%d-final', data.cid)); }); }); it('should succeed with 200 and expected response', (done: Function): void => { var opt = { url: HOST + '/request?ns=blp&service=refdata&type=HistoricalDataRequest', body: {}, json: true }; request.post(opt, (error: Error, response: any, body: any): void => { should.ifError(error); response.statusCode.should.be.a.Number.and.equal(200); response.headers.should.have.property('content-type') .equal('application/json'); body.status.should.be.a.Number.and.equal(0); body.message.should.be.a.String.and.equal('OK'); body.data.should.be.an.Array.and.have.length(3); body.data.should.eql(['TestData', 'TestData', 'FinalTestData']); done(); }); }); }); describe('request data arrives in 1 chunk then hang', (): void => { var cids: number[] = []; beforeEach((): void => { ipc.once('wait-to-request', (data: any): void => { cids.push(data.cid); ipc.emit(util.format('request-%d-partial', data.cid)); }); }); after((): void => { _.forEach(cids, (cid: number): void => { ipc.emit(util.format('request-%d-final', cid)); }); }); // Use function instead of lambda to avoid ts capturing "this" in a variable it('should timeout after 2000ms', function(done: Function): void { var EXPECTED_TIMEOUT: number = 2000; var p: Promise<void>; this.timeout(EXPECTED_TIMEOUT + 100); var timeout = setTimeout((): void => { p.cancel(); done(); }, EXPECTED_TIMEOUT); var opt = { url: HOST + '/request?ns=blp&service=refdata&type=HistoricalDataRequest', body: {}, json: true }; p = (Promise.promisify(request.post))(opt) .then((): void => { clearTimeout(timeout); done(new Error('Timeout did not happen!')); }) .cancellable() .catch(Promise.CancellationError, (err: Error): void => { // Do nothing, this is expected }) .catch((err: Error): void => { done(err); }); }); }); describe('request type is not in internal map', (): void => { it('should fail with 500 if request type is invalid', (done: Function): void => { var opt = { url: HOST + '/request?ns=blp&service=refdata&type=FutureDataRequest', body: {}, json: true }; request.post(opt, (error: Error, response: any, body: any): void => { should.ifError(error); response.statusCode.should.be.a.Number.and.equal(500); done(); }); }); }); describe('request error out immediately', (): void => { // Set instructions before((): Promise<void> => { return ipc.emitAcknowledge('set-instructions', { request: ['throwError'] }); }); // Clear instructions after((): Promise<void> => { return ipc.emitAcknowledge('clear-instructions', ['request']); }); it('should fail with 500 if error occur', (done: Function): void => { var opt = { url: HOST + '/request?ns=blp&service=refdata&type=HistoricalDataRequest', body: {}, json: true }; request.post(opt, (error: Error, response: any, body: any): void => { should.ifError(error); response.statusCode.should.be.a.Number.and.equal(500); done(); }); }); }); describe('session terminated before request arrive', (): void => { beforeEach((): void => { ipc.emit('terminate-session'); ipc.once('wait-to-request', (data: any): void => { ipc.emit(util.format('request-%d-final', data.cid)); }); }); it('should succeed with 200 and expected response', (done: Function): void => { var opt = { url: HOST + '/request?ns=blp&service=refdata&type=HistoricalDataRequest', body: {}, json: true }; request.post(opt, (error: Error, response: any, body: any): void => { should.ifError(error); response.statusCode.should.be.a.Number.and.equal(200); response.headers.should.have.property('content-type') .equal('application/json'); body.status.should.be.a.Number.and.equal(0); body.message.should.be.a.String.and.equal('OK'); body.data.should.be.an.Array.and.have.length(1); body.data.should.eql(['FinalTestData']); done(); }); }); }); describe('session terminated when request arrive', (): void => { beforeEach((): void => { ipc.once('wait-to-request', (data: any): void => { ipc.emit('terminate-session'); }); }); it('should fail with 500 with error message', (done: Function): void => { var opt = { url: HOST + '/request?ns=blp&service=refdata&type=HistoricalDataRequest', body: {}, json: true }; request.post(opt, (error: Error, response: any, body: any): void => { should.ifError(error); response.statusCode.should.be.a.Number.and.equal(500); done(); }); }); }); describe('request data arrives in 1 chunk then session ternimated', (): void => { beforeEach((): void => { ipc.once('wait-to-request', (data: any): void => { ipc.emit(util.format('request-%d-partial', data.cid)); ipc.emit('terminate-session'); }); }); it('should succeed with 200 with error message', (done: Function): void => { var opt = { url: HOST + '/request?ns=blp&service=refdata&type=HistoricalDataRequest', body: {}, json: true }; request.post(opt, (error: Error, response: any, body: any): void => { should.ifError(error); response.statusCode.should.be.a.Number.and.equal(200); response.headers.should.have.property('content-type') .and.equal('application/json'); body.status.should.be.a.Number.and.equal(-1); body.message.should.be.a.String.and.equal('session terminated'); body.data.should.be.an.Array.and.have.length(1); body.data.should.eql(['TestData']); done(); }); }); }); }); }); });
the_stack
import React, { useState } from 'react'; import { Story } from '@storybook/react'; import { useArgs } from '@storybook/client-api'; import GuideIcon from '@zendeskgarden/svg-icons/src/26/relationshape-guide.svg'; import SupportIcon from '@zendeskgarden/svg-icons/src/26/relationshape-support.svg'; import ChatIcon from '@zendeskgarden/svg-icons/src/26/relationshape-chat.svg'; import ConnectIcon from '@zendeskgarden/svg-icons/src/26/relationshape-connect.svg'; import ExploreIcon from '@zendeskgarden/svg-icons/src/26/relationshape-explore.svg'; import MessageIcon from '@zendeskgarden/svg-icons/src/26/relationshape-message.svg'; import TalkIcon from '@zendeskgarden/svg-icons/src/26/relationshape-talk.svg'; import HomeIcon from '@zendeskgarden/svg-icons/src/26/home-fill.svg'; import ListsIcon from '@zendeskgarden/svg-icons/src/26/customer-lists-fill.svg'; import EmailIcon from '@zendeskgarden/svg-icons/src/26/email-fill.svg'; import SettingsIcon from '@zendeskgarden/svg-icons/src/26/settings-fill.svg'; import ZendeskIcon from '@zendeskgarden/svg-icons/src/26/zendesk.svg'; import MenuTrayIcon from '@zendeskgarden/svg-icons/src/16/grid-2x2-stroke.svg'; import PersonIcon from '@zendeskgarden/svg-icons/src/16/user-solo-stroke.svg'; import { Body, SkipNav, Chrome, CollapsibleSubNavItem, Content, Footer, FooterItem, Header, HeaderItem, HeaderItemIcon, HeaderItemText, Main, Nav, NavItem, NavItemIcon, NavItemText, Sidebar, SubNav, SubNavItem, SubNavItemText, Sheet } from '@zendeskgarden/react-chrome'; import { Accordion } from '@zendeskgarden/react-accordions'; import { Button } from '@zendeskgarden/react-buttons'; type PRODUCT = 'chat' | 'connect' | 'explore' | 'guide' | 'message' | 'support' | 'talk'; const ProductIcon: React.FC<{ product: PRODUCT }> = ({ product }) => { if (product === 'guide') { return <GuideIcon />; } else if (product === 'support') { return <SupportIcon />; } else if (product === 'chat') { return <ChatIcon />; } else if (product === 'connect') { return <ConnectIcon />; } else if (product === 'explore') { return <ExploreIcon />; } else if (product === 'message') { return <MessageIcon />; } else if (product === 'talk') { return <TalkIcon />; } return <ZendeskIcon />; }; interface IDefaultStoryProps { product: PRODUCT; isExpanded: boolean; showSubnav: boolean; showSidebar: boolean; showSheet: boolean; hueColor?: string; itemCount: number; } export const Default: Story<IDefaultStoryProps> = ({ product, isExpanded, showSubnav, showSidebar, showSheet, hueColor, itemCount }) => { const [, updateArgs] = useArgs(); const [currentNavItem, setCurrentNavItem] = useState('home'); const [currentSubnavItem, setCurrentSubnavItem] = useState('item-1'); const [showCollapsed, setShowCollapsed] = useState(false); const subNavItems = Array(itemCount) .fill(undefined) .map((s, i) => i); return ( <Chrome isFluid style={{ height: 650 }} hue={hueColor}> <SkipNav targetId="main-content">Skip to main content</SkipNav> <Nav isExpanded={isExpanded}> <NavItem hasLogo product={product} title="Zendesk"> <NavItemIcon> <ProductIcon product={product} /> </NavItemIcon> <NavItemText>Zendesk Connect</NavItemText> </NavItem> <NavItem title="Home" isCurrent={currentNavItem === 'home'} onClick={() => setCurrentNavItem('home')} > <NavItemIcon> <HomeIcon /> </NavItemIcon> <NavItemText>Home</NavItemText> </NavItem> <NavItem title="Segment" isCurrent={currentNavItem === 'segment'} onClick={() => setCurrentNavItem('segment')} > <NavItemIcon> <ListsIcon /> </NavItemIcon> <NavItemText>Segment</NavItemText> </NavItem> <NavItem title="Campaigns" isCurrent={currentNavItem === 'campaigns'} onClick={() => setCurrentNavItem('campaigns')} > <NavItemIcon> <EmailIcon /> </NavItemIcon> <NavItemText>Campaigns</NavItemText> </NavItem> <NavItem title="Settings" isCurrent={currentNavItem === 'settings'} onClick={() => setCurrentNavItem('settings')} > <NavItemIcon> <SettingsIcon /> </NavItemIcon> <NavItemText>Settings</NavItemText> </NavItem> <NavItem hasBrandmark title="Zendesk"> <NavItemIcon> <ZendeskIcon /> </NavItemIcon> <NavItemText>&copy;Zendesk</NavItemText> </NavItem> </Nav> {showSubnav && ( <SubNav aria-label="Subnav"> <SubNavItem isCurrent={currentSubnavItem === 'item-1'} onClick={() => setCurrentSubnavItem('item-1')} > <SubNavItemText>Subnav 1</SubNavItemText> </SubNavItem> <SubNavItem isCurrent={currentSubnavItem === 'item-2'} onClick={() => setCurrentSubnavItem('item-2')} > <SubNavItemText>Subnav 2</SubNavItemText> </SubNavItem> <CollapsibleSubNavItem header="Collapsible Item" isExpanded={showCollapsed} onChange={setShowCollapsed} > {subNavItems.map(item => ( <SubNavItem key={item} isCurrent={currentSubnavItem === `collapsed-item-${item}`} onClick={() => setCurrentSubnavItem(`collapsed-item-${item}`)} > <SubNavItemText>Item {item + 1}</SubNavItemText> </SubNavItem> ))} </CollapsibleSubNavItem> <SubNavItem isCurrent={currentSubnavItem === 'item-3'} onClick={() => setCurrentSubnavItem('item-3')} > <SubNavItemText>Subnav 3</SubNavItemText> </SubNavItem> </SubNav> )} <Body hasFooter> <Header> <HeaderItem> <HeaderItemIcon> <MenuTrayIcon /> </HeaderItemIcon> <HeaderItemText isClipped>Products</HeaderItemText> </HeaderItem> <HeaderItem isRound> <HeaderItemIcon> <PersonIcon /> </HeaderItemIcon> <HeaderItemText isClipped>User</HeaderItemText> </HeaderItem> </Header> <Content id="main-content"> {showSidebar && ( <Sidebar style={{ padding: 28 }}> <h2>Example Sidebar</h2> <p> Beetroot water spinach okra water chestnut ricebean pea catsear courgette summer purslane. Water spinach arugula pea tatsoi aubergine spring onion bush tomato kale radicchio turnip chicory salsify pea sprouts fava bean. </p> <p> Dandelion zucchini burdock yarrow chickpea dandelion sorrel courgette turnip greens tigernut soybean radish artichoke wattle seed endive groundnut broccoli arugula. </p> </Sidebar> )} <Main style={{ padding: 28 }}> <h2>Main Content</h2> <p> Beetroot water spinach okra water chestnut ricebean pea catsear courgette summer purslane. Water spinach arugula pea tatsoi aubergine spring onion bush tomato kale radicchio turnip chicory salsify pea sprouts fava bean. Dandelion zucchini burdock yarrow chickpea dandelion sorrel courgette turnip greens tigernut soybean radish artichoke wattle seed endive groundnut broccoli arugula. </p> <p> Pea horseradish azuki bean lettuce avocado asparagus okra. Kohlrabi radish okra azuki bean corn fava bean mustard tigernut jícama green bean celtuce collard greens avocado quandong fennel gumbo black-eyed pea. Grape silver beet watercress potato tigernut corn groundnut. Chickweed okra pea winter purslane coriander yarrow sweet pepper radish garlic brussels sprout groundnut summer purslane earthnut pea tomato spring onion azuki bean gourd. Gumbo kakadu plum komatsuna black-eyed pea green bean zucchini gourd winter purslane silver beet rock melon radish asparagus spinach. </p> <p> Celery quandong swiss chard chicory earthnut pea potato. Salsify taro catsear garlic gram celery bitterleaf wattle seed collard greens nori. Grape wattle seed kombu beetroot horseradish carrot squash brussels sprout chard. </p> <Button aria-expanded={showSheet} onClick={() => updateArgs({ showSheet: !showSheet })}> {' '} {showSheet ? 'Close' : 'Open'} Sheet{' '} </Button> </Main> <Sheet isOpen={showSheet} focusOnMount restoreFocus> <Sheet.Header> <Sheet.Title> Gardening </Sheet.Title> <Sheet.Description> Somebody gotta start gardening. </Sheet.Description> </Sheet.Header> <Sheet.Body style={{ padding: 0 }}> <Accordion level={4}> <Accordion.Section> <Accordion.Header> <Accordion.Label>How do you start gardening?</Accordion.Label> </Accordion.Header> <Accordion.Panel> Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. </Accordion.Panel> </Accordion.Section> <Accordion.Section> <Accordion.Header> <Accordion.Label>What are the basics of gardening?</Accordion.Label> </Accordion.Header> <Accordion.Panel> <p> Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke. Nori grape silver beet broccoli kombu beet greens fava bean potato quandong celery. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke. Nori grape silver beet broccoli kombu beet greens fava bean potato quandong celery. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke. Nori grape silver beet broccoli kombu beet greens fava bean potato quandong celery. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke. Nori grape silver beet broccoli kombu beet greens fava bean potato quandong celery. </p> <p> Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke. Nori grape silver beet broccoli kombu beet greens fava bean potato quandong celery. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke. Nori grape silver beet broccoli kombu beet greens fava bean potato quandong celery. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke. Nori grape silver beet broccoli kombu beet greens fava bean potato quandong celery. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke. Nori grape silver beet broccoli kombu beet greens fava bean potato quandong celery. </p> <p> Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke. Nori grape silver beet broccoli kombu beet greens fava bean potato quandong celery. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke. Nori grape silver beet broccoli kombu beet greens fava bean potato quandong celery. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke. Nori grape silver beet broccoli kombu beet greens fava bean potato quandong celery. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke. Nori grape silver beet broccoli kombu beet greens fava bean potato quandong celery. </p> </Accordion.Panel> </Accordion.Section> <Accordion.Section> <Accordion.Header> <Accordion.Label>What are the best tools?</Accordion.Label> </Accordion.Header> <Accordion.Panel> Celery quandong swiss chard chicory earthnut pea potato. Salsify taro catsear garlic gram celery bitterleaf wattle seed collard greens nori. </Accordion.Panel> </Accordion.Section> </Accordion> </Sheet.Body> <Sheet.Footer> <Sheet.FooterItem> <Button isBasic> Action </Button> </Sheet.FooterItem> <Sheet.FooterItem> <Button isPrimary onClick={() => updateArgs({ showSheet: false })}> {' '} Close{' '} </Button> </Sheet.FooterItem> </Sheet.Footer> <Sheet.Close onClick={() => updateArgs({ showSheet: false })} /> </Sheet> </Content> <Footer> <FooterItem> <Button isBasic>Cancel</Button> </FooterItem> <FooterItem> <Button isPrimary>Save</Button> </FooterItem> </Footer> </Body> </Chrome> ); }; Default.args = { product: 'guide', isExpanded: false, showSubnav: true, showSidebar: false, showSheet: false, hueColor: undefined, itemCount: 3 }; Default.argTypes = { product: { name: 'Product', control: { type: 'select', options: ['chat', 'connect', 'explore', 'guide', 'message', 'support', 'talk'] } }, isExpanded: { name: 'Expanded' }, showSubnav: { name: 'Show subnav' }, showSidebar: { name: 'Show sidebar' }, showSheet: { name: 'Show sheet' }, hueColor: { name: 'Hue', control: 'color' }, itemCount: { name: 'Item count', control: { type: 'range', min: 1, max: 8, step: 1 } } }; Default.parameters = { docs: { description: { component: ` Due to the wide variety of routing strategies within React, the \`Chrome\` component doesn't provide any opinionated navigation solutions. The \`NavItem\` and \`SubNavItem\` components are \`button\` elements that accept all native attributes and events. If you are using a routing library like [react-router](https://github.com/ReactTraining/react-router), you can programmatically trigger navigation with the \`onClick\` events. #### Custom Nav Colors By default, the \`Nav\` and \`SubNav\` components are styled with a Zendesk branded palette. For white-labeling purposes a custom \`hue\` prop may be applied. The \`Chrome\` component uses the [PolishedJS readableColor()](https://polished.js.org/docs/#readablecolor) utility to modify colors to maintain accessible contrast levels. ` } } };
the_stack
import { DestinyVersion, InfuseDirection } from '@destinyitemmanager/dim-api-types'; import { settingsSelector } from 'app/dim-api/selectors'; import { t } from 'app/i18next-t'; import { applyLoadout } from 'app/loadout-drawer/loadout-apply'; import { LoadoutItem } from 'app/loadout-drawer/loadout-types'; import { ItemFilter } from 'app/search/filter-types'; import SearchBar from 'app/search/SearchBar'; import { DimThunkDispatch, RootState, ThunkDispatchProp } from 'app/store/types'; import { useEventBusListener } from 'app/utils/hooks'; import { isD1Item } from 'app/utils/item-utils'; import clsx from 'clsx'; import React, { useCallback, useEffect, useReducer } from 'react'; import { connect } from 'react-redux'; import { useLocation } from 'react-router'; import Sheet from '../dim-ui/Sheet'; import ConnectedInventoryItem from '../inventory/ConnectedInventoryItem'; import { DimItem } from '../inventory/item-types'; import { allItemsSelector, currentStoreSelector } from '../inventory/selectors'; import { DimStore } from '../inventory/store-types'; import { convertToLoadoutItem, newLoadout } from '../loadout-drawer/loadout-utils'; import { showNotification } from '../notifications/notifications'; import { filterFactorySelector } from '../search/search-filter'; import { setSettingAction } from '../settings/actions'; import { AppIcon, faArrowCircleDown, faEquals, faRandom, helpIcon, plusIcon } from '../shell/icons'; import { chainComparator, compareBy, reverseComparator } from '../utils/comparators'; import { showInfuse$ } from './infuse'; import './InfusionFinder.scss'; const itemComparator = chainComparator( reverseComparator(compareBy((item: DimItem) => item.primStat?.value ?? 0)), compareBy((item: DimItem) => isD1Item(item) && item.talentGrid ? (item.talentGrid.totalXP / item.talentGrid.totalXPRequired) * 0.5 : 0 ) ); interface ProvidedProps { destinyVersion: DestinyVersion; } interface StoreProps { allItems: DimItem[]; currentStore?: DimStore; lastInfusionDirection: InfuseDirection; filters(query: string): ItemFilter; } function mapStateToProps(state: RootState): StoreProps { return { allItems: allItemsSelector(state), currentStore: currentStoreSelector(state)!, filters: filterFactorySelector(state), lastInfusionDirection: settingsSelector(state).infusionDirection, }; } type Props = ProvidedProps & StoreProps & ThunkDispatchProp; interface State { direction: InfuseDirection; /** The item we're focused on */ query?: DimItem; /** The item that will be consumed by infusion */ source?: DimItem; /** The item that will have its power increased by infusion */ target?: DimItem; /** Search filter string */ filter: string; } type Action = /** Reset the tool (for when the sheet is closed) */ | { type: 'reset' } /** Set up the tool with a new focus item */ | { type: 'init'; item: DimItem; hasInfusables: boolean; hasFuel: boolean } /** Swap infusion direction */ | { type: 'swapDirection' } /** Select one of the items in the list */ | { type: 'selectItem'; item: DimItem } | { type: 'setFilter'; filter: string }; /** * All state for this component is managed through this reducer and the Actions above. */ function stateReducer(state: State, action: Action): State { switch (action.type) { case 'reset': return { ...state, query: undefined, source: undefined, target: undefined, filter: '', }; case 'init': { const direction = state.direction === InfuseDirection.INFUSE ? action.hasInfusables ? InfuseDirection.INFUSE : InfuseDirection.FUEL : action.hasFuel ? InfuseDirection.FUEL : InfuseDirection.INFUSE; return { ...state, direction, query: action.item, target: direction === InfuseDirection.INFUSE ? action.item : undefined, source: direction === InfuseDirection.INFUSE ? undefined : action.item, }; } case 'swapDirection': { const direction = state.direction === InfuseDirection.INFUSE ? InfuseDirection.FUEL : InfuseDirection.INFUSE; return { ...state, direction, target: direction === InfuseDirection.INFUSE ? state.query : undefined, source: direction === InfuseDirection.FUEL ? state.query : undefined, }; } case 'selectItem': { if (state.direction === InfuseDirection.INFUSE) { return { ...state, target: state.query, source: action.item, }; } else { return { ...state, target: action.item, source: state.query, }; } } case 'setFilter': { return { ...state, filter: action.filter, }; } } } function InfusionFinder({ allItems, currentStore, filters, lastInfusionDirection, dispatch, }: Props) { const [{ direction, query, source, target, filter }, stateDispatch] = useReducer(stateReducer, { direction: lastInfusionDirection, filter: '', }); const reset = () => stateDispatch({ type: 'reset' }); const selectItem = (item: DimItem) => stateDispatch({ type: 'selectItem', item }); const onQueryChanged = (filter: string) => stateDispatch({ type: 'setFilter', filter }); const switchDirection = () => stateDispatch({ type: 'swapDirection' }); const show = query !== undefined; const destinyVersion = currentStore?.destinyVersion; useEffect(() => { if (show && destinyVersion) { ga('send', 'pageview', `/profileMembershipId/d${destinyVersion}/infuse`); } }, [destinyVersion, show]); // Listen for items coming in via showInfuse$ useEventBusListener( showInfuse$, useCallback( (item) => { const hasInfusables = allItems.some((i) => isInfusable(item, i)); const hasFuel = allItems.some((i) => isInfusable(i, item)); stateDispatch({ type: 'init', item, hasInfusables: hasInfusables, hasFuel }); }, [allItems] ) ); // Close the sheet on navigation const { pathname } = useLocation(); useEffect(reset, [pathname]); // Save direction to settings useEffect(() => { if (direction !== lastInfusionDirection) { dispatch(setSettingAction('infusionDirection', direction)); } }, [direction, lastInfusionDirection, dispatch]); if (!query || !currentStore) { return null; } const filterFn = filters(filter); let items = allItems.filter( (item) => (direction === InfuseDirection.INFUSE ? isInfusable(query, item) : isInfusable(item, query)) && filterFn(item) ); const dupes = items.filter((item) => item.hash === query.hash); dupes.sort(itemComparator); items = items.filter((item) => item.hash !== query.hash); items.sort(itemComparator); const effectiveTarget = target || dupes[0] || items[0]; const effectiveSource = source || dupes[0] || items[0]; let result: DimItem | undefined; if (effectiveSource?.primStat && effectiveTarget?.primStat) { const infused = effectiveSource.primStat?.value || 0; result = { ...effectiveTarget, primStat: { ...effectiveTarget.primStat, value: infused, }, }; } const missingItem = ( <div className="item missingItem"> <div className="item-img"> <AppIcon icon={helpIcon} /> </div> <div className="item-stat">???</div> </div> ); const header = ({ onClose }: { onClose(): void }) => ( <div className="infuseHeader"> <h1> {direction === InfuseDirection.INFUSE ? t('Infusion.InfuseTarget', { name: query.name, }) : t('Infusion.InfuseSource', { name: query.name, })} </h1> <div className="infusionControls"> <div className="infuseTopRow"> <div className="infusionEquation"> {effectiveTarget ? <ConnectedInventoryItem item={effectiveTarget} /> : missingItem} <div className="icon"> <AppIcon icon={plusIcon} /> </div> {effectiveSource ? <ConnectedInventoryItem item={effectiveSource} /> : missingItem} <div className="icon"> <AppIcon icon={faEquals} /> </div> {result ? <ConnectedInventoryItem item={result} /> : missingItem} </div> <div className="infuseActions"> <button type="button" className="dim-button" onClick={switchDirection}> <AppIcon icon={faRandom} /> {t('Infusion.SwitchDirection')} </button> {result && effectiveSource && effectiveTarget && ( <button type="button" className="dim-button" onClick={() => transferItems(dispatch, currentStore, onClose, effectiveSource, effectiveTarget) } > <AppIcon icon={faArrowCircleDown} /> {t('Infusion.TransferItems')} </button> )} </div> </div> <div className="infuseSearch"> <SearchBar onQueryChanged={onQueryChanged} placeholder={t('Infusion.Filter')} /> </div> </div> </div> ); const renderItem = (item: DimItem) => ( <div key={item.id} className={clsx({ 'infuse-selected': item === target })} onClick={() => selectItem(item)} > <ConnectedInventoryItem item={item} /> </div> ); return ( <Sheet onClose={reset} header={header} sheetClassName="infuseDialog" freezeInitialHeight={true}> <div className="infuseSources"> {items.length > 0 || dupes.length > 0 ? ( <> <div className="sub-bucket">{dupes.map(renderItem)}</div> <div className="sub-bucket">{items.map(renderItem)}</div> </> ) : ( <strong>{t('Infusion.NoItems')}</strong> )} </div> </Sheet> ); } export default connect<StoreProps>(mapStateToProps)(InfusionFinder); /** * Can source be infused into target? */ function isInfusable(target: DimItem, source: DimItem) { if (!target.infusable || !source.infusionFuel) { return false; } if (source.destinyVersion === 1 && target.destinyVersion === 1) { return source.type === target.type && target.primStat!.value < source.primStat!.value; } return ( source.infusionQuality && target.infusionQuality && target.infusionQuality.infusionCategoryHashes.some((h) => source.infusionQuality!.infusionCategoryHashes.includes(h) ) && target.basePower < source.basePower ); } async function transferItems( dispatch: DimThunkDispatch, currentStore: DimStore, onClose: () => void, source: DimItem, target: DimItem ) { if (!source || !target) { return; } if (target.notransfer || source.notransfer) { const name = source.notransfer ? source.name : target.name; showNotification({ type: 'error', title: t('Infusion.NoTransfer', { target: name }) }); return; } onClose(); const items: LoadoutItem[] = [ convertToLoadoutItem(target, false), // Include the source, since we wouldn't want it to get moved out of the way convertToLoadoutItem(source, source.equipped), ]; if (source.destinyVersion === 1) { if (target.bucket.sort === 'General') { // Mote of Light items.push({ id: '0', hash: 937555249, amount: 2, equipped: false, }); } else if (target.bucket.sort === 'Weapons') { // Weapon Parts items.push({ id: '0', hash: 1898539128, amount: 10, equipped: false, }); } else { // Armor Materials items.push({ id: '0', hash: 1542293174, amount: 10, equipped: false, }); } if (source.isExotic) { // Exotic shard items.push({ id: '0', hash: 452597397, amount: 1, equipped: false, }); } } // TODO: another one where we want to respect equipped const loadout = newLoadout(t('Infusion.InfusionMaterials'), items); await dispatch(applyLoadout(currentStore, loadout)); }
the_stack
import { Protocol } from './protocol'; import { ChildProcess } from 'child_process'; import { EventEmitter } from 'events'; import { Readable } from 'stream'; import { ReadStream } from 'fs'; import { Serializable, EvaluationArgument, PageFunction, PageFunctionOn, SmartHandle, ElementHandleForTag, BindingSource } from './structs'; type PageWaitForSelectorOptionsNotHidden = PageWaitForSelectorOptions & { state?: 'visible'|'attached'; }; type ElementHandleWaitForSelectorOptionsNotHidden = ElementHandleWaitForSelectorOptions & { state?: 'visible'|'attached'; }; export interface Page { evaluate<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg): Promise<R>; evaluate<R>(pageFunction: PageFunction<void, R>, arg?: any): Promise<R>; evaluateHandle<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg): Promise<SmartHandle<R>>; evaluateHandle<R>(pageFunction: PageFunction<void, R>, arg?: any): Promise<SmartHandle<R>>; $<K extends keyof HTMLElementTagNameMap>(selector: K, options?: { strict: boolean }): Promise<ElementHandleForTag<K> | null>; $(selector: string, options?: { strict: boolean }): Promise<ElementHandle<SVGElement | HTMLElement> | null>; $$<K extends keyof HTMLElementTagNameMap>(selector: K): Promise<ElementHandleForTag<K>[]>; $$(selector: string): Promise<ElementHandle<SVGElement | HTMLElement>[]>; $eval<K extends keyof HTMLElementTagNameMap, R, Arg>(selector: K, pageFunction: PageFunctionOn<HTMLElementTagNameMap[K], Arg, R>, arg: Arg): Promise<R>; $eval<R, Arg, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(selector: string, pageFunction: PageFunctionOn<E, Arg, R>, arg: Arg): Promise<R>; $eval<K extends keyof HTMLElementTagNameMap, R>(selector: K, pageFunction: PageFunctionOn<HTMLElementTagNameMap[K], void, R>, arg?: any): Promise<R>; $eval<R, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(selector: string, pageFunction: PageFunctionOn<E, void, R>, arg?: any): Promise<R>; $$eval<K extends keyof HTMLElementTagNameMap, R, Arg>(selector: K, pageFunction: PageFunctionOn<HTMLElementTagNameMap[K][], Arg, R>, arg: Arg): Promise<R>; $$eval<R, Arg, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(selector: string, pageFunction: PageFunctionOn<E[], Arg, R>, arg: Arg): Promise<R>; $$eval<K extends keyof HTMLElementTagNameMap, R>(selector: K, pageFunction: PageFunctionOn<HTMLElementTagNameMap[K][], void, R>, arg?: any): Promise<R>; $$eval<R, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(selector: string, pageFunction: PageFunctionOn<E[], void, R>, arg?: any): Promise<R>; waitForFunction<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg, options?: PageWaitForFunctionOptions): Promise<SmartHandle<R>>; waitForFunction<R>(pageFunction: PageFunction<void, R>, arg?: any, options?: PageWaitForFunctionOptions): Promise<SmartHandle<R>>; waitForSelector<K extends keyof HTMLElementTagNameMap>(selector: K, options?: PageWaitForSelectorOptionsNotHidden): Promise<ElementHandleForTag<K>>; waitForSelector(selector: string, options?: PageWaitForSelectorOptionsNotHidden): Promise<ElementHandle<SVGElement | HTMLElement>>; waitForSelector<K extends keyof HTMLElementTagNameMap>(selector: K, options: PageWaitForSelectorOptions): Promise<ElementHandleForTag<K> | null>; waitForSelector(selector: string, options: PageWaitForSelectorOptions): Promise<null|ElementHandle<SVGElement | HTMLElement>>; exposeBinding(name: string, playwrightBinding: (source: BindingSource, arg: JSHandle) => any, options: { handle: true }): Promise<void>; exposeBinding(name: string, playwrightBinding: (source: BindingSource, ...args: any[]) => any, options?: { handle?: boolean }): Promise<void>; } export interface Frame { evaluate<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg): Promise<R>; evaluate<R>(pageFunction: PageFunction<void, R>, arg?: any): Promise<R>; evaluateHandle<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg): Promise<SmartHandle<R>>; evaluateHandle<R>(pageFunction: PageFunction<void, R>, arg?: any): Promise<SmartHandle<R>>; $<K extends keyof HTMLElementTagNameMap>(selector: K, options?: { strict: boolean }): Promise<ElementHandleForTag<K> | null>; $(selector: string, options?: { strict: boolean }): Promise<ElementHandle<SVGElement | HTMLElement> | null>; $$<K extends keyof HTMLElementTagNameMap>(selector: K): Promise<ElementHandleForTag<K>[]>; $$(selector: string): Promise<ElementHandle<SVGElement | HTMLElement>[]>; $eval<K extends keyof HTMLElementTagNameMap, R, Arg>(selector: K, pageFunction: PageFunctionOn<HTMLElementTagNameMap[K], Arg, R>, arg: Arg): Promise<R>; $eval<R, Arg, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(selector: string, pageFunction: PageFunctionOn<E, Arg, R>, arg: Arg): Promise<R>; $eval<K extends keyof HTMLElementTagNameMap, R>(selector: K, pageFunction: PageFunctionOn<HTMLElementTagNameMap[K], void, R>, arg?: any): Promise<R>; $eval<R, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(selector: string, pageFunction: PageFunctionOn<E, void, R>, arg?: any): Promise<R>; $$eval<K extends keyof HTMLElementTagNameMap, R, Arg>(selector: K, pageFunction: PageFunctionOn<HTMLElementTagNameMap[K][], Arg, R>, arg: Arg): Promise<R>; $$eval<R, Arg, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(selector: string, pageFunction: PageFunctionOn<E[], Arg, R>, arg: Arg): Promise<R>; $$eval<K extends keyof HTMLElementTagNameMap, R>(selector: K, pageFunction: PageFunctionOn<HTMLElementTagNameMap[K][], void, R>, arg?: any): Promise<R>; $$eval<R, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(selector: string, pageFunction: PageFunctionOn<E[], void, R>, arg?: any): Promise<R>; waitForFunction<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg, options?: PageWaitForFunctionOptions): Promise<SmartHandle<R>>; waitForFunction<R>(pageFunction: PageFunction<void, R>, arg?: any, options?: PageWaitForFunctionOptions): Promise<SmartHandle<R>>; waitForSelector<K extends keyof HTMLElementTagNameMap>(selector: K, options?: PageWaitForSelectorOptionsNotHidden): Promise<ElementHandleForTag<K>>; waitForSelector(selector: string, options?: PageWaitForSelectorOptionsNotHidden): Promise<ElementHandle<SVGElement | HTMLElement>>; waitForSelector<K extends keyof HTMLElementTagNameMap>(selector: K, options: PageWaitForSelectorOptions): Promise<ElementHandleForTag<K> | null>; waitForSelector(selector: string, options: PageWaitForSelectorOptions): Promise<null|ElementHandle<SVGElement | HTMLElement>>; } export interface BrowserContext { exposeBinding(name: string, playwrightBinding: (source: BindingSource, arg: JSHandle) => any, options: { handle: true }): Promise<void>; exposeBinding(name: string, playwrightBinding: (source: BindingSource, ...args: any[]) => any, options?: { handle?: boolean }): Promise<void>; } export interface Worker { evaluate<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg): Promise<R>; evaluate<R>(pageFunction: PageFunction<void, R>, arg?: any): Promise<R>; evaluateHandle<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg): Promise<SmartHandle<R>>; evaluateHandle<R>(pageFunction: PageFunction<void, R>, arg?: any): Promise<SmartHandle<R>>; } export interface JSHandle<T = any> { evaluate<R, Arg, O extends T = T>(pageFunction: PageFunctionOn<O, Arg, R>, arg: Arg): Promise<R>; evaluate<R, O extends T = T>(pageFunction: PageFunctionOn<O, void, R>, arg?: any): Promise<R>; evaluateHandle<R, Arg, O extends T = T>(pageFunction: PageFunctionOn<O, Arg, R>, arg: Arg): Promise<SmartHandle<R>>; evaluateHandle<R, O extends T = T>(pageFunction: PageFunctionOn<O, void, R>, arg?: any): Promise<SmartHandle<R>>; jsonValue(): Promise<T>; asElement(): T extends Node ? ElementHandle<T> : null; } export interface ElementHandle<T=Node> extends JSHandle<T> { $<K extends keyof HTMLElementTagNameMap>(selector: K, options?: { strict: boolean }): Promise<ElementHandleForTag<K> | null>; $(selector: string, options?: { strict: boolean }): Promise<ElementHandle<SVGElement | HTMLElement> | null>; $$<K extends keyof HTMLElementTagNameMap>(selector: K): Promise<ElementHandleForTag<K>[]>; $$(selector: string): Promise<ElementHandle<SVGElement | HTMLElement>[]>; $eval<K extends keyof HTMLElementTagNameMap, R, Arg>(selector: K, pageFunction: PageFunctionOn<HTMLElementTagNameMap[K], Arg, R>, arg: Arg): Promise<R>; $eval<R, Arg, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(selector: string, pageFunction: PageFunctionOn<E, Arg, R>, arg: Arg): Promise<R>; $eval<K extends keyof HTMLElementTagNameMap, R>(selector: K, pageFunction: PageFunctionOn<HTMLElementTagNameMap[K], void, R>, arg?: any): Promise<R>; $eval<R, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(selector: string, pageFunction: PageFunctionOn<E, void, R>, arg?: any): Promise<R>; $$eval<K extends keyof HTMLElementTagNameMap, R, Arg>(selector: K, pageFunction: PageFunctionOn<HTMLElementTagNameMap[K][], Arg, R>, arg: Arg): Promise<R>; $$eval<R, Arg, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(selector: string, pageFunction: PageFunctionOn<E[], Arg, R>, arg: Arg): Promise<R>; $$eval<K extends keyof HTMLElementTagNameMap, R>(selector: K, pageFunction: PageFunctionOn<HTMLElementTagNameMap[K][], void, R>, arg?: any): Promise<R>; $$eval<R, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(selector: string, pageFunction: PageFunctionOn<E[], void, R>, arg?: any): Promise<R>; waitForSelector<K extends keyof HTMLElementTagNameMap>(selector: K, options?: ElementHandleWaitForSelectorOptionsNotHidden): Promise<ElementHandleForTag<K>>; waitForSelector(selector: string, options?: ElementHandleWaitForSelectorOptionsNotHidden): Promise<ElementHandle<SVGElement | HTMLElement>>; waitForSelector<K extends keyof HTMLElementTagNameMap>(selector: K, options: ElementHandleWaitForSelectorOptions): Promise<ElementHandleForTag<K> | null>; waitForSelector(selector: string, options: ElementHandleWaitForSelectorOptions): Promise<null|ElementHandle<SVGElement | HTMLElement>>; } export interface Locator { evaluate<R, Arg, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(pageFunction: PageFunctionOn<E, Arg, R>, arg: Arg, options?: { timeout?: number; }): Promise<R>; evaluate<R, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(pageFunction: PageFunctionOn<E, void, R>, options?: { timeout?: number; }): Promise<R>; evaluateAll<R, Arg, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(pageFunction: PageFunctionOn<E[], Arg, R>, arg: Arg): Promise<R>; evaluateAll<R, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(pageFunction: PageFunctionOn<E[], void, R>): Promise<R>; elementHandle(options?: { timeout?: number; }): Promise<null|ElementHandle<SVGElement | HTMLElement>>; } export interface BrowserType<Unused = {}> { connectOverCDP(endpointURL: string, options?: ConnectOverCDPOptions): Promise<Browser>; /** * Option `wsEndpoint` is deprecated. Instead use `endpointURL`. * @deprecated */ connectOverCDP(options: ConnectOverCDPOptions & { wsEndpoint?: string }): Promise<Browser>; connect(wsEndpoint: string, options?: ConnectOptions): Promise<Browser>; /** * wsEndpoint in options is deprecated. Instead use `wsEndpoint`. * @param wsEndpoint A browser websocket endpoint to connect to. * @param options * @deprecated */ connect(options: ConnectOptions & { wsEndpoint?: string }): Promise<Browser>; } export interface CDPSession { on: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this; addListener: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this; off: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this; removeListener: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this; once: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this; send<T extends keyof Protocol.CommandParameters>( method: T, params?: Protocol.CommandParameters[T] ): Promise<Protocol.CommandReturnValues[T]>; } type DeviceDescriptor = { viewport: ViewportSize; userAgent: string; deviceScaleFactor: number; isMobile: boolean; hasTouch: boolean; defaultBrowserType: 'chromium' | 'firefox' | 'webkit'; }; export namespace errors { class TimeoutError extends Error {} } export interface Accessibility { snapshot(options?: { /** * Prune uninteresting nodes from the tree. Defaults to `true`. */ interestingOnly?: boolean; /** * The root DOM element for the snapshot. Defaults to the whole page. */ root?: ElementHandle; }): Promise<null|AccessibilityNode>; } type AccessibilityNode = { role: string; name: string; value?: string|number; description?: string; keyshortcuts?: string; roledescription?: string; valuetext?: string; disabled?: boolean; expanded?: boolean; focused?: boolean; modal?: boolean; multiline?: boolean; multiselectable?: boolean; readonly?: boolean; required?: boolean; selected?: boolean; checked?: boolean|"mixed"; pressed?: boolean|"mixed"; level?: number; valuemin?: number; valuemax?: number; autocomplete?: string; haspopup?: string; invalid?: string; orientation?: string; children?: AccessibilityNode[]; } export const devices: Devices & DeviceDescriptor[]; //@ts-ignore this will be any if electron is not installed type ElectronType = typeof import('electron'); export interface ElectronApplication { evaluate<R, Arg>(pageFunction: PageFunctionOn<ElectronType, Arg, R>, arg: Arg): Promise<R>; evaluate<R>(pageFunction: PageFunctionOn<ElectronType, void, R>, arg?: any): Promise<R>; evaluateHandle<R, Arg>(pageFunction: PageFunctionOn<ElectronType, Arg, R>, arg: Arg): Promise<SmartHandle<R>>; evaluateHandle<R>(pageFunction: PageFunctionOn<ElectronType, void, R>, arg?: any): Promise<SmartHandle<R>>; } export type AndroidElementInfo = { clazz: string; desc: string; res: string; pkg: string; text: string; bounds: { x: number, y: number, width: number, height: number }; checkable: boolean; checked: boolean; clickable: boolean; enabled: boolean; focusable: boolean; focused: boolean; longClickable: boolean; scrollable: boolean; selected: boolean; }; export type AndroidSelector = { checkable?: boolean, checked?: boolean, clazz?: string | RegExp, clickable?: boolean, depth?: number, desc?: string | RegExp, enabled?: boolean, focusable?: boolean, focused?: boolean, hasChild?: { selector: AndroidSelector }, hasDescendant?: { selector: AndroidSelector, maxDepth?: number }, longClickable?: boolean, pkg?: string | RegExp, res?: string | RegExp, scrollable?: boolean, selected?: boolean, text?: string | RegExp, }; export type AndroidKey = 'Unknown' | 'SoftLeft' | 'SoftRight' | 'Home' | 'Back' | 'Call' | 'EndCall' | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 'Star' | 'Pound' | '*' | '#' | 'DialUp' | 'DialDown' | 'DialLeft' | 'DialRight' | 'DialCenter' | 'VolumeUp' | 'VolumeDown' | 'Power' | 'Camera' | 'Clear' | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z' | 'Comma' | ',' | 'Period' | '.' | 'AltLeft' | 'AltRight' | 'ShiftLeft' | 'ShiftRight' | 'Tab' | '\t' | 'Space' | ' ' | 'Sym' | 'Explorer' | 'Envelop' | 'Enter' | '\n' | 'Del' | 'Grave' | 'Minus' | '-' | 'Equals' | '=' | 'LeftBracket' | '(' | 'RightBracket' | ')' | 'Backslash' | '\\' | 'Semicolon' | ';' | 'Apostrophe' | '`' | 'Slash' | '/' | 'At' | '@' | 'Num' | 'HeadsetHook' | 'Focus' | 'Plus' | '+' | 'Menu' | 'Notification' | 'Search' | 'RecentApps' | 'AppSwitch' | 'Assist' | 'Cut' | 'Copy' | 'Paste'; export const _electron: Electron; export const _android: Android; // This is required to not export everything by default. See https://github.com/Microsoft/TypeScript/issues/19545#issuecomment-340490459 export {};
the_stack
import * as fs from "fs"; import * as path from "path"; import * as yargs from "yargs"; import { DbResult, Id64Array, Id64String, Logger, LogLevel } from "@itwin/core-bentley"; import { Angle, Geometry, Matrix3d, Point3d } from "@itwin/core-geometry"; import { ECSqlStatement, ExportGraphics, ExportGraphicsInfo, ExportGraphicsLines, ExportGraphicsMesh, ExportLinesInfo, ExportPartInfo, ExportPartInstanceInfo, ExportPartLinesInfo, IModelHost, SnapshotDb, Texture, } from "@itwin/core-backend"; import { ColorDef, ImageSourceFormat } from "@itwin/core-common"; const exportGraphicsDetailOptions = { chordTol: 0.001, angleTol: Angle.degreesToRadians(45), decimationTol: 0.001, minBRepFeatureSize: 0.01, minLineStyleComponentSize: 0.1, }; class GltfGlobals { public static iModel: SnapshotDb; public static gltf: Gltf; public static binFile: number; public static texturesDir: string; public static binBytesWritten: number; public static colorToMaterialMap: Map<number, number>; public static textureToMaterialMap: Map<Id64String, number>; public static initialize(iModelName: string, gltfName: string) { GltfGlobals.iModel = SnapshotDb.openFile(iModelName); process.stdout.write(`Opened ${iModelName} successfully...\n`); const gltfPathParts = path.parse(gltfName); const binName = `${gltfPathParts.name}.bin`; GltfGlobals.binFile = fs.openSync(path.join(gltfPathParts.dir, binName), "w"); GltfGlobals.texturesDir = gltfPathParts.dir; process.stdout.write(`Writing to ${gltfName} and ${binName}...\n`); GltfGlobals.gltf = { accessors: [], asset: { generator: "iModel.js export-gltf", version: "2.0", }, buffers: [{ uri: binName, byteLength: 0 }], bufferViews: [], materials: [], meshes: [], nodes: [], scenes: [{ nodes: [] }], scene: 0, // per GLTF spec, need to define default scene }; GltfGlobals.binBytesWritten = 0; GltfGlobals.colorToMaterialMap = new Map<number, number>(); GltfGlobals.textureToMaterialMap = new Map<Id64String, number>(); } } function findOrAddMaterialIndexForTexture(textureId: Id64String): number { let result = GltfGlobals.textureToMaterialMap.get(textureId); if (result !== undefined) return result; // glTF-Validator complains if textures/images are defined but empty - wait for texture to define. if (GltfGlobals.gltf.textures === undefined) { GltfGlobals.gltf.textures = []; GltfGlobals.gltf.images = []; GltfGlobals.gltf.samplers = [{}]; // Just use default sampler values } const textureInfo = GltfGlobals.iModel.elements.getElement<Texture>(textureId); const textureName = textureId + (textureInfo.format === ImageSourceFormat.Jpeg ? ".jpg" : ".png"); const texturePath = path.join(GltfGlobals.texturesDir, textureName); fs.writeFile(texturePath, textureInfo.data, () => { }); // async is fine const texture: GltfTexture = { source: GltfGlobals.gltf.images!.length, sampler: 0 }; GltfGlobals.gltf.textures.push(texture); GltfGlobals.gltf.images!.push({ uri: textureName }); const pbrMetallicRoughness: GltfMaterialPbrMetallicRoughness = { baseColorTexture: { index: GltfGlobals.gltf.textures.length - 1 }, baseColorFactor: [1, 1, 1, 1], metallicFactor: 0, roughnessFactor: 1, }; const material: GltfMaterial = ({ pbrMetallicRoughness, doubleSided: true }); result = GltfGlobals.gltf.materials.length; GltfGlobals.gltf.materials.push(material); GltfGlobals.textureToMaterialMap.set(textureId, result); return result; } function findOrAddMaterialIndexForColor(color: number): number { let result = GltfGlobals.colorToMaterialMap.get(color); if (result !== undefined) return result; const rgb = ColorDef.getColors(color); const pbrMetallicRoughness: GltfMaterialPbrMetallicRoughness = { baseColorFactor: [rgb.r / 255, rgb.g / 255, rgb.b / 255, (255 - rgb.t) / 255], metallicFactor: 0, roughnessFactor: 1, }; const material: GltfMaterial = ({ pbrMetallicRoughness, doubleSided: true }); if (rgb.t > 10) material.alphaMode = "BLEND"; result = GltfGlobals.gltf.materials.length; GltfGlobals.gltf.materials.push(material); GltfGlobals.colorToMaterialMap.set(color, result); return result; } function addMeshIndices(indices: Int32Array) { GltfGlobals.gltf.accessors.push({ bufferView: GltfGlobals.gltf.bufferViews.length, byteOffset: 0, componentType: AccessorComponentType.UInt32, count: indices.length, type: "SCALAR", }); GltfGlobals.gltf.bufferViews.push({ buffer: 0, target: BufferViewTarget.ElementArrayBuffer, byteOffset: GltfGlobals.binBytesWritten, byteLength: indices.byteLength, }); GltfGlobals.binBytesWritten += indices.byteLength; fs.writeSync(GltfGlobals.binFile, indices); } function addMeshPointsAndNormals(points: Float64Array, normals: Float32Array, translation: Point3d) { const outPoints = new Float32Array(points.length); for (let i = 0; i < points.length; i += 3) { // GLTF is RHS with Y-up, iModel.js is RHS with Z-up outPoints[i] = points[i] + translation.x; outPoints[i + 1] = points[i + 2] + translation.z; outPoints[i + 2] = -(points[i + 1] + translation.y); } const outNormals = new Float32Array(normals.length); for (let i = 0; i < normals.length; i += 3) { // GLTF is RHS with Y-up, iModel.js is RHS with Z-up outNormals[i] = normals[i]; outNormals[i + 1] = normals[i + 2]; outNormals[i + 2] = -(normals[i + 1]); } GltfGlobals.gltf.bufferViews.push({ buffer: 0, target: BufferViewTarget.ArrayBuffer, byteOffset: GltfGlobals.binBytesWritten, byteLength: outPoints.byteLength + outNormals.byteLength, byteStride: 12, }); fs.writeSync(GltfGlobals.binFile, outPoints); fs.writeSync(GltfGlobals.binFile, outNormals); GltfGlobals.binBytesWritten += outPoints.byteLength + outNormals.byteLength; const minPos = [outPoints[0], outPoints[1], outPoints[2]]; const maxPos = Array.from(minPos); for (let i = 0; i < outPoints.length; i += 3) { for (let j = 0; j < 3; ++j) { minPos[j] = Math.min(minPos[j], outPoints[i + j]); maxPos[j] = Math.max(maxPos[j], outPoints[i + j]); } } GltfGlobals.gltf.accessors.push({ bufferView: GltfGlobals.gltf.bufferViews.length - 1, byteOffset: 0, componentType: AccessorComponentType.Float, count: outPoints.length / 3, type: "VEC3", max: maxPos, min: minPos, }); GltfGlobals.gltf.accessors.push({ bufferView: GltfGlobals.gltf.bufferViews.length - 1, byteOffset: outPoints.byteLength, componentType: AccessorComponentType.Float, count: outNormals.length / 3, type: "VEC3", }); } function addMeshParams(params: Float32Array) { const outParams = new Float32Array(params.length); for (let i = 0; i < params.length; i += 2) { outParams[i] = params[i]; outParams[i + 1] = 1 - params[i + 1]; // Flip to match GLTF spec } GltfGlobals.gltf.bufferViews.push({ buffer: 0, target: BufferViewTarget.ArrayBuffer, byteOffset: GltfGlobals.binBytesWritten, byteLength: outParams.byteLength, byteStride: 8, }); fs.writeSync(GltfGlobals.binFile, outParams); GltfGlobals.binBytesWritten += outParams.byteLength; GltfGlobals.gltf.accessors.push({ bufferView: GltfGlobals.gltf.bufferViews.length - 1, byteOffset: 0, componentType: AccessorComponentType.Float, count: outParams.length / 2, type: "VEC2", }); } function addMesh(mesh: ExportGraphicsMesh, translation: Point3d, color: number, textureId?: Id64String) { const material = textureId !== undefined ? findOrAddMaterialIndexForTexture(textureId) : findOrAddMaterialIndexForColor(color); const primitive: GltfMeshPrimitive = { mode: MeshPrimitiveMode.GlTriangles, material, indices: GltfGlobals.gltf.accessors.length, attributes: { // eslint-disable-next-line @typescript-eslint/naming-convention POSITION: GltfGlobals.gltf.accessors.length + 1, // eslint-disable-next-line @typescript-eslint/naming-convention NORMAL: GltfGlobals.gltf.accessors.length + 2, }, }; if (textureId !== undefined) primitive.attributes.TEXCOORD_0 = GltfGlobals.gltf.accessors.length + 3; GltfGlobals.gltf.meshes.push({ primitives: [primitive] }); addMeshIndices(mesh.indices); addMeshPointsAndNormals(mesh.points, mesh.normals, translation); if (textureId !== undefined) addMeshParams(mesh.params); } function addMeshNode(name: string) { GltfGlobals.gltf.scenes[0].nodes.push(GltfGlobals.gltf.nodes.length); GltfGlobals.gltf.nodes.push({ name, mesh: GltfGlobals.gltf.meshes.length }); } function addLines(lines: ExportGraphicsLines, translation: Point3d, color: number) { const primitive: GltfMeshPrimitive = { mode: MeshPrimitiveMode.GlLines, material: findOrAddMaterialIndexForColor(color), indices: GltfGlobals.gltf.accessors.length, attributes: { // eslint-disable-next-line @typescript-eslint/naming-convention POSITION: GltfGlobals.gltf.accessors.length + 1, }, }; GltfGlobals.gltf.meshes.push({ primitives: [primitive] }); addMeshIndices(lines.indices); // GLTF is RHS with Y-up, iModel.js is RHS with Z-up const outPoints = new Float32Array(lines.points.length); for (let i = 0; i < outPoints.length; i += 3) { // GLTF is RHS with Y-up, iModel.js is RHS with Z-up outPoints[i] = lines.points[i] + translation.x; outPoints[i + 1] = lines.points[i + 2] + translation.z; outPoints[i + 2] = -(lines.points[i + 1] + translation.y); } GltfGlobals.gltf.bufferViews.push({ buffer: 0, target: BufferViewTarget.ArrayBuffer, byteOffset: GltfGlobals.binBytesWritten, byteLength: outPoints.byteLength, byteStride: 12, }); fs.writeSync(GltfGlobals.binFile, outPoints); GltfGlobals.binBytesWritten += outPoints.byteLength; const minPos = [outPoints[0], outPoints[1], outPoints[2]]; const maxPos = Array.from(minPos); for (let i = 0; i < outPoints.length; i += 3) { for (let j = 0; j < 3; ++j) { minPos[j] = Math.min(minPos[j], outPoints[i + j]); maxPos[j] = Math.max(maxPos[j], outPoints[i + j]); } } GltfGlobals.gltf.accessors.push({ bufferView: GltfGlobals.gltf.bufferViews.length - 1, byteOffset: 0, componentType: AccessorComponentType.Float, count: outPoints.length / 3, type: "VEC3", max: maxPos, min: minPos, }); } function exportElements(elementIdArray: Id64Array, partInstanceArray: ExportPartInstanceInfo[], recenterTranslation: Point3d) { const onGraphics = (info: ExportGraphicsInfo) => { addMeshNode(info.elementId); addMesh(info.mesh, recenterTranslation, info.color, info.textureId); }; const onLineGraphics = (info: ExportLinesInfo) => { addMeshNode(info.elementId); addLines(info.lines, recenterTranslation, info.color); }; GltfGlobals.iModel.exportGraphics({ ...exportGraphicsDetailOptions, onGraphics, onLineGraphics, elementIdArray, partInstanceArray, }); } function getInstancesByPart(instances: ExportPartInstanceInfo[]): Map<Id64String, ExportPartInstanceInfo[]> { const partMap = new Map<Id64String, ExportPartInstanceInfo[]>(); for (const instance of instances) { const instancesForThisPart = partMap.get(instance.partId); if (instancesForThisPart !== undefined) instancesForThisPart.push(instance); else partMap.set(instance.partId, [instance]); } return partMap; } function almostEqual(testValue: number, ...arrayValues: number[]): boolean { for (const val of arrayValues) { if (!Geometry.isAlmostEqualNumber(testValue, val)) return false; } return true; } // translation, rotation, scale only defined if different from GLTF default transforms class TranslationRotationScale { public readonly translation?: number[]; public readonly rotation?: number[]; public readonly scale?: number[]; constructor(recenterTranslation: Point3d, xform?: Float64Array) { // GLTF = RHS Y-up, iModel.js = RHS Z-up this.translation = [recenterTranslation.x, recenterTranslation.z, -recenterTranslation.y]; if (!xform) return; if (!almostEqual(0, xform[3], xform[7], xform[11])) { this.translation[0] = this.translation[0] + xform[3]; this.translation[1] = this.translation[1] + xform[11]; this.translation[2] = this.translation[2] - xform[7]; } // Uniform and positive scale guaranteed by exportGraphics const xColumnMagnitude = Geometry.hypotenuseXYZ(xform[0], xform[4], xform[8]); if (!almostEqual(1, xColumnMagnitude)) this.scale = [xColumnMagnitude, xColumnMagnitude, xColumnMagnitude]; const invScale = 1.0 / xColumnMagnitude; const matrix = Matrix3d.createRowValues( xform[0] * invScale, xform[1] * invScale, xform[2] * invScale, xform[4] * invScale, xform[5] * invScale, xform[6] * invScale, xform[8] * invScale, xform[9] * invScale, xform[10] * invScale); if (!matrix.isIdentity) { const q = matrix.toQuaternion(); this.rotation = [q.x, q.z, -q.y, -q.w]; // GLTF = RHS Y-up, iModel.js = RHS Z-up } } } function exportInstances(partInstanceArray: ExportPartInstanceInfo[], recenterTranslation: Point3d) { const partMap: Map<Id64String, ExportPartInstanceInfo[]> = getInstancesByPart(partInstanceArray); process.stdout.write(`Found ${partInstanceArray.length} instances for ${partMap.size} parts...\n`); const zeroTranslation = Point3d.createZero(); // Apply recenterTranslation to instance xform, not actual geometry const onPartLineGraphics = (meshIndices: number[]) => (info: ExportPartLinesInfo) => { meshIndices.push(GltfGlobals.gltf.meshes.length); addLines(info.lines, zeroTranslation, info.color); }; const onPartGraphics = (meshIndices: number[]) => (info: ExportPartInfo) => { meshIndices.push(GltfGlobals.gltf.meshes.length); addMesh(info.mesh, zeroTranslation, info.color, info.textureId); }; const nodes: GltfNode[] = GltfGlobals.gltf.nodes; const nodeIndices: number[] = GltfGlobals.gltf.scenes[0].nodes; for (const instanceList of partMap.values()) { const meshIndices: number[] = []; const baseDisplayProps = instanceList[0].displayProps; GltfGlobals.iModel.exportPartGraphics({ elementId: instanceList[0].partId, displayProps: instanceList[0].displayProps, onPartGraphics: onPartGraphics(meshIndices), onPartLineGraphics: onPartLineGraphics(meshIndices), ...exportGraphicsDetailOptions, }); for (const instance of instanceList) { // It is legal for different GeometryPartInstances of the same GeometryPart to have different // display properties. This can lead to different colors, materials or textures so an exporter // that is concerned about matching the appearance of the original iModel should not reuse a // GeometryPart exported with different display properties. if (!ExportGraphics.arePartDisplayInfosEqual(baseDisplayProps, instance.displayProps)) process.stdout.write("Warning: GeometryPartInstances found using different display properties.\n"); const trs = new TranslationRotationScale(recenterTranslation, instance.transform); for (const meshIndex of meshIndices) { nodeIndices.push(nodes.length); nodes.push({ mesh: meshIndex, name: instance.partInstanceId, rotation: trs.rotation, scale: trs.scale, translation: trs.translation, }); } } } } interface ExportGltfArgs { input: string; output: string; } const exportGltfArgs: yargs.Arguments<ExportGltfArgs> = yargs .usage("Usage: $0 --input [Snapshot iModel] --output [GLTF file]") .string("input") .alias("input", "i") .demandOption(["input"]) .describe("input", "Path to the Snapshot iModel") .string("output") .alias("output", "o") .demandOption(["output"]) .describe("output", "Path to the GLTF file that will be created") .argv; (async () => { await IModelHost.startup(); Logger.initializeToConsole(); Logger.setLevelDefault(LogLevel.Warning); GltfGlobals.initialize(exportGltfArgs.input, exportGltfArgs.output); const elementIdArray: Id64Array = []; // Get all 3D elements that aren't part of template definitions or in private models. const sql = "SELECT e.ECInstanceId FROM bis.GeometricElement3d e JOIN bis.Model m ON e.Model.Id=m.ECInstanceId WHERE m.isTemplate=false AND m.isPrivate=false"; GltfGlobals.iModel.withPreparedStatement(sql, (stmt: ECSqlStatement) => { while (stmt.step() === DbResult.BE_SQLITE_ROW) elementIdArray.push(stmt.getValue(0).getId()); }); process.stdout.write(`Found ${elementIdArray.length} 3D elements...\n`); if (elementIdArray.length === 0) return; // Since we write Float32 into the file for points, we need to proactively recenter to avoid // baking in data loss due to quantization. const recenterTranslation: Point3d = GltfGlobals.iModel.projectExtents.center; recenterTranslation.scaleInPlace(-1); const partInstanceArray: ExportPartInstanceInfo[] = []; exportElements(elementIdArray, partInstanceArray, recenterTranslation); exportInstances(partInstanceArray, recenterTranslation); GltfGlobals.gltf.buffers[0].byteLength = GltfGlobals.binBytesWritten; fs.writeFileSync(exportGltfArgs.output, JSON.stringify(GltfGlobals.gltf, undefined, 2)); fs.closeSync(GltfGlobals.binFile); process.stdout.write(`Export successful, wrote ${GltfGlobals.binBytesWritten} bytes.\n`); })().catch((error) => { process.stdout.write(`${error.message}\n${error.stack}\n`); });
the_stack
import debounce from 'lodash/debounce'; import flattenDeep from 'lodash/flattenDeep'; import groupBy from 'lodash/groupBy'; import { observable, computed, action } from 'mobx'; import { INJECTOR_TOKEN, Injector, Injectable, Autowired } from '@opensumi/di'; import { Disposable, IRange, URI, Emitter, AppConfig, localize, getIcon, Event, memoize, IDisposable, positionToRange, Deferred, path, LRUCache, } from '@opensumi/ide-core-browser'; import { IEditor } from '@opensumi/ide-editor'; import { IEditorDecorationCollectionService, IEditorDocumentModelService, ResourceService, WorkbenchEditorService, } from '@opensumi/ide-editor/lib/browser'; import { IMainLayoutService } from '@opensumi/ide-main-layout'; import { IIconService, IconType } from '@opensumi/ide-theme'; import * as model from '@opensumi/monaco-editor-core/esm/vs/editor/common/model'; import * as textModel from '@opensumi/monaco-editor-core/esm/vs/editor/common/model/textModel'; import * as monaco from '@opensumi/monaco-editor-core/esm/vs/editor/editor.api'; import { ICommentsService, ICommentsThread, ICommentsTreeNode, ICommentsFeatureRegistry, CommentPanelId, ICommentRangeProvider, ICommentsThreadOptions, } from '../common'; import { CommentsPanel } from './comments-panel.view'; import { CommentsThread } from './comments-thread'; const { dirname } = path; @Injectable() export class CommentsService extends Disposable implements ICommentsService { @Autowired(INJECTOR_TOKEN) private readonly injector: Injector; @Autowired(AppConfig) private readonly appConfig: AppConfig; @Autowired(IEditorDecorationCollectionService) private readonly editorDecorationCollectionService: IEditorDecorationCollectionService; @Autowired(IIconService) private readonly iconService: IIconService; @Autowired(ICommentsFeatureRegistry) private readonly commentsFeatureRegistry: ICommentsFeatureRegistry; @Autowired(IEditorDocumentModelService) private readonly documentService: IEditorDocumentModelService; @Autowired(IMainLayoutService) private readonly layoutService: IMainLayoutService; @Autowired(WorkbenchEditorService) private readonly workbenchEditorService: WorkbenchEditorService; @Autowired(ResourceService) private readonly resourceService: ResourceService; private decorationChangeEmitter = new Emitter<URI>(); @observable private threads = new Map<string, ICommentsThread>(); private threadsChangeEmitter = new Emitter<ICommentsThread>(); private threadsCreatedEmitter = new Emitter<ICommentsThread>(); private rangeProviderMap = new Map<string, ICommentRangeProvider>(); private rangeOwner = new Map<string, IRange[]>(); private providerDecorationCache = new LRUCache<string, Deferred<IRange[]>>(10000); // 默认在 file 协议和 git 协议中显示评论数据 private shouldShowCommentsSchemes = new Set(['file', 'git']); private decorationProviderDisposer = Disposable.NULL; @observable private forceUpdateCount = 0; @computed get commentsThreads() { return [...this.threads.values()]; } @memoize get isMultiCommentsForSingleLine() { return !!this.commentsFeatureRegistry.getConfig()?.isMultiCommentsForSingleLine; } @memoize get currentAuthorAvatar() { return this.commentsFeatureRegistry.getConfig()?.author?.avatar; } @memoize get filterThreadDecoration() { return this.commentsFeatureRegistry.getConfig()?.filterThreadDecoration; } get onThreadsChanged(): Event<ICommentsThread> { return this.threadsChangeEmitter.event; } get onThreadsCreated(): Event<ICommentsThread> { return this.threadsCreatedEmitter.event; } /** * -------------------------------- IMPORTANT -------------------------------- * 需要注意区分 model.IModelDecorationOptions 与 monaco.editor.IModelDecorationOptions 两个类型 * 将 model.IModelDecorationOptions 类型的对象传给签名为 monaco.editor.IModelDecorationOptions 的方法时需要做 Type Assertion * 这是因为 monaco.d.ts 与 vs/editor/common/model 分别导出了枚举 TrackedRangeStickiness * 这种情况下两个枚举的类型是不兼容的,即使他们是同一段代码的编译产物 * -------------------------------- IMPORTANT -------------------------------- * @param thread */ private createThreadDecoration(thread: ICommentsThread): model.IModelDecorationOptions { // 对于新增的空的 thread,默认显示当前用户的头像,否则使用第一个用户的头像 const avatar = thread.comments.length === 0 ? this.currentAuthorAvatar : thread.comments[0].author.iconPath?.toString(); const icon = avatar ? this.iconService.fromIcon('', avatar, IconType.Background) : getIcon('message'); const decorationOptions: model.IModelDecorationOptions = { description: 'comments-thread-decoration', // 创建评论显示在 glyph margin 处 glyphMarginClassName: ['comments-decoration', 'comments-thread', icon].join(' '), }; return textModel.ModelDecorationOptions.createDynamic(decorationOptions); } private createHoverDecoration(): model.IModelDecorationOptions { const decorationOptions: model.IModelDecorationOptions = { description: 'comments-hover-decoration', linesDecorationsClassName: ['comments-decoration', 'comments-add', getIcon('message')].join(' '), }; return textModel.ModelDecorationOptions.createDynamic(decorationOptions); } public init() { // 插件注册 ResourceProvider 时重新注册 CommentDecorationProvider // 例如 Github Pull Request 插件的 scheme 为 pr this.addDispose( this.resourceService.onRegisterResourceProvider((provider) => { if (provider.scheme) { this.shouldShowCommentsSchemes.add(provider.scheme); this.registerDecorationProvider(); } }), ); this.addDispose( this.resourceService.onUnregisterResourceProvider((provider) => { if (provider.scheme) { this.shouldShowCommentsSchemes.delete(provider.scheme); this.registerDecorationProvider(); } }), ); this.registerDecorationProvider(); } public handleOnCreateEditor(editor: IEditor) { const disposer = new Disposable(); disposer.addDispose( editor.monacoEditor.onMouseDown((event) => { if ( event.target.type === monaco.editor.MouseTargetType.GUTTER_LINE_DECORATIONS && event.target.element && event.target.element.className.indexOf('comments-add') > -1 ) { const { target } = event; if (target && target.range) { const { range } = target; // 如果已经存在一个待输入的评论组件,则不创建新的 if ( this.commentsThreads.some( (thread) => thread.comments.length === 0 && thread.uri.isEqual(editor.currentUri!) && thread.range.startLineNumber === range.startLineNumber, ) ) { return; } const thread = this.createThread(editor.currentUri!, range); thread.show(editor); } } else if ( event.target.type === monaco.editor.MouseTargetType.GUTTER_GLYPH_MARGIN && event.target.element && event.target.element.className.indexOf('comments-thread') > -1 ) { const { target } = event; if (target && target.range) { const { range } = target; const threads = this.commentsThreads.filter( (thread) => thread.uri.isEqual(editor.currentUri!) && thread.range.startLineNumber === range.startLineNumber, ); if (threads.length) { // 判断当前 widget 是否是显示的 const isShowWidget = threads.some((thread) => thread.isShowWidget(editor)); if (isShowWidget) { threads.forEach((thread) => thread.hide(editor)); } else { threads.forEach((thread) => thread.show(editor)); } } } } }), ); let oldDecorations: string[] = []; disposer.addDispose( editor.monacoEditor.onMouseMove( debounce(async (event) => { const uri = editor.currentUri; const range = event.target.range; if (uri && range && (await this.shouldShowHoverDecoration(uri, range))) { oldDecorations = editor.monacoEditor.deltaDecorations(oldDecorations, [ { range: positionToRange(range.startLineNumber), options: this.createHoverDecoration() as unknown as monaco.editor.IModelDecorationOptions, }, ]); } else { oldDecorations = editor.monacoEditor.deltaDecorations(oldDecorations, []); } }, 10), ), ); disposer.addDispose( editor.monacoEditor.onMouseLeave( debounce(() => { oldDecorations = editor.monacoEditor.deltaDecorations(oldDecorations, []); }, 10), ), ); return disposer; } private async shouldShowHoverDecoration(uri: URI, range: IRange) { if (!this.shouldShowCommentsSchemes.has(uri.scheme)) { return false; } const contributionRanges = await this.getContributionRanges(uri); const isProviderRanges = contributionRanges.some( (contributionRange) => range.startLineNumber >= contributionRange.startLineNumber && range.startLineNumber <= contributionRange.endLineNumber, ); // 如果不支持对同一行进行多个评论,那么过滤掉当前有 thread 行号的 decoration const isShowHoverToSingleLine = this.isMultiCommentsForSingleLine || !this.commentsThreads.some( (thread) => thread.uri.isEqual(uri) && thread.range.startLineNumber === range.startLineNumber, ); return isProviderRanges && isShowHoverToSingleLine; } public createThread( uri: URI, range: IRange, options: ICommentsThreadOptions = { comments: [], readOnly: false, }, ) { // 获取当前 range 的 providerId,用于 commentController contextKey 的生成 const providerId = this.getProviderIdsByLine(range.startLineNumber)[0]; const thread = this.injector.get(CommentsThread, [uri, range, providerId, options]); thread.onDispose(() => { this.threads.delete(thread.id); this.threadsChangeEmitter.fire(thread); this.decorationChangeEmitter.fire(uri); }); this.threads.set(thread.id, thread); this.addDispose(thread); this.threadsChangeEmitter.fire(thread); this.threadsCreatedEmitter.fire(thread); this.decorationChangeEmitter.fire(uri); return thread; } public getThreadsByUri(uri: URI) { return ( this.commentsThreads .filter((thread) => thread.uri.isEqual(uri)) // 默认按照 rang 顺序 升序排列 .sort((a, b) => a.range.startLineNumber - b.range.startLineNumber) ); } @action public forceUpdateTreeNodes() { this.forceUpdateCount++; } @computed get commentsTreeNodes(): ICommentsTreeNode[] { let treeNodes: ICommentsTreeNode[] = []; const commentThreads = [...this.threads.values()].filter((thread) => thread.comments.length); const threadUris = groupBy(commentThreads, (thread: ICommentsThread) => thread.uri); Object.keys(threadUris).forEach((uri) => { const threads: ICommentsThread[] = threadUris[uri]; if (threads.length === 0) { return; } const firstThread = threads[0]; const firstThreadUri = firstThread.uri; const filePath = dirname(firstThreadUri.path.toString().replace(this.appConfig.workspaceDir, '')); const rootNode: ICommentsTreeNode = { id: uri, name: firstThreadUri.displayName, uri: firstThreadUri, description: filePath.replace(/^\//, ''), parent: undefined, thread: firstThread, ...(threads.length && { expanded: true, children: [], }), // 跳过 mobx computed, 强制在走一次 getCommentsPanelTreeNodeHandlers 逻辑 _forceUpdateCount: this.forceUpdateCount, }; treeNodes.push(rootNode); threads.forEach((thread) => { if (thread.comments.length === 0) { return; } const [firstComment, ...otherComments] = thread.comments; const firstCommentNode: ICommentsTreeNode = { id: firstComment.id, name: firstComment.author.name, iconStyle: { marginRight: 5, backgroundSize: '14px 14px', }, icon: this.iconService.fromIcon('', firstComment.author.iconPath?.toString(), IconType.Background), description: firstComment.body, uri: thread.uri, parent: rootNode, depth: 1, thread, ...(otherComments.length && { expanded: true, children: [], }), comment: firstComment, }; const firstCommentChildren = otherComments.map((comment) => { const otherCommentNode: ICommentsTreeNode = { id: comment.id, name: comment.author.name, description: comment.body, uri: thread.uri, iconStyle: { marginRight: 5, backgroundSize: '14px 14px', }, icon: this.iconService.fromIcon('', comment.author.iconPath?.toString(), IconType.Background), parent: firstCommentNode, depth: 2, thread, comment, }; return otherCommentNode; }); treeNodes.push(firstCommentNode); treeNodes.push(...firstCommentChildren); }); }); for (const handler of this.commentsFeatureRegistry.getCommentsPanelTreeNodeHandlers()) { treeNodes = handler(treeNodes); } return treeNodes; } public async getContributionRanges(uri: URI): Promise<IRange[]> { // 一个diff editor对应两个uri,两个uri的rangeOwner不应该互相覆盖 const cache = this.providerDecorationCache.get(uri.toString()); // 优先从缓存中拿 if (cache) { return await cache.promise; } const model = this.documentService.getModelReference(uri); const rangePromise: Promise<IRange[] | undefined>[] = []; for (const rangeProvider of this.rangeProviderMap) { const [id, provider] = rangeProvider; rangePromise.push( (async () => { const ranges = await provider.getCommentingRanges(model?.instance!); if (ranges && ranges.length) { // FIXME: ranges 会被 Diff uri 的两个 range 互相覆盖,导致可能根据行查不到 provider this.rangeOwner.set(id, ranges); } return ranges; })(), ); } const deferredRes = new Deferred<IRange[]>(); this.providerDecorationCache.set(uri.toString(), deferredRes); const res = await Promise.all(rangePromise); // 消除 document 引用 model?.dispose(); // 拍平,去掉 undefined const flattenRange: IRange[] = flattenDeep(res).filter(Boolean) as IRange[]; deferredRes.resolve(flattenRange); return flattenRange; } private registerDecorationProvider() { // dispose 掉上一个 decorationProvider this.decorationProviderDisposer.dispose(); this.decorationProviderDisposer = this.editorDecorationCollectionService.registerDecorationProvider({ schemes: [...this.shouldShowCommentsSchemes.values()], key: 'comments', onDidDecorationChange: this.decorationChangeEmitter.event, provideEditorDecoration: (uri: URI) => this.commentsThreads .map((thread) => { if (thread.uri.isEqual(uri)) { // 恢复之前的现场 thread.showWidgetsIfShowed(); } else { // 临时隐藏,当切回来时会恢复 thread.hideWidgetsByDispose(); } return thread; }) .filter((thread) => { const isCurrentThread = thread.uri.isEqual(uri); if (this.filterThreadDecoration) { return isCurrentThread && this.filterThreadDecoration(thread); } return isCurrentThread; }) .map((thread) => ({ range: thread.range, options: this.createThreadDecoration(thread) as unknown as monaco.editor.IModelDecorationOptions, })), }); this.addDispose(this.decorationProviderDisposer); } public registerCommentPanel() { // 面板只注册一次 if (this.layoutService.getTabbarHandler(CommentPanelId)) { return; } this.layoutService.collectTabbarComponent( [ { id: CommentPanelId, component: CommentsPanel, }, ], { badge: this.panelBadge, containerId: CommentPanelId, title: localize('comments').toUpperCase(), hidden: false, activateKeyBinding: 'ctrlcmd+shift+c', ...this.commentsFeatureRegistry.getCommentsPanelOptions(), }, 'bottom', ); } get panelBadge() { const length = this.commentsThreads.length; return length ? length + '' : ''; } registerCommentRangeProvider(id: string, provider: ICommentRangeProvider): IDisposable { this.rangeProviderMap.set(id, provider); // 注册一个新的 range provider 后清理掉之前的缓存 this.providerDecorationCache.clear(); return Disposable.create(() => { this.rangeProviderMap.delete(id); this.rangeOwner.delete(id); this.providerDecorationCache.clear(); }); } forceUpdateDecoration(): void { // 默认适应当前 uri 去强刷 decoration // 这个值为 core editor 或者 modified editor const uri = this.workbenchEditorService.currentEditor?.currentUri; uri && this.decorationChangeEmitter.fire(uri); // diffeditor 的 originalUri 也需要更新 Decoration const originalUri = this.workbenchEditorService.currentEditorGroup?.diffEditor.originalEditor.currentUri; originalUri && this.decorationChangeEmitter.fire(originalUri); } public getProviderIdsByLine(line: number): string[] { const result: string[] = []; if (this.rangeOwner.size === 1) { // 只有一个provider,直接返回 return [this.rangeOwner.keys().next().value]; } for (const rangeOwner of this.rangeOwner) { const [id, ranges] = rangeOwner; if (ranges && ranges.some((range) => range.startLineNumber <= line && line <= range.endLineNumber)) { result.push(id); } } return result; } }
the_stack
import { $enum } from "../src"; // NOTE: Intentionally out of order keys and values to confirm original // defined order is retained enum TestEnum { D = 0, // duplicate of A B = -1.7, // not a positive integer A = 0, C = 2 } describe("EnumWrapper: string enum", () => { const enumWrapper = $enum(TestEnum); test("@@toStringTag()", () => { expect(Object.prototype.toString.call(enumWrapper)).toBe( "[object EnumWrapper]" ); }); test("toString()", () => { expect(enumWrapper.toString()).toBe("[object EnumWrapper]"); }); test("does not observably alter the enum", () => { // Wrap the enum, then confirm that there are no extra properties/keys available $enum(TestEnum); expect(Object.keys(TestEnum)).toEqual([ "0", "2", "D", "B", "-1.7", "A", "C" ]); expect(Object.getOwnPropertyNames(TestEnum)).toEqual([ "0", "2", "D", "B", "-1.7", "A", "C" ]); const result = []; // tslint:disable-next-line:forin for (const key in TestEnum) { result.push(key); } expect(result).toEqual(["0", "2", "D", "B", "-1.7", "A", "C"]); }); describe("is immutable at run time", () => { test("length", () => { expect(() => { (enumWrapper as any).length = 42; }).toThrow(); }); test("size", () => { expect(() => { (enumWrapper as any).size = 42; }).toThrow(); }); test("index signature", () => { expect(() => { (enumWrapper as any)[0] = ["D", TestEnum.D]; }).toThrow(); }); test("index signature entries", () => { expect(() => { (enumWrapper[0] as any)[0] = "BLAH!"; }).toThrow(); expect(() => { (enumWrapper[0] as any)[1] = "FOO!"; }).toThrow(); }); }); describe("is Array-Like", () => { test("length", () => { expect(enumWrapper.length).toBe(4); }); test("index signature", () => { expect(enumWrapper[0]).toEqual(["D", TestEnum.D]); expect(enumWrapper[1]).toEqual(["B", TestEnum.B]); expect(enumWrapper[2]).toEqual(["A", TestEnum.A]); expect(enumWrapper[3]).toEqual(["C", TestEnum.C]); }); }); describe("is Map-Like", () => { test("size", () => { expect(enumWrapper.size).toBe(4); }); describe("keys()", () => { test("returns an iterator", () => { const keys = enumWrapper.keys(); const next = keys.next(); expect(next).toEqual({ done: false, value: "D" }); }); test("iterates all keys", () => { const expected = ["D", "B", "A", "C"]; const result = Array.from(enumWrapper.keys()); expect(result).toEqual(expected); }); }); describe("values()", () => { test("returns an iterator", () => { const values = enumWrapper.values(); const next = values.next(); expect(next).toEqual({ done: false, value: TestEnum.D }); }); test("iterates all values", () => { const expected = [ TestEnum.D, TestEnum.B, TestEnum.A, TestEnum.C ]; const result = Array.from(enumWrapper.values()); expect(result).toEqual(expected); }); }); describe("entries()", () => { test("returns an iterator", () => { const entries = enumWrapper.entries(); const next = entries.next(); expect(next).toEqual({ done: false, value: ["D", TestEnum.D] }); }); test("iterates all entries", () => { const expected = [ ["D", TestEnum.D], ["B", TestEnum.B], ["A", TestEnum.A], ["C", TestEnum.C] ]; const result = Array.from(enumWrapper.entries()); expect(result).toEqual(expected); }); test("iterated entries are immutable", () => { const entry = enumWrapper.entries().next().value; expect(() => { (entry[0] as any) = "C"; }).toThrow(); expect(() => { (entry[1] as any) = TestEnum.C; }).toThrow(); }); }); describe("@@iterator()", () => { test("returns an iterator", () => { const entries = enumWrapper[Symbol.iterator](); const next = entries.next(); expect(next).toEqual({ done: false, value: ["D", TestEnum.D] }); }); test("iterates all entries", () => { const expected = [ ["D", TestEnum.D], ["B", TestEnum.B], ["A", TestEnum.A], ["C", TestEnum.C] ]; const result = Array.from(enumWrapper[Symbol.iterator]()); expect(result).toEqual(expected); }); test("iterated entries are immutable", () => { const entry = enumWrapper[Symbol.iterator]().next().value; expect(() => { (entry[0] as any) = "C"; }).toThrow(); expect(() => { (entry[1] as any) = TestEnum.C; }).toThrow(); }); }); describe("forEach()", () => { test("without context", () => { const context = { iteratee: function(): void { expect(this).not.toBe(context); } }; const iterateeSpy = jest.fn(context.iteratee); enumWrapper.forEach(iterateeSpy); expect(iterateeSpy.mock.calls).toEqual([ [TestEnum.D, "D", enumWrapper, 0], [TestEnum.B, "B", enumWrapper, 1], [TestEnum.A, "A", enumWrapper, 2], [TestEnum.C, "C", enumWrapper, 3] ]); }); test("with context", () => { const context = { iteratee: function(): void { expect(this).toBe(context); } }; const iterateeSpy = jest.fn(context.iteratee); enumWrapper.forEach(iterateeSpy, context); expect(iterateeSpy.mock.calls).toEqual([ [TestEnum.D, "D", enumWrapper, 0], [TestEnum.B, "B", enumWrapper, 1], [TestEnum.A, "A", enumWrapper, 2], [TestEnum.C, "C", enumWrapper, 3] ]); }); }); }); test("indexOfKey()", () => { expect(enumWrapper.indexOfKey("B")).toBe(1); expect(enumWrapper.indexOfKey("C")).toBe(3); }); test("indexOfValue()", () => { expect(enumWrapper.indexOfValue(TestEnum.B)).toBe(1); expect(enumWrapper.indexOfValue(TestEnum.C)).toBe(3); }); test("getKeys()", () => { const expected = ["D", "B", "A", "C"]; const result = enumWrapper.getKeys(); expect(result).toEqual(expected); // test for defensive copy result[0] = "C"; expect(enumWrapper.getKeys()).toEqual(expected); }); test("getValues()", () => { const expected = [TestEnum.D, TestEnum.B, TestEnum.A, TestEnum.C]; const result = enumWrapper.getValues(); expect(result).toEqual(expected); // test for defensive copy result[0] = TestEnum.C; expect(enumWrapper.getValues()).toEqual(expected); }); describe("getEntries()", () => { test("returns array of entries", () => { const expected = [ ["D", TestEnum.D], ["B", TestEnum.B], ["A", TestEnum.A], ["C", TestEnum.C] ]; const result = enumWrapper.getEntries(); expect(result).toEqual(expected); // test for defensive copy result[0] = ["C", TestEnum.C]; expect(enumWrapper.getEntries()).toEqual(expected); }); test("entries are immutable", () => { const entry = enumWrapper.getEntries()[0]; expect(() => { (entry[0] as any) = "C"; }).toThrow(); expect(() => { (entry[1] as any) = TestEnum.C; }).toThrow(); }); }); describe("map()", () => { test("without context", () => { const context = { iteratee: function(value: TestEnum, key: string): string { expect(this).not.toBe(context); return key + String(value); } }; const iterateeSpy = jest.fn(context.iteratee); const result = enumWrapper.map(iterateeSpy); expect(result).toEqual(["D0", "B-1.7", "A0", "C2"]); expect(iterateeSpy.mock.calls).toEqual([ [TestEnum.D, "D", enumWrapper, 0], [TestEnum.B, "B", enumWrapper, 1], [TestEnum.A, "A", enumWrapper, 2], [TestEnum.C, "C", enumWrapper, 3] ]); }); test("with context", () => { const context = { iteratee: function(value: TestEnum, key: string): string { expect(this).toBe(context); return key + String(value); } }; const iterateeSpy = jest.fn(context.iteratee); const result = enumWrapper.map(iterateeSpy, context); expect(result).toEqual(["D0", "B-1.7", "A0", "C2"]); expect(iterateeSpy.mock.calls).toEqual([ [TestEnum.D, "D", enumWrapper, 0], [TestEnum.B, "B", enumWrapper, 1], [TestEnum.A, "A", enumWrapper, 2], [TestEnum.C, "C", enumWrapper, 3] ]); }); }); test("isKey()", () => { expect(enumWrapper.isKey("A")).toBe(true); expect(enumWrapper.isKey("B")).toBe(true); expect(enumWrapper.isKey("C")).toBe(true); expect(enumWrapper.isKey("D")).toBe(true); expect(enumWrapper.isKey("blah")).toBe(false); // Name of a property on Object.prototype expect(enumWrapper.isKey("toString")).toBe(false); expect(enumWrapper.isKey(null)).toBe(false); expect(enumWrapper.isKey(undefined)).toBe(false); }); test("asKeyOrThrow()", () => { expect(enumWrapper.asKeyOrThrow("A")).toBe("A"); expect(enumWrapper.asKeyOrThrow("B")).toBe("B"); expect(enumWrapper.asKeyOrThrow("C")).toBe("C"); expect(enumWrapper.asKeyOrThrow("D")).toBe("D"); expect(() => { enumWrapper.asKeyOrThrow("blah"); }).toThrow(); expect(() => { // Name of a property on Object.prototype enumWrapper.asKeyOrThrow("toString"); }).toThrow(); expect(() => { enumWrapper.asKeyOrThrow(null); }).toThrow(); expect(() => { enumWrapper.asKeyOrThrow(undefined); }).toThrow(); }); test("asKeyOrDefault()", () => { expect(enumWrapper.asKeyOrDefault("A")).toBe("A"); expect(enumWrapper.asKeyOrDefault("B")).toBe("B"); expect(enumWrapper.asKeyOrDefault("C")).toBe("C"); expect(enumWrapper.asKeyOrDefault("D")).toBe("D"); expect(enumWrapper.asKeyOrDefault("blah")).toBe(undefined); // Name of a property on Object.prototype expect(enumWrapper.asKeyOrDefault("toString")).toBe(undefined); expect(enumWrapper.asKeyOrDefault(null, "A")).toBe("A"); expect(enumWrapper.asKeyOrDefault(undefined, "foo")).toBe("foo"); }); test("isValue()", () => { expect(enumWrapper.isValue(TestEnum.A)).toBe(true); expect(enumWrapper.isValue(TestEnum.B)).toBe(true); expect(enumWrapper.isValue(TestEnum.C)).toBe(true); expect(enumWrapper.isValue(TestEnum.D)).toBe(true); expect(enumWrapper.isValue(-1)).toBe(false); expect(enumWrapper.isValue(null)).toBe(false); expect(enumWrapper.isValue(undefined)).toBe(false); }); test("asValueOrThrow()", () => { expect(enumWrapper.asValueOrThrow(TestEnum.A)).toBe(TestEnum.A); expect(enumWrapper.asValueOrThrow(TestEnum.B)).toBe(TestEnum.B); expect(enumWrapper.asValueOrThrow(TestEnum.C)).toBe(TestEnum.C); expect(enumWrapper.asValueOrThrow(TestEnum.D)).toBe(TestEnum.D); expect(() => { enumWrapper.asValueOrThrow(-1); }).toThrow(); expect(() => { enumWrapper.asValueOrThrow(null); }).toThrow(); expect(() => { enumWrapper.asValueOrThrow(undefined); }).toThrow(); }); test("asValueOrDefault()", () => { expect(enumWrapper.asValueOrDefault(TestEnum.A)).toBe(TestEnum.A); expect(enumWrapper.asValueOrDefault(TestEnum.B)).toBe(TestEnum.B); expect(enumWrapper.asValueOrDefault(TestEnum.C)).toBe(TestEnum.C); expect(enumWrapper.asValueOrDefault(TestEnum.D)).toBe(TestEnum.D); expect(enumWrapper.asValueOrDefault(-1)).toBe(undefined); expect(enumWrapper.asValueOrDefault(null, TestEnum.A)).toBe(TestEnum.A); expect(enumWrapper.asValueOrDefault(undefined, -2)).toBe(-2); }); test("getKeyOrThrow()", () => { // A and D have duplicate values, but A is ordered after D, and last duplicate entry wins, // so A's key is returned when looking up the value of A or D. expect(enumWrapper.getKeyOrThrow(TestEnum.A)).toBe("A"); expect(enumWrapper.getKeyOrThrow(TestEnum.B)).toBe("B"); expect(enumWrapper.getKeyOrThrow(TestEnum.C)).toBe("C"); expect(enumWrapper.getKeyOrThrow(TestEnum.D)).toBe("A"); expect(() => { enumWrapper.getKeyOrThrow(-1); }).toThrow(); expect(() => { enumWrapper.getKeyOrThrow(null); }).toThrow(); expect(() => { enumWrapper.getKeyOrThrow(undefined); }).toThrow(); }); test("getKeyOrDefault()", () => { // A and D have duplicate values, but A is ordered after D, and last duplicate entry wins, // so A's key is returned when looking up the value of A or D. expect(enumWrapper.getKeyOrDefault(TestEnum.A)).toBe("A"); expect(enumWrapper.getKeyOrDefault(TestEnum.B)).toBe("B"); expect(enumWrapper.getKeyOrDefault(TestEnum.C)).toBe("C"); expect(enumWrapper.getKeyOrDefault(TestEnum.D)).toBe("A"); expect(enumWrapper.getKeyOrDefault(-1)).toBe(undefined); expect(enumWrapper.getKeyOrDefault(null, "A")).toBe("A"); expect(enumWrapper.getKeyOrDefault(undefined, "foo")).toBe("foo"); }); test("getValueOrThrow()", () => { expect(enumWrapper.getValueOrThrow("A")).toBe(TestEnum.A); expect(enumWrapper.getValueOrThrow("B")).toBe(TestEnum.B); expect(enumWrapper.getValueOrThrow("C")).toBe(TestEnum.C); expect(enumWrapper.getValueOrThrow("D")).toBe(TestEnum.D); expect(() => { enumWrapper.getValueOrThrow("blah"); }).toThrow(); expect(() => { // Name of a property on Object.prototype enumWrapper.getValueOrThrow("toString"); }).toThrow(); expect(() => { enumWrapper.getValueOrThrow(null); }).toThrow(); expect(() => { enumWrapper.getValueOrThrow(undefined); }).toThrow(); }); test("getValueOrDefault()", () => { expect(enumWrapper.getValueOrDefault("A")).toBe(TestEnum.A); expect(enumWrapper.getValueOrDefault("B")).toBe(TestEnum.B); expect(enumWrapper.getValueOrDefault("C")).toBe(TestEnum.C); expect(enumWrapper.getValueOrDefault("D")).toBe(TestEnum.D); expect(enumWrapper.getValueOrDefault("blah")).toBe(undefined); // Name of a property on Object.prototype expect(enumWrapper.getValueOrDefault("toString")).toBe(undefined); expect(enumWrapper.getValueOrDefault(null, TestEnum.A)).toBe( TestEnum.A ); expect(enumWrapper.getValueOrDefault(undefined, -1)).toBe(-1); }); });
the_stack
import { default as assert } from 'assert'; import { SinonSandbox, createSandbox } from 'sinon'; import { CredentialStore } from '../../github/credentials'; import { MockCommandRegistry } from '../mocks/mockCommandRegistry'; import { MockTelemetry } from '../mocks/mockTelemetry'; import { ReviewCommentController } from '../../view/reviewCommentController'; import { FolderRepositoryManager } from '../../github/folderRepositoryManager'; import { MockRepository } from '../mocks/mockRepository'; import { GitFileChangeNode } from '../../view/treeNodes/fileChangeNode'; import { PullRequestsTreeDataProvider } from '../../view/prsTreeDataProvider'; import { GitChangeType } from '../../common/file'; import { toReviewUri } from '../../common/uri'; import * as vscode from 'vscode'; import { PullRequestBuilder } from '../builders/rest/pullRequestBuilder'; import { convertRESTPullRequestToRawPullRequest } from '../../github/utils'; import { PullRequestModel } from '../../github/pullRequestModel'; import { Protocol } from '../../common/protocol'; import { Remote } from '../../common/remote'; import { GHPRCommentThread } from '../../github/prComment'; import { DiffLine } from '../../common/diffHunk'; import { MockGitHubRepository } from '../mocks/mockGitHubRepository'; import { GitApiImpl } from '../../api/api1'; import { DiffSide } from '../../common/comment'; import { ReviewManager, ShowPullRequest } from '../../view/reviewManager'; import { PullRequestChangesTreeDataProvider } from '../../view/prChangesTreeDataProvider'; import { MockExtensionContext } from '../mocks/mockExtensionContext'; import { MockSessionState } from '../mocks/mockSessionState'; import { ReviewModel } from '../../view/reviewModel'; import { Resource } from '../../common/resources'; import { RepositoriesManager } from '../../github/repositoriesManager'; import { GitFileChangeModel } from '../../view/fileChangeModel'; import { WebviewViewCoordinator } from '../../view/webviewViewCoordinator'; const schema = require('../../github/queries.gql'); const protocol = new Protocol('https://github.com/github/test.git'); const remote = new Remote('test', 'github/test', protocol); class TestReviewCommentController extends ReviewCommentController { public workspaceFileChangeCommentThreads() { return this._workspaceFileChangeCommentThreads; } } describe('ReviewCommentController', function () { let sinon: SinonSandbox; let credentialStore: CredentialStore; let repository: MockRepository; let telemetry: MockTelemetry; let provider: PullRequestsTreeDataProvider; let manager: FolderRepositoryManager; let activePullRequest: PullRequestModel; let githubRepo: MockGitHubRepository; let reviewManager: ReviewManager; beforeEach(async function () { sinon = createSandbox(); MockCommandRegistry.install(sinon); telemetry = new MockTelemetry(); credentialStore = new CredentialStore(telemetry); repository = new MockRepository(); repository.addRemote('origin', 'git@github.com:aaa/bbb'); provider = new PullRequestsTreeDataProvider(telemetry); const context = new MockExtensionContext(); const activePrViewCoordinator = new WebviewViewCoordinator(context); Resource.initialize(context); const gitApiImpl = new GitApiImpl(); manager = new FolderRepositoryManager(context, repository, telemetry, gitApiImpl, credentialStore, new MockSessionState()); const tree = new PullRequestChangesTreeDataProvider(context, gitApiImpl, new RepositoriesManager([manager], credentialStore, telemetry, new MockSessionState())); reviewManager = new ReviewManager(context, repository, manager, telemetry, tree, new ShowPullRequest(), new MockSessionState(), activePrViewCoordinator); sinon.stub(manager, 'createGitHubRepository').callsFake((r, cStore) => { return new MockGitHubRepository(r, cStore, telemetry, sinon); }); sinon.stub(credentialStore, 'isAuthenticated').returns(false); await manager.updateRepositories(); const pr = new PullRequestBuilder().build(); githubRepo = new MockGitHubRepository(remote, credentialStore, telemetry, sinon); activePullRequest = new PullRequestModel( telemetry, githubRepo, remote, convertRESTPullRequestToRawPullRequest(pr, githubRepo), ); manager.activePullRequest = activePullRequest; }); afterEach(function () { sinon.restore(); }); function createLocalFileChange(uri: vscode.Uri, fileName: string, rootUri: vscode.Uri): GitFileChangeNode { const gitFileChangeModel = new GitFileChangeModel( manager, activePullRequest, { status: GitChangeType.MODIFY, fileName, blobUrl: 'https://example.com', diffHunks: [ { oldLineNumber: 22, oldLength: 5, newLineNumber: 22, newLength: 11, positionInHunk: 0, diffLines: [ new DiffLine(3, -1, -1, 0, '@@ -22,5 +22,11 @@', true), new DiffLine(0, 22, 22, 1, " 'title': 'Papayas',", true), new DiffLine(0, 23, 23, 2, " 'title': 'Papayas',", true), new DiffLine(0, 24, 24, 3, " 'title': 'Papayas',", true), new DiffLine(1, -1, 25, 4, '+ {', true), new DiffLine(1, -1, 26, 5, '+ {', true), new DiffLine(1, -1, 27, 6, '+ {', true), new DiffLine(1, -1, 28, 7, '+ {', true), new DiffLine(1, -1, 29, 8, '+ {', true), new DiffLine(1, -1, 30, 9, '+ {', true), new DiffLine(0, 25, 31, 10, '+ {', true), new DiffLine(0, 26, 32, 11, '+ {', true), ], }, ] }, uri, toReviewUri(uri, fileName, undefined, '1', false, { base: true }, rootUri), 'abcd' ); return new GitFileChangeNode( provider, manager, activePullRequest, gitFileChangeModel ); } function createGHPRCommentThread(threadId: string, uri: vscode.Uri): GHPRCommentThread { return { gitHubThreadId: threadId, uri, range: new vscode.Range(new vscode.Position(21, 0), new vscode.Position(21, 0)), comments: [], collapsibleState: vscode.CommentThreadCollapsibleState.Expanded, label: 'Start discussion', state: vscode.CommentThreadState.Unresolved, canReply: false, dispose: () => {}, }; } describe('initializes workspace thread data', async function () { const fileName = 'data/products.json'; const uri = vscode.Uri.parse(`${repository.rootUri.toString()}/${fileName}`); const localFileChanges = [createLocalFileChange(uri, fileName, repository.rootUri)]; const reviewModel = new ReviewModel(); reviewModel.localFileChanges = localFileChanges; const reviewCommentController = new TestReviewCommentController(reviewManager, manager, repository, reviewModel, new MockSessionState()); sinon.stub(activePullRequest, 'validateDraftMode').returns(Promise.resolve(false)); sinon.stub(activePullRequest, 'getReviewThreads').returns( Promise.resolve([ { id: '1', isResolved: false, viewerCanResolve: false, viewerCanUnresolve: false, path: fileName, diffSide: DiffSide.RIGHT, startLine: 372, endLine: 372, originalStartLine: 372, originalEndLine: 372, isOutdated: false, comments: [ { id: 1, url: '', diffHunk: '', body: '', createdAt: '', htmlUrl: '', graphNodeId: '', } ], }, ]), ); sinon.stub(manager, 'getCurrentUser').returns({ login: 'rmacfarlane', url: 'https://github.com/rmacfarlane', }); sinon.stub(vscode.workspace, 'getWorkspaceFolder').returns({ uri: repository.rootUri, name: '', index: 0, }); await reviewCommentController.initialize(); const workspaceFileChangeCommentThreads = reviewCommentController.workspaceFileChangeCommentThreads(); assert.strictEqual(Object.keys(workspaceFileChangeCommentThreads).length, 1); assert.strictEqual(Object.keys(workspaceFileChangeCommentThreads)[0], fileName); assert.strictEqual(workspaceFileChangeCommentThreads[fileName].length, 1); }); describe('createOrReplyComment', function () { it('creates a new comment on an empty thread in a local file', async function () { const fileName = 'data/products.json'; const uri = vscode.Uri.parse(`${repository.rootUri.toString()}/${fileName}`); await activePullRequest.initializeReviewThreadCache(); const localFileChanges = [createLocalFileChange(uri, fileName, repository.rootUri)]; const reviewModel = new ReviewModel(); reviewModel.localFileChanges = localFileChanges; const reviewCommentController = new TestReviewCommentController( reviewManager, manager, repository, reviewModel, new MockSessionState() ); const thread = createGHPRCommentThread('review-1.1', uri); sinon.stub(activePullRequest, 'validateDraftMode').returns(Promise.resolve(false)); sinon.stub(activePullRequest, 'getReviewThreads').returns(Promise.resolve([])); sinon.stub(activePullRequest, 'getPendingReviewId').returns(Promise.resolve(undefined)); sinon.stub(manager, 'getCurrentUser').returns({ login: 'rmacfarlane', url: 'https://github.com/rmacfarlane', }); sinon.stub(vscode.workspace, 'getWorkspaceFolder').returns({ uri: repository.rootUri, name: '', index: 0, }); sinon.stub(vscode.workspace, 'asRelativePath').callsFake((pathOrUri: string | vscode.Uri): string => { const path = pathOrUri.toString(); return path.substring('/root/'.length); }); sinon.stub(repository, 'diffWith').returns(Promise.resolve('')); await reviewCommentController.initialize(); const workspaceFileChangeCommentThreads = reviewCommentController.workspaceFileChangeCommentThreads(); assert.strictEqual(Object.keys(workspaceFileChangeCommentThreads).length, 0); githubRepo.queryProvider.expectGraphQLMutation( { mutation: schema.AddReviewThread, variables: { input: { path: fileName, body: 'hello world', pullRequestId: activePullRequest.graphNodeId, pullRequestReviewId: undefined, startLine: undefined, line: 22, side: 'RIGHT' } } }, { data: { addPullRequestReviewThread: { thread: { id: 1, isResolved: false, viewCanResolve: true, path: fileName, line: 22, startLine: null, originalStartLine: null, originalLine: 22, diffSide: 'RIGHT', isOutdated: false, comments: { nodes: [ { databaseId: 1, id: 1, body: 'hello world', commit: {}, diffHunk: '', reactionGroups: [], author: {} } ] } } } } } ) await reviewCommentController.createOrReplyComment(thread, 'hello world', false); assert.strictEqual(thread.comments.length, 1); assert.strictEqual(thread.comments[0].parent, thread); assert.strictEqual(Object.keys(workspaceFileChangeCommentThreads).length, 1); assert.strictEqual(Object.keys(workspaceFileChangeCommentThreads)[0], fileName); assert.strictEqual(workspaceFileChangeCommentThreads[fileName].length, 1); }); }); });
the_stack
import { ChangeDetectorRef, Component, NgZone, ErrorHandler, OnDestroy, DoCheck, OnInit } from '@angular/core'; import { UncaughtErrorHandler } from './utils/uncaught-error-handler'; import { reportUncaughtError } from '../utils/error-handling'; import { Connection, DirectConnection } from './channel'; import { ApplicationError, ApplicationErrorType, Message, MessageFactory, MessageResponse, MessageType, Subscription } from '../communication'; import { ComponentInstanceState, ExpandState, Options, Tab, StateTab, Theme, ComponentViewState, AnalyticsConsent } from './state'; import { Change, MutableTree, Node, Path, deserializeChangePath, serializePath, InstanceWithMetadata } from '../tree'; import { createTree } from '../tree/mutable-tree-factory'; import { UserActions } from './actions/user-actions/user-actions'; import { Route } from '../backend/utils'; import { select } from '@angular-redux/store'; import { NgRedux } from '@angular-redux/store'; import { IAppState } from './store/model'; import { MainActions } from './actions/main-actions'; require('!style!css!postcss!../styles/app.css'); @Component({ selector: 'bt-app', templateUrl: './app.html', styleUrls: ['./app.css'] }) export class App implements OnInit, DoCheck, OnDestroy { private Theme = Theme; private AnalyticsConsent = AnalyticsConsent; private componentState: ComponentInstanceState; private routerTree: Array<Route>; private ngModules: { [key: string]: any }; private ngVersion: string; private selectedNode: Node; private subscription: Subscription; private tree: MutableTree; private error: ApplicationError = null; private unsubscribeUncaughtErrorListener; @select(store => store.main.selectedTab) selectedTab; @select(store => store.main.selectedComponentsSubTab) selectedComponentsSubTab; @select(store => store.main.DOMSelectionActive) domSelectionActive; constructor( private ngRedux: NgRedux<IAppState>, private mainActions: MainActions, private changeDetector: ChangeDetectorRef, private connection: Connection, private directConnection: DirectConnection, private options: Options, private userActions: UserActions, private viewState: ComponentViewState, private zone: NgZone, private errorHandler: ErrorHandler ) { // this should be our special ErrorHandler subclass which we can listen to if (this.errorHandler instanceof UncaughtErrorHandler) { this.unsubscribeUncaughtErrorListener = (<UncaughtErrorHandler>this.errorHandler).addListener((err: Error) => { this.error = new ApplicationError(ApplicationErrorType.UncaughtException, { name: err.name, message: err.message, stack: err.stack }); }); } this.componentState = new ComponentInstanceState(changeDetector); this.options.changes.subscribe(() => this.requestTree()); this.options.load().then(() => this.changeDetector.detectChanges()); this.viewState.changes.subscribe(() => this.changeDetector.detectChanges()); this.mainActions.initializeAugury(); } hasContent() { return this.tree && this.tree.roots && this.tree.roots.length > 0; } ngDoCheck() { this.selectedNode = this.viewState.selectedTreeNode(this.tree); this.changeDetector.detectChanges(); } ngOnInit() { this.subscription = this.connection.subscribe(this.onReceiveMessage.bind(this)); this.connection.reconnect().then(() => this.requestTree()); } ngOnDestroy() { if (this.subscription) { this.subscription.unsubscribe(); } if (this.unsubscribeUncaughtErrorListener) { this.unsubscribeUncaughtErrorListener(); } this.connection.close(); } onSelectNode(node: Node, beforeLoad?: () => void) { this.selectedNode = node; if (node == null) { this.viewState.unselect(); return; } this.viewState.select(node); const m = MessageFactory.selectComponent(node, node.isComponent); const promise = this.directConnection.handleImmediate(m).then(response => { if (!response) { return; } if (typeof beforeLoad === 'function') { beforeLoad(); } const { instance, metadata, providers, componentMetadata } = response; return <InstanceWithMetadata>{ instance, providers, metadata: new Map(metadata), componentMetadata: new Map(componentMetadata) }; }); this.componentState.wait(node, promise); } onInspectElement(node: Node) { chrome.devtools.inspectedWindow.eval(`inspect(inspectedApplication.nodeFromPath('${node.id}'))`); } onCollapseChildren(node: Node) { this.recursiveExpansionState(node, ExpandState.Collapsed); } onExpandChildren(node: Node) { this.recursiveExpansionState(node, ExpandState.Expanded); } onReportError() { if (this.error && this.error.errorType === ApplicationErrorType.UncaughtException) { reportUncaughtError(this.error.error, this.ngVersion); this.error = null; } } onSelectedTabChange(tab: Tab) { this.routerTree = this.routerTree ? [].concat(this.routerTree) : null; this.mainActions.selectTab(tab); } onSelectedComponentsSubTabMenuChange(tab: StateTab) { this.mainActions.selectComponentsSubTab(tab); } onDOMSelectionActiveChange(state: boolean) { this.mainActions.setDOMSelectionActive(state); } onEmitValue(data) { this.mainActions.emitValue(data.path, data.data); } onUpdateProperty(data) { this.mainActions.updateProperty(data.path, data.data); } private requestTree() { const options = this.options.simpleOptions(); this.connection.send(MessageFactory.initialize(options)).catch(error => { this.error = new ApplicationError(ApplicationErrorType.UncaughtException, error); this.changeDetector.detectChanges(); }); } private refresh() { this.connection.send(MessageFactory.refresh()); } onRefresh() { this.error = null; this.refresh(); } private restoreSelection() { this.selectedNode = this.viewState.selectedTreeNode(this.tree); this.onSelectNode(this.selectedNode, () => this.componentState.reset()); } private processMessage(msg: Message<any>, sendResponse: (response: MessageResponse<any>) => void) { const respond = () => { sendResponse(MessageFactory.response(msg, { processed: true }, false)); }; switch (msg.messageType) { case MessageType.Ping: this.restoreSelection(); break; case MessageType.NotNgApp: this.error = new ApplicationError(ApplicationErrorType.NotNgApp); respond(); break; case MessageType.Push: this.directConnection.readQueue((innerMessage, innerRespond) => this.processMessage(innerMessage, innerRespond) ); break; case MessageType.CompleteTree: this.createTree(msg.content); respond(); break; case MessageType.TreeDiff: if (this.tree == null) { this.connection.send(MessageFactory.initialize(this.options.simpleOptions())); // request tree } else { this.updateTree(msg.content); } respond(); break; case MessageType.TreeUnchanged: this.restoreSelection(); break; case MessageType.RouterTree: // TODO(cbond): support router tree diff this.routerTree = msg.content; respond(); break; case MessageType.NgModules: this.ngModules = msg.content; respond(); break; case MessageType.NgVersion: this.ngVersion = msg.content; respond(); break; case MessageType.FindElement: if (msg.content.node) { this.viewState.select(msg.content.node); this.viewState.expandState(msg.content.node, ExpandState.Expanded); this.mainActions.setDOMSelectionActive(true); if (msg.content.stop) { this.userActions.cancelFindElement(); this.mainActions.setDOMSelectionActive(false); } break; } break; case MessageType.ApplicationError: this.error = msg.content; respond(); break; case MessageType.ErrorCleared: if (this.error && msg.content.errorTypes.includes(this.error.errorType)) { this.error = null; } respond(); break; } } private createTree(roots: Array<Node>) { this.componentState.reset(); this.tree = createTree(roots); this.restoreSelection(); } private updateTree(changes) { /// Patch the treee this.tree.patch(changes); /// This operation must happen after the tree patch const changedIdentifiers = this.extractIdentifiersFromChanges(changes); /// Highlight the nodes that have changed this.viewState.nodesChanged(changedIdentifiers); this.restoreSelection(); } private onReceiveMessage(msg: Message<any>, sendResponse: (response: MessageResponse<any>) => void) { this.zone.run(() => this.processMessage(msg, sendResponse)); } private extractIdentifiersFromChanges(changes: Array<Change>): string[] { const identifiers = new Set<string>(); for (const change of changes) { const path = this.nodePathFromChangePath(deserializeChangePath(change.path)); identifiers.add(serializePath(path)); } const results = new Array<string>(); identifiers.forEach(id => results.push(id)); return results; } private nodePathFromChangePath(changePath: Path) { const result = new Array<string | number>(); for (let index = 0; index < changePath.length; ++index) { switch (changePath[index]) { case 'roots': case 'children': result.push(changePath[++index]); break; } } return result; } private recursiveExpansionState(from: Node, state: ExpandState) { const apply = (node: Node) => { this.viewState.expandState(node, state); node.children.forEach(n => apply(n)); }; apply(from); } }
the_stack
import React, { useEffect, useState } from 'react'; import Form from 'antd/es/form'; import { Input, Switch, Select, Button, Tag, AutoComplete, Row, Col, notification } from 'antd'; import { useIntl } from 'umi'; import PanelSection from '@/components/PanelSection'; import { FORM_ITEM_WITHOUT_LABEL } from '@/pages/Route/constants'; import LabelsDrawer from '@/components/LabelsfDrawer'; import { fetchLabelList, fetchServiceList } from '../../service'; const MetaView: React.FC<RouteModule.Step1PassProps> = ({ disabled, form, isEdit, upstreamForm, onChange = () => {}, }) => { const { formatMessage } = useIntl(); const [visible, setVisible] = useState(false); const [labelList, setLabelList] = useState<LabelList>({}); const [serviceList, setServiceList] = useState<ServiceModule.ResponseBody[]>([]); useEffect(() => { fetchLabelList().then(setLabelList); fetchServiceList().then(({ data }) => setServiceList(data)); }, []); const NormalLabelComponent = () => { const field = 'custom_normal_labels'; return ( <React.Fragment> <Form.Item label={formatMessage({ id: 'component.global.labels' })} name={field} tooltip={formatMessage({ id: 'page.route.configuration.normal-labels.tooltip' })} > <Select mode="tags" style={{ width: '100%' }} placeholder="--" disabled={disabled} open={false} bordered={false} tagRender={(props) => { const { value, closable, onClose } = props; return ( <Tag closable={closable && !disabled} onClose={onClose} style={{ marginRight: 3 }}> {value} </Tag> ); }} /> </Form.Item> <Form.Item {...FORM_ITEM_WITHOUT_LABEL}> <Button type="dashed" disabled={disabled} onClick={() => setVisible(true)}> {formatMessage({ id: 'component.global.manage' })} </Button> </Form.Item> {visible && ( <Form.Item shouldUpdate noStyle> {() => { const labels = form.getFieldValue(field) || []; return ( <LabelsDrawer title={formatMessage({ id: 'component.label-manager' })} actionName={field} dataSource={labels} disabled={disabled || false} onChange={onChange} onClose={() => setVisible(false)} filterList={['API_VERSION']} fetchLabelList={fetchLabelList} /> ); }} </Form.Item> )} </React.Fragment> ); }; const VersionLabelComponent = () => { return ( <Form.Item label={formatMessage({ id: 'component.global.version' })} tooltip={formatMessage({ id: 'page.route.configuration.version.tooltip' })} > <Row> <Col span={10}> <Form.Item noStyle name="custom_version_label"> <AutoComplete options={(labelList.API_VERSION || []).map((item) => ({ value: item }))} disabled={disabled} placeholder={formatMessage({ id: 'page.route.configuration.version.placeholder' })} /> </Form.Item> </Col> </Row> </Form.Item> ); }; const Name: React.FC = () => ( <Form.Item label={formatMessage({ id: 'component.global.name' })} required tooltip={formatMessage({ id: 'page.route.form.itemRulesPatternMessage.apiNameRule' })} > <Row> <Col span={10}> <Form.Item noStyle name="name" rules={[ { required: true, message: formatMessage({ id: 'page.route.configuration.name.rules.required.description', }), }, { pattern: new RegExp(/^.{0,100}$/, 'g'), message: formatMessage({ id: 'page.route.form.itemRulesPatternMessage.apiNameRule', }), }, ]} > <Input placeholder={formatMessage({ id: 'page.route.configuration.name.placeholder' })} disabled={disabled} /> </Form.Item> </Col> </Row> </Form.Item> ); const Description: React.FC = () => ( <Form.Item label={formatMessage({ id: 'component.global.description' })}> <Row> <Col span={10}> <Form.Item noStyle name="desc"> <Input.TextArea placeholder={formatMessage({ id: 'component.global.input.placeholder.description' })} disabled={disabled} showCount maxLength={256} /> </Form.Item> </Col> </Row> </Form.Item> ); const Publish: React.FC = () => ( <Form.Item label={formatMessage({ id: 'page.route.publish' })} tooltip={formatMessage({ id: 'page.route.configuration.publish.tooltip' })} > <Row> <Col> <Form.Item noStyle name="status" valuePropName="checked"> <Switch disabled={isEdit} /> </Form.Item> </Col> </Row> </Form.Item> ); const WebSocket: React.FC = () => ( <Form.Item label="WebSocket"> <Row> <Col> <Form.Item noStyle valuePropName="checked" name="enable_websocket"> <Switch disabled={disabled} /> </Form.Item> </Col> </Row> </Form.Item> ); const Redirect: React.FC = () => { const list = [ { value: 'forceHttps', label: formatMessage({ id: 'page.route.select.option.enableHttps' }), }, { value: 'customRedirect', label: formatMessage({ id: 'page.route.select.option.configCustom' }), }, { value: 'disabled', label: formatMessage({ id: 'page.route.select.option.forbidden' }), }, ]; return ( <Form.Item label={formatMessage({ id: 'page.route.form.itemLabel.redirect' })} tooltip={formatMessage({ id: 'page.route.fields.custom.redirectOption.tooltip' })} > <Row> <Col span={5}> <Form.Item name="redirectOption" noStyle> <Select disabled={disabled} data-cy="route-redirect" onChange={(params) => { onChange({ action: 'redirectOptionChange', data: params }); }} > {list.map((item) => ( <Select.Option value={item.value} key={item.value}> {item.label} </Select.Option> ))} </Select> </Form.Item> </Col> </Row> </Form.Item> ); }; const CustomRedirect: React.FC = () => ( <Form.Item noStyle shouldUpdate={(prev, next) => { if (prev.redirectOption !== next.redirectOption) { onChange({ action: 'redirectOptionChange', data: next.redirectOption }); } return prev.redirectOption !== next.redirectOption; }} > {() => { if (form.getFieldValue('redirectOption') === 'customRedirect') { return ( <Form.Item label={formatMessage({ id: 'page.route.form.itemLabel.redirectCustom' })} required style={{ marginBottom: 0 }} > <Row gutter={10}> <Col span={5}> <Form.Item name="redirectURI" rules={[ { required: true, message: `${formatMessage({ id: 'component.global.pleaseEnter', })}${formatMessage({ id: 'page.route.form.itemLabel.redirectURI', })}`, }, ]} > <Input placeholder={formatMessage({ id: 'page.route.input.placeholder.redirectCustom', })} disabled={disabled} /> </Form.Item> </Col> <Col span={5}> <Form.Item name="ret_code" rules={[{ required: true }]}> <Select disabled={disabled} data-cy="redirect_code"> <Select.Option value={301}> {formatMessage({ id: 'page.route.select.option.redirect301' })} </Select.Option> <Select.Option value={302}> {formatMessage({ id: 'page.route.select.option.redirect302' })} </Select.Option> </Select> </Form.Item> </Col> </Row> </Form.Item> ); } return null; }} </Form.Item> ); const ServiceSelector: React.FC = () => ( <React.Fragment> <Form.Item label={formatMessage({ id: 'page.route.service' })} tooltip={formatMessage({ id: 'page.route.fields.service_id.tooltip' })} > <Row> <Col span={5}> <Form.Item noStyle name="service_id"> <Select showSearch disabled={disabled} optionFilterProp="children" filterOption={(input, option) => option?.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} > {/* TODO: value === '' means no service_id select, need to find a better way */} <Select.Option value="" key={Math.random().toString(36).substring(7)}> {formatMessage({ id: 'page.route.service.none' })} </Select.Option> {serviceList.map((item) => { return ( <Select.Option value={item.id} key={item.id}> {item.name} </Select.Option> ); })} </Select> </Form.Item> </Col> </Row> </Form.Item> <Form.Item noStyle shouldUpdate={(prev, next) => { // route with redirect plugin can be edit without service and upstream if (next.redirectOption === 'customRedirect') { return false; } if (next.service_id === '') { const upstream_id = upstreamForm?.getFieldValue('upstream_id'); if (upstream_id === 'None') { notification.warning({ message: formatMessage({ id: 'page.route.fields.service_id.invalid' }), description: formatMessage({ id: 'page.route.fields.service_id.without-upstream' }), }); } } return prev.service_id !== next.service_id; }} > {() => null} </Form.Item> </React.Fragment> ); return ( <PanelSection title={formatMessage({ id: 'page.route.panelSection.title.nameDescription' })}> <Name /> <NormalLabelComponent /> <VersionLabelComponent /> <Description /> <Redirect /> <CustomRedirect /> <ServiceSelector /> <WebSocket /> <Publish /> </PanelSection> ); }; export default MetaView;
the_stack
import { HardhatRuntimeEnvironment } from "hardhat/types"; import { DeployFunction } from "hardhat-deploy/types"; import { ethers, upgrades, network } from "hardhat"; import { Timelock__factory, PancakeswapV2RestrictedSingleAssetStrategyAddBaseTokenOnly__factory, PancakeswapV2RestrictedSingleAssetStrategyLiquidate__factory, PancakeswapV2RestrictedSingleAssetStrategyAddBaseWithFarm__factory, PancakeswapV2RestrictedSingleAssetStrategyWithdrawMinimizeTrading__factory, CakeMaxiWorker02__factory, CakeMaxiWorker02, } from "../../../../typechain"; import { ConfigEntity } from "../../../entities"; interface ICakeMaxiWorkerInput { VAULT_SYMBOL: string; WORKER_NAME: string; REINVEST_BOT: string; POOL_ID: number; BENEFICIAL_VAULT_SYMBOL: string; REINVEST_BOUNTY_BPS: string; BENEFICIAL_VAULT_BOUNTY_BPS: string; WORK_FACTOR: string; KILL_FACTOR: string; MAX_PRICE_DIFF: string; PATH: Array<string>; REWARD_PATH: Array<string>; REINVEST_THRESHOLD: string; EXACT_ETA: string; } interface ICakeMaxiWorkerParams { WORKER_NAME: string; VAULT_CONFIG_ADDR: string; WORKER_CONFIG_ADDR: string; REINVEST_BOT: string; POOL_ID: number; VAULT_ADDR: string; BASE_TOKEN_ADDR: string; MASTER_CHEF_ADDR: string; PANCAKESWAP_ROUTER_ADDR: string; BENEFICIAL_VAULT: string; ADD_STRAT_ADDR: string; LIQ_STRAT_ADDR: string; ADD_BASE_WITH_FARM_STRAT_ADDR: string; MINIMIZE_TRADE_STRAT_ADDR: string; REINVEST_BOUNTY_BPS: string; BENEFICIAL_VAULT_BOUNTY_BPS: string; PATH: Array<string>; REWARD_PATH: Array<string>; REINVEST_THRESHOLD: string; WORK_FACTOR: string; KILL_FACTOR: string; MAX_PRICE_DIFF: string; TIMELOCK: string; EXACT_ETA: string; } const func: DeployFunction = async function (hre: HardhatRuntimeEnvironment) { /* ░██╗░░░░░░░██╗░█████╗░██████╗░███╗░░██╗██╗███╗░░██╗░██████╗░ ░██║░░██╗░░██║██╔══██╗██╔══██╗████╗░██║██║████╗░██║██╔════╝░ ░╚██╗████╗██╔╝███████║██████╔╝██╔██╗██║██║██╔██╗██║██║░░██╗░ ░░████╔═████║░██╔══██║██╔══██╗██║╚████║██║██║╚████║██║░░╚██╗ ░░╚██╔╝░╚██╔╝░██║░░██║██║░░██║██║░╚███║██║██║░╚███║╚██████╔╝ ░░░╚═╝░░░╚═╝░░╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░╚══╝╚═╝╚═╝░░╚══╝░╚═════╝░ Check all variables below before execute the deployment script */ const shortCakeMaxiWorkerInfo: Array<ICakeMaxiWorkerInput> = [ { VAULT_SYMBOL: "ibTUSD", WORKER_NAME: "TUSD CakeMaxiWorker", POOL_ID: 0, REINVEST_BOT: "0xcf28b4da7d3ed29986831876b74af6e95211d3f9", BENEFICIAL_VAULT_SYMBOL: "ibALPACA", REINVEST_BOUNTY_BPS: "1900", BENEFICIAL_VAULT_BOUNTY_BPS: "5263", WORK_FACTOR: "6240", KILL_FACTOR: "8000", MAX_PRICE_DIFF: "11000", PATH: ["TUSD", "BUSD", "CAKE"], REWARD_PATH: ["CAKE", "BUSD", "ALPACA"], REINVEST_THRESHOLD: "1", EXACT_ETA: "1626667200", }, ]; const config = ConfigEntity.getConfig(); const workerInfos: ICakeMaxiWorkerParams[] = shortCakeMaxiWorkerInfo.map((n) => { const vault = config.Vaults.find((v) => v.symbol === n.VAULT_SYMBOL); if (vault === undefined) { throw "error: unable to find vault from the given VAULT_SYMBOL"; } const beneficialVault = config.Vaults.find((v) => v.symbol === n.BENEFICIAL_VAULT_SYMBOL); if (beneficialVault === undefined) { throw "error: unable to find beneficialVault from the given BENEFICIAL_VAULT_SYMBOL"; } const tokenList: any = config.Tokens; const path: Array<string> = n.PATH.map((p) => { const addr = tokenList[p]; if (addr === undefined) { throw `error: path: unable to find address of ${p}`; } return addr; }); const rewardPath: Array<string> = n.REWARD_PATH.map((rp) => { const addr = tokenList[rp]; if (addr === undefined) { throw `error: reward path: unable to find address of ${rp}`; } return addr; }); return { WORKER_NAME: n.WORKER_NAME, VAULT_CONFIG_ADDR: vault.config, WORKER_CONFIG_ADDR: config.SharedConfig.PancakeswapSingleAssetWorkerConfig, REINVEST_BOT: n.REINVEST_BOT, POOL_ID: n.POOL_ID, VAULT_ADDR: vault.address, BASE_TOKEN_ADDR: vault.baseToken, MASTER_CHEF_ADDR: config.Exchanges.Pancakeswap.MasterChef, PANCAKESWAP_ROUTER_ADDR: config.Exchanges.Pancakeswap.RouterV2, BENEFICIAL_VAULT: beneficialVault.address, ADD_STRAT_ADDR: config.SharedStrategies.PancakeswapSingleAsset.StrategyAddBaseTokenOnly, LIQ_STRAT_ADDR: config.SharedStrategies.PancakeswapSingleAsset.StrategyLiquidate, ADD_BASE_WITH_FARM_STRAT_ADDR: vault.StrategyAddTwoSidesOptimal.PancakeswapSingleAsset, MINIMIZE_TRADE_STRAT_ADDR: config.SharedStrategies.PancakeswapSingleAsset.StrategyWithdrawMinimizeTrading, REINVEST_BOUNTY_BPS: n.REINVEST_BOUNTY_BPS, BENEFICIAL_VAULT_BOUNTY_BPS: n.BENEFICIAL_VAULT_BOUNTY_BPS, WORK_FACTOR: n.WORK_FACTOR, KILL_FACTOR: n.KILL_FACTOR, MAX_PRICE_DIFF: n.MAX_PRICE_DIFF, PATH: path, REWARD_PATH: rewardPath, REINVEST_THRESHOLD: ethers.utils.parseEther(n.REINVEST_THRESHOLD).toString(), TIMELOCK: config.Timelock, EXACT_ETA: n.EXACT_ETA, }; }); for (let i = 0; i < workerInfos.length; i++) { console.log("==================================================================================="); console.log(`>> Deploying an upgradable CakeMaxiWorker02 contract for ${workerInfos[i].WORKER_NAME}`); const CakeMaxiWorker02 = (await ethers.getContractFactory( "CakeMaxiWorker02", ( await ethers.getSigners() )[0] )) as CakeMaxiWorker02__factory; const cakeMaxiWorker02 = (await upgrades.deployProxy(CakeMaxiWorker02, [ workerInfos[i].VAULT_ADDR, workerInfos[i].BASE_TOKEN_ADDR, workerInfos[i].MASTER_CHEF_ADDR, workerInfos[i].PANCAKESWAP_ROUTER_ADDR, workerInfos[i].BENEFICIAL_VAULT, workerInfos[i].POOL_ID, workerInfos[i].ADD_STRAT_ADDR, workerInfos[i].LIQ_STRAT_ADDR, workerInfos[i].REINVEST_BOUNTY_BPS, workerInfos[i].BENEFICIAL_VAULT_BOUNTY_BPS, workerInfos[i].PATH, workerInfos[i].REWARD_PATH, workerInfos[i].REINVEST_THRESHOLD, ])) as CakeMaxiWorker02; await cakeMaxiWorker02.deployed(); console.log(`>> Deployed at ${cakeMaxiWorker02.address}`); console.log(`>> Adding REINVEST_BOT`); await cakeMaxiWorker02.setReinvestorOk([workerInfos[i].REINVEST_BOT], true); console.log("✅ Done"); console.log(`>> Set Treasury Account`); await cakeMaxiWorker02.setTreasuryConfig(workerInfos[i].REINVEST_BOT, workerInfos[i].REINVEST_BOUNTY_BPS); console.log(`>> Adding Strategies`); await cakeMaxiWorker02.setStrategyOk( [workerInfos[i].ADD_BASE_WITH_FARM_STRAT_ADDR, workerInfos[i].MINIMIZE_TRADE_STRAT_ADDR], true ); console.log("✅ Done"); console.log(`>> Whitelisting a worker on strats`); const addStrat = PancakeswapV2RestrictedSingleAssetStrategyAddBaseTokenOnly__factory.connect( workerInfos[i].ADD_STRAT_ADDR, (await ethers.getSigners())[0] ); await addStrat.setWorkersOk([cakeMaxiWorker02.address], true); const liqStrat = PancakeswapV2RestrictedSingleAssetStrategyLiquidate__factory.connect( workerInfos[i].LIQ_STRAT_ADDR, (await ethers.getSigners())[0] ); await liqStrat.setWorkersOk([cakeMaxiWorker02.address], true); const twoSidesStrat = PancakeswapV2RestrictedSingleAssetStrategyAddBaseWithFarm__factory.connect( workerInfos[i].ADD_BASE_WITH_FARM_STRAT_ADDR, (await ethers.getSigners())[0] ); await twoSidesStrat.setWorkersOk([cakeMaxiWorker02.address], true); const minimizeStrat = PancakeswapV2RestrictedSingleAssetStrategyWithdrawMinimizeTrading__factory.connect( workerInfos[i].MINIMIZE_TRADE_STRAT_ADDR, (await ethers.getSigners())[0] ); await minimizeStrat.setWorkersOk([cakeMaxiWorker02.address], true); console.log("✅ Done"); const timelock = Timelock__factory.connect(config.Timelock, (await ethers.getSigners())[0]); console.log(">> Timelock: Setting WorkerConfig via Timelock"); const setConfigsTx = await timelock.queueTransaction( workerInfos[i].WORKER_CONFIG_ADDR, "0", "setConfigs(address[],(bool,uint64,uint64,uint64)[])", ethers.utils.defaultAbiCoder.encode( ["address[]", "(bool acceptDebt,uint64 workFactor,uint64 killFactor,uint64 maxPriceDiff)[]"], [ [cakeMaxiWorker02.address], [ { acceptDebt: true, workFactor: workerInfos[i].WORK_FACTOR, killFactor: workerInfos[i].KILL_FACTOR, maxPriceDiff: workerInfos[i].MAX_PRICE_DIFF, }, ], ] ), workerInfos[i].EXACT_ETA ); console.log(`queue setConfigs at: ${setConfigsTx.hash}`); console.log("generate timelock.executeTransaction:"); console.log( `await timelock.executeTransaction('${workerInfos[i].WORKER_CONFIG_ADDR}', '0', 'setConfigs(address[],(bool,uint64,uint64,uint64)[])', ethers.utils.defaultAbiCoder.encode(['address[]','(bool acceptDebt,uint64 workFactor,uint64 killFactor,uint64 maxPriceDiff)[]'],[['${cakeMaxiWorker02.address}'], [{acceptDebt: true, workFactor: ${workerInfos[i].WORK_FACTOR}, killFactor: ${workerInfos[i].KILL_FACTOR}, maxPriceDiff: ${workerInfos[i].MAX_PRICE_DIFF}}]]), ${workerInfos[i].EXACT_ETA})` ); console.log("✅ Done"); console.log(">> Timelock: Linking VaultConfig with WorkerConfig via Timelock"); const setWorkersTx = await timelock.queueTransaction( workerInfos[i].VAULT_CONFIG_ADDR, "0", "setWorkers(address[],address[])", ethers.utils.defaultAbiCoder.encode( ["address[]", "address[]"], [[cakeMaxiWorker02.address], [workerInfos[i].WORKER_CONFIG_ADDR]] ), workerInfos[i].EXACT_ETA ); console.log(`queue setWorkers at: ${setWorkersTx.hash}`); console.log("generate timelock.executeTransaction:"); console.log( `await timelock.executeTransaction('${workerInfos[i].VAULT_CONFIG_ADDR}', '0','setWorkers(address[],address[])', ethers.utils.defaultAbiCoder.encode(['address[]','address[]'],[['${cakeMaxiWorker02.address}'], ['${workerInfos[i].WORKER_CONFIG_ADDR}']]), ${workerInfos[i].EXACT_ETA})` ); console.log("✅ Done"); } }; export default func; func.tags = ["CakeMaxiWorkers02"];
the_stack
import { Address, AppInstanceJson, EventNames, IChannelSigner, ILockService, ILoggerService, IMessagingService, IStoreService, ProtocolEventMessage, MethodName, MethodNames, MethodParams, MiddlewareContext, MinimalTransaction, NetworkContexts, Opcode, ProtocolMessage, ProtocolMessageData, ProtocolName, PublicIdentifier, STORE_SCHEMA_VERSION, ValidationMiddleware, EventName, IOnchainTransactionService, } from "@connext/types"; import { abrv, delay, nullLogger, stringify } from "@connext/utils"; import EventEmitter from "eventemitter3"; import { UNASSIGNED_SEQ_NO, IO_SEND_AND_WAIT_TIMEOUT } from "./constants"; import { Deferred } from "./deferred"; import { SetStateCommitment, ConditionalTransactionCommitment } from "./ethereum"; import { ProtocolRunner } from "./machine"; import { StateChannel, AppInstance } from "./models"; import { RequestHandler } from "./request-handler"; import { RpcRouter } from "./rpc-router"; import { MethodRequest, MethodResponse, PersistAppType, PersistStateChannelType } from "./types"; export interface NodeConfig { STORE_KEY_PREFIX: string; } const REASONABLE_NUM_BLOCKS_TO_WAIT = 1; export class CFCore { private readonly incoming: EventEmitter; private readonly outgoing: EventEmitter; private readonly ioSendDeferrals = new Map<string, Deferred<ProtocolMessage>>(); private readonly protocolRunner: ProtocolRunner; /** * These properties don't have initializers in the constructor, since they must be initialized * asynchronously. This is done via the `asynchronouslySetupUsingRemoteServices` function. * Since we have a private constructor and only allow instances of CFCore to be created * via `create` which immediately calls `asynchronouslySetupUsingRemoteServices`, these are * always non-null when CFCore is being used. */ protected requestHandler!: RequestHandler; public rpcRouter!: RpcRouter; static create( messagingService: IMessagingService, storeService: IStoreService, networkContexts: NetworkContexts, signer: IChannelSigner, lockService: ILockService, blocksNeededForConfirmation?: number, logger?: ILoggerService, syncOnStart: boolean = true, onchainTransactionService: IOnchainTransactionService | undefined = undefined, ): Promise<CFCore> { const node = new CFCore( signer, messagingService, storeService, networkContexts, blocksNeededForConfirmation, logger, lockService, onchainTransactionService, ); return node.asynchronouslySetupUsingRemoteServices(syncOnStart); } private constructor( private readonly signer: IChannelSigner, private readonly messagingService: IMessagingService, private readonly storeService: IStoreService, public readonly networkContexts: NetworkContexts, public readonly blocksNeededForConfirmation: number = REASONABLE_NUM_BLOCKS_TO_WAIT, public readonly log: ILoggerService = nullLogger, private readonly lockService: ILockService, private readonly transactionService: IOnchainTransactionService | undefined = undefined, ) { this.log = log.newContext("CFCore"); this.incoming = new EventEmitter(); this.outgoing = new EventEmitter(); this.protocolRunner = this.buildProtocolRunner(); this.log.info(`Using network contexts with chain ids: ${Object.keys(networkContexts)}`); } get signerAddress(): Address { return this.signer.address; } get publicIdentifier(): PublicIdentifier { return this.signer.publicIdentifier; } private async asynchronouslySetupUsingRemoteServices(syncOnStart: boolean): Promise<CFCore> { this.log.info( `Signer address: ${this.signer.address} | public id: ${this.signer.publicIdentifier}`, ); this.requestHandler = new RequestHandler( this.publicIdentifier, this.incoming, this.outgoing, this.storeService, this.messagingService, this.protocolRunner, this.networkContexts, this.signer, this.blocksNeededForConfirmation!, this.lockService, this.log, this.transactionService, ); this.registerMessagingConnection(); this.rpcRouter = new RpcRouter(this.requestHandler); this.requestHandler.injectRouter(this.rpcRouter); const channels = await this.storeService.getAllChannels(); this.log.info( `Given store contains ${channels.length} channels: [${ channels.length > 10 ? channels .map((c) => abrv(c.multisigAddress)) .slice(0, 10) .toString() + ", ..." : channels.map((c) => abrv(c.multisigAddress)) }]`, ); if (!syncOnStart) { return this; } await Promise.all( channels.map(async (channel) => { this.log.info(`Syncing channel ${channel.multisigAddress}`); await this.rpcRouter.dispatch({ methodName: MethodNames.chan_sync, parameters: { multisigAddress: channel.multisigAddress } as MethodParams.Sync, id: Date.now(), }); }), ); return this; } /** * Attaches middleware for the chosen opcode. Currently, only `OP_VALIDATE` * is accepted as an injected middleware */ public injectMiddleware(opcode: Opcode, middleware: ValidationMiddleware): void { if (opcode !== Opcode.OP_VALIDATE) { throw new Error(`Cannot inject middleware for opcode: ${opcode}`); } this.protocolRunner.register(opcode, async (args: [ProtocolName, MiddlewareContext]) => { const [protocol, context] = args; const middlewareRet = await Promise.race([ new Promise((resolve) => { middleware(protocol, context) .catch((e) => resolve(e.stack || e.message)) .then(() => resolve(undefined)); }), new Promise((resolve) => { delay(IO_SEND_AND_WAIT_TIMEOUT).then(() => resolve( `Failed to execute validation middleware for ${protocol} within ${ IO_SEND_AND_WAIT_TIMEOUT / 1000 }s.`, ), ); }), ]); return middlewareRet; }); } /** * Instantiates a new _ProtocolRunner_ object and attaches middleware * for the OP_SIGN, IO_SEND, and IO_SEND_AND_WAIT opcodes. */ private buildProtocolRunner(): ProtocolRunner { const protocolRunner = new ProtocolRunner( this.networkContexts, this.storeService, this.log.newContext("CF-ProtocolRunner"), ); protocolRunner.register(Opcode.OP_SIGN, async (args: any[]) => { if (args.length !== 1) { throw new Error("OP_SIGN middleware received wrong number of arguments."); } const [commitmentHash] = args; return this.signer.signMessage(commitmentHash); }); protocolRunner.register( Opcode.IO_SEND, async (args: [ProtocolMessageData, StateChannel, AppInstance, any]) => { const [data, channel, appContext, protocolMeta] = args; // check if the protocol start time exists within the message // and if it is a final protocol message (see note in // types/messaging.ts) const { prevMessageReceived, seq } = data; if (prevMessageReceived && seq === UNASSIGNED_SEQ_NO) { const diff = Date.now() - prevMessageReceived; if (diff > IO_SEND_AND_WAIT_TIMEOUT) { throw new Error( `Execution took longer than ${ IO_SEND_AND_WAIT_TIMEOUT / 1000 }s. Aborting message: ${stringify(data)}`, ); } } await this.messagingService.send(data.to, { data, from: this.publicIdentifier, type: EventNames.PROTOCOL_MESSAGE_EVENT, }); return { channel, appContext, protocolMeta }; }, ); protocolRunner.register( Opcode.IO_SEND_AND_WAIT, async (args: [ProtocolMessageData, StateChannel?, AppInstance?]) => { const [data, channel, appContext] = args; const deferral = new Deferred<ProtocolMessage>(); this.ioSendDeferrals.set(data.processID, deferral); const counterpartyResponse = deferral.promise; await this.messagingService.send(data.to, { data, from: this.publicIdentifier, type: EventNames.PROTOCOL_MESSAGE_EVENT, }); // 10 seconds is the default lock acquiring time time const msg = await Promise.race<ProtocolMessage | void>([ counterpartyResponse, delay(IO_SEND_AND_WAIT_TIMEOUT), ]); if (!msg || !msg.data) { throw new Error( `IO_SEND_AND_WAIT timed out after ${ IO_SEND_AND_WAIT_TIMEOUT / 1000 }s waiting for counterparty reply in ${data.protocol}`, ); } // Removes the deferral from the list of pending defferals after // its promise has been resolved and the necessary callback (above) // has been called. Note that, as is, only one defferal can be open // per counterparty at the moment. this.ioSendDeferrals.delete(data.processID); // Check if there is an error reason in the response, and throw // the error here if so // NOTE: only errors that are thrown from protocol execution when the // counterparty is waiting for a response should be sent const { error } = msg.data; if (error) { throw new Error( `Counterparty execution of ${ data.protocol } failed: ${error}. \nCounterparty was responding to: ${stringify(data)}`, ); } return { message: msg, channel, appContext }; }, ); protocolRunner.register( Opcode.PERSIST_STATE_CHANNEL, async ( args: [ PersistStateChannelType, StateChannel, // post protocol channel (MinimalTransaction | SetStateCommitment | ConditionalTransactionCommitment)[], // signed commitments AppInstance[], // affected apps (multiple for reject) ], ) => { const [type, stateChannel, signedCommitments, affectedApps] = args; switch (type) { case PersistStateChannelType.CreateChannel: { const [setup, freeBalance] = signedCommitments as [ MinimalTransaction, SetStateCommitment, ]; await this.storeService.createStateChannel( stateChannel.toJson(), setup, freeBalance.toJson(), ); await this.storeService.updateSchemaVersion(STORE_SCHEMA_VERSION); break; } case PersistStateChannelType.SyncRejectedProposals: { // NOTE: this relies on `removeAppProposal` being idempotent // and functional concurrent writes of the store await Promise.all( affectedApps.map((app) => this.storeService.removeAppProposal( stateChannel.multisigAddress, app.identityHash, stateChannel.toJson(), ), ), ); break; } case PersistStateChannelType.SyncProposal: { const [setState, conditional] = signedCommitments as [ SetStateCommitment, ConditionalTransactionCommitment, ]; const [appContext] = affectedApps; if (!appContext || !setState || !conditional) { // adding a rejected proposal await this.storeService.updateNumProposedApps( stateChannel.multisigAddress, stateChannel.numProposedApps, stateChannel.toJson(), ); break; } // this is adding a proposal await this.storeService.createAppProposal( stateChannel.multisigAddress, appContext.toJson(), stateChannel.numProposedApps, setState.toJson(), conditional.toJson(), stateChannel.toJson(), ); break; } case PersistStateChannelType.SyncInstall: { const [setState] = signedCommitments as [SetStateCommitment]; const [appContext] = affectedApps; if (!appContext || !setState) { throw new Error( "Could not find sufficient information to store channel with installed app from sync method. Check middlewares.", ); } await this.storeService.createAppInstance( stateChannel.multisigAddress, appContext.toJson(), stateChannel.freeBalance.toJson(), setState.toJson(), stateChannel.toJson(), ); break; } case PersistStateChannelType.SyncUninstall: { const [setState] = signedCommitments as [SetStateCommitment]; const [appContext] = affectedApps; if (!appContext || !setState) { throw new Error( `Could not find sufficient information to store channel with uninstalled app from sync method. Check middlewares. Missing appContext: ${!!appContext}, missing setState: ${!!setState}`, ); } await this.storeService.removeAppInstance( stateChannel.multisigAddress, appContext.toJson(), stateChannel.freeBalance.toJson(), setState.toJson(), stateChannel.toJson(), ); break; } case PersistStateChannelType.SyncAppInstances: { for (const commitment of signedCommitments as SetStateCommitment[]) { await this.storeService.updateAppInstance( stateChannel.multisigAddress, stateChannel.appInstances.get(commitment.appIdentityHash)!.toJson(), commitment.toJson(), stateChannel.toJson(), ); } break; } case PersistStateChannelType.NoChange: { break; } default: { const c: never = type; throw new Error(`Unrecognized persist state channel type: ${stringify(c)}`); } } return { channel: stateChannel }; }, ); protocolRunner.register( Opcode.PERSIST_APP_INSTANCE, async ( args: [ PersistAppType, StateChannel, AppInstance | AppInstanceJson, SetStateCommitment, ConditionalTransactionCommitment, ], ) => { const [ type, postProtocolChannel, app, signedSetStateCommitment, signedConditionalTxCommitment, ] = args; const { multisigAddress, numProposedApps, freeBalance } = postProtocolChannel; const { identityHash } = app; let appContext: AppInstance | AppInstanceJson | undefined; switch (type) { case PersistAppType.CreateProposal: { await this.storeService.createAppProposal( multisigAddress, app as AppInstanceJson, numProposedApps, signedSetStateCommitment.toJson(), signedConditionalTxCommitment.toJson(), postProtocolChannel.toJson(), ); break; } case PersistAppType.RemoveProposal: { await this.storeService.removeAppProposal( multisigAddress, identityHash, postProtocolChannel.toJson(), ); break; } case PersistAppType.CreateInstance: { await this.storeService.createAppInstance( multisigAddress, (app as AppInstance).toJson(), freeBalance.toJson(), signedSetStateCommitment.toJson(), postProtocolChannel.toJson(), ); break; } case PersistAppType.UpdateInstance: { await this.storeService.updateAppInstance( multisigAddress, (app as AppInstance).toJson(), signedSetStateCommitment.toJson(), postProtocolChannel.toJson(), ); break; } case PersistAppType.RemoveInstance: { await this.storeService.removeAppInstance( multisigAddress, (app as AppInstance).toJson(), freeBalance.toJson(), signedSetStateCommitment.toJson(), postProtocolChannel.toJson(), ); // final state of app before uninstall appContext = app; break; } case PersistAppType.Reject: { await this.storeService.removeAppProposal( multisigAddress, identityHash, postProtocolChannel.toJson(), ); break; } default: { const c: never = type; throw new Error(`Unrecognized app persistence call: ${c}`); } } return { channel: postProtocolChannel, appContext }; }, ); return protocolRunner; } /** * This is the entrypoint to listening for messages from other CFCores. * Delegates setting up a listener to CFCore's outgoing EventEmitter. * @param event * @param callback */ on(event: EventName | MethodName, callback: (res: any) => void) { this.rpcRouter.subscribe(event, async (res: any) => callback(res)); } /** * Stops listening for a given message from other CFCores. If no callback is passed, * all callbacks are removed. * * @param event * @param [callback] */ off(event: EventName | MethodName, callback?: (res: any) => void) { this.rpcRouter.unsubscribe(event, callback ? async (res: any) => callback(res) : undefined); } removeAllListeners() { this.rpcRouter.unsubscribeAll(); } /** * This is the entrypoint to listening for messages from other CFCores. * Delegates setting up a listener to CFCore's outgoing EventEmitter. * It'll run the callback *only* once. * * @param event * @param [callback] */ once(event: EventName | MethodName, callback: (res: any) => void) { this.rpcRouter.subscribeOnce(event, async (res: any) => callback(res)); } /** * Delegates emitting events to CFCore's incoming EventEmitter. * @param event * @param req */ emit(event: EventName | MethodName, req: MethodRequest) { this.rpcRouter.emit(event, req); } /** * Makes a direct call to CFCore for a specific method. * @param method * @param req */ async call(method: MethodName, req: MethodRequest): Promise<MethodResponse> { return this.requestHandler.callMethod(method, req); } /** * When CFCore is first instantiated, it establishes a connection * with the messaging service. When it receives a message, it emits * the message to its registered subscribers, usually external * subscribed (i.e. consumers of CFCore). */ private registerMessagingConnection() { this.messagingService.onReceive( this.publicIdentifier, async (msg: ProtocolEventMessage<any>) => { try { await this.handleReceivedMessage(msg); this.rpcRouter.emit(msg.type, msg, "outgoing"); } catch (e) { // No need to crash the entire cfCore if we receive an invalid message. // Just log & wait for the next one this.log.error(`Failed to handle ${msg.type} message: ${e.message}`); } }, ); } /** * Messages received by CFCore fit into one of three categories: * * (a) A Message which is _not_ a ProtocolMessage; * this is a standard received message which is handled by a named * controller in the _events_ folder. * * (b) A Message which is a ProtocolMessage _and_ * has no registered _ioSendDeferral_ callback. In this case, it means * it will be sent to the protocol message event controller to dispatch * the received message to the instruction executor. * * (c) A Message which is a ProtocolMessage _and_ * _does have_ an _ioSendDeferral_, in which case the message is dispatched * solely to the deffered promise's resolve callback. */ private async handleReceivedMessage(msg: ProtocolEventMessage<any>) { if (!Object.values(EventNames).includes(msg.type)) { this.log.error(`Received message with unknown event type: ${msg.type}`); } const isProtocolMessage = (msg: ProtocolEventMessage<any>) => msg.type === EventNames.PROTOCOL_MESSAGE_EVENT; const isExpectingResponse = (msg: ProtocolMessage) => this.ioSendDeferrals.has(msg.data.processID); if (isProtocolMessage(msg) && isExpectingResponse(msg as ProtocolMessage)) { await this.handleIoSendDeferral(msg as ProtocolMessage); } else if (this.requestHandler.isLegacyEvent(msg.type)) { await this.requestHandler.callEvent(msg.type, msg); } else { await this.rpcRouter.emit(msg.type, msg); } } private async handleIoSendDeferral(msg: ProtocolMessage) { const key = msg.data.processID; if (!this.ioSendDeferrals.has(key)) { throw new Error("CFCore received message intended for machine but no handler was present"); } const promise = this.ioSendDeferrals.get(key)!; try { promise.resolve(msg); } catch (error) { this.log.error( `Error while executing callback registered by IO_SEND_AND_WAIT middleware hook error ${JSON.stringify( error, null, 2, )} msg ${JSON.stringify(msg, null, 2)}`, ); } } }
the_stack
import { assert } from 'chai'; import { addStage, Konva, simulateMouseDown, simulateMouseMove, simulateMouseUp, simulateTouchStart, simulateTouchEnd, simulateTouchMove, } from './test-utils'; describe('DragAndDrop', function () { // ====================================================== it('test drag and drop properties and methods', function (done) { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: stage.width() / 2, y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', }); stage.add(layer); layer.add(circle); setTimeout(function () { layer.draw(); // test defaults assert.equal(circle.draggable(), false); //change properties circle.setDraggable(true); //circle.on('click', function(){}); layer.draw(); // test new properties assert.equal(circle.draggable(), true); done(); }, 50); }); // ====================================================== it('multiple drag and drop sets with setDraggable()', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 380, y: stage.height() / 2, radius: 70, strokeWidth: 4, fill: 'red', stroke: 'black', }); circle.setDraggable(true); assert.equal(circle.draggable(), true); circle.setDraggable(true); assert.equal(circle.draggable(), true); circle.setDraggable(false); assert.equal(!circle.draggable(), true); layer.add(circle); stage.add(layer); }); // ====================================================== it('right click is not for dragging', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: stage.width() / 2, y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); layer.add(circle); stage.add(layer); simulateMouseDown(stage, { x: 291, y: 112, }); simulateMouseMove(stage, { x: 311, y: 112, }); assert(circle.isDragging(), 'dragging is ok'); simulateMouseUp(stage, { x: 291, y: 112, }); assert(!circle.isDragging(), 'drag stopped'); simulateMouseDown(stage, { x: 291, y: 112, button: 2, }); simulateMouseMove(stage, { x: 311, y: 112, button: 2, }); assert(circle.isDragging() === false, 'no dragging with right click'); Konva.dragButtons = [0, 2]; simulateMouseUp(stage, { x: 291, y: 112, button: 2, }); // simulate buttons change simulateMouseDown(stage, { x: 291, y: 112, button: 2, }); simulateMouseMove(stage, { x: 311, y: 112, button: 2, }); assert(circle.isDragging() === true, 'now dragging with right click'); simulateMouseUp(stage, { x: 291, y: 112, button: 2, }); Konva.dragButtons = [0]; }); // ====================================================== it('changing draggable on mousedown should take effect', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: stage.width() / 2, y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', }); layer.add(circle); stage.add(layer); circle.on('mousedown', () => { circle.draggable(true); }); simulateMouseDown(stage, { x: circle.x(), y: circle.y(), }); simulateMouseMove(stage, { x: circle.x() + 10, y: circle.y() + 10, }); assert.equal(circle.isDragging(), true); simulateMouseUp(stage, { x: circle.x() + 10, y: circle.y() + 10, }); }); // ====================================================== it('while dragging do not draw hit', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var dragLayer = new Konva.Layer(); stage.add(dragLayer); var circle = new Konva.Circle({ x: stage.width() / 2, y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); dragLayer.add(circle); dragLayer.draw(); var rect = new Konva.Rect({ fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', width: 50, height: 50, draggable: true, }); layer.add(rect); layer.draw(); var shape = layer.getIntersection({ x: 2, y: 2, }); assert.equal(shape, rect, 'rect is detected'); simulateMouseDown(stage, { x: stage.width() / 2, y: stage.height() / 2, }); simulateMouseMove(stage, { x: stage.width() / 2 + 5, y: stage.height() / 2, }); // redraw layer. hit must be not touched for not dragging layer layer.draw(); shape = layer.getIntersection({ x: 2, y: 2, }); assert.equal(shape, rect, 'rect is still detected'); assert(circle.isDragging(), 'dragging is ok'); dragLayer.draw(); shape = dragLayer.getIntersection({ x: stage.width() / 2, y: stage.height() / 2, }); // as dragLayer under dragging we should not able to detect intersect assert.equal(!!shape, false, 'circle is not detected'); simulateMouseUp(stage, { x: 291, y: 112, }); }); // ====================================================== it('it is possible to change layer while dragging', function () { var stage = addStage(); var startDragLayer = new Konva.Layer(); stage.add(startDragLayer); var endDragLayer = new Konva.Layer(); stage.add(endDragLayer); var circle = new Konva.Circle({ x: stage.width() / 2, y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); startDragLayer.add(circle); startDragLayer.draw(); var rect = new Konva.Rect({ fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', width: 50, height: 50, draggable: true, }); endDragLayer.add(rect); endDragLayer.draw(); simulateMouseDown(stage, { x: stage.width() / 2, y: stage.height() / 2, }); simulateMouseMove(stage, { x: stage.width() / 2 + 5, y: stage.height() / 2, }); // change layer while dragging circle circle.moveTo(endDragLayer); // move rectange for test hit update rect.moveTo(startDragLayer); startDragLayer.draw(); var shape = startDragLayer.getIntersection({ x: 2, y: 2, }); assert.equal(shape, rect, 'rect is detected'); assert(circle.isDragging(), 'dragging is ok'); endDragLayer.draw(); shape = endDragLayer.getIntersection({ x: stage.width() / 2, y: stage.height() / 2, }); // as endDragLayer under dragging we should not able to detect intersect assert.equal(!!shape, false, 'circle is not detected'); simulateMouseUp(stage, { x: 291, y: 112, }); }); // ====================================================== it('removing parent of draggable node should not throw error', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var circle = new Konva.Circle({ x: 380, y: stage.height() / 2, radius: 70, strokeWidth: 4, fill: 'red', stroke: 'black', draggable: true, }); layer.add(circle); simulateMouseMove(stage, { x: stage.width() / 2 + 5, y: stage.height() / 2, }); circle.startDrag(); try { layer.destroy(); assert.equal(true, true, 'no error, that is very good'); } catch (e) { assert.equal(true, false, 'error happened'); } }); it('update hit on stage drag end', function (done) { var stage = addStage(); stage.draggable(true); var layer = new Konva.Layer(); stage.add(layer); var circle = new Konva.Circle({ x: stage.width() / 2, y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', }); layer.add(circle); layer.draw(); simulateMouseDown(stage, { x: stage.width() / 2, y: stage.height() / 2, }); simulateMouseMove(stage, { x: stage.width() / 2 - 50, y: stage.height() / 2, }); setTimeout(function () { assert.equal(stage.isDragging(), true); simulateMouseUp(stage, { x: stage.width() / 2 - 50, y: stage.height() / 2, }); setTimeout(function () { var shape = layer.getIntersection({ x: stage.width() / 2 + 5, y: stage.height() / 2, }); assert.equal(shape, circle); done(); }, 100); }, 50); }); it('removing shape while drag and drop should no throw error', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: stage.width() / 2, y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); layer.add(circle); stage.add(layer); simulateMouseDown(stage, { x: 291, y: 112, }); circle.remove(); simulateMouseMove(stage, { x: 311, y: 112, }); simulateMouseUp(stage, { x: 291, y: 112, button: 2, }); assert(Konva.isDragging() === false); }); it('destroying shape while drag and drop should no throw error', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: stage.width() / 2, y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); layer.add(circle); stage.add(layer); simulateMouseDown(stage, { x: 291, y: 112, }); circle.destroy(); simulateMouseMove(stage, { x: 311, y: 112, }); simulateMouseUp(stage, { x: 291, y: 112, }); assert(Konva.isDragging() === false); }); it('drag start should trigger before movement', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 70, y: 70, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); layer.add(circle); stage.add(layer); circle.on('dragstart', function () { assert.equal(circle.x(), 70); assert.equal(circle.y(), 70); }); simulateMouseDown(stage, { x: 70, y: 70, }); simulateMouseMove(stage, { x: 100, y: 100, }); simulateMouseUp(stage, { x: 100, y: 100, }); }); it('drag with touch', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 70, y: 70, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); layer.add(circle); stage.add(layer); circle.on('dragstart', function () { assert.equal(circle.x(), 70); assert.equal(circle.y(), 70); }); simulateTouchStart(stage, { x: 70, y: 70, }); simulateTouchMove(stage, { x: 100, y: 100, }); simulateTouchEnd(stage, { x: 100, y: 100, }); assert.equal(circle.x(), 100); assert.equal(circle.y(), 100); }); it('drag with multi-touch (second finger on empty space)', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 70, y: 70, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); layer.add(circle); stage.add(layer); circle.on('dragstart', function () { assert.equal(circle.x(), 70); assert.equal(circle.y(), 70); }); simulateTouchStart(stage, [ { x: 70, y: 70, id: 0, }, { x: 270, y: 270, id: 1, }, ]); simulateTouchMove(stage, [ { x: 100, y: 100, id: 0, }, { x: 270, y: 270, id: 1, }, ]); simulateTouchEnd(stage, [ { x: 100, y: 100, id: 0, }, { x: 270, y: 270, id: 1, }, ]); assert.equal(circle.x(), 100); assert.equal(circle.y(), 100); }); it('drag with multi-touch (two shapes)', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var circle1 = new Konva.Circle({ x: 70, y: 70, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); layer.add(circle1); var circle2 = new Konva.Circle({ x: 270, y: 70, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); layer.add(circle2); layer.draw(); var dragstart1 = 0; var dragmove1 = 0; circle1.on('dragstart', function () { dragstart1 += 1; }); circle1.on('dragmove', function () { dragmove1 += 1; }); var dragstart2 = 0; var dragmove2 = 0; circle2.on('dragstart', function () { dragstart2 += 1; }); circle2.on('dragmove', function () { dragmove2 += 1; }); simulateTouchStart(stage, [ { x: 70, y: 70, id: 0, }, { x: 270, y: 70, id: 1, }, ]); // move one finger simulateTouchMove( stage, [ { x: 100, y: 100, id: 0, }, { x: 270, y: 70, id: 1, }, ], [ { x: 100, y: 100, id: 0, }, ] ); assert.equal(dragstart1, 1); assert.equal(circle1.isDragging(), true); assert.equal(dragmove1, 1); assert.equal(dragmove2, 0); assert.equal(circle1.x(), 100); assert.equal(circle1.y(), 100); // move second finger simulateTouchMove(stage, [ { x: 100, y: 100, id: 0, }, { x: 290, y: 70, id: 1, }, ]); assert.equal(dragstart2, 1); assert.equal(circle2.isDragging(), true); assert.equal(dragmove2, 1); assert.equal(circle2.x(), 290); assert.equal(circle2.y(), 70); // remove first finger simulateTouchEnd( stage, [ { x: 290, y: 70, id: 1, }, ], [ { x: 100, y: 100, id: 0, }, ] ); assert.equal(circle1.isDragging(), false); assert.equal(circle2.isDragging(), true); assert.equal(Konva.DD.isDragging, true); // remove first finger simulateTouchEnd( stage, [], [ { x: 290, y: 70, id: 1, }, ] ); assert.equal(circle2.isDragging(), false); assert.equal(Konva.DD.isDragging, false); }); it('drag with multi-touch (same shape)', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var circle1 = new Konva.Circle({ x: 70, y: 70, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); layer.add(circle1); layer.draw(); var dragstart1 = 0; var dragmove1 = 0; circle1.on('dragstart', function () { dragstart1 += 1; }); circle1.on('dragmove', function () { dragmove1 += 1; }); simulateTouchStart(stage, [ { x: 70, y: 70, id: 0, }, ]); // move one finger simulateTouchMove(stage, [ { x: 75, y: 75, id: 0, }, ]); simulateTouchStart( stage, [ { x: 75, y: 75, id: 0, }, { x: 80, y: 80, id: 1, }, ], [ { x: 80, y: 80, id: 1, }, ] ); simulateTouchMove( stage, [ { x: 75, y: 75, id: 0, }, { x: 85, y: 85, id: 1, }, ], [ { x: 85, y: 85, id: 1, }, ] ); assert.equal(dragstart1, 1); assert.equal(circle1.isDragging(), true); assert.equal(dragmove1, 1); assert.equal(circle1.x(), 75); assert.equal(circle1.y(), 75); // remove first finger simulateTouchEnd( stage, [], [ { x: 75, y: 75, id: 0, }, { x: 85, y: 85, id: 1, }, ] ); }); it('can stop drag on dragstart without changing position later', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 70, y: 70, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); layer.add(circle); stage.add(layer); circle.on('dragstart', function () { circle.stopDrag(); }); circle.on('dragmove', function () { assert.equal(false, true, 'dragmove called!'); }); simulateMouseDown(stage, { x: 70, y: 70, }); simulateMouseMove(stage, { x: 100, y: 100, }); simulateMouseUp(stage, { x: 100, y: 100, }); assert.equal(circle.x(), 70); assert.equal(circle.y(), 70); }); it('can force drag at any time (when pointer already registered)', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 70, y: 70, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); layer.add(circle); stage.add(layer); simulateMouseMove(stage, { x: 70, y: 70 }); circle.startDrag(); assert.equal(circle.isDragging(), true); simulateMouseMove(stage, { x: 80, y: 80 }); simulateMouseUp(stage, { x: 80, y: 80 }); assert.equal(circle.x(), 80); assert.equal(circle.y(), 80); }); it('can force drag at any time (when pointer not registered)', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 70, y: 70, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); layer.add(circle); stage.add(layer); circle.startDrag(); assert.equal(circle.isDragging(), true); // let us think that offset will be equal 0 if not registered pointers simulateMouseMove(stage, { x: 80, y: 80 }); simulateMouseUp(stage, { x: 80, y: 80 }); assert.equal(circle.x(), 80); assert.equal(circle.y(), 80); }); it('calling startDrag show still fire event when required', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 70, y: 70, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); var dragstart = 0; circle.on('dragstart', function () { dragstart += 1; }); layer.add(circle); stage.add(layer); // register pointer simulateMouseMove(stage, { x: 70, y: 80 }); circle.startDrag(); assert.equal(dragstart, 1); assert.equal(circle.isDragging(), true); // moving by one pixel should move circle too simulateMouseMove(stage, { x: 70, y: 81 }); simulateMouseUp(stage, { x: 70, y: 81 }); assert.equal(circle.x(), 70); assert.equal(circle.y(), 71); }); it('make sure we have event object', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 70, y: 70, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); circle.on('dragstart', function (e) { assert.equal(e.evt === undefined, false); }); circle.on('dragmove', function (e) { assert.equal(e.evt === undefined, false); }); circle.on('dragend', function (e) { assert.equal(e.evt === undefined, false); }); layer.add(circle); stage.add(layer); // register pointer simulateMouseDown(stage, { x: 70, y: 80 }); // moving by one pixel should move circle too simulateMouseMove(stage, { x: 80, y: 80 }); simulateMouseUp(stage, { x: 70, y: 80 }); }); it('try nested dragging', function () { var stage = addStage(); var layer = new Konva.Layer({ draggable: true, }); var circle = new Konva.Circle({ x: 70, y: 70, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); layer.add(circle); stage.add(layer); layer.add(circle.clone({ x: 30, fill: 'red', draggable: false })); simulateMouseDown(stage, { x: 70, y: 70 }); simulateMouseMove(stage, { x: 80, y: 80 }); assert.equal(circle.x(), 80); assert.equal(circle.y(), 80); assert.equal(layer.x(), 0); assert.equal(layer.y(), 0); // layer is not dragging, because drag is registered on circle assert.equal(layer.isDragging(), false); simulateMouseUp(stage, { x: 80, y: 80 }); }); it('warn on bad dragBoundFunc', function () { var stage = addStage(); var layer = new Konva.Layer({ draggable: true, }); var circle = new Konva.Circle({ x: 70, y: 70, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, dragBoundFunc: function () {} as any, }); layer.add(circle); stage.add(layer); var counter = 0; var oldWarn = Konva.Util.warn; Konva.Util.warn = function () { counter += 1; }; simulateMouseDown(stage, { x: 70, y: 70 }); simulateMouseMove(stage, { x: 80, y: 80 }); simulateMouseUp(stage, { x: 80, y: 80 }); assert.equal(counter > 0, true); Konva.Util.warn = oldWarn; }); it('deletage drag', function () { var stage = addStage(); stage.draggable(true); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 70, y: 70, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', }); layer.add(circle); stage.add(layer); stage.on('dragstart', function (e) { if (e.target === stage) { stage.stopDrag(); circle.startDrag(); } }); simulateMouseDown(stage, { x: 5, y: 5 }); simulateMouseMove(stage, { x: 10, y: 10 }); assert.equal(circle.isDragging(), true); assert.equal(stage.isDragging(), false); simulateMouseUp(stage, { x: 10, y: 10 }); assert.equal(circle.x(), 70); assert.equal(circle.y(), 70); }); it('disable drag on click', function () { var stage = addStage(); stage.draggable(true); var layer = new Konva.Layer(); stage.add(layer); var circle = new Konva.Circle({ x: 70, y: 70, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); layer.add(circle); layer.draw(); circle.on('click', function () { circle.draggable(false); circle.draggable(true); }); var dragstart = 0; var dragend = 0; stage.on('dragstart', function (e) { dragstart += 1; }); stage.on('dragend', function (e) { dragend += 1; }); simulateMouseDown(stage, { x: 70, y: 75 }); simulateMouseUp(stage, { x: 70, y: 70 }); // drag events should not be called assert.equal(dragstart, 0); assert.equal(dragend, 0); }); });
the_stack
import * as assert from 'assert'; import { Agent } from 'http'; import fetch, { Headers, Response as FetchResponse } from 'node-fetch'; import * as promiseLimit from 'promise-limit'; import * as zlib from 'zlib'; const BASE_URL = 'https://exp.host'; const BASE_API_URL = `${BASE_URL}/--/api/v2`; /** * The max number of push notifications to be sent at once. Since we can't automatically upgrade * everyone using this library, we should strongly try not to decrease it. */ const PUSH_NOTIFICATION_CHUNK_LIMIT = 100; /** * The max number of push notification receipts to request at once. */ const PUSH_NOTIFICATION_RECEIPT_CHUNK_LIMIT = 300; /** * The default max number of concurrent HTTP requests to send at once and spread out the load, * increasing the reliability of notification delivery. */ const DEFAULT_CONCURRENT_REQUEST_LIMIT = 6; export class Expo { static pushNotificationChunkSizeLimit = PUSH_NOTIFICATION_CHUNK_LIMIT; static pushNotificationReceiptChunkSizeLimit = PUSH_NOTIFICATION_RECEIPT_CHUNK_LIMIT; private httpAgent: Agent | undefined; private limitConcurrentRequests: <T>(thunk: () => Promise<T>) => Promise<T>; private accessToken: string | undefined; constructor(options: ExpoClientOptions = {}) { this.httpAgent = options.httpAgent; this.limitConcurrentRequests = promiseLimit( options.maxConcurrentRequests != null ? options.maxConcurrentRequests : DEFAULT_CONCURRENT_REQUEST_LIMIT ); this.accessToken = options.accessToken; } /** * Returns `true` if the token is an Expo push token */ static isExpoPushToken(token: unknown): token is ExpoPushToken { return ( typeof token === 'string' && (((token.startsWith('ExponentPushToken[') || token.startsWith('ExpoPushToken[')) && token.endsWith(']')) || /^[a-z\d]{8}-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{12}$/i.test(token)) ); } /** * Sends the given messages to their recipients via push notifications and returns an array of * push tickets. Each ticket corresponds to the message at its respective index (the nth receipt * is for the nth message) and contains a receipt ID. Later, after Expo attempts to deliver the * messages to the underlying push notification services, the receipts with those IDs will be * available for a period of time (approximately a day). * * There is a limit on the number of push notifications you can send at once. Use * `chunkPushNotifications` to divide an array of push notification messages into appropriately * sized chunks. */ async sendPushNotificationsAsync(messages: ExpoPushMessage[]): Promise<ExpoPushTicket[]> { const actualMessagesCount = Expo._getActualMessageCount(messages); const data = await this.requestAsync(`${BASE_API_URL}/push/send`, { httpMethod: 'post', body: messages, shouldCompress(body) { return body.length > 1024; }, }); if (!Array.isArray(data) || data.length !== actualMessagesCount) { const apiError: ExtensibleError = new Error( `Expected Expo to respond with ${actualMessagesCount} ${ actualMessagesCount === 1 ? 'ticket' : 'tickets' } but got ${data.length}` ); apiError.data = data; throw apiError; } return data; } async getPushNotificationReceiptsAsync( receiptIds: ExpoPushReceiptId[] ): Promise<{ [id: string]: ExpoPushReceipt }> { const data = await this.requestAsync(`${BASE_API_URL}/push/getReceipts`, { httpMethod: 'post', body: { ids: receiptIds }, shouldCompress(body) { return body.length > 1024; }, }); if (!data || typeof data !== 'object' || Array.isArray(data)) { const apiError: ExtensibleError = new Error( `Expected Expo to respond with a map from receipt IDs to receipts but received data of another type` ); apiError.data = data; throw apiError; } return data; } chunkPushNotifications(messages: ExpoPushMessage[]): ExpoPushMessage[][] { const chunks: ExpoPushMessage[][] = []; let chunk: ExpoPushMessage[] = []; let chunkMessagesCount = 0; for (const message of messages) { if (Array.isArray(message.to)) { let partialTo: ExpoPushToken[] = []; for (const recipient of message.to) { partialTo.push(recipient); chunkMessagesCount++; if (chunkMessagesCount >= PUSH_NOTIFICATION_CHUNK_LIMIT) { // Cap this chunk here if it already exceeds PUSH_NOTIFICATION_CHUNK_LIMIT. // Then create a new chunk to continue on the remaining recipients for this message. chunk.push({ ...message, to: partialTo }); chunks.push(chunk); chunk = []; chunkMessagesCount = 0; partialTo = []; } } if (partialTo.length) { // Add remaining `partialTo` to the chunk. chunk.push({ ...message, to: partialTo }); } } else { chunk.push(message); chunkMessagesCount++; } if (chunkMessagesCount >= PUSH_NOTIFICATION_CHUNK_LIMIT) { // Cap this chunk if it exceeds PUSH_NOTIFICATION_CHUNK_LIMIT. // Then create a new chunk to continue on the remaining messages. chunks.push(chunk); chunk = []; chunkMessagesCount = 0; } } if (chunkMessagesCount) { // Add the remaining chunk to the chunks. chunks.push(chunk); } return chunks; } chunkPushNotificationReceiptIds(receiptIds: ExpoPushReceiptId[]): ExpoPushReceiptId[][] { return this.chunkItems(receiptIds, PUSH_NOTIFICATION_RECEIPT_CHUNK_LIMIT); } private chunkItems<T>(items: T[], chunkSize: number): T[][] { const chunks: T[][] = []; let chunk: T[] = []; for (const item of items) { chunk.push(item); if (chunk.length >= chunkSize) { chunks.push(chunk); chunk = []; } } if (chunk.length) { chunks.push(chunk); } return chunks; } private async requestAsync(url: string, options: RequestOptions): Promise<any> { let requestBody: string | Buffer | undefined; const sdkVersion = require('../package.json').version; const requestHeaders = new Headers({ Accept: 'application/json', 'Accept-Encoding': 'gzip, deflate', 'User-Agent': `expo-server-sdk-node/${sdkVersion}`, }); if (this.accessToken) { requestHeaders.set('Authorization', `Bearer ${this.accessToken}`); } if (options.body != null) { const json = JSON.stringify(options.body); assert(json != null, `JSON request body must not be null`); if (options.shouldCompress(json)) { requestBody = await gzipAsync(Buffer.from(json)); requestHeaders.set('Content-Encoding', 'gzip'); } else { requestBody = json; } requestHeaders.set('Content-Type', 'application/json'); } const response = await this.limitConcurrentRequests(() => fetch(url, { method: options.httpMethod, body: requestBody, headers: requestHeaders, agent: this.httpAgent, }) ); if (response.status !== 200) { const apiError = await this.parseErrorResponseAsync(response); throw apiError; } const textBody = await response.text(); // We expect the API response body to be JSON let result: ApiResult; try { result = JSON.parse(textBody); } catch (e) { const apiError = await this.getTextResponseErrorAsync(response, textBody); throw apiError; } if (result.errors) { const apiError = this.getErrorFromResult(result); throw apiError; } return result.data; } private async parseErrorResponseAsync(response: FetchResponse): Promise<Error> { const textBody = await response.text(); let result: ApiResult; try { result = JSON.parse(textBody); } catch (e) { return await this.getTextResponseErrorAsync(response, textBody); } if (!result.errors || !Array.isArray(result.errors) || !result.errors.length) { const apiError: ExtensibleError = await this.getTextResponseErrorAsync(response, textBody); apiError.errorData = result; return apiError; } return this.getErrorFromResult(result); } private async getTextResponseErrorAsync(response: FetchResponse, text: string): Promise<Error> { const apiError: ExtensibleError = new Error( `Expo responded with an error with status code ${response.status}: ` + text ); apiError.statusCode = response.status; apiError.errorText = text; return apiError; } /** * Returns an error for the first API error in the result, with an optional `others` field that * contains any other errors. */ private getErrorFromResult(result: ApiResult): Error { assert(result.errors && result.errors.length > 0, `Expected at least one error from Expo`); const [errorData, ...otherErrorData] = result.errors!; const error: ExtensibleError = this.getErrorFromResultError(errorData); if (otherErrorData.length) { error.others = otherErrorData.map((data) => this.getErrorFromResultError(data)); } return error; } /** * Returns an error for a single API error */ private getErrorFromResultError(errorData: ApiResultError): Error { const error: ExtensibleError = new Error(errorData.message); error.code = errorData.code; if (errorData.details != null) { error.details = errorData.details; } if (errorData.stack != null) { error.serverStack = errorData.stack; } return error; } static _getActualMessageCount(messages: ExpoPushMessage[]): number { return messages.reduce((total, message) => { if (Array.isArray(message.to)) { total += message.to.length; } else { total++; } return total; }, 0); } } export default Expo; function gzipAsync(data: Buffer): Promise<Buffer> { return new Promise((resolve, reject) => { zlib.gzip(data, (error, result) => { if (error) { reject(error); } else { resolve(result); } }); }); } export type ExpoClientOptions = { httpAgent?: Agent; maxConcurrentRequests?: number; accessToken?: string; }; export type ExpoPushToken = string; export type ExpoPushMessage = { to: ExpoPushToken | ExpoPushToken[]; data?: object; title?: string; subtitle?: string; body?: string; sound?: | 'default' | null | { critical?: boolean; name?: 'default' | null; volume?: number; }; ttl?: number; expiration?: number; priority?: 'default' | 'normal' | 'high'; badge?: number; channelId?: string; categoryId?: string; mutableContent?: boolean; }; export type ExpoPushReceiptId = string; export type ExpoPushSuccessTicket = { status: 'ok'; id: ExpoPushReceiptId; }; export type ExpoPushErrorTicket = ExpoPushErrorReceipt; export type ExpoPushTicket = ExpoPushSuccessTicket | ExpoPushErrorTicket; export type ExpoPushSuccessReceipt = { status: 'ok'; details?: object; // Internal field used only by developers working on Expo __debug?: any; }; export type ExpoPushErrorReceipt = { status: 'error'; message: string; details?: { error?: 'DeviceNotRegistered' | 'InvalidCredentials' | 'MessageTooBig' | 'MessageRateExceeded'; }; // Internal field used only by developers working on Expo __debug?: any; }; export type ExpoPushReceipt = ExpoPushSuccessReceipt | ExpoPushErrorReceipt; type RequestOptions = { httpMethod: 'get' | 'post'; body?: any; shouldCompress: (body: string) => boolean; }; type ApiResult = { errors?: ApiResultError[]; data?: any; }; type ApiResultError = { message: string; code: string; details?: any; stack?: string; }; class ExtensibleError extends Error { [key: string]: any; }
the_stack
export const version: string; /** SSF Formatter Library */ // export { SSF }; export const SSF: any; /** CFB Library */ // export { CFB }; export const CFB: any; /** ESM ONLY! Set internal `fs` instance */ export function set_fs(fs: any): void; /** ESM ONLY! Set internal codepage tables */ export function set_cptable(cptable: any): void; /** NODE ONLY! Attempts to read filename and parse */ export function readFile(filename: string, opts?: ParsingOptions): WorkBook; /** Attempts to parse data */ export function read(data: any, opts?: ParsingOptions): WorkBook; /** Attempts to write or download workbook data to file */ export function writeFile(data: WorkBook, filename: string, opts?: WritingOptions): any; /** Attempts to write or download workbook data to XLSX file */ export function writeFileXLSX(data: WorkBook, filename: string, opts?: WritingOptions): any; /** Attempts to write or download workbook data to file asynchronously */ type CBFunc = () => void; export function writeFileAsync(filename: string, data: WorkBook, opts: WritingOptions | CBFunc, cb?: CBFunc): any; /** Attempts to write the workbook data */ export function write(data: WorkBook, opts: WritingOptions): any; /** Attempts to write the workbook data as XLSX */ export function writeXLSX(data: WorkBook, opts: WritingOptions): any; /** Utility Functions */ export const utils: XLSX$Utils; /** Stream Utility Functions */ export const stream: StreamUtils; /** Number Format (either a string or an index to the format table) */ export type NumberFormat = string | number; /** Worksheet specifier (string, number, worksheet) */ export type WSSpec = string | number | WorkSheet; /** Range specifier (string or range or cell), single-cell lifted to range */ export type RangeSpec = string | Range | CellAddress; /** Basic File Properties */ export interface Properties { /** Summary tab "Title" */ Title?: string; /** Summary tab "Subject" */ Subject?: string; /** Summary tab "Author" */ Author?: string; /** Summary tab "Manager" */ Manager?: string; /** Summary tab "Company" */ Company?: string; /** Summary tab "Category" */ Category?: string; /** Summary tab "Keywords" */ Keywords?: string; /** Summary tab "Comments" */ Comments?: string; /** Statistics tab "Last saved by" */ LastAuthor?: string; /** Statistics tab "Created" */ CreatedDate?: Date; } /** Other supported properties */ export interface FullProperties extends Properties { ModifiedDate?: Date; Application?: string; AppVersion?: string; DocSecurity?: string; HyperlinksChanged?: boolean; SharedDoc?: boolean; LinksUpToDate?: boolean; ScaleCrop?: boolean; Worksheets?: number; SheetNames?: string[]; ContentStatus?: string; LastPrinted?: string; Revision?: string | number; Version?: string; Identifier?: string; Language?: string; } export interface CommonOptions { /** * If true, throw errors when features are not understood * @default false */ WTF?: boolean; /** * When reading a file with VBA macros, expose CFB blob to `vbaraw` field * When writing BIFF8/XLSB/XLSM, reseat `vbaraw` and export to file * @default false */ bookVBA?: boolean; /** * When reading a file, store dates as type d (default is n) * When writing XLSX/XLSM file, use native date (default uses date codes) * @default false */ cellDates?: boolean; /** * Create cell objects for stub cells * @default false */ sheetStubs?: boolean; /** * When reading a file, save style/theme info to the .s field * When writing a file, export style/theme info * @default false */ cellStyles?: boolean; /** * If defined and file is encrypted, use password * @default '' */ password?: string; } export interface DateNFOption { /** Use specified date format */ dateNF?: NumberFormat; } /** Options for read and readFile */ export interface ParsingOptions extends CommonOptions { /** Input data encoding */ type?: 'base64' | 'binary' | 'buffer' | 'file' | 'array' | 'string'; /** Default codepage */ codepage?: number; /** * Save formulae to the .f field * @default true */ cellFormula?: boolean; /** * Parse rich text and save HTML to the .h field * @default true */ cellHTML?: boolean; /** * Save number format string to the .z field * @default false */ cellNF?: boolean; /** * Generate formatted text to the .w field * @default true */ cellText?: boolean; /** Override default date format (code 14) */ dateNF?: string; /** Field Separator ("Delimiter" override) */ FS?: string; /** * If >0, read the first sheetRows rows * @default 0 */ sheetRows?: number; /** * If true, parse calculation chains * @default false */ bookDeps?: boolean; /** * If true, add raw files to book object * @default false */ bookFiles?: boolean; /** * If true, only parse enough to get book metadata * @default false */ bookProps?: boolean; /** * If true, only parse enough to get the sheet names * @default false */ bookSheets?: boolean; /** If specified, only parse the specified sheets or sheet names */ sheets?: number | string | Array<number | string>; /** If true, plaintext parsing will not parse values */ raw?: boolean; /** If true, preserve _xlfn. prefixes in formula function names */ xlfn?: boolean; dense?: boolean; PRN?: boolean; } export interface SheetOption { /** * Name of Worksheet (for single-sheet formats) * @default '' */ sheet?: string; } /** Options for write and writeFile */ export interface WritingOptions extends CommonOptions, SheetOption { /** Output data encoding */ type?: 'base64' | 'binary' | 'buffer' | 'file' | 'array' | 'string'; /** * Generate Shared String Table * @default false */ bookSST?: boolean; /** * File format of generated workbook * @default 'xlsx' */ bookType?: BookType; /** * Use ZIP compression for ZIP-based formats * @default false */ compression?: boolean; /** * Suppress "number stored as text" errors in generated files * @default true */ ignoreEC?: boolean; /** Override workbook properties on save */ Props?: Properties; /** Base64 encoding of NUMBERS base for exports */ numbers?: string; } /** Workbook Object */ export interface WorkBook { /** * A dictionary of the worksheets in the workbook. * Use SheetNames to reference these. */ Sheets: { [sheet: string]: WorkSheet }; /** Ordered list of the sheet names in the workbook */ SheetNames: string[]; /** Standard workbook Properties */ Props?: FullProperties; /** Custom workbook Properties */ Custprops?: object; Workbook?: WBProps; vbaraw?: any; } export interface SheetProps { /** Name of Sheet */ name?: string; /** Sheet Visibility (0=Visible 1=Hidden 2=VeryHidden) */ Hidden?: 0 | 1 | 2; /** Name of Document Module in associated VBA Project */ CodeName?: string; } /** Defined Name Object */ export interface DefinedName { /** Name */ Name: string; /** Reference */ Ref: string; /** Scope (undefined for workbook scope) */ Sheet?: number; /** Name comment */ Comment?: string; } /** Workbook-Level Attributes */ export interface WBProps { /** Sheet Properties */ Sheets?: SheetProps[]; /** Defined Names */ Names?: DefinedName[]; /** Workbook Views */ Views?: WBView[]; /** Other Workbook Properties */ WBProps?: WorkbookProperties; } /** Workbook View */ export interface WBView { /** Right-to-left mode */ RTL?: boolean; } /** Other Workbook Properties */ export interface WorkbookProperties { /** Worksheet Epoch (1904 if true, 1900 if false) */ date1904?: boolean; /** Warn or strip personally identifying info on save */ filterPrivacy?: boolean; /** Name of Document Module in associated VBA Project */ CodeName?: string; } /** DBF Field Header */ export interface DBFField { /** Original Field Name */ name?: string; /** Field Type */ type?: string; /** Field Length */ len?: number; /** Field Decimal Count */ dec?: number; } /** Column Properties Object */ export interface ColInfo { /* --- visibility --- */ /** if true, the column is hidden */ hidden?: boolean; /* --- column width --- */ /** width in Excel's "Max Digit Width", width*256 is integral */ width?: number; /** width in screen pixels */ wpx?: number; /** width in "characters" */ wch?: number; /** outline / group level */ level?: number; /** Excel's "Max Digit Width" unit, always integral */ MDW?: number; /** DBF Field Header */ DBF?: DBFField; } /** Row Properties Object */ export interface RowInfo { /* --- visibility --- */ /** if true, the column is hidden */ hidden?: boolean; /* --- row height --- */ /** height in screen pixels */ hpx?: number; /** height in points */ hpt?: number; /** outline / group level */ level?: number; } /** * Write sheet protection properties. */ export interface ProtectInfo { /** * The password for formats that support password-protected sheets * (XLSX/XLSB/XLS). The writer uses the XOR obfuscation method. */ password?: string; /** * Select locked cells * @default: true */ selectLockedCells?: boolean; /** * Select unlocked cells * @default: true */ selectUnlockedCells?: boolean; /** * Format cells * @default: false */ formatCells?: boolean; /** * Format columns * @default: false */ formatColumns?: boolean; /** * Format rows * @default: false */ formatRows?: boolean; /** * Insert columns * @default: false */ insertColumns?: boolean; /** * Insert rows * @default: false */ insertRows?: boolean; /** * Insert hyperlinks * @default: false */ insertHyperlinks?: boolean; /** * Delete columns * @default: false */ deleteColumns?: boolean; /** * Delete rows * @default: false */ deleteRows?: boolean; /** * Sort * @default: false */ sort?: boolean; /** * Filter * @default: false */ autoFilter?: boolean; /** * Use PivotTable reports * @default: false */ pivotTables?: boolean; /** * Edit objects * @default: true */ objects?: boolean; /** * Edit scenarios * @default: true */ scenarios?: boolean; } /** Page Margins -- see Excel Page Setup .. Margins diagram for explanation */ export interface MarginInfo { /** Left side margin (inches) */ left?: number; /** Right side margin (inches) */ right?: number; /** Top side margin (inches) */ top?: number; /** Bottom side margin (inches) */ bottom?: number; /** Header top margin (inches) */ header?: number; /** Footer bottom height (inches) */ footer?: number; } export type SheetType = 'sheet' | 'chart'; export type SheetKeys = string | MarginInfo | SheetType; /** General object representing a Sheet (worksheet or chartsheet) */ export interface Sheet { /** * Indexing with a cell address string maps to a cell object * Special keys start with '!' */ [cell: string]: CellObject | SheetKeys | any; /** Sheet type */ '!type'?: SheetType; /** Sheet Range */ '!ref'?: string; /** Page Margins */ '!margins'?: MarginInfo; } /** AutoFilter properties */ export interface AutoFilterInfo { /** Range of the AutoFilter table */ ref: string; } export type WSKeys = SheetKeys | ColInfo[] | RowInfo[] | Range[] | ProtectInfo | AutoFilterInfo; /** Worksheet Object */ export interface WorkSheet extends Sheet { /** * Indexing with a cell address string maps to a cell object * Special keys start with '!' */ [cell: string]: CellObject | WSKeys | any; /** Column Info */ '!cols'?: ColInfo[]; /** Row Info */ '!rows'?: RowInfo[]; /** Merge Ranges */ '!merges'?: Range[]; /** Worksheet Protection info */ '!protect'?: ProtectInfo; /** AutoFilter info */ '!autofilter'?: AutoFilterInfo; } /** * Worksheet Object with CellObject type * * The normal Worksheet type uses indexer of type `any` -- this enforces CellObject */ export interface StrictWS { [addr: string]: CellObject; } /** * The Excel data type for a cell. * b Boolean, n Number, e error, s String, d Date, z Stub */ export type ExcelDataType = 'b' | 'n' | 'e' | 's' | 'd' | 'z'; /** * Type of generated workbook * @default 'xlsx' */ export type BookType = 'xlsx' | 'xlsm' | 'xlsb' | 'xls' | 'xla' | 'biff8' | 'biff5' | 'biff2' | 'xlml' | 'ods' | 'fods' | 'csv' | 'txt' | 'sylk' | 'slk' | 'html' | 'dif' | 'rtf' | 'prn' | 'eth' | 'dbf' | 'numbers'; /** Comment element */ export interface Comment { /** Author of the comment block */ a?: string; /** Plaintext of the comment */ t: string; /** If true, mark the comment as a part of a thread */ T?: boolean; } /** Cell comments */ export interface Comments extends Array<Comment> { /** Hide comment by default */ hidden?: boolean; } /** Link object */ export interface Hyperlink { /** Target of the link (HREF) */ Target: string; /** Plaintext tooltip to display when mouse is over cell */ Tooltip?: string; } /** Worksheet Cell Object */ export interface CellObject { /** The raw value of the cell. Can be omitted if a formula is specified */ v?: string | number | boolean | Date; /** Formatted text (if applicable) */ w?: string; /** * The Excel Data Type of the cell. * b Boolean, n Number, e Error, s String, d Date, z Empty */ t: ExcelDataType; /** Cell formula (if applicable) */ f?: string; /** Range of enclosing array if formula is array formula (if applicable) */ F?: string; /** Rich text encoding (if applicable) */ r?: any; /** HTML rendering of the rich text (if applicable) */ h?: string; /** Comments associated with the cell */ c?: Comments; /** Number format string associated with the cell (if requested) */ z?: NumberFormat; /** Cell hyperlink object (.Target holds link, .tooltip is tooltip) */ l?: Hyperlink; /** The style/theme of the cell (if applicable) */ s?: any; } /** Simple Cell Address */ export interface CellAddress { /** Column number */ c: number; /** Row number */ r: number; } /** Range object (representing ranges like "A1:B2") */ export interface Range { /** Starting cell */ s: CellAddress; /** Ending cell */ e: CellAddress; } export interface Sheet2CSVOpts extends DateNFOption { /** Field Separator ("delimiter") */ FS?: string; /** Record Separator ("row separator") */ RS?: string; /** Remove trailing field separators in each record */ strip?: boolean; /** Include blank lines in the CSV output */ blankrows?: boolean; /** Skip hidden rows and columns in the CSV output */ skipHidden?: boolean; /** Force quotes around fields */ forceQuotes?: boolean; /** if true, return raw numbers; if false, return formatted numbers */ rawNumbers?: boolean; } export interface OriginOption { /** Top-Left cell for operation (CellAddress or A1 string or row) */ origin?: number | string | CellAddress; } export interface Sheet2HTMLOpts { /** TABLE element id attribute */ id?: string; /** Add contenteditable to every cell */ editable?: boolean; /** Header HTML */ header?: string; /** Footer HTML */ footer?: string; } export interface Sheet2JSONOpts extends DateNFOption { /** Output format */ header?: "A"|number|string[]; /** Override worksheet range */ range?: any; /** Include or omit blank lines in the output */ blankrows?: boolean; /** Default value for null/undefined values */ defval?: any; /** if true, return raw data; if false, return formatted text */ raw?: boolean; /** if true, skip hidden rows and columns */ skipHidden?: boolean; /** if true, return raw numbers; if false, return formatted numbers */ rawNumbers?: boolean; } export interface AOA2SheetOpts extends CommonOptions, DateNFOption { /** * Create cell objects for stub cells * @default false */ sheetStubs?: boolean; } export interface SheetAOAOpts extends AOA2SheetOpts, OriginOption {} export interface JSON2SheetOpts extends CommonOptions, DateNFOption { /** Use specified column order */ header?: string[]; /** Skip header row in generated sheet */ skipHeader?: boolean; } export interface SheetJSONOpts extends JSON2SheetOpts, OriginOption {} export interface Table2SheetOpts extends CommonOptions, DateNFOption, OriginOption, SheetOption { /** If true, plaintext parsing will not parse values */ raw?: boolean; /** * If >0, read the first sheetRows rows * @default 0 */ sheetRows?: number; /** If true, hidden rows and cells will not be parsed */ display?: boolean; } /** General utilities */ export interface XLSX$Utils { /* --- Import Functions --- */ /** Converts an array of arrays of JS data to a worksheet. */ aoa_to_sheet<T>(data: T[][], opts?: AOA2SheetOpts): WorkSheet; aoa_to_sheet(data: any[][], opts?: AOA2SheetOpts): WorkSheet; /** Converts an array of JS objects to a worksheet. */ json_to_sheet<T>(data: T[], opts?: JSON2SheetOpts): WorkSheet; json_to_sheet(data: any[], opts?: JSON2SheetOpts): WorkSheet; /** BROWSER ONLY! Converts a TABLE DOM element to a worksheet. */ table_to_sheet(data: any, opts?: Table2SheetOpts): WorkSheet; table_to_book(data: any, opts?: Table2SheetOpts): WorkBook; sheet_add_dom(ws: WorkSheet, data: any, opts?: Table2SheetOpts): WorkSheet; /* --- Export Functions --- */ /** Converts a worksheet object to an array of JSON objects */ sheet_to_json<T>(worksheet: WorkSheet, opts?: Sheet2JSONOpts): T[]; sheet_to_json(worksheet: WorkSheet, opts?: Sheet2JSONOpts): any[][]; sheet_to_json(worksheet: WorkSheet, opts?: Sheet2JSONOpts): any[]; /** Generates delimiter-separated-values output */ sheet_to_csv(worksheet: WorkSheet, options?: Sheet2CSVOpts): string; /** Generates UTF16 Formatted Text */ sheet_to_txt(worksheet: WorkSheet, options?: Sheet2CSVOpts): string; /** Generates HTML */ sheet_to_html(worksheet: WorkSheet, options?: Sheet2HTMLOpts): string; /** Generates a list of the formulae (with value fallbacks) */ sheet_to_formulae(worksheet: WorkSheet): string[]; /** Generates DIF */ sheet_to_dif(worksheet: WorkSheet, options?: Sheet2HTMLOpts): string; /** Generates SYLK (Symbolic Link) */ sheet_to_slk(worksheet: WorkSheet, options?: Sheet2HTMLOpts): string; /** Generates ETH */ sheet_to_eth(worksheet: WorkSheet, options?: Sheet2HTMLOpts): string; /* --- Cell Address Utilities --- */ /** Converts 0-indexed cell address to A1 form */ encode_cell(cell: CellAddress): string; /** Converts 0-indexed row to A1 form */ encode_row(row: number): string; /** Converts 0-indexed column to A1 form */ encode_col(col: number): string; /** Converts 0-indexed range to A1 form */ encode_range(s: CellAddress, e: CellAddress): string; encode_range(r: Range): string; /** Converts A1 cell address to 0-indexed form */ decode_cell(address: string): CellAddress; /** Converts A1 row to 0-indexed form */ decode_row(row: string): number; /** Converts A1 column to 0-indexed form */ decode_col(col: string): number; /** Converts A1 range to 0-indexed form */ decode_range(range: string): Range; /** Format cell */ format_cell(cell: CellObject, v?: any, opts?: any): string; /* --- General Utilities --- */ /** Creates a new workbook */ book_new(): WorkBook; /** Append a worksheet to a workbook, returns new worksheet name */ book_append_sheet(workbook: WorkBook, worksheet: WorkSheet, name?: string, roll?: boolean): string; /** Set sheet visibility (visible/hidden/very hidden) */ book_set_sheet_visibility(workbook: WorkBook, sheet: number|string, visibility: number): void; /** Set number format for a cell */ cell_set_number_format(cell: CellObject, fmt: string|number): CellObject; /** Set hyperlink for a cell */ cell_set_hyperlink(cell: CellObject, target: string, tooltip?: string): CellObject; /** Set internal link for a cell */ cell_set_internal_link(cell: CellObject, target: string, tooltip?: string): CellObject; /** Add comment to a cell */ cell_add_comment(cell: CellObject, text: string, author?: string): void; /** Assign an Array Formula to a range */ sheet_set_array_formula(ws: WorkSheet, range: Range|string, formula: string, dynamic?: boolean): WorkSheet; /** Add an array of arrays of JS data to a worksheet */ sheet_add_aoa<T>(ws: WorkSheet, data: T[][], opts?: SheetAOAOpts): WorkSheet; sheet_add_aoa(ws: WorkSheet, data: any[][], opts?: SheetAOAOpts): WorkSheet; /** Add an array of JS objects to a worksheet */ sheet_add_json(ws: WorkSheet, data: any[], opts?: SheetJSONOpts): WorkSheet; sheet_add_json<T>(ws: WorkSheet, data: T[], opts?: SheetJSONOpts): WorkSheet; consts: XLSX$Consts; } export interface XLSX$Consts { /* --- Sheet Visibility --- */ /** Visibility: Visible */ SHEET_VISIBLE: 0; /** Visibility: Hidden */ SHEET_HIDDEN: 1; /** Visibility: Very Hidden */ SHEET_VERYHIDDEN: 2; } /** NODE ONLY! these return Readable Streams */ export interface StreamUtils { /** CSV output stream, generate one line at a time */ to_csv(sheet: WorkSheet, opts?: Sheet2CSVOpts): any; /** HTML output stream, generate one line at a time */ to_html(sheet: WorkSheet, opts?: Sheet2HTMLOpts): any; /** JSON object stream, generate one row at a time */ to_json(sheet: WorkSheet, opts?: Sheet2JSONOpts): any; /** Set `Readable` (internal) */ set_readable(Readable: any): void; }
the_stack
import { expect } from "chai"; import { mount, shallow } from "enzyme"; import React from "react"; import * as sinon from "sinon"; import { fireEvent, render } from "@testing-library/react"; import { IconEditorParams, InputEditorSizeParams, PrimitiveValue, PropertyEditorParamTypes, SpecialKey, } from "@itwin/appui-abstract"; import { CustomNumberEditor } from "../../components-react/editors/CustomNumberEditor"; import { EditorContainer, PropertyUpdatedArgs } from "../../components-react/editors/EditorContainer"; import TestUtils, { MineDataController } from "../TestUtils"; import { PropertyEditorManager } from "../../components-react/editors/PropertyEditorManager"; // cSpell:ignore customnumber const numVal = 3.345689; const displayVal = "3.35"; describe("<CustomNumberEditor />", () => { it("should render", () => { const record = TestUtils.createCustomNumberProperty("FormattedNumber", numVal, displayVal); const renderedComponent = render(<CustomNumberEditor propertyRecord={record} />); expect(renderedComponent).not.to.be.undefined; }); it("renders correctly with style", () => { const record = TestUtils.createCustomNumberProperty("FormattedNumber", numVal, displayVal); shallow(<CustomNumberEditor propertyRecord={record} style={{ color: "red" }} />).should.matchSnapshot(); }); it("change input value", () => { const record = TestUtils.createCustomNumberProperty("FormattedNumber", numVal, displayVal); const renderedComponent = render(<CustomNumberEditor propertyRecord={record} />); expect(renderedComponent).not.to.be.undefined; const inputField = renderedComponent.getByTestId("components-customnumber-editor") as HTMLInputElement; expect(inputField.value).to.be.equal(displayVal); const newValue = "7.777"; fireEvent.change(inputField, { target: { value: newValue } }); expect(inputField.value).to.be.equal(newValue); }); it("EditorContainer with CustomNumberPropertyEditor", async () => { const spyOnCommit = sinon.spy(); const spyOnCancel = sinon.spy(); const newDisplayValue = "7.78"; function handleCommit(commit: PropertyUpdatedArgs): void { const numValue = (commit.newValue as PrimitiveValue).value as number; const displayValue = (commit.newValue as PrimitiveValue).displayValue; expect(numValue).to.be.equal(7.777); expect(displayValue).to.be.equal(newDisplayValue); spyOnCommit(); } const propertyRecord = TestUtils.createCustomNumberProperty("FormattedNumber", numVal, displayVal); const renderedComponent = render(<EditorContainer propertyRecord={propertyRecord} title="abc" onCommit={handleCommit} onCancel={spyOnCancel} />); // renderedComponent.debug(); const inputField = renderedComponent.getByTestId("components-customnumber-editor") as HTMLInputElement; expect(inputField.value).to.be.equal(displayVal); const container = renderedComponent.getByTestId("editor-container") as HTMLSpanElement; fireEvent.change(inputField, { target: { value: "zzzz" } }); expect(inputField.value).to.be.equal("zzzz"); fireEvent.keyDown(container, { key: "Enter" }); await TestUtils.flushAsyncOperations(); // resetToOriginalValue fireEvent.keyDown(inputField, { key: SpecialKey.Escape }); expect(inputField.value).to.be.equal(displayVal); expect(spyOnCancel).not.to.be.called; // since value is same as original, cancel fireEvent.keyDown(inputField, { key: SpecialKey.Escape }); expect(inputField.value).to.be.equal(displayVal); expect(spyOnCancel).to.be.calledOnce; const newValue = "7.777"; fireEvent.change(inputField, { target: { value: newValue } }); expect(inputField.value).to.be.equal(newValue); fireEvent.keyDown(container, { key: "Enter" }); await TestUtils.flushAsyncOperations(); // renderedComponent.debug(); expect(spyOnCommit).to.be.calledOnce; fireEvent.change(inputField, { target: { value: "zzzz" } }); expect(inputField.value).to.be.equal("zzzz"); fireEvent.keyDown(container, { key: "Enter" }); await TestUtils.flushAsyncOperations(); // resetToLastValue fireEvent.keyDown(inputField, { key: SpecialKey.Escape }); expect(inputField.value).to.be.equal(newDisplayValue); }); it("CustomNumberPropertyEditor with undefined initial display value", async () => { const spyOnCommit = sinon.spy(); function handleCommit(commit: PropertyUpdatedArgs): void { const newNumValue = (commit.newValue as PrimitiveValue).value as number; const newDisplayValue = (commit.newValue as PrimitiveValue).displayValue; expect(newNumValue).to.be.equal(7.777); expect(newDisplayValue).to.be.equal("7.78"); spyOnCommit(); } function handleBadKeyinCommit(commit: PropertyUpdatedArgs): void { const newNumValue = (commit.newValue as PrimitiveValue).value as number; const newDisplayValue = (commit.newValue as PrimitiveValue).displayValue; expect(newNumValue).to.be.equal(numVal); expect(newDisplayValue).to.be.equal(displayVal); spyOnCommit(); } const propertyRecord = TestUtils.createCustomNumberProperty("FormattedNumber", numVal); // add size and width params for testing if (propertyRecord.property.editor && propertyRecord.property.editor.params) { const inputEditorSizeParams: InputEditorSizeParams = { type: PropertyEditorParamTypes.InputEditorSize, size: 8, maxLength: 20, }; propertyRecord.property.editor.params.push(inputEditorSizeParams); } const renderedComponent = render(<EditorContainer propertyRecord={propertyRecord} title="abc" onCommit={handleCommit} onCancel={() => { }} />); // renderedComponent.debug(); const inputField = renderedComponent.getByTestId("components-customnumber-editor") as HTMLInputElement; expect(inputField.value).to.be.equal(displayVal); const newValue = "7.777"; fireEvent.change(inputField, { target: { value: newValue } }); expect(inputField.value).to.be.equal(newValue); const container = renderedComponent.getByTestId("editor-container") as HTMLSpanElement; fireEvent.keyDown(container, { key: "Enter" }); await TestUtils.flushAsyncOperations(); // renderedComponent.debug(); expect(spyOnCommit).to.be.calledOnce; // trigger componentDidUpdate processing const newPropertyRecord = TestUtils.createCustomNumberProperty("FormattedNumber", numVal, displayVal); renderedComponent.rerender(<EditorContainer propertyRecord={newPropertyRecord} title="abc" onCommit={handleBadKeyinCommit} onCancel={() => { }} />); // handle bad value processing const badValue = "abcd"; fireEvent.change(inputField, { target: { value: badValue } }); fireEvent.keyDown(container, { key: "Enter" }); await TestUtils.flushAsyncOperations(); // make sure handleBadKeyinCommit is processed }); it("EditorContainer with readonly CustomNumberPropertyEditor", async () => { const propertyRecord = TestUtils.createCustomNumberProperty("FormattedNumber", numVal, displayVal); propertyRecord.isReadonly = true; propertyRecord.isDisabled = true; const spyOnCommit = sinon.spy(); function handleCommit(commit: PropertyUpdatedArgs): void { const newNumValue = (commit.newValue as PrimitiveValue).value as number; const newDisplayValue = (commit.newValue as PrimitiveValue).displayValue; expect(newNumValue).to.be.equal(numVal); expect(newDisplayValue).to.be.equal(displayVal); spyOnCommit(); } const renderedComponent = render(<EditorContainer propertyRecord={propertyRecord} title="abc" onCommit={handleCommit} onCancel={() => { }} />); const inputField = renderedComponent.getByTestId("components-customnumber-editor") as HTMLInputElement; expect(inputField.value).to.be.equal(displayVal); const newValue = "7.777"; fireEvent.change(inputField, { target: { value: newValue } }); expect(inputField.value).to.be.equal(displayVal); const container = renderedComponent.getByTestId("editor-container") as HTMLSpanElement; fireEvent.keyDown(container, { key: "Enter" }); await TestUtils.flushAsyncOperations(); expect(spyOnCommit).to.be.calledOnce; // renderedComponent.debug(); expect(inputField.value).to.be.equal(displayVal); }); it("test with no editor params", async () => { const propertyRecord = TestUtils.createCustomNumberProperty("FormattedNumber", numVal, displayVal); propertyRecord.property.editor!.params!.splice(0, 1); const renderedComponent = render(<EditorContainer propertyRecord={propertyRecord} title="abc" onCommit={() => { }} onCancel={() => { }} />); // renderedComponent.debug(); const inputField = renderedComponent.queryByTestId("components-customnumber-editor") as HTMLInputElement; expect(inputField).to.be.null; }); it("should support IconEditor params", async () => { const iconSpec = "icon-placeholder"; const iconParams: IconEditorParams = { type: PropertyEditorParamTypes.Icon, definition: { iconSpec }, }; const propertyRecord = TestUtils.createCustomNumberProperty("FormattedNumber", numVal, displayVal, [iconParams]); const wrapper = mount(<EditorContainer propertyRecord={propertyRecord} title="abc" onCommit={() => { }} onCancel={() => { }} />); await TestUtils.flushAsyncOperations(); const textEditor = wrapper.find(CustomNumberEditor); expect(textEditor.length).to.eq(1); expect(textEditor.state("iconSpec")).to.eq(iconSpec); wrapper.unmount(); }); it("should not commit if DataController fails to validate", async () => { PropertyEditorManager.registerDataController("myData", MineDataController); const propertyRecord = TestUtils.createCustomNumberProperty("FormattedNumber", numVal, displayVal); propertyRecord.property.dataController = "myData"; const spyOnCommit = sinon.spy(); const wrapper = render(<EditorContainer propertyRecord={propertyRecord} title="abc" onCommit={spyOnCommit} onCancel={() => { }} />); const inputNode = wrapper.queryByTestId("components-customnumber-editor") as HTMLInputElement; expect(inputNode).not.to.be.null; fireEvent.keyDown(inputNode as HTMLElement, { key: SpecialKey.Enter }); await TestUtils.flushAsyncOperations(); expect(spyOnCommit.calledOnce).to.be.false; PropertyEditorManager.deregisterDataController("myData"); }); });
the_stack
import chart_global_FontFamily from '@patternfly/react-tokens/dist/esm/chart_global_FontFamily'; import chart_global_letter_spacing from '@patternfly/react-tokens/dist/esm/chart_global_letter_spacing'; import chart_global_FontSize_sm from '@patternfly/react-tokens/dist/esm/chart_global_FontSize_sm'; import chart_global_label_Padding from '@patternfly/react-tokens/dist/esm/chart_global_label_Padding'; import chart_global_label_stroke from '@patternfly/react-tokens/dist/esm/chart_global_label_stroke'; import chart_global_label_text_anchor from '@patternfly/react-tokens/dist/esm/chart_global_label_text_anchor'; import chart_global_layout_Padding from '@patternfly/react-tokens/dist/esm/chart_global_layout_Padding'; import chart_global_layout_Height from '@patternfly/react-tokens/dist/esm/chart_global_layout_Height'; import chart_global_layout_Width from '@patternfly/react-tokens/dist/esm/chart_global_layout_Width'; import chart_global_stroke_line_cap from '@patternfly/react-tokens/dist/esm/chart_global_stroke_line_cap'; import chart_global_stroke_line_join from '@patternfly/react-tokens/dist/esm/chart_global_stroke_line_join'; import chart_area_data_Fill from '@patternfly/react-tokens/dist/esm/chart_area_data_Fill'; import chart_area_Opacity from '@patternfly/react-tokens/dist/esm/chart_area_Opacity'; import chart_area_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_area_stroke_Width'; import chart_axis_axis_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_axis_axis_stroke_Width'; import chart_axis_axis_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_axis_axis_stroke_Color'; import chart_axis_axis_Fill from '@patternfly/react-tokens/dist/esm/chart_axis_axis_Fill'; import chart_axis_axis_label_Padding from '@patternfly/react-tokens/dist/esm/chart_axis_axis_label_Padding'; import chart_axis_axis_label_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_axis_axis_label_stroke_Color'; import chart_axis_grid_Fill from '@patternfly/react-tokens/dist/esm/chart_axis_grid_Fill'; import chart_axis_grid_PointerEvents from '@patternfly/react-tokens/dist/esm/chart_axis_grid_PointerEvents'; import chart_axis_tick_Fill from '@patternfly/react-tokens/dist/esm/chart_axis_tick_Fill'; import chart_axis_tick_Size from '@patternfly/react-tokens/dist/esm/chart_axis_tick_Size'; import chart_axis_tick_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_axis_tick_stroke_Color'; import chart_axis_tick_Width from '@patternfly/react-tokens/dist/esm/chart_axis_tick_Width'; import chart_axis_tick_label_Fill from '@patternfly/react-tokens/dist/esm/chart_axis_tick_label_Fill'; import chart_bar_Width from '@patternfly/react-tokens/dist/esm/chart_bar_Width'; import chart_bar_data_stroke from '@patternfly/react-tokens/dist/esm/chart_bar_data_stroke'; import chart_bar_data_Fill from '@patternfly/react-tokens/dist/esm/chart_bar_data_Fill'; import chart_bar_data_Padding from '@patternfly/react-tokens/dist/esm/chart_bar_data_Padding'; import chart_bar_data_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_bar_data_stroke_Width'; import chart_boxplot_max_Padding from '@patternfly/react-tokens/dist/esm/chart_boxplot_max_Padding'; import chart_boxplot_max_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_boxplot_max_stroke_Color'; import chart_boxplot_max_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_boxplot_max_stroke_Width'; import chart_boxplot_median_Padding from '@patternfly/react-tokens/dist/esm/chart_boxplot_median_Padding'; import chart_boxplot_median_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_boxplot_median_stroke_Color'; import chart_boxplot_median_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_boxplot_median_stroke_Width'; import chart_boxplot_min_Padding from '@patternfly/react-tokens/dist/esm/chart_boxplot_min_Padding'; import chart_boxplot_min_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_boxplot_min_stroke_Width'; import chart_boxplot_min_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_boxplot_min_stroke_Color'; import chart_boxplot_lower_quartile_Padding from '@patternfly/react-tokens/dist/esm/chart_boxplot_lower_quartile_Padding'; import chart_boxplot_lower_quartile_Fill from '@patternfly/react-tokens/dist/esm/chart_boxplot_lower_quartile_Fill'; import chart_boxplot_upper_quartile_Padding from '@patternfly/react-tokens/dist/esm/chart_boxplot_upper_quartile_Padding'; import chart_boxplot_upper_quartile_Fill from '@patternfly/react-tokens/dist/esm/chart_boxplot_upper_quartile_Fill'; import chart_boxplot_box_Width from '@patternfly/react-tokens/dist/esm/chart_boxplot_box_Width'; import chart_candelstick_data_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_candelstick_data_stroke_Width'; import chart_candelstick_data_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_candelstick_data_stroke_Color'; import chart_candelstick_candle_positive_Color from '@patternfly/react-tokens/dist/esm/chart_candelstick_candle_positive_Color'; import chart_candelstick_candle_negative_Color from '@patternfly/react-tokens/dist/esm/chart_candelstick_candle_negative_Color'; import chart_errorbar_BorderWidth from '@patternfly/react-tokens/dist/esm/chart_errorbar_BorderWidth'; import chart_errorbar_data_Fill from '@patternfly/react-tokens/dist/esm/chart_errorbar_data_Fill'; import chart_errorbar_data_Opacity from '@patternfly/react-tokens/dist/esm/chart_errorbar_data_Opacity'; import chart_errorbar_data_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_errorbar_data_stroke_Width'; import chart_errorbar_data_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_errorbar_data_stroke_Color'; import chart_legend_gutter_Width from '@patternfly/react-tokens/dist/esm/chart_legend_gutter_Width'; import chart_legend_orientation from '@patternfly/react-tokens/dist/esm/chart_legend_orientation'; import chart_legend_title_orientation from '@patternfly/react-tokens/dist/esm/chart_legend_title_orientation'; import chart_legend_data_type from '@patternfly/react-tokens/dist/esm/chart_legend_data_type'; import chart_legend_title_Padding from '@patternfly/react-tokens/dist/esm/chart_legend_title_Padding'; import chart_line_data_Fill from '@patternfly/react-tokens/dist/esm/chart_line_data_Fill'; import chart_line_data_Opacity from '@patternfly/react-tokens/dist/esm/chart_line_data_Opacity'; import chart_line_data_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_line_data_stroke_Width'; import chart_line_data_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_line_data_stroke_Color'; import chart_pie_Padding from '@patternfly/react-tokens/dist/esm/chart_pie_Padding'; import chart_pie_data_Padding from '@patternfly/react-tokens/dist/esm/chart_pie_data_Padding'; import chart_pie_data_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_pie_data_stroke_Width'; import chart_pie_data_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_pie_data_stroke_Color'; import chart_pie_labels_Padding from '@patternfly/react-tokens/dist/esm/chart_pie_labels_Padding'; import chart_pie_Height from '@patternfly/react-tokens/dist/esm/chart_pie_Height'; import chart_pie_Width from '@patternfly/react-tokens/dist/esm/chart_pie_Width'; import chart_scatter_data_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_scatter_data_stroke_Color'; import chart_scatter_data_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_scatter_data_stroke_Width'; import chart_scatter_data_Opacity from '@patternfly/react-tokens/dist/esm/chart_scatter_data_Opacity'; import chart_scatter_data_Fill from '@patternfly/react-tokens/dist/esm/chart_scatter_data_Fill'; import chart_stack_data_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_stack_data_stroke_Width'; import chart_tooltip_corner_radius from '@patternfly/react-tokens/dist/esm/chart_tooltip_corner_radius'; import chart_tooltip_pointer_length from '@patternfly/react-tokens/dist/esm/chart_tooltip_pointer_length'; import chart_tooltip_Fill from '@patternfly/react-tokens/dist/esm/chart_tooltip_Fill'; import chart_tooltip_flyoutStyle_corner_radius from '@patternfly/react-tokens/dist/esm/chart_tooltip_flyoutStyle_corner_radius'; import chart_tooltip_flyoutStyle_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_tooltip_flyoutStyle_stroke_Width'; import chart_tooltip_flyoutStyle_PointerEvents from '@patternfly/react-tokens/dist/esm/chart_tooltip_flyoutStyle_PointerEvents'; import chart_tooltip_flyoutStyle_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_tooltip_flyoutStyle_stroke_Color'; import chart_tooltip_flyoutStyle_Fill from '@patternfly/react-tokens/dist/esm/chart_tooltip_flyoutStyle_Fill'; import chart_tooltip_pointer_Width from '@patternfly/react-tokens/dist/esm/chart_tooltip_pointer_Width'; import chart_tooltip_Padding from '@patternfly/react-tokens/dist/esm/chart_tooltip_Padding'; import chart_tooltip_PointerEvents from '@patternfly/react-tokens/dist/esm/chart_tooltip_PointerEvents'; import chart_voronoi_data_Fill from '@patternfly/react-tokens/dist/esm/chart_voronoi_data_Fill'; import chart_voronoi_data_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_voronoi_data_stroke_Color'; import chart_voronoi_data_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_voronoi_data_stroke_Width'; import chart_voronoi_labels_Fill from '@patternfly/react-tokens/dist/esm/chart_voronoi_labels_Fill'; import chart_voronoi_labels_Padding from '@patternfly/react-tokens/dist/esm/chart_voronoi_labels_Padding'; import chart_voronoi_labels_PointerEvents from '@patternfly/react-tokens/dist/esm/chart_voronoi_labels_PointerEvents'; import chart_voronoi_flyout_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_voronoi_flyout_stroke_Width'; import chart_voronoi_flyout_PointerEvents from '@patternfly/react-tokens/dist/esm/chart_voronoi_flyout_PointerEvents'; import chart_voronoi_flyout_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_voronoi_flyout_stroke_Color'; import chart_voronoi_flyout_stroke_Fill from '@patternfly/react-tokens/dist/esm/chart_voronoi_flyout_stroke_Fill'; // Note: Values must be in pixles // Typography // // Note: Victory's approximateTextSize function uses specific character widths and does not work with font variables // See https://github.com/patternfly/patternfly-react/issues/5300 const TYPOGRAPHY_FONT_FAMILY = chart_global_FontFamily.value.replace(/ /g, ''); const TYPOGRAPHY_LETTER_SPACING = chart_global_letter_spacing.value; const TYPOGRAPHY_FONT_SIZE = chart_global_FontSize_sm.value; // Labels const LABEL_PROPS = { fontFamily: TYPOGRAPHY_FONT_FAMILY, fontSize: TYPOGRAPHY_FONT_SIZE, letterSpacing: TYPOGRAPHY_LETTER_SPACING, padding: chart_global_label_Padding.value, stroke: chart_global_label_stroke.value }; const LABEL_CENTERED_PROPS = { ...LABEL_PROPS, textAnchor: chart_global_label_text_anchor.value }; // Layout const LAYOUT_PROPS = { padding: chart_global_layout_Padding.value, height: chart_global_layout_Height.value, width: chart_global_layout_Width.value }; // Strokes const STROKE_LINE_CAP = chart_global_stroke_line_cap.value; const STROKE_LINE_JOIN = chart_global_stroke_line_join.value; // Victory theme properties only export const BaseTheme = { area: { ...LAYOUT_PROPS, style: { data: { fill: chart_area_data_Fill.value, fillOpacity: chart_area_Opacity.value, // Omit stroke to add a line border from color scale // stroke: chart_global_label_stroke.value, strokeWidth: chart_area_stroke_Width.value }, labels: LABEL_CENTERED_PROPS } }, axis: { ...LAYOUT_PROPS, style: { axis: { fill: chart_axis_axis_Fill.value, strokeWidth: chart_axis_axis_stroke_Width.value, stroke: chart_axis_axis_stroke_Color.value, strokeLinecap: STROKE_LINE_CAP, strokeLinejoin: STROKE_LINE_JOIN }, axisLabel: { ...LABEL_CENTERED_PROPS, padding: chart_axis_axis_label_Padding.value, stroke: chart_axis_axis_label_stroke_Color.value }, grid: { fill: chart_axis_grid_Fill.value, stroke: 'none', pointerEvents: chart_axis_grid_PointerEvents.value, strokeLinecap: STROKE_LINE_CAP, strokeLinejoin: STROKE_LINE_JOIN }, ticks: { fill: chart_axis_tick_Fill.value, size: chart_axis_tick_Size.value, stroke: chart_axis_tick_stroke_Color.value, strokeLinecap: STROKE_LINE_CAP, strokeLinejoin: STROKE_LINE_JOIN, strokeWidth: chart_axis_tick_Width.value }, tickLabels: { ...LABEL_PROPS, fill: chart_axis_tick_label_Fill.value } } }, bar: { ...LAYOUT_PROPS, barWidth: chart_bar_Width.value, style: { data: { fill: chart_bar_data_Fill.value, padding: chart_bar_data_Padding.value, stroke: chart_bar_data_stroke.value, strokeWidth: chart_bar_data_stroke_Width.value }, labels: LABEL_PROPS } }, boxplot: { ...LAYOUT_PROPS, style: { max: { padding: chart_boxplot_max_Padding.value, stroke: chart_boxplot_max_stroke_Color.value, strokeWidth: chart_boxplot_max_stroke_Width.value }, maxLabels: LABEL_PROPS, median: { padding: chart_boxplot_median_Padding.value, stroke: chart_boxplot_median_stroke_Color.value, strokeWidth: chart_boxplot_median_stroke_Width.value }, medianLabels: LABEL_PROPS, min: { padding: chart_boxplot_min_Padding.value, stroke: chart_boxplot_min_stroke_Color.value, strokeWidth: chart_boxplot_min_stroke_Width.value }, minLabels: LABEL_PROPS, q1: { fill: chart_boxplot_lower_quartile_Fill.value, padding: chart_boxplot_lower_quartile_Padding.value }, q1Labels: LABEL_PROPS, q3: { fill: chart_boxplot_upper_quartile_Fill.value, padding: chart_boxplot_upper_quartile_Padding.value }, q3Labels: LABEL_PROPS }, boxWidth: chart_boxplot_box_Width.value }, candlestick: { ...LAYOUT_PROPS, candleColors: { positive: chart_candelstick_candle_positive_Color.value, negative: chart_candelstick_candle_negative_Color.value }, style: { data: { stroke: chart_candelstick_data_stroke_Color.value, strokeWidth: chart_candelstick_data_stroke_Width.value }, labels: LABEL_CENTERED_PROPS } }, chart: { ...LAYOUT_PROPS }, errorbar: { ...LAYOUT_PROPS, borderWidth: chart_errorbar_BorderWidth.value, style: { data: { fill: chart_errorbar_data_Fill.value, opacity: chart_errorbar_data_Opacity.value, stroke: chart_errorbar_data_stroke_Color.value, strokeWidth: chart_errorbar_data_stroke_Width.value }, labels: LABEL_CENTERED_PROPS } }, group: { ...LAYOUT_PROPS }, legend: { gutter: chart_legend_gutter_Width.value, orientation: chart_legend_orientation.value, titleOrientation: chart_legend_title_orientation.value, style: { data: { type: chart_legend_data_type.value }, labels: LABEL_PROPS, title: { ...LABEL_PROPS, fontSize: TYPOGRAPHY_FONT_SIZE, padding: chart_legend_title_Padding.value } } }, line: { ...LAYOUT_PROPS, style: { data: { fill: chart_line_data_Fill.value, opacity: chart_line_data_Opacity.value, stroke: chart_line_data_stroke_Color.value, strokeWidth: chart_line_data_stroke_Width.value }, labels: LABEL_CENTERED_PROPS } }, pie: { padding: chart_pie_Padding.value, style: { data: { padding: chart_pie_data_Padding.value, stroke: chart_pie_data_stroke_Color.value, strokeWidth: chart_pie_data_stroke_Width.value }, labels: { ...LABEL_PROPS, padding: chart_pie_labels_Padding.value } }, height: chart_pie_Height.value, width: chart_pie_Width.value }, scatter: { ...LAYOUT_PROPS, style: { data: { fill: chart_scatter_data_Fill.value, opacity: chart_scatter_data_Opacity.value, stroke: chart_scatter_data_stroke_Color.value, strokeWidth: chart_scatter_data_stroke_Width.value }, labels: LABEL_CENTERED_PROPS } }, stack: { ...LAYOUT_PROPS, style: { data: { strokeWidth: chart_stack_data_stroke_Width.value } } }, tooltip: { cornerRadius: chart_tooltip_corner_radius.value, flyoutPadding: chart_tooltip_Padding.value, flyoutStyle: { cornerRadius: chart_tooltip_flyoutStyle_corner_radius.value, fill: chart_tooltip_flyoutStyle_Fill.value, // background pointerEvents: chart_tooltip_flyoutStyle_PointerEvents.value, stroke: chart_tooltip_flyoutStyle_stroke_Color.value, // border strokeWidth: chart_tooltip_flyoutStyle_stroke_Width.value }, pointerLength: chart_tooltip_pointer_length.value, pointerWidth: chart_tooltip_pointer_Width.value, style: { fill: chart_tooltip_Fill.value, // text pointerEvents: chart_tooltip_PointerEvents.value } }, voronoi: { ...LAYOUT_PROPS, style: { data: { fill: chart_voronoi_data_Fill.value, stroke: chart_voronoi_data_stroke_Color.value, strokeWidth: chart_voronoi_data_stroke_Width.value }, labels: { ...LABEL_CENTERED_PROPS, fill: chart_voronoi_labels_Fill.value, // text padding: chart_voronoi_labels_Padding.value, pointerEvents: chart_voronoi_labels_PointerEvents.value }, // Note: These properties override tooltip flyout: { fill: chart_voronoi_flyout_stroke_Fill.value, // background pointerEvents: chart_voronoi_flyout_PointerEvents.value, stroke: chart_voronoi_flyout_stroke_Color.value, // border strokeWidth: chart_voronoi_flyout_stroke_Width.value } } } };
the_stack
import { FullChannelState, INodeService, Result, NodeResponses, IVectorChainReader, jsonifyError, } from "@connext/vector-types"; import { getBalanceForAssetId, getRandomBytes32, getParticipant } from "@connext/vector-utils"; import { getAddress } from "@ethersproject/address"; import { BigNumber } from "@ethersproject/bignumber"; import { BaseLogger } from "pino"; import { CollateralError } from "../errors"; import { getRebalanceProfile } from "./config"; /** * This function should be called before a transfer is created/forwarded. * It will ensure there is always sufficient collateral in the channel for * the router to forward along the payment. */ export const justInTimeCollateral = async ( channelAddress: string, assetId: string, publicIdentifier: string, node: INodeService, chainReader: IVectorChainReader, logger: BaseLogger, transferAmount: string, ): Promise<Result<undefined | NodeResponses.Deposit, CollateralError>> => { const method = "justInTimeCollateral"; const methodId = getRandomBytes32(); logger.info({ method, methodId, channelAddress, assetId, transferAmount }, "Method started"); // pull from store // because this is a "justInTime" method, you must make sure you are using // the source of truth to judge if collateral is needed const channelRes = await node.getStateChannel({ channelAddress }); if (channelRes.isError || !channelRes.getValue()) { return Result.fail( new CollateralError(CollateralError.reasons.ChannelNotFound, channelAddress, assetId, {} as any, undefined, { getChannelError: channelRes.isError ? jsonifyError(channelRes.getError()!) : "Channel not found", }), ); } const channel = channelRes.getValue() as FullChannelState; // If there is sufficient balance in the channel to handle the transfer // amount, no need for collateralization const participant = getParticipant(channel, publicIdentifier); if (!participant) { return Result.fail( new CollateralError( CollateralError.reasons.NotInChannel, channel.channelAddress, assetId, {} as any, transferAmount, { publicIdentifier, alice: channel.aliceIdentifier, bob: channel.bobIdentifier }, ), ); } const myBalance = getBalanceForAssetId(channel, assetId, participant); if (BigNumber.from(myBalance).gte(transferAmount)) { logger.info( { method, methodId, channelAddress: channel.channelAddress, balance: myBalance.toString(), transferAmount }, "Balance is sufficient, not collateralizing", ); return Result.ok(undefined); } // Get profile information const profileRes = getRebalanceProfile(channel.networkContext.chainId, assetId); if (profileRes.isError) { return Result.fail( new CollateralError( CollateralError.reasons.UnableToGetRebalanceProfile, channel.channelAddress, assetId, {} as any, undefined, { profileError: jsonifyError(profileRes.getError()!), transferAmount, }, ), ); } const profile = profileRes.getValue(); const target = BigNumber.from(profile.target); const res = await requestCollateral( channel, assetId, publicIdentifier, node, chainReader, logger, BigNumber.from(transferAmount).add(target).toString(), ); logger.info({ method, methodId }, "Method complete"); return res; }; /** * This function should be called after a transfer is resolved to eiher * reclaim or add collateral to adjust the channel to `profile.target` */ export const adjustCollateral = async ( channelAddress: string, assetId: string, publicIdentifier: string, node: INodeService, chainReader: IVectorChainReader, logger: BaseLogger, ): Promise<Result<undefined | NodeResponses.Withdraw | NodeResponses.Deposit, CollateralError>> => { const method = "adjustCollateral"; const methodId = getRandomBytes32(); logger.debug({ method, methodId, channelAddress, assetId }, "Method started"); // Get channel const channelRes = await node.getStateChannel({ publicIdentifier, channelAddress }); if (channelRes.isError || !channelRes.getValue()) { return Result.fail( new CollateralError(CollateralError.reasons.ChannelNotFound, channelAddress, assetId, {} as any, undefined, { getChannelError: jsonifyError(channelRes.getError()!), }), ); } const channel = channelRes.getValue() as FullChannelState; // Get profile information const profileRes = getRebalanceProfile(channel.networkContext.chainId, assetId); if (profileRes.isError) { return Result.fail( new CollateralError( CollateralError.reasons.UnableToGetRebalanceProfile, channelAddress, assetId, {} as any, undefined, { profileError: jsonifyError(profileRes.getError()!), }, ), ); } const profile = profileRes.getValue(); const target = BigNumber.from(profile.target); const collateralizeThreshold = BigNumber.from(profile.collateralizeThreshold); const reclaimThreshold = BigNumber.from(profile.reclaimThreshold); // Get channel balance const participant = getParticipant(channel, publicIdentifier); if (!participant) { return Result.fail( new CollateralError(CollateralError.reasons.NotInChannel, channel.channelAddress, assetId, profile, undefined, { publicIdentifier, alice: channel.aliceIdentifier, bob: channel.bobIdentifier, }), ); } const myBalance = BigNumber.from(getBalanceForAssetId(channel, assetId, participant)); // Establish needed action if (myBalance.gt(collateralizeThreshold) && myBalance.lte(reclaimThreshold)) { // Channel balance is within reason, nothing to do logger.info({ myBalance: myBalance.toString(), assetId, channelAddress }, "No collateral actions needed"); return Result.ok(undefined); } if (myBalance.lte(collateralizeThreshold)) { logger.info( { method, methodId, channelAddress, assetId, myBalance: myBalance.toString(), collateralizeThreshold: profile.collateralizeThreshold, }, "Adding collateral", ); // Must collateralize return requestCollateral(channel, assetId, publicIdentifier, node, chainReader, logger); } // balance should be above reclaim threshold, must reclaim const reclaimable = myBalance.sub(target); if (reclaimable.eq(0)) { logger.info({ assetId, channelAddress }, "Nothing to reclaim"); return Result.ok(undefined); } logger.info({ reclaimable: reclaimable.toString(), assetId, channelAddress }, "Reclaiming funds"); // NOTE: would be interesting to find another channel that needs collateral // in this asset and set the withdrawal to just call `depositA` on that // channel's multisig const withdrawRes = await node.withdraw({ publicIdentifier, assetId, channelAddress: channel.channelAddress, amount: reclaimable.toString(), recipient: participant === "alice" ? channel.alice : channel.bob, }); if (!withdrawRes.isError) { logger.info({ method, methodId }, "Method complete"); return withdrawRes as Result<NodeResponses.Withdraw>; } const withdrawalErr = withdrawRes.getError(); return Result.fail( new CollateralError(CollateralError.reasons.UnableToReclaim, channel.channelAddress, assetId, profile, undefined, { withdrawError: jsonifyError(withdrawalErr!), }), ); }; /** * This function should be called when a deposit may need to be added to * the channel. Will bring the value up to the `requestedAmount`, or if not * provided the `profile.target` */ export const requestCollateral = async ( channel: FullChannelState, assetId: string, publicIdentifier: string, node: INodeService, chainReader: IVectorChainReader, logger: BaseLogger, requestedAmount?: string, ): Promise<Result<undefined | NodeResponses.Deposit, CollateralError>> => { const method = "requestCollateral"; const methodId = getRandomBytes32(); logger.debug({ method, methodId, assetId, publicIdentifier, channel }, "Method started"); const profileRes = getRebalanceProfile(channel.networkContext.chainId, assetId); if (profileRes.isError) { return Result.fail( new CollateralError( CollateralError.reasons.UnableToGetRebalanceProfile, channel.channelAddress, assetId, {} as any, requestedAmount, { profileError: jsonifyError(profileRes.getError()!), }, ), ); } const profile = profileRes.getValue(); const target = BigNumber.from(requestedAmount ?? profile.target); logger.info( { method, methodId, target: target.toString(), channel: channel.channelAddress, assetId }, "Collateral target calculated", ); const participant = getParticipant(channel, publicIdentifier); if (!participant) { return Result.fail( new CollateralError(CollateralError.reasons.NotInChannel, channel.channelAddress, assetId, profile, undefined, { publicIdentifier, alice: channel.aliceIdentifier, bob: channel.bobIdentifier, }), ); } const assetIdx = channel.assetIds.findIndex((a: string) => getAddress(a) === getAddress(assetId)); const myBalance = BigNumber.from(getBalanceForAssetId(channel, assetId, participant)); if (myBalance.gte(target)) { logger.info( { method, methodId, balance: myBalance.toString(), target: target.toString() }, "Current balance is sufficient, not collateralizing", ); return Result.ok(undefined); } logger.info( { method, methodId, target: target.toString(), myBalance: myBalance.toString() }, "Adding collateral to channel", ); const providers = chainReader.getHydratedProviders(); if (providers.isError) { return Result.fail( new CollateralError( CollateralError.reasons.ProviderNotFound, channel.channelAddress, assetId, profile, requestedAmount, { chainId: channel.networkContext.chainId, }, ), ); } const provider = providers.getValue()[channel.networkContext.chainId]; if (!provider) { return Result.fail( new CollateralError( CollateralError.reasons.ProviderNotFound, channel.channelAddress, assetId, profile, requestedAmount, { chainId: channel.networkContext.chainId, }, ), ); } // Check if a tx has already been sent, but has not been reconciled // Get the total deposits vs. processed deposits const totalDeposited = participant === "alice" ? await chainReader.getTotalDepositedA(channel.channelAddress, channel.networkContext.chainId, assetId) : await chainReader.getTotalDepositedB(channel.channelAddress, channel.networkContext.chainId, assetId); if (totalDeposited.isError) { return Result.fail( new CollateralError( CollateralError.reasons.CouldNotGetOnchainDeposits, channel.channelAddress, assetId, profile, requestedAmount, { chainError: jsonifyError(totalDeposited.getError()!), }, ), ); } const processed = participant === "alice" ? channel.processedDepositsA[assetIdx] : channel.processedDepositsB[assetIdx]; const amountToDeposit = BigNumber.from(target).sub(myBalance); const reconcilable = totalDeposited.getValue().sub(processed ?? "0"); if (reconcilable.lt(amountToDeposit)) { // Deposit needed logger.info( { method, methodId, amountToDeposit: amountToDeposit.sub(reconcilable).toString(), target: target.toString(), channelAddress: channel.channelAddress, assetId, reconcilable: reconcilable.toString(), }, "Deposit calculated, submitting tx", ); const txRes = await node.sendDepositTx({ amount: amountToDeposit.sub(reconcilable).toString(), assetId: assetId, chainId: channel.networkContext.chainId, channelAddress: channel.channelAddress, publicIdentifier, }); if (txRes.isError) { return Result.fail( new CollateralError( CollateralError.reasons.TxError, channel.channelAddress, assetId, profile, requestedAmount, { error: jsonifyError(txRes.getError()!), amountToDeposit: amountToDeposit.sub(reconcilable).toString(), }, ), ); } const receipt = txRes.getValue(); logger.info({ method, methodId, txHash: receipt.txHash }, "Tx mined"); } else { logger.info( { method, methodId, assetId, channelAddress: channel.channelAddress, processed, balance: myBalance.toString(), totalDeposited: totalDeposited.getValue().toString(), amountToDeposit: amountToDeposit.toString(), reconcilable: reconcilable.toString(), target: target.toString(), participant, assetIdx, }, "Owed onchain funds are sufficient", ); } const params = { assetId: assetId, publicIdentifier, channelAddress: channel.channelAddress, }; logger.info( { method, methodId, balance: myBalance.toString(), target: target.toString() }, "Reconciling onchain funds", ); // check that funds actually made it into the channel // hard error here if not so that the sender can know that the transfer // will not properly get forwarded // TODO: make depositRes include full channel state #395 const depositRes = await node.reconcileDeposit(params); if (!depositRes.isError) { const postReconcile = await node.getStateChannel({ channelAddress: channel.channelAddress }); if (postReconcile.isError) { return Result.fail( new CollateralError( CollateralError.reasons.UnableToCollateralize, channel.channelAddress, assetId, profile, requestedAmount, { message: "Could not getStateChannel after reconcile", nodeError: jsonifyError(postReconcile.getError()!), }, ), ); } const myBalance = BigNumber.from( getBalanceForAssetId(postReconcile.getValue() as FullChannelState, assetId, participant), ); if (myBalance.lt(target)) { return Result.fail( new CollateralError( CollateralError.reasons.UnableToCollateralize, channel.channelAddress, assetId, profile, requestedAmount, { message: "After reconcile, balance was not present in channel", channel: postReconcile.getValue(), }, ), ); } logger.info({ method, methodId, myBalance: myBalance.toString() }, "Method complete"); return depositRes as Result<NodeResponses.Deposit>; } const error = depositRes.getError()!; return Result.fail( new CollateralError( CollateralError.reasons.UnableToCollateralize, channel.channelAddress, assetId, profile, requestedAmount, { nodeError: jsonifyError(error), }, ), ); };
the_stack
declare module 'vscode-mssql' { import * as vscode from 'vscode'; /** * Covers defining what the vscode-mssql extension exports to other extensions * * IMPORTANT: THIS IS NOT A HARD DEFINITION unlike vscode; therefore no enums or classes should be defined here * (const enums get evaluated when typescript -> javascript so those are fine) */ export const enum extension { name = 'ms-mssql.mssql' } /** * The APIs provided by Mssql extension */ export interface IExtension { /** * Path to the root of the SQL Tools Service folder */ readonly sqlToolsServicePath: string; /** * Service for accessing DacFx functionality */ readonly dacFx: IDacFxService; /** * Service for accessing SchemaCompare functionality */ readonly schemaCompare: ISchemaCompareService; /** * Service for accessing AzureFunctions functionality */ readonly azureFunctions: IAzureFunctionsService; /** * Prompts the user to select an existing connection or create a new one, and then returns the result * @param ignoreFocusOut Whether the quickpick prompt ignores focus out (default false) */ promptForConnection(ignoreFocusOut?: boolean): Promise<IConnectionInfo | undefined>; /** * Attempts to create a new connection for the given connection info. An error is thrown and displayed * to the user if an error occurs while connecting. * Warning: setting the saveConnection to true will save a new connection profile each time this is called. * Make sure to use that parameter only when you want to actually save a new profile. * @param connectionInfo The connection info * @param saveConnection Save the connection profile if sets to true * @returns The URI associated with this connection */ connect(connectionInfo: IConnectionInfo, saveConnection?: boolean): Promise<string>; /** * Lists the databases for a given connection. Must be given an already-opened connection to succeed. * @param connectionUri The URI of the connection to list the databases for. * @returns The list of database names */ listDatabases(connectionUri: string): Promise<string[]>; /** * Gets the database name for the node - which is the database name of the connection for a server node, the database name * for nodes at or under a database node or a default value if it's neither of those. * @param node The node to get the database name of * @returns The database name */ getDatabaseNameFromTreeNode(node: ITreeNodeInfo): string; } /** * Information about a database connection */ export interface IConnectionInfo { /** * server name */ server: string; /** * database name */ database: string; /** * user name */ user: string; /** * password */ password: string; /** * email */ email: string | undefined; /** * accountId */ accountId: string | undefined; /** * The port number to connect to. */ port: number; /** * Gets or sets the authentication to use. */ authenticationType: string; /** * Gets or sets the azure account token to use. */ azureAccountToken: string | undefined; /** * Gets or sets a Boolean value that indicates whether SQL Server uses SSL encryption for all data sent between the client and server if * the server has a certificate installed. */ encrypt: boolean; /** * Gets or sets a value that indicates whether the channel will be encrypted while bypassing walking the certificate chain to validate trust. */ trustServerCertificate: boolean | undefined; /** * Gets or sets a Boolean value that indicates if security-sensitive information, such as the password, is not returned as part of the connection * if the connection is open or has ever been in an open state. */ persistSecurityInfo: boolean | undefined; /** * Gets or sets the length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error. */ connectTimeout: number | undefined; /** * The number of reconnections attempted after identifying that there was an idle connection failure. */ connectRetryCount: number | undefined; /** * Amount of time (in seconds) between each reconnection attempt after identifying that there was an idle connection failure. */ connectRetryInterval: number | undefined; /** * Gets or sets the name of the application associated with the connection string. */ applicationName: string | undefined; /** * Gets or sets the name of the workstation connecting to SQL Server. */ workstationId: string | undefined; /** * Declares the application workload type when connecting to a database in an SQL Server Availability Group. */ applicationIntent: string | undefined; /** * Gets or sets the SQL Server Language record name. */ currentLanguage: string | undefined; /** * Gets or sets a Boolean value that indicates whether the connection will be pooled or explicitly opened every time that the connection is requested. */ pooling: boolean | undefined; /** * Gets or sets the maximum number of connections allowed in the connection pool for this specific connection string. */ maxPoolSize: number | undefined; /** * Gets or sets the minimum number of connections allowed in the connection pool for this specific connection string. */ minPoolSize: number | undefined; /** * Gets or sets the minimum time, in seconds, for the connection to live in the connection pool before being destroyed. */ loadBalanceTimeout: number | undefined; /** * Gets or sets a Boolean value that indicates whether replication is supported using the connection. */ replication: boolean | undefined; /** * Gets or sets a string that contains the name of the primary data file. This includes the full path name of an attachable database. */ attachDbFilename: string | undefined; /** * Gets or sets the name or address of the partner server to connect to if the primary server is down. */ failoverPartner: string | undefined; /** * If your application is connecting to an AlwaysOn availability group (AG) on different subnets, setting MultiSubnetFailover=true * provides faster detection of and connection to the (currently) active server. */ multiSubnetFailover: boolean | undefined; /** * When true, an application can maintain multiple active result sets (MARS). */ multipleActiveResultSets: boolean | undefined; /** * Gets or sets the size in bytes of the network packets used to communicate with an instance of SQL Server. */ packetSize: number | undefined; /** * Gets or sets a string value that indicates the type system the application expects. */ typeSystemVersion: string | undefined; /** * Gets or sets the connection string to use for this connection. */ connectionString: string | undefined; } export const enum ExtractTarget { dacpac = 0, file = 1, flat = 2, objectType = 3, schema = 4, schemaObjectType = 5 } export interface ISchemaCompareService { schemaCompareGetDefaultOptions(): Thenable<SchemaCompareOptionsResult>; } export interface IDacFxService { exportBacpac(databaseName: string, packageFilePath: string, ownerUri: string, taskExecutionMode: TaskExecutionMode): Thenable<DacFxResult>; importBacpac(packageFilePath: string, databaseName: string, ownerUri: string, taskExecutionMode: TaskExecutionMode): Thenable<DacFxResult>; extractDacpac(databaseName: string, packageFilePath: string, applicationName: string, applicationVersion: string, ownerUri: string, taskExecutionMode: TaskExecutionMode): Thenable<DacFxResult>; createProjectFromDatabase(databaseName: string, targetFilePath: string, applicationName: string, applicationVersion: string, ownerUri: string, extractTarget: ExtractTarget, taskExecutionMode: TaskExecutionMode): Thenable<DacFxResult>; deployDacpac(packageFilePath: string, databaseName: string, upgradeExisting: boolean, ownerUri: string, taskExecutionMode: TaskExecutionMode, sqlCommandVariableValues?: Record<string, string>, deploymentOptions?: DeploymentOptions): Thenable<DacFxResult>; generateDeployScript(packageFilePath: string, databaseName: string, ownerUri: string, taskExecutionMode: TaskExecutionMode, sqlCommandVariableValues?: Record<string, string>, deploymentOptions?: DeploymentOptions): Thenable<DacFxResult>; generateDeployPlan(packageFilePath: string, databaseName: string, ownerUri: string, taskExecutionMode: TaskExecutionMode): Thenable<GenerateDeployPlanResult>; getOptionsFromProfile(profilePath: string): Thenable<DacFxOptionsResult>; validateStreamingJob(packageFilePath: string, createStreamingJobTsql: string): Thenable<ValidateStreamingJobResult>; } export interface IAzureFunctionsService { /** * Adds a SQL Binding to a specified Azure function in a file * @param bindingType Type of SQL Binding * @param filePath Path of the file where the Azure Functions are * @param functionName Name of the function where the SQL Binding is to be added * @param objectName Name of Object for the SQL Query * @param connectionStringSetting Setting for the connection string */ addSqlBinding(bindingType: BindingType, filePath: string, functionName: string, objectName: string, connectionStringSetting: string): Thenable<ResultStatus>; /** * Gets the names of the Azure functions in the file * @param filePath Path of the file to get the Azure functions * @returns array of names of Azure functions in the file */ getAzureFunctions(filePath: string): Thenable<GetAzureFunctionsResult>; } export const enum TaskExecutionMode { execute = 0, script = 1, executeAndScript = 2 } export interface DeploymentOptions { ignoreTableOptions: boolean; ignoreSemicolonBetweenStatements: boolean; ignoreRouteLifetime: boolean; ignoreRoleMembership: boolean; ignoreQuotedIdentifiers: boolean; ignorePermissions: boolean; ignorePartitionSchemes: boolean; ignoreObjectPlacementOnPartitionScheme: boolean; ignoreNotForReplication: boolean; ignoreLoginSids: boolean; ignoreLockHintsOnIndexes: boolean; ignoreKeywordCasing: boolean; ignoreIndexPadding: boolean; ignoreIndexOptions: boolean; ignoreIncrement: boolean; ignoreIdentitySeed: boolean; ignoreUserSettingsObjects: boolean; ignoreFullTextCatalogFilePath: boolean; ignoreWhitespace: boolean; ignoreWithNocheckOnForeignKeys: boolean; verifyCollationCompatibility: boolean; unmodifiableObjectWarnings: boolean; treatVerificationErrorsAsWarnings: boolean; scriptRefreshModule: boolean; scriptNewConstraintValidation: boolean; scriptFileSize: boolean; scriptDeployStateChecks: boolean; scriptDatabaseOptions: boolean; scriptDatabaseCompatibility: boolean; scriptDatabaseCollation: boolean; runDeploymentPlanExecutors: boolean; registerDataTierApplication: boolean; populateFilesOnFileGroups: boolean; noAlterStatementsToChangeClrTypes: boolean; includeTransactionalScripts: boolean; includeCompositeObjects: boolean; allowUnsafeRowLevelSecurityDataMovement: boolean; ignoreWithNocheckOnCheckConstraints: boolean; ignoreFillFactor: boolean; ignoreFileSize: boolean; ignoreFilegroupPlacement: boolean; doNotAlterReplicatedObjects: boolean; doNotAlterChangeDataCaptureObjects: boolean; disableAndReenableDdlTriggers: boolean; deployDatabaseInSingleUserMode: boolean; createNewDatabase: boolean; compareUsingTargetCollation: boolean; commentOutSetVarDeclarations: boolean; blockWhenDriftDetected: boolean; blockOnPossibleDataLoss: boolean; backupDatabaseBeforeChanges: boolean; allowIncompatiblePlatform: boolean; allowDropBlockingAssemblies: boolean; dropConstraintsNotInSource: boolean; dropDmlTriggersNotInSource: boolean; dropExtendedPropertiesNotInSource: boolean; dropIndexesNotInSource: boolean; ignoreFileAndLogFilePath: boolean; ignoreExtendedProperties: boolean; ignoreDmlTriggerState: boolean; ignoreDmlTriggerOrder: boolean; ignoreDefaultSchema: boolean; ignoreDdlTriggerState: boolean; ignoreDdlTriggerOrder: boolean; ignoreCryptographicProviderFilePath: boolean; verifyDeployment: boolean; ignoreComments: boolean; ignoreColumnCollation: boolean; ignoreAuthorizer: boolean; ignoreAnsiNulls: boolean; generateSmartDefaults: boolean; dropStatisticsNotInSource: boolean; dropRoleMembersNotInSource: boolean; dropPermissionsNotInSource: boolean; dropObjectsNotInSource: boolean; ignoreColumnOrder: boolean; doNotDropObjectTypes: SchemaObjectType[]; excludeObjectTypes: SchemaObjectType[]; } /** * Values from <DacFx>\Product\Source\DeploymentApi\ObjectTypes.cs */ export const enum SchemaObjectType { Aggregates = 0, ApplicationRoles = 1, Assemblies = 2, AssemblyFiles = 3, AsymmetricKeys = 4, BrokerPriorities = 5, Certificates = 6, ColumnEncryptionKeys = 7, ColumnMasterKeys = 8, Contracts = 9, DatabaseOptions = 10, DatabaseRoles = 11, DatabaseTriggers = 12, Defaults = 13, ExtendedProperties = 14, ExternalDataSources = 15, ExternalFileFormats = 16, ExternalTables = 17, Filegroups = 18, Files = 19, FileTables = 20, FullTextCatalogs = 21, FullTextStoplists = 22, MessageTypes = 23, PartitionFunctions = 24, PartitionSchemes = 25, Permissions = 26, Queues = 27, RemoteServiceBindings = 28, RoleMembership = 29, Rules = 30, ScalarValuedFunctions = 31, SearchPropertyLists = 32, SecurityPolicies = 33, Sequences = 34, Services = 35, Signatures = 36, StoredProcedures = 37, SymmetricKeys = 38, Synonyms = 39, Tables = 40, TableValuedFunctions = 41, UserDefinedDataTypes = 42, UserDefinedTableTypes = 43, ClrUserDefinedTypes = 44, Users = 45, Views = 46, XmlSchemaCollections = 47, Audits = 48, Credentials = 49, CryptographicProviders = 50, DatabaseAuditSpecifications = 51, DatabaseEncryptionKeys = 52, DatabaseScopedCredentials = 53, Endpoints = 54, ErrorMessages = 55, EventNotifications = 56, EventSessions = 57, LinkedServerLogins = 58, LinkedServers = 59, Logins = 60, MasterKeys = 61, Routes = 62, ServerAuditSpecifications = 63, ServerRoleMembership = 64, ServerRoles = 65, ServerTriggers = 66, ExternalStreams = 67, ExternalStreamingJobs = 68 } /** * ResultStatus from d.ts */ export interface ResultStatus { success: boolean; errorMessage: string; } export interface DacFxResult extends ResultStatus { operationId: string; } export interface GenerateDeployPlanResult extends DacFxResult { report: string; } export interface DacFxOptionsResult extends ResultStatus { deploymentOptions: DeploymentOptions; } export interface ValidateStreamingJobResult extends ResultStatus { } export interface ExportParams { databaseName: string; packageFilePath: string; ownerUri: string; taskExecutionMode: TaskExecutionMode; } export interface ImportParams { packageFilePath: string; databaseName: string; ownerUri: string; taskExecutionMode: TaskExecutionMode; } export interface ExtractParams { databaseName: string; packageFilePath: string; applicationName: string; applicationVersion: string; ownerUri: string; extractTarget?: ExtractTarget; taskExecutionMode: TaskExecutionMode; } export interface DeployParams { packageFilePath: string; databaseName: string; upgradeExisting: boolean; sqlCommandVariableValues?: Record<string, string>; deploymentOptions?: DeploymentOptions; ownerUri: string; taskExecutionMode: TaskExecutionMode; } export interface GenerateDeployScriptParams { packageFilePath: string; databaseName: string; sqlCommandVariableValues?: Record<string, string>; deploymentOptions?: DeploymentOptions; ownerUri: string; taskExecutionMode: TaskExecutionMode; } export interface GenerateDeployPlanParams { packageFilePath: string; databaseName: string; ownerUri: string; taskExecutionMode: TaskExecutionMode; } export interface GetOptionsFromProfileParams { profilePath: string; } export interface ValidateStreamingJobParams { packageFilePath: string; createStreamingJobTsql: string; } export interface SchemaCompareGetOptionsParams { } export interface SchemaCompareOptionsResult extends ResultStatus { defaultDeploymentOptions: DeploymentOptions; } export interface ITreeNodeInfo extends vscode.TreeItem { readonly connectionInfo: IConnectionInfo; nodeType: string; metadata: ObjectMetadata; parentNode: ITreeNodeInfo; } export const enum MetadataType { Table = 0, View = 1, SProc = 2, Function = 3 } export interface ObjectMetadata { metadataType: MetadataType; metadataTypeName: string; urn: string; name: string; schema: string; parentName?: string; parentTypeName?: string; } /** * Azure functions binding type */ export const enum BindingType { input, output } /** * Parameters for adding a SQL binding to an Azure function */ export interface AddSqlBindingParams { /** * Aboslute file path of file to add SQL binding */ filePath: string; /** * Name of function to add SQL binding */ functionName: string; /** * Name of object to use in SQL binding */ objectName: string; /** * Type of Azure function binding */ bindingType: BindingType; /** * Name of SQL connection string setting specified in local.settings.json */ connectionStringSetting: string; } /** * Parameters for getting the names of the Azure functions in a file */ export interface GetAzureFunctionsParams { /** * Absolute file path of file to get Azure functions */ filePath: string; } /** * Result from a get Azure functions request */ export interface GetAzureFunctionsResult extends ResultStatus { /** * Array of names of Azure functions in the file */ azureFunctions: string[]; } }
the_stack
import { CanvasRenderingContext2D, CanvasDirection, CanvasFillRule, CanvasImageSource, CanvasLineCap, CanvasLineJoin, CanvasTextAlign, CanvasTextBaseline, ImageSmoothingQuality, CanvasGradient, CanvasPattern, } from './CanvasTypes'; import { MessageType, OffscreenCanvasToWorker } from '../../transfer/Messages'; import { TransferrableKeys } from '../../transfer/TransferrableKeys'; import { transfer } from '../MutationTransfer'; import { TransferrableMutationType } from '../../transfer/TransferrableMutation'; import { OffscreenCanvasPolyfill } from './OffscreenCanvasPolyfill'; import { Document } from '../dom/Document'; import { HTMLElement } from '../dom/HTMLElement'; import { FakeNativeCanvasPattern } from './FakeNativeCanvasPattern'; import { retrieveImageBitmap } from './canvas-utils'; import { HTMLCanvasElement } from '../dom/HTMLCanvasElement'; export const deferredUpgrades = new WeakMap(); /** * Delegates all CanvasRenderingContext2D calls, either to an OffscreenCanvas or a polyfill * (depending on whether it is supported). */ export class CanvasRenderingContext2DShim<ElementType extends HTMLElement> implements CanvasRenderingContext2D { private queue = [] as { fnName: string; args: any[]; isSetter: boolean }[]; private implementation: CanvasRenderingContext2D; private upgraded = false; private canvasElement: ElementType; private polyfillUsed: boolean; // createPattern calls need to retrieve an ImageBitmap from the main-thread. Since those can // happen subsequently, we must keep track of these to avoid reentrancy problems. private unresolvedCalls = 0; private goodImplementation: CanvasRenderingContext2D; constructor(canvas: ElementType) { this.canvasElement = canvas; const OffscreenCanvas = canvas.ownerDocument.defaultView.OffscreenCanvas; // If the browser does not support OffscreenCanvas, use polyfill if (typeof OffscreenCanvas === 'undefined') { this.implementation = new OffscreenCanvasPolyfill<ElementType>(canvas).getContext('2d'); this.upgraded = true; this.polyfillUsed = true; } // If the browser supports OffscreenCanvas: // 1. Use un-upgraded (not auto-synchronized) version for all calls performed immediately after // creation. All calls will be queued to call on upgraded version after. // 2. Retrieve an auto-synchronized OffscreenCanvas from the main-thread and call all methods // in the queue. else { this.implementation = new OffscreenCanvas(0, 0).getContext('2d'); this.getOffscreenCanvasAsync(this.canvasElement); this.polyfillUsed = false; } } /** * Retrieves auto-synchronized version of an OffscreenCanvas from the main-thread. * @param canvas HTMLCanvasElement associated with this context. */ private getOffscreenCanvasAsync(canvas: ElementType): Promise<void> { this.unresolvedCalls++; const deferred: { resolve?: (value?: {} | PromiseLike<{}>) => void; upgradePromise?: Promise<void>; } = {}; const document = this.canvasElement.ownerDocument; const isTestMode = !document.addGlobalEventListener; const upgradePromise = new Promise((resolve) => { const messageHandler = ({ data }: { data: OffscreenCanvasToWorker }) => { if ( data[TransferrableKeys.type] === MessageType.OFFSCREEN_CANVAS_INSTANCE && data[TransferrableKeys.target][0] === canvas[TransferrableKeys.index] ) { document.removeGlobalEventListener('message', messageHandler); const transferredOffscreenCanvas = (data as OffscreenCanvasToWorker)[TransferrableKeys.data]; resolve( transferredOffscreenCanvas as { getContext(c: '2d'): CanvasRenderingContext2D; }, ); } }; if (!document.addGlobalEventListener) { if (isTestMode) { deferred.resolve = resolve; } else { throw new Error('addGlobalEventListener is not defined.'); } } else { document.addGlobalEventListener('message', messageHandler); transfer(canvas.ownerDocument as Document, [TransferrableMutationType.OFFSCREEN_CANVAS_INSTANCE, canvas[TransferrableKeys.index]]); } }).then((instance: { getContext(c: '2d'): CanvasRenderingContext2D }) => { this.goodImplementation = instance.getContext('2d'); this.maybeUpgradeImplementation(); }); if (isTestMode) { deferred.upgradePromise = upgradePromise; deferredUpgrades.set(canvas, deferred); } return upgradePromise; } /** * Degrades the underlying context implementation and adds to the unresolved call count. */ private degradeImplementation() { this.upgraded = false; const OffscreenCanvas = this.canvasElement.ownerDocument.defaultView.OffscreenCanvas; this.implementation = new OffscreenCanvas(0, 0).getContext('2d'); this.unresolvedCalls++; } /** * Will upgrade the underlying context implementation if no more unresolved calls remain. */ private maybeUpgradeImplementation() { this.unresolvedCalls--; if (this.unresolvedCalls === 0) { this.implementation = this.goodImplementation; this.upgraded = true; this.flushQueue(); } } private flushQueue() { for (const call of this.queue) { if (call.isSetter) { (this as any)[call.fnName] = call.args[0]; } else { (this as any)[call.fnName](...call.args); } } this.queue.length = 0; } private delegateFunc(name: string, args: any[]) { const returnValue = (this.implementation as any)[name](...args); if (!this.upgraded) { this.queue.push({ fnName: name, args, isSetter: false }); } return returnValue; } private delegateSetter(name: string, args: any[]) { (this.implementation as any)[name] = args[0]; if (!this.upgraded) { this.queue.push({ fnName: name, args, isSetter: true }); } } private delegateGetter(name: string) { return (this.implementation as any)[name]; } /* DRAWING RECTANGLES */ clearRect(x: number, y: number, width: number, height: number): void { this.delegateFunc('clearRect', [...arguments]); } fillRect(x: number, y: number, width: number, height: number): void { this.delegateFunc('fillRect', [...arguments]); } strokeRect(x: number, y: number, width: number, height: number): void { this.delegateFunc('strokeRect', [...arguments]); } /* DRAWING TEXT */ fillText(text: string, x: number, y: number, maxWidth?: number): void { this.delegateFunc('fillText', [...arguments]); } strokeText(text: string, x: number, y: number, maxWidth?: number): void { this.delegateFunc('strokeText', [...arguments]); } measureText(text: string): TextMetrics { return this.delegateFunc('measureText', [...arguments]); } /* LINE STYLES */ set lineWidth(value: number) { this.delegateSetter('lineWidth', [...arguments]); } get lineWidth(): number { return this.delegateGetter('lineWidth'); } set lineCap(value: CanvasLineCap) { this.delegateSetter('lineCap', [...arguments]); } get lineCap(): CanvasLineCap { return this.delegateGetter('lineCap'); } set lineJoin(value: CanvasLineJoin) { this.delegateSetter('lineJoin', [...arguments]); } get lineJoin(): CanvasLineJoin { return this.delegateGetter('lineJoin'); } set miterLimit(value: number) { this.delegateSetter('miterLimit', [...arguments]); } get miterLimit(): number { return this.delegateGetter('miterLimit'); } getLineDash(): number[] { return this.delegateFunc('getLineDash', [...arguments]); } setLineDash(segments: number[]): void { this.delegateFunc('setLineDash', [...arguments]); } set lineDashOffset(value: number) { this.delegateSetter('lineDashOffset', [...arguments]); } get lineDashOffset(): number { return this.delegateGetter('lineDashOffset'); } /* TEXT STYLES */ set font(value: string) { this.delegateSetter('font', [...arguments]); } get font(): string { return this.delegateGetter('font'); } set textAlign(value: CanvasTextAlign) { this.delegateSetter('textAlign', [...arguments]); } get textAlign(): CanvasTextAlign { return this.delegateGetter('textAlign'); } set textBaseline(value: CanvasTextBaseline) { this.delegateSetter('textBaseline', [...arguments]); } get textBaseline(): CanvasTextBaseline { return this.delegateGetter('textBaseline'); } set direction(value: CanvasDirection) { this.delegateSetter('direction', [...arguments]); } get direction(): CanvasDirection { return this.delegateGetter('direction'); } /* FILL AND STROKE STYLES */ set fillStyle(value: string | CanvasGradient | CanvasPattern) { // 1. Native pattern instances given to the user hold the 'real' pattern as their implementation prop. // 2. Pattern must be upgraded, otherwise an undefined 'implementation' will be queued instead of the wrapper object. if (value instanceof FakeNativeCanvasPattern && this.upgraded) { // This case occurs only when an un-upgraded pattern is passed into a different (already // upgraded) canvas context. if (!value[TransferrableKeys.patternUpgraded]) { this.queue.push({ fnName: 'fillStyle', args: [value], isSetter: true }); this.degradeImplementation(); value[TransferrableKeys.patternUpgradePromise].then(() => { this.maybeUpgradeImplementation(); }); } else { this.delegateSetter('fillStyle', [value[TransferrableKeys.patternImplementation]]); } // Any other case does not require special handling. } else { this.delegateSetter('fillStyle', [...arguments]); } } get fillStyle(): string | CanvasGradient | CanvasPattern { return this.delegateGetter('fillStyle'); } set strokeStyle(value: string | CanvasGradient | CanvasPattern) { // 1. Native pattern instances given to the user hold the 'real' pattern as their implementation prop. // 2. Pattern must be upgraded, otherwise an undefined 'implementation' could be queued instead of the wrapper object. if (value instanceof FakeNativeCanvasPattern && this.upgraded) { // This case occurs only when an un-upgraded pattern is passed into a different (already // upgraded) canvas context. if (!value[TransferrableKeys.patternUpgraded]) { this.queue.push({ fnName: 'strokeStyle', args: [value], isSetter: true, }); this.degradeImplementation(); value[TransferrableKeys.patternUpgradePromise].then(() => { this.maybeUpgradeImplementation(); }); } else { this.delegateSetter('strokeStyle', [value[TransferrableKeys.patternImplementation]]); } // Any other case does not require special handling. } else { this.delegateSetter('strokeStyle', [...arguments]); } } get strokeStyle(): string | CanvasGradient | CanvasPattern { return this.delegateGetter('strokeStyle'); } /* GRADIENTS AND PATTERNS */ createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient { return this.delegateFunc('createLinearGradient', [...arguments]); } createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient { return this.delegateFunc('createRadialGradient', [...arguments]); } createPattern(image: CanvasImageSource, repetition: string): CanvasPattern | null { const ImageBitmap = this.canvasElement.ownerDocument.defaultView.ImageBitmap; // Only HTMLElement image sources require special handling. ImageBitmap is OK to use. if (this.polyfillUsed || image instanceof ImageBitmap) { return this.delegateFunc('createPattern', [...arguments]); } else { // Degrade the underlying implementation because we don't want calls on the real one until // after pattern is retrieved this.degradeImplementation(); const fakePattern = new FakeNativeCanvasPattern<ElementType>(); fakePattern[TransferrableKeys.retrieveCanvasPattern](this.canvas, image, repetition).then(() => { this.maybeUpgradeImplementation(); }); return fakePattern; } } /* DRAWING IMAGES */ drawImage(image: CanvasImageSource, dx: number, dy: number): void { const ImageBitmap = this.canvasElement.ownerDocument.defaultView.ImageBitmap; // Only HTMLElement image sources require special handling. ImageBitmap is OK to use. if (this.polyfillUsed || image instanceof ImageBitmap) { this.delegateFunc('drawImage', [...arguments]); } else { // Queue the drawImage call to make sure it gets called in correct order const args = [] as any[]; this.queue.push({ fnName: 'drawImage', args, isSetter: false }); // Degrade the underlying implementation because we don't want calls on the real one // until after the ImageBitmap is received. this.degradeImplementation(); // Retrieve an ImageBitmap from the main-thread with the same image as the input image retrieveImageBitmap(image as any, this.canvas as unknown as HTMLCanvasElement) // Then call the actual method with the retrieved ImageBitmap .then((instance: ImageBitmap) => { args.push(instance, dx, dy); this.maybeUpgradeImplementation(); }); } } /* SHADOWS */ set shadowBlur(value: number) { this.delegateSetter('shadowBlur', [...arguments]); } get shadowBlur(): number { return this.delegateGetter('shadowBlur'); } set shadowColor(value: string) { this.delegateSetter('shadowColor', [...arguments]); } get shadowColor(): string { return this.delegateGetter('shadowColor'); } set shadowOffsetX(value: number) { this.delegateSetter('shadowOffsetX', [...arguments]); } get shadowOffsetX(): number { return this.delegateGetter('shadowOffsetX'); } set shadowOffsetY(value: number) { this.delegateSetter('shadowOffsetY', [...arguments]); } get shadowOffsetY(): number { return this.delegateGetter('shadowOffsetY'); } /* PATHS */ beginPath(): void { this.delegateFunc('beginPath', [...arguments]); } closePath(): void { this.delegateFunc('closePath', [...arguments]); } moveTo(x: number, y: number): void { this.delegateFunc('moveTo', [...arguments]); } lineTo(x: number, y: number): void { this.delegateFunc('lineTo', [...arguments]); } bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void { this.delegateFunc('bezierCurveTo', [...arguments]); } quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void { this.delegateFunc('quadraticCurveTo', [...arguments]); } arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, antiClockwise?: boolean): void { this.delegateFunc('arc', [...arguments]); } arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void { this.delegateFunc('arcTo', [...arguments]); } ellipse( x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, antiClockwise?: boolean, ): void { this.delegateFunc('ellipse', [...arguments]); } rect(x: number, y: number, width: number, height: number): void { this.delegateFunc('rect', [...arguments]); } /* DRAWING PATHS */ fill(pathOrFillRule?: Path2D | CanvasFillRule, fillRule?: CanvasFillRule): void { const args = [...arguments] as [Path2D, CanvasFillRule | undefined] | [CanvasFillRule | undefined]; this.delegateFunc('fill', args); } stroke(path?: Path2D): void { const args = [...arguments] as [Path2D] | []; this.delegateFunc('stroke', args); } clip(pathOrFillRule?: Path2D | CanvasFillRule, fillRule?: CanvasFillRule): void { const args = [...arguments] as [Path2D, CanvasFillRule | undefined] | [CanvasFillRule | undefined]; this.delegateFunc('clip', args); } isPointInPath(pathOrX: Path2D | number, xOrY: number, yOrFillRule?: number | CanvasFillRule, fillRule?: CanvasFillRule): boolean { const args = [...arguments] as [number, number, CanvasFillRule | undefined] | [Path2D, number, number, CanvasFillRule | undefined]; return this.delegateFunc('isPointInPath', args); } isPointInStroke(pathOrX: Path2D | number, xOrY: number, y?: number): boolean { const args = [...arguments] as [number, number] | [Path2D, number, number]; return this.delegateFunc('isPointInStroke', args); } /* TRANSFORMATIONS */ rotate(angle: number): void { this.delegateFunc('rotate', [...arguments]); } scale(x: number, y: number): void { this.delegateFunc('scale', [...arguments]); } translate(x: number, y: number): void { this.delegateFunc('translate', [...arguments]); } transform(a: number, b: number, c: number, d: number, e: number, f: number): void { this.delegateFunc('transform', [...arguments]); } setTransform(transformOrA?: DOMMatrix2DInit | number, bOrC?: number, cOrD?: number, dOrE?: number, eOrF?: number, f?: number): void { const args = [...arguments] as [] | [DOMMatrix2DInit] | [number, number, number, number, number, number]; this.delegateFunc('setTransform', args); } /* experimental */ resetTransform(): void { this.delegateFunc('resetTransform', [...arguments]); } /* COMPOSITING */ set globalAlpha(value: number) { this.delegateSetter('globalAlpha', [...arguments]); } get globalAlpha(): number { return this.delegateGetter('globalAlpha'); } set globalCompositeOperation(value: string) { this.delegateSetter('globalCompositeOperation', [...arguments]); } get globalCompositeOperation(): string { return this.delegateGetter('globalCompositeOperation'); } /* PIXEL MANIPULATION */ createImageData(imagedataOrWidth: ImageData | number, height?: number): ImageData { const args = [...arguments] as [ImageData] | [number, number]; return this.delegateFunc('createImageData', args); } getImageData(sx: number, sy: number, sw: number, sh: number): ImageData { return this.delegateFunc('getImageData', [...arguments]); } putImageData(imageData: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void { this.delegateFunc('putImageData', [...arguments]); } /* IMAGE SMOOTHING */ /* experimental */ set imageSmoothingEnabled(value: boolean) { this.delegateSetter('imageSmoothingEnabled', [...arguments]); } /* experimental */ get imageSmoothingEnabled(): boolean { return this.delegateGetter('imageSmoothingEnabled'); } /* experimental */ set imageSmoothingQuality(value: ImageSmoothingQuality) { this.delegateSetter('imageSmoothingQuality', [...arguments]); } /* experimental */ get imageSmoothingQuality(): ImageSmoothingQuality { return this.delegateGetter('imageSmoothingQuality'); } /* THE CANVAS STATE */ save(): void { this.delegateFunc('save', [...arguments]); } restore(): void { this.delegateFunc('restore', [...arguments]); } // canvas property is readonly. We don't want to implement getters, but this must be here // in order for TypeScript to not complain (for now) get canvas(): ElementType { return this.canvasElement; } /* FILTERS */ /* experimental */ set filter(value: string) { this.delegateSetter('filter', [...arguments]); } /* experimental */ get filter(): string { return this.delegateGetter('filter'); } }
the_stack
import WDIOReporter, { SuiteStats, Tag, HookStats, RunnerStats, TestStats, BeforeCommandArgs, AfterCommandArgs, CommandArgs, Argument } from '@wdio/reporter' import { Capabilities, Options } from '@wdio/types' import { getTestStatus, isEmpty, tellReporter, isMochaEachHooks, getErrorFromFailedTest, isMochaAllHooks, getLinkByTemplate, attachConsoleLogs } from './utils' import { events, PASSED, PENDING, SKIPPED, stepStatuses } from './constants' import { AddAttachmentEventArgs, AddDescriptionEventArgs, AddEnvironmentEventArgs, AddFeatureEventArgs, AddIssueEventArgs, AddLabelEventArgs, AddSeverityEventArgs, AddStoryEventArgs, AddTestIdEventArgs, AllureReporterOptions, Status } from './types' import { stringify } from 'csv-stringify/sync' /** * Allure v1 has no proper TS support * ToDo(Christian): update to Allure v2 (https://github.com/webdriverio/webdriverio/issues/6313) */ const Allure = require('allure-js-commons') const Step = require('allure-js-commons/beans/step') class AllureReporter extends WDIOReporter { private _allure: any private _capabilities: Capabilities.RemoteCapability private _isMultiremote?: boolean private _config?: Options.Testrunner private _lastScreenshot?: string private _options: AllureReporterOptions private _consoleOutput: string private _originalStdoutWrite: Function private _addConsoleLogs: boolean constructor(options: AllureReporterOptions = {}) { const outputDir = options.outputDir || 'allure-results' super({ ...options, outputDir, }) this._addConsoleLogs = false this._consoleOutput = '' this._originalStdoutWrite = process.stdout.write.bind(process.stdout) this._allure = new Allure() this._capabilities = {} this._options = options this._allure.setOptions({ targetDir: outputDir }) this.registerListeners() this._lastScreenshot = undefined let processObj:any = process if (options.addConsoleLogs || this._addConsoleLogs) { processObj.stdout.write = (chunk: string, encoding: BufferEncoding, callback: ((err?: Error) => void)) => { if (typeof chunk === 'string' && !chunk.includes('mwebdriver')) { this._consoleOutput += chunk } return this._originalStdoutWrite(chunk, encoding, callback) } } } registerListeners() { process.on(events.addLabel, this.addLabel.bind(this)) process.on(events.addFeature, this.addFeature.bind(this)) process.on(events.addStory, this.addStory.bind(this)) process.on(events.addSeverity, this.addSeverity.bind(this)) process.on(events.addIssue, this.addIssue.bind(this)) process.on(events.addTestId, this.addTestId.bind(this)) process.on(events.addEnvironment, this.addEnvironment.bind(this)) process.on(events.addAttachment, this.addAttachment.bind(this)) process.on(events.addDescription, this.addDescription.bind(this)) process.on(events.startStep, this.startStep.bind(this)) process.on(events.endStep, this.endStep.bind(this)) process.on(events.addStep, this.addStep.bind(this)) process.on(events.addArgument, this.addArgument.bind(this)) } onRunnerStart(runner: RunnerStats) { this._config = runner.config this._capabilities = runner.capabilities this._isMultiremote = runner.isMultiremote || false } onSuiteStart(suite: SuiteStats) { if (this._options.useCucumberStepReporter) { if (suite.type === 'feature') { // handle cucumber features as allure "suite" return this._allure.startSuite(suite.title) } // handle cucumber scenario as allure "case" instead of "suite" this._allure.startCase(suite.title) const currentTest = this._allure.getCurrentTest() this.getLabels(suite).forEach(({ name, value }) => { currentTest.addLabel(name, value) }) if (suite.description) { this.addDescription(suite) } return this.setCaseParameters(suite.cid) } const currentSuite = this._allure.getCurrentSuite() const prefix = currentSuite ? currentSuite.name + ': ' : '' this._allure.startSuite(prefix + suite.title) } onSuiteEnd(suite: SuiteStats) { if (this._options.useCucumberStepReporter && suite.type === 'scenario') { // passing hooks are missing the 'state' property suite.hooks = suite.hooks!.map((hook) => { hook.state = hook.state ? hook.state : 'passed' return hook }) const suiteChildren = [...suite.tests!, ...suite.hooks] const isPassed = !suiteChildren.some(item => item.state !== 'passed') if (isPassed) { return this._allure.endCase('passed') } // A scenario is it skipped if every steps are skipped and hooks are passed or skipped const isSkipped = suite.tests.every(item => [SKIPPED].indexOf(item.state!) >= 0) && suite.hooks.every(item => [PASSED, SKIPPED].indexOf(item.state!) >= 0) if (isSkipped) { return this._allure.endCase(PENDING) } // A scenario is it passed if certain steps are passed and all other are skipped and every hooks are passed or skipped const isPartiallySkipped = suiteChildren.every(item => [PASSED, SKIPPED].indexOf(item.state!) >= 0) if (isPartiallySkipped) { return this._allure.endCase('passed') } // Only close passing and skipped tests because // failing tests are closed in onTestFailed event return } this._allure.endSuite() } onTestStart(test: TestStats | HookStats) { this._consoleOutput = '' const testTitle = test.currentTest ? test.currentTest : test.title if (this.isAnyTestRunning() && this._allure.getCurrentTest().name == testTitle) { // Test already in progress, most likely started by a before each hook this.setCaseParameters(test.cid) return } if (this._options.useCucumberStepReporter) { const step = this._allure.startStep(testTitle) const testObj = test as TestStats const argument = testObj?.argument as Argument const dataTable = argument?.rows?.map((a: { cells: string[] }) => a?.cells) if (dataTable) { this._allure.addAttachment('Data Table', stringify(dataTable), 'text/csv') } return step } this._allure.startCase(testTitle) this.setCaseParameters(test.cid) } setCaseParameters(cid: string | undefined) { const currentTest = this._allure.getCurrentTest() if (!this._isMultiremote) { const caps = this._capabilities as Capabilities.DesiredCapabilities const { browserName, deviceName, desired, device } = caps let targetName = device || browserName || deviceName || cid // custom mobile grids can have device information in a `desired` cap if (desired && desired.deviceName && desired.platformVersion) { targetName = `${device || desired.deviceName} ${desired.platformVersion}` } const browserstackVersion = caps.os_version || caps.osVersion const version = browserstackVersion || caps.browserVersion || caps.version || caps.platformVersion || '' const paramName = (deviceName || device) ? 'device' : 'browser' const paramValue = version ? `${targetName}-${version}` : targetName currentTest.addParameter('argument', paramName, paramValue) } else { currentTest.addParameter('argument', 'isMultiremote', 'true') } // Allure analytics labels. See https://github.com/allure-framework/allure2/blob/master/Analytics.md currentTest.addLabel('language', 'javascript') currentTest.addLabel('framework', 'wdio') currentTest.addLabel('thread', cid) } getLabels({ tags }: SuiteStats) { const labels: { name: string, value: string }[] = [] if (tags) { (tags as Tag[]).forEach((tag: Tag) => { const label = tag.name.replace(/[@]/, '').split('=') if (label.length === 2) { labels.push({ name: label[0], value: label[1] }) } }) } return labels } onTestPass() { attachConsoleLogs(this._consoleOutput, this._allure) if (this._options.useCucumberStepReporter) { const suite = this._allure.getCurrentSuite() if (suite && suite.currentStep instanceof Step) { return this._allure.endStep('passed') } } this._allure.endCase(PASSED) } onTestFail(test: TestStats | HookStats) { if (this._options.useCucumberStepReporter) { attachConsoleLogs(this._consoleOutput, this._allure) const testStatus = getTestStatus(test, this._config) const stepStatus: Status = Object.values(stepStatuses).indexOf(testStatus) >= 0 ? testStatus : 'failed' const suite = this._allure.getCurrentSuite() if (suite && suite.currentStep instanceof Step) { this._allure.endStep(stepStatus) } this._allure.endCase(testStatus, getErrorFromFailedTest(test)) return } if (!this.isAnyTestRunning()) { // is any CASE running this.onTestStart(test) } else { this._allure.getCurrentTest().name = test.title } attachConsoleLogs(this._consoleOutput, this._allure) const status = getTestStatus(test, this._config) while (this._allure.getCurrentSuite().currentStep instanceof Step) { this._allure.endStep(status) } this._allure.endCase(status, getErrorFromFailedTest(test)) } onTestSkip(test: TestStats) { attachConsoleLogs(this._consoleOutput, this._allure) if (this._options.useCucumberStepReporter) { const suite = this._allure.getCurrentSuite() if (suite && suite.currentStep instanceof Step) { this._allure.endStep('canceled') } } else if (!this._allure.getCurrentTest() || this._allure.getCurrentTest().name !== test.title) { this._allure.pendingCase(test.title) } else { this._allure.endCase('pending') } } onBeforeCommand(command: BeforeCommandArgs) { if (!this.isAnyTestRunning()) { return } const { disableWebdriverStepsReporting } = this._options if (disableWebdriverStepsReporting || this._isMultiremote) { return } this._allure.startStep(command.method ? `${command.method} ${command.endpoint}` : command.command ) const payload = command.body || command.params if (!isEmpty(payload)) { this.dumpJSON('Request', payload) } } onAfterCommand(command: AfterCommandArgs) { const { disableWebdriverStepsReporting, disableWebdriverScreenshotsReporting } = this._options if (this.isScreenshotCommand(command) && command.result.value) { if (!disableWebdriverScreenshotsReporting) { this._lastScreenshot = command.result.value } } if (!this.isAnyTestRunning()) { return } this.attachScreenshot() if (this._isMultiremote) { return } if (!disableWebdriverStepsReporting) { if (command.result && command.result.value && !this.isScreenshotCommand(command)) { this.dumpJSON('Response', command.result.value) } const suite = this._allure.getCurrentSuite() if (!suite || !(suite.currentStep instanceof Step)) { return } this._allure.endStep('passed') } } onHookStart(hook: HookStats) { // ignore global hooks if (!hook.parent || !this._allure.getCurrentSuite()) { return false } // add beforeEach / afterEach hook as step to test if (this._options.disableMochaHooks && isMochaEachHooks(hook.title)) { if (this._allure.getCurrentTest()) { this._allure.startStep(hook.title) } return } // don't add hook as test to suite for mocha All hooks if (this._options.disableMochaHooks && isMochaAllHooks(hook.title)) { return } // add hook as test to suite this.onTestStart(hook) } onHookEnd(hook: HookStats) { // ignore global hooks if (!hook.parent || !this._allure.getCurrentSuite() || (this._options.disableMochaHooks && !isMochaAllHooks(hook.title) && !this._allure.getCurrentTest())) { return false } // set beforeEach / afterEach hook (step) status if (this._options.disableMochaHooks && isMochaEachHooks(hook.title)) { if (hook.error) { this._allure.endStep('failed') } else { this._allure.endStep('passed') } return } // set hook (test) status if (hook.error) { if (this._options.disableMochaHooks && isMochaAllHooks(hook.title)) { this.onTestStart(hook) this.attachScreenshot() } this.onTestFail(hook) } else if (this._options.disableMochaHooks || this._options.useCucumberStepReporter) { if (!isMochaAllHooks(hook.title)) { this.onTestPass() // remove hook from suite if it has no steps if (this._allure.getCurrentTest().steps.length === 0 && !this._options.useCucumberStepReporter) { this._allure.getCurrentSuite().testcases.pop() } else if (this._options.useCucumberStepReporter) { // remove hook when it's registered as a step and if it's passed const step = this._allure.getCurrentTest().steps.pop() // if it had any attachments, reattach them to current test if (step && step.attachments.length >= 1) { step.attachments.forEach((attachment: any) => { this._allure.getCurrentTest().addAttachment(attachment) }) } } } } else if (!this._options.disableMochaHooks) this.onTestPass() } addLabel({ name, value }: AddLabelEventArgs) { if (!this.isAnyTestRunning()) { return false } const test = this._allure.getCurrentTest() test.addLabel(name, value) } addStory({ storyName }: AddStoryEventArgs) { if (!this.isAnyTestRunning()) { return false } const test = this._allure.getCurrentTest() test.addLabel('story', storyName) } addFeature({ featureName }: AddFeatureEventArgs) { if (!this.isAnyTestRunning()) { return false } const test = this._allure.getCurrentTest() test.addLabel('feature', featureName) } addSeverity({ severity }: AddSeverityEventArgs) { if (!this.isAnyTestRunning()) { return false } const test = this._allure.getCurrentTest() test.addLabel('severity', severity) } addIssue({ issue }: AddIssueEventArgs) { if (!this.isAnyTestRunning()) { return false } const test = this._allure.getCurrentTest() const issueLink = getLinkByTemplate(this._options.issueLinkTemplate, issue) test.addLabel('issue', issueLink) } addTestId({ testId }: AddTestIdEventArgs) { if (!this.isAnyTestRunning()) { return false } const test = this._allure.getCurrentTest() const tmsLink = getLinkByTemplate(this._options.tmsLinkTemplate, testId) test.addLabel('testId', tmsLink) } addEnvironment({ name, value }: AddEnvironmentEventArgs) { if (!this.isAnyTestRunning()) { return false } const test = this._allure.getCurrentTest() test.addParameter('environment-variable', name, value) } addDescription({ description, descriptionType }: AddDescriptionEventArgs) { if (!this.isAnyTestRunning()) { return false } const test = this._allure.getCurrentTest() test.setDescription(description, descriptionType) } addAttachment({ name, content, type = 'text/plain' }: AddAttachmentEventArgs) { if (!this.isAnyTestRunning()) { return false } if (type === 'application/json') { this.dumpJSON(name, content as object) } else { this._allure.addAttachment(name, Buffer.from(content as string), type) } } startStep(title: string) { if (!this.isAnyTestRunning()) { return false } this._allure.startStep(title) } endStep(status: Status) { if (!this.isAnyTestRunning()) { return false } this._allure.endStep(status) } addStep({ step }: any) { if (!this.isAnyTestRunning()) { return false } this.startStep(step.title) if (step.attachment) { this.addAttachment(step.attachment) } this.endStep(step.status) } addArgument({ name, value }: any) { if (!this.isAnyTestRunning()) { return false } const test = this._allure.getCurrentTest() test.addParameter('argument', name, value) } isAnyTestRunning() { return this._allure.getCurrentSuite() && this._allure.getCurrentTest() } isScreenshotCommand(command: CommandArgs) { const isScrenshotEndpoint = /\/session\/[^/]*(\/element\/[^/]*)?\/screenshot/ return ( // WebDriver protocol (command.endpoint && isScrenshotEndpoint.test(command.endpoint)) || // DevTools protocol command.command === 'takeScreenshot' ) } dumpJSON(name: string, json: object) { const content = JSON.stringify(json, null, 2) const isStr = typeof content === 'string' this._allure.addAttachment(name, isStr ? content : `${content}`, isStr ? 'application/json' : 'text/plain') } attachScreenshot() { if (this._lastScreenshot && !this._options.disableWebdriverScreenshotsReporting) { this._allure.addAttachment('Screenshot', Buffer.from(this._lastScreenshot, 'base64')) this._lastScreenshot = undefined } } /** * Assign feature to test * @name addFeature * @param {(string)} featureName - feature name or an array of names */ static addFeature = (featureName: string) => { tellReporter(events.addFeature, { featureName }) } /** * Assign label to test * @name addLabel * @param {string} name - label name * @param {string} value - label value */ static addLabel = (name: string, value: string) => { tellReporter(events.addLabel, { name, value }) } /** * Assign severity to test * @name addSeverity * @param {string} severity - severity value */ static addSeverity = (severity: string) => { tellReporter(events.addSeverity, { severity }) } /** * Assign issue id to test * @name addIssue * @param {string} issue - issue id value */ static addIssue = (issue: string) => { tellReporter(events.addIssue, { issue }) } /** * Assign TMS test id to test * @name addTestId * @param {string} testId - test id value */ static addTestId = (testId: string) => { tellReporter(events.addTestId, { testId }) } /** * Assign story to test * @name addStory * @param {string} storyName - story name for test */ static addStory = (storyName: string) => { tellReporter(events.addStory, { storyName }) } /** * Add environment value * @name addEnvironment * @param {string} name - environment name * @param {string} value - environment value */ static addEnvironment = (name: string, value: string) => { tellReporter(events.addEnvironment, { name, value }) } /** * Assign test description to test * @name addDescription * @param {string} description - description for test * @param {string} descriptionType - description type 'text'\'html'\'markdown' */ static addDescription = (description: string, descriptionType: string) => { tellReporter(events.addDescription, { description, descriptionType }) } /** * Add attachment * @name addAttachment * @param {string} name - attachment file name * @param {*} content - attachment content * @param {string=} mimeType - attachment mime type */ static addAttachment = (name: string, content: string | Buffer | object, type: string) => { if (!type) { type = content instanceof Buffer ? 'image/png' : typeof content === 'string' ? 'text/plain' : 'application/json' } tellReporter(events.addAttachment, { name, content, type }) } /** * Start allure step * @name startStep * @param {string} title - step name in report */ static startStep = (title: string) => { tellReporter(events.startStep, title) } /** * End current allure step * @name endStep * @param {StepStatus} [status='passed'] - step status */ static endStep = (status: Status = 'passed') => { if (!Object.values(stepStatuses).includes(status)) { throw new Error(`Step status must be ${Object.values(stepStatuses).join(' or ')}. You tried to set "${status}"`) } tellReporter(events.endStep, status) } /** * Create allure step * @name addStep * @param {string} title - step name in report * @param {Object} [attachmentObject={}] - attachment for step * @param {string} attachmentObject.content - attachment content * @param {string} [attachmentObject.name='attachment'] - attachment name * @param {string} [attachmentObject.type='text/plain'] - attachment type * @param {string} [status='passed'] - step status */ static addStep = (title: string, { content, name = 'attachment', type = 'text/plain' }: any = {}, status: Status = 'passed') => { if (!Object.values(stepStatuses).includes(status)) { throw new Error(`Step status must be ${Object.values(stepStatuses).join(' or ')}. You tried to set "${status}"`) } const step = content ? { title, attachment: { content, name, type }, status } : { title, status } tellReporter(events.addStep, { step }) } /** * Add additional argument to test * @name addArgument * @param {string} name - argument name * @param {string} value - argument value */ static addArgument = (name: string, value: string) => { tellReporter(events.addArgument, { name, value }) } } export default AllureReporter export { AllureReporterOptions } export * from './types' declare global { namespace WebdriverIO { interface ReporterOption extends AllureReporterOptions { } } }
the_stack
import {Program} from "../src/runtime/dsl2"; import {verify, createVerifier} from "./util"; import * as test from "tape"; test("Choose: basic", (assert) => { let prog = new Program("test"); prog.bind("simple block", ({find, record, lib, choose}) => { let person = find("person"); let [info] = choose(() => { person.dog; return "cool"; }, () => { return "not cool"; }); return [ record("dog-less", {info}) ] }); verify(assert, prog, [ [1, "tag", "person"], ], [ [2, "tag", "dog-less", 1], [2, "info", "not cool", 1], ]) verify(assert, prog, [ [1, "dog", "spot"], ], [ [2, "tag", "dog-less", 1, -1], [2, "info", "not cool", 1, -1], [3, "tag", "dog-less", 1], [3, "info", "cool", 1], ]) assert.end(); }); test("Choose: 3 branches", (assert) => { let prog = new Program("test"); prog.bind("simple block", ({find, record, lib, choose}) => { let person = find("person"); let [info] = choose(() => { person.dog; return "cool"; }, () => { person.foo; return "zomg"; }, () => { return "not cool"; }); return [ record("dog-less", {info}) ] }); verify(assert, prog, [ [1, "tag", "person"], ], [ [2, "tag", "dog-less", 1], [2, "info", "not cool", 1], ]) verify(assert, prog, [ [1, "dog", "spot"], ], [ [2, "tag", "dog-less", 1, -1], [2, "info", "not cool", 1, -1], [3, "tag", "dog-less", 1], [3, "info", "cool", 1], ]) verify(assert, prog, [ [1, "dog", "spot", 0, -1], [1, "foo", "woop"], ], [ [3, "tag", "dog-less", 1, -1], [3, "info", "cool", 1, -1], [4, "tag", "dog-less", 1], [4, "info", "zomg", 1], ]) verify(assert, prog, [ [1, "foo", "woop", 0, -1], ], [ [3, "tag", "dog-less", 1, -1], [3, "info", "zomg", 1, -1], [4, "tag", "dog-less", 1], [4, "info", "not cool", 1], ]) assert.end(); }); test("Choose: 4 branches", (assert) => { let prog = new Program("test"); prog.bind("simple block", ({find, record, lib, choose}) => { let person = find("person"); let {boat} = person; let [info] = choose(() => { person.dog; return "cool"; }, () => { person.foo; return "zomg"; }, () => { boat.foo; return "woah"; }, () => { return "not cool"; }); return [ record("dog-less", {info}) ] }); verify(assert, prog, [ [1, "tag", "person"], [1, "boat", 9], ], [ [2, "tag", "dog-less", 1], [2, "info", "not cool", 1], ]) verify(assert, prog, [ [1, "dog", "spot"], ], [ [2, "tag", "dog-less", 1, -1], [2, "info", "not cool", 1, -1], [3, "tag", "dog-less", 1], [3, "info", "cool", 1], ]) verify(assert, prog, [ [1, "dog", "spot", 0, -1], [1, "foo", "woop"], ], [ [3, "tag", "dog-less", 1, -1], [3, "info", "cool", 1, -1], [4, "tag", "dog-less", 1], [4, "info", "zomg", 1], ]) verify(assert, prog, [ [1, "foo", "woop", 0, -1], ], [ [3, "tag", "dog-less", 1, -1], [3, "info", "zomg", 1, -1], [4, "tag", "dog-less", 1], [4, "info", "not cool", 1], ]) verify(assert, prog, [ [9, "foo", "meep moop"], ], [ [3, "tag", "dog-less", 1, -1], [3, "info", "not cool", 1, -1], [4, "tag", "dog-less", 1], [4, "info", "woah", 1], ]) verify(assert, prog, [ [9, "foo", "meep moop", 0, -1], ], [ [3, "tag", "dog-less", 1, -1], [3, "info", "woah", 1, -1], [4, "tag", "dog-less", 1], [4, "info", "not cool", 1], ]) verify(assert, prog, [ [1, "dog", "spot"], ], [ [3, "tag", "dog-less", 1, -1], [3, "info", "not cool", 1, -1], [4, "tag", "dog-less", 1], [4, "info", "cool", 1], ]) verify(assert, prog, [ [5, "tag", "person"], [5, "boat", 10], ], [ [4, "tag", "dog-less", 1], [4, "info", "not cool", 1], ]) verify(assert, prog, [ [5, "tag", "person", 0, -1], [1, "tag", "person", 0, -1], ], [ [4, "tag", "dog-less", 1, -1], [4, "info", "not cool", 1, -1], [6, "tag", "dog-less", 1, -1], [6, "info", "cool", 1, -1], ]) verify(assert, prog, [ [5, "tag", "person"], [1, "tag", "person"], ], [ [4, "tag", "dog-less", 1], [4, "info", "not cool", 1], [6, "tag", "dog-less", 1], [6, "info", "cool", 1], ]) assert.end(); }); // @TODO: Give this a better name when we figure out the specific issue. test("Choose: Busted partial identity", (assert) => { let prog = new Program("test"); prog.bind("Split up our cat attributes", ({find, lookup, record}) => { let cat = find("cat"); let {attribute, value} = lookup(cat); return [ // @NOTE: Issue has to do with add, can't repro if value is part of the identity. record("cat-attribute", {cat, attribute}).add("value", value) ]; }) prog.bind("Create value records for each cat attribute.", ({find, lookup, choose, record}) => { let catAttribute = find("cat-attribute"); // Tags about cats are cool. // @FIXME: In some (but not all) cases where the first branch matches both branches emit. // This may be multiplicity/retraction related. let [attrName] = choose( () => { catAttribute.attribute == "tag"; return "cool tags"; }, () => catAttribute.attribute ); let {cat, value} = catAttribute; return [ record("cat-value", {cat, attr: attrName, val: value}) ]; }); verify(assert, prog, [ [1, "tag", "pet"], [1, "tag", "cat"], [1, "name", "Felicia"], ], [ [2, "tag", "cat-attribute", 1], [2, "cat", 1, 1], [2, "attribute", "tag", 1], [2, "value", "pet", 1], [2, "value", "cat", 1], [3, "tag", "cat-attribute", 1], [3, "cat", 1, 1], [3, "attribute", "name", 1], [3, "value", "Felicia", 1], [4, "tag", "cat-value", 2], [4, "cat", 1, 2], [4, "attr", "cool tags", 2], [4, "val", "pet", 2], [5, "tag", "cat-value", 2], [5, "cat", 1, 2], [5, "attr", "cool tags", 2], [5, "val", "cat", 2], [6, "tag", "cat-value", 2], [6, "cat", 1, 2], [6, "attr", "name", 2], [6, "val", "Felicia", 2], ]); assert.end(); }); test("Choose: multiple return", (assert) => { let prog = new Program("test"); prog.bind("simple block", ({find, record, lib, choose}) => { let person = find("person"); let [displayName, coolness] = choose(() => { return [person.nickName, "cool"]; }, () => { return [person.name, "not cool"]; }); return [ person.add("displayName", displayName), person.add("coolness", coolness), ] }); verify(assert, prog, [ [1, "tag", "person"], [1, "name", "joseph"], ], [ [1, "displayName", "joseph", 1], [1, "coolness", "not cool", 1], ]) verify(assert, prog, [ [1, "nickName", "joey"], ], [ [1, "displayName", "joseph", 1, -1], [1, "coolness", "not cool", 1, -1], [1, "displayName", "joey", 1], [1, "coolness", "cool", 1], ]) verify(assert, prog, [ [1, "nickName", "joey", 0, -1], ], [ [1, "displayName", "joseph", 1], [1, "coolness", "not cool", 1], [1, "displayName", "joey", 1, -1], [1, "coolness", "cool", 1, -1], ]) assert.end(); }); test("Choose: moves only", (assert) => { let prog = new Program("test"); prog.bind("simple block", ({find, record, choose}) => { let person = find("person"); let {name} = person; let [displayName] = choose( () => { name == "christopher"; return "chris"; }, () => name ); return [ person.add({displayName}) ] }); verify(assert, prog, [ [1, "tag", "person"], [1, "name", "christopher"], [2, "tag", "person"], [2, "name", "jane"], ], [ [1, "displayName", "chris", 1], [2, "displayName", "jane", 1], ]) assert.end(); }); test("Choose: post-filtering outer", (assert) => { let prog = new Program("test"); prog.bind("froofy", ({find, choose, record}) => { let person = find("person"); let [display] = choose(() => person.display); display.name == "Ferdinand"; return [record("result", {name: display.name})]; }); verify(assert, prog, [ [1, "tag", "person"], [1, "display", 2], [2, "name", "Jess"], [3, "tag", "cat"], [3, "display", 4], [4, "name", "Ferdinand"], ], []); assert.end(); }); test("Choose: expression-only dynamic branch", (assert) => { let prog = new Program("test"); prog.bind("Choose non-static expression only.", ({find, choose, record}) => { let guy = find("guy"); let {radness} = guy; let [radometer] = choose(() => radness * 3); // This does not. // let radometer = radness * 3; // This works return [guy.add("radometer", radometer)]; }); verify(assert, prog, [ [1, "tag", "guy"], [1, "radness", 1], ], [ [1, "radometer", 3, 1] ]); assert.end(); }); test("Choose: filter and expression-only dynamic branches", (assert) => { let prog = new Program("test"); prog.bind("Choose non-static expression only.", ({find, choose, record}) => { let guy = find("guy"); let {radness} = guy; // We need to adjust the scale since radness is roughly logarithmic. let [radometer] = choose( () => { radness < 2; return radness; }, () => { radness < 4; return radness * 2; }, () => radness * 3 ); // let radometer = radness * 3; return [guy.add("radometer", radometer)]; }); verify(assert, prog, [ [1, "tag", "guy"], [1, "radness", 0], [2, "tag", "guy"], [2, "radness", 1], [3, "tag", "guy"], [3, "radness", 2], [4, "tag", "guy"], [4, "radness", 4], ], [ [1, "radometer", 0, 1], [2, "radometer", 1, 1], [3, "radometer", 4, 1], [4, "radometer", 12, 1] ]); verify(assert, prog, [ [1, "radness", 0, 0, -1], [1, "radness", 8], ], [ [1, "radometer", 24, 1], [1, "radometer", 0, 1, -1], ]); assert.end(); }); let programs = { "1 static": () => { let prog = new Program("1 static branch"); prog.bind("simple block", ({find, choose, record}) => { let foo = find("input"); let [branch] = choose(() => 1); return [ record("result", {branch}) ]; }); return prog; }, "1 dynamic": () => { let prog = new Program("1 dynamic branch"); prog.bind("simple block", ({find, choose, record}) => { let foo = find("input"); let [output] = choose(() => foo.arg0); return [ record("result", {output}) ]; }); return prog; }, "1 dynamic 1 static": () => { let prog = new Program("1 dynamic branch"); prog.bind("simple block", ({find, choose, record}) => { let foo = find("input"); let [output] = choose( () => {foo.arg0 == 1; return "one"}, () => "else" ); return [ record("result", {output}) ]; }); return prog; }, "2 dynamic": () => { let prog = new Program("1 dynamic branch"); prog.bind("simple block", ({find, choose, record}) => { let foo = find("input"); let [output] = choose( () => {foo.arg0 == 1; return "one"}, () => foo.arg0 ); return [ record("result", {output}) ]; }); return prog; }, }; let verifyBranches = createVerifier(programs); // ----------------------------------------------------- // 1 Static branch // ----------------------------------------------------- test("Choose: 1 static branch +A; -A; +A", (assert) => { verifyBranches(assert, "1 static", "+A; -A; +A", [ [[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]], [[2, "tag", "result", 1, -1], [2, "branch", 1, 1, -1]], [[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]] ]); }); test("Choose: 1 static branch +A; -A; +B", (assert) => { verifyBranches(assert, "1 static", "+A; -A; +B", [ [[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]], [[2, "tag", "result", 1, -1], [2, "branch", 1, 1, -1]], [[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]] ]); }); // @NOTE: Broken due to verify being too simple. test("Choose: 1 static branch +A; +A; -A", (assert) => { verifyBranches(assert, "1 static", "+A; +A; -A", [ [[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]], [], [] ]); }); // @NOTE: Broken due to verify being too simple. test("Choose: 1 static branch +A; +A; -A; -A", (assert) => { verifyBranches(assert, "1 static", "+A; +A; -A; -A", [ [[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]], [], [], [[2, "tag", "result", 1, -1], [2, "branch", 1, 1, -1]], ]); }); test("Choose: 1 static branch +A +B; -A; +A", (assert) => { verifyBranches(assert, "1 static", "+A +B; -A; +A", [ [[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]], [], [] ]); }); test("Choose: 1 static branch +A +B; -A -B", (assert) => { verifyBranches(assert, "1 static", "+A +B; -A -B", [ [[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]], [[2, "tag", "result", 1, -1], [2, "branch", 1, 1, -1]] ]); }); test("Choose: 1 static branch +A; -A +B", (assert) => { verifyBranches(assert, "1 static", "+A; -A +B", [ [[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]], [] ]); }); test("Choose: 1 static branch +A, -A", (assert) => { verifyBranches(assert, "1 static", "+A, -A", [ [[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1], [2, "tag", "result", 2, -1], [2, "branch", 1, 2, -1]] ]); }); test("Choose: 1 static branch +A, -A +B", (assert) => { verifyBranches(assert, "1 static", "+A, -A +B", [ [[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]] ]); }); test("Choose: 1 static branch +A, +B", (assert) => { verifyBranches(assert, "1 static", "+A, +B", [ [[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]] ]); }); test("Choose: 1 static branch +A, +B; -A", (assert) => { verifyBranches(assert, "1 static", "+A, +B; -A", [ [[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]], [[2, "tag", "result", 1, -1], [2, "branch", 1, 1, -1], [2, "tag", "result", 2, +1], [2, "branch", 1, 2, +1]] ]); }); test("Choose: 1 static branch +A; -A, +B", (assert) => { verifyBranches(assert, "1 static", "+A; -A, +B", [ [[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]], [[2, "tag", "result", 1, -1], [2, "branch", 1, 1, -1], [2, "tag", "result", 2, +1], [2, "branch", 1, 2, +1]] ]); }); // ----------------------------------------------------- // 1 dynamic branch // ----------------------------------------------------- test("Choose: 1 dynamic branch +A:1; -A:1", (assert) => { verifyBranches(assert, "1 dynamic", "+A:1; -A:1", [ [[1, "tag", "result", 1, +1], [1, "output", 1, 1, +1]], [[1, "tag", "result", 1, -1], [1, "output", 1, 1, -1]], ]); }); test("Choose: 1 dynamic branch +A:1; -A:1; +A:1", (assert) => { verifyBranches(assert, "1 dynamic", "+A:1; -A:1; +A:1", [ [[1, "tag", "result", 1, +1], [1, "output", 1, 1, +1]], [[1, "tag", "result", 1, -1], [1, "output", 1, 1, -1]], [[1, "tag", "result", 1, +1], [1, "output", 1, 1, +1]], ]); }); test("Choose: 1 dynamic branch +A:1; -A:1; +A:2", (assert) => { verifyBranches(assert, "1 dynamic", "+A:1; -A:1; +A:2", [ [[1, "tag", "result", 1, +1], [1, "output", 1, 1, +1]], [[1, "tag", "result", 1, -1], [1, "output", 1, 1, -1]], [[1, "tag", "result", 1, +1], [1, "output", 2, 1, +1]], ]); }); test("Choose: 1 dynamic branch +A:1; +A:2; -A:1", (assert) => { verifyBranches(assert, "1 dynamic", "+A:1; +A:2; -A:1", [ [[1, "tag", "result", 1, +1], [1, "output", 1, 1, +1]], [[1, "tag", "result", 1, +1], [1, "output", 2, 1, +1]], [[1, "tag", "result", 1, -1], [1, "output", 1, 1, -1]], ]); }); test("Choose: 1 dynamic branch +A:1; +B:1; -A:1", (assert) => { verifyBranches(assert, "1 dynamic", "+A:1; +B:1; -A:1", [ [[1, "tag", "result", 1, +1], [1, "output", 1, 1, +1]], [], [], ]); }); test("Choose: 1 dynamic branch +A:1; +B:1; -A:1, -B:1", (assert) => { verifyBranches(assert, "1 dynamic", "+A:1; +B:1; -A:1, -B:1", [ [[1, "tag", "result", 1, +1], [1, "output", 1, 1, +1]], [], [[1, "tag", "result", 2, -1], [1, "output", 1, 2, -1]], ]); }); // ----------------------------------------------------- // 1 dynamic 1 static // ----------------------------------------------------- test("Choose: 1 dynamic 1 static branch +A:1; -A:1; +A:1", (assert) => { verifyBranches(assert, "1 dynamic 1 static", "+A:1; -A:1; +A:1", [ [[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1]], [[1, "tag", "result", 1, -1], [1, "output", "one", 1, -1]], [[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1]] ]); }); test("Choose: 1 dynamic 1 static branch +A:2; -A:2; +A:2", (assert) => { verifyBranches(assert, "1 dynamic 1 static", "+A:2; -A:2; +A:2", [ [[1, "tag", "result", 1, +1], [1, "output", "else", 1, +1]], [[1, "tag", "result", 1, -1], [1, "output", "else", 1, -1]], [[1, "tag", "result", 1, +1], [1, "output", "else", 1, +1]] ]); }); test("Choose: 1 dynamic 1 static branch +A:1; -A:1; +A:2", (assert) => { verifyBranches(assert, "1 dynamic 1 static", "+A:1; -A:1; +A:2", [ [[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1]], [[1, "tag", "result", 1, -1], [1, "output", "one", 1, -1]], [[2, "tag", "result", 1, +1], [2, "output", "else", 1, +1]] ]); }); test("Choose: 1 dynamic 1 static branch +A:1; +A:2", (assert) => { verifyBranches(assert, "1 dynamic 1 static", "+A:1; +A:2", [ [[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1]], [] ]); }); test("Choose: 1 dynamic 1 static branch +A:1; +B:2", (assert) => { verifyBranches(assert, "1 dynamic 1 static", "+A:1; +B:2", [ [[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1]], [[2, "tag", "result", 1, +1], [2, "output", "else", 1, +1]] ]); }); test("Choose: 1 dynamic 1 static branch +A:1; +B:1; -A:1", (assert) => { verifyBranches(assert, "1 dynamic 1 static", "+A:1; +B:1; -A:1", [ [[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1]], [], [] ]); }); test("Choose: 1 dynamic 1 static branch +A:1, -A:1", (assert) => { verifyBranches(assert, "1 dynamic 1 static", "+A:1, -A:1", [ [[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1], [1, "tag", "result", 2, -1], [1, "output", "one", 2, -1]] ]); }); test("Choose: 1 dynamic 1 static branch +A:1, -A:1, +A:1", (assert) => { verifyBranches(assert, "1 dynamic 1 static", "+A:1, -A:1, +A:1", [ [[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1], [1, "tag", "result", 2, -1], [1, "output", "one", 2, -1], [1, "tag", "result", 3, +1], [1, "output", "one", 3, +1]] ]); }); test("Choose: 1 dynamic 1 static branch +A:1; +B:1; -B:1; +B:1", (assert) => { verifyBranches(assert, "1 dynamic 1 static", "+A:1; +B:1; -B:1; +B:1", [ [[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1]], [], [], [] ]); }); // ----------------------------------------------------- // 2 dynamics // ----------------------------------------------------- test("Choose: 2 dynamic branch +A:1; -A:1; +A:1", (assert) => { verifyBranches(assert, "2 dynamic", "+A:1; -A:1; +A:1", [ [[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1]], [[1, "tag", "result", 1, -1], [1, "output", "one", 1, -1]], [[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1]] ]); }); test("Choose: 2 dynamic branch +A:2; -A:2; +A:2", (assert) => { verifyBranches(assert, "2 dynamic", "+A:2; -A:2; +A:2", [ [[1, "tag", "result", 1, +1], [1, "output", 2, 1, +1]], [[1, "tag", "result", 1, -1], [1, "output", 2, 1, -1]], [[1, "tag", "result", 1, +1], [1, "output", 2, 1, +1]] ]); }); test("Choose: 2 dynamic branch +A:1; -A:1; +A:2", (assert) => { verifyBranches(assert, "2 dynamic", "+A:1; -A:1; +A:2", [ [[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1]], [[1, "tag", "result", 1, -1], [1, "output", "one", 1, -1]], [[2, "tag", "result", 1, +1], [2, "output", 2, 1, +1]] ]); }); test("Choose: 2 dynamic branch +A:1; +A:2", (assert) => { verifyBranches(assert, "2 dynamic", "+A:1; +A:2", [ [[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1]], [] ]); }); test("Choose: 2 dynamic branch +A:1; +B:2", (assert) => { verifyBranches(assert, "2 dynamic", "+A:1; +B:2", [ [[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1]], [[2, "tag", "result", 1, +1], [2, "output", 2, 1, +1]] ]); }); test("Choose: 2 dynamic branch +A:1; +B:1; -A:1", (assert) => { verifyBranches(assert, "2 dynamic", "+A:1; +B:1; -A:1", [ [[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1]], [], [] ]); }); test("Choose: 2 dynamic branch +A:1, -A:1", (assert) => { verifyBranches(assert, "2 dynamic", "+A:1, -A:1", [ [[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1], [1, "tag", "result", 2, -1], [1, "output", "one", 2, -1]] ]); }); test("Choose: 2 dynamic branch +A:1, -A:1, +A:1", (assert) => { verifyBranches(assert, "2 dynamic", "+A:1, -A:1, +A:1", [ [[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1], [1, "tag", "result", 2, -1], [1, "output", "one", 2, -1], [1, "tag", "result", 3, +1], [1, "output", "one", 3, +1]] ]); }); test("Choose: 2 dynamic branch +A:1; +B:1; -B:1; +B:1", (assert) => { verifyBranches(assert, "2 dynamic", "+A:1; +B:1; -B:1; +B:1", [ [[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1]], [], [], [] ]); });
the_stack
import React, { Component } from 'react'; /*-- Apply Third-party plugins (import location should be in front of "GLOBAL STYLES") --*/ import '@/components/_plugins/_lib-bootstrap'; import '@/components/_plugins/_lib-icons'; /*-- Apply global scripts and styles --*/ import '@/components/_utils/styles/_all.scss'; import '@/components/_utils/styles/rtl/_all.scss'; import { __ } from '@/components/_utils/_all'; /*-- Apply this component styles --*/ import '@/components/ModalDialog/styles/_style.scss'; import '@/components/ModalDialog/styles/rtl/_style.scss'; /*-- Apply Third-party animation plugins --*/ import TweenMax from '@/components/_plugins/_lib-gsap'; //Destroys body scroll locking import { clearAllBodyScrollLocks } from '@/components/_plugins/_lib-scrolllock'; // import { fireModalDialog } from '@/components/ModalDialog/fire-modal-dialog'; import { closeModalDialog } from '@/components/ModalDialog/close-modal-dialog'; declare global { interface Window { curVideo?: any; setCloseModalDialog?: any; } } type ModalDialogProps = { /** Custom modal height whick need a unit string. * This attribute "data-modal-height" may not exist. Such as: 200px */ height?: number | string | boolean; /** Custom modal width whick need a unit string. * This attribute "data-modal-width" may not exist. Such as: 200px */ width?: number | string | boolean; /** Whether to enable the lightbox effect */ lightbox?: boolean; /** Specify auto-close time. This function is not enabled when this value is false. If the value is 2000, it will automatically close after 2 seconds. */ autoClose?: number | boolean; /** Disable mask to close the window */ closeOnlyBtn?: boolean; /** ///// */ /** Toggles whether fullscreen should be enabled */ fullscreen?: boolean; /** Set a window title */ heading?: React.ReactNode; /** Tag name of the trigger. Allowed values are: `a`, `button`, `div`, `span` */ triggerTagName?: string; /** Specify a class for this Node. */ triggerClassName?: string; /** Set a piece of text or HTML code for the trigger */ triggerContent?: React.ReactNode; /** Automatically open the component, you can use it with the `autoClose` property at the same time */ autoOpen?: boolean; /** Adapt the video to the window */ enableVideo?: boolean; /** -- */ id?: string; }; type ModalDialogState = false; export default class ModalDialog extends Component<ModalDialogProps, ModalDialogState> { uniqueID: string; constructor(props) { super(props); this.uniqueID = 'app-' + __.GUID.create(); } closeWin(e) { e.preventDefault(); this.closeAction(); } openWin(e, obj) { e.preventDefault(); this.openAction(obj); } closeAction() { // pause video without controls //------------------------------------------ if (window.curVideo !== null) window.curVideo.pause(); // close Modal Dialog //------------------------------------------ closeModalDialog( __( '.poemkit-modal-box' ) ); } openAction(obj) { const self = this; const curModalID = '#' + obj.data('modal-id'); //Delay Time when Full Screen Effect is fired. const modalSpeed: any = __.cssProperty.getTransitionDuration(__('.poemkit-modal-box:first-child')[0]); let dataH = obj.data('modal-height'), dataW = obj.data('modal-width'), dataLightbox = obj.data('modal-lightbox'), dataCloseTime = obj.data('modal-close-time'), dataCloseOnlyBtn = obj.data('modal-close-onlybtn'); if (dataH === null) dataH = false; if (dataW === null) dataW = false; if (dataLightbox === null) dataLightbox = true; if (dataCloseTime === null) dataCloseTime = false; if (dataCloseOnlyBtn === null) dataCloseOnlyBtn = false; // Video PopUp Interaction //------------------------------------------ const hasVideo = __( curModalID ).hasClass('is-video') ? true : false; if (hasVideo) { const windowWidth = window.innerWidth; const windowHeight = window.innerHeight; const $videoWrapper = __( curModalID ).find('.poemkit-modal-box__video-container'); const isIframe = $videoWrapper.find('iframe').len() > 0 ? true : false; let $video: any = isIframe ? $videoWrapper.find('iframe') : $videoWrapper.find('video'); // const setVideo = function (currentWidth, currentHeight, obj) { const newMaxW = windowWidth - 80, newMaxH = windowHeight - 80; let newW = currentWidth, newH = currentHeight; if (currentHeight > newMaxH) { newH = newMaxH; //Scaled/Proportional Content newW = currentWidth * (newH / currentHeight); } if (newW > newMaxW) { newW = newMaxW; //Scaled/Proportional Content newH = currentHeight * (newW / currentWidth); } obj.css({ 'left': (newMaxW - newW) / 2 + 'px', 'top': (newMaxH - newH) / 2 + 'px', 'height': newH + 'px', 'width': newW + 'px' }); if (windowWidth <= 768) { obj.css({ 'top': 0 }).parent().css({ 'top': (newMaxH - newH) / 2 + 'px' }); } }; if (isIframe) { setVideo($video.width(), $video.height(), $video); } else { const _sources = $video.get(0).getElementsByTagName('source'); const _src = _sources.length > 0 ? _sources[0].src : $video.get(0).src; self.getVideoDimensions(_src).then(function (res: any): void { setVideo(res.width, res.height, $video); }); } //Set current video when the tag is <video> window.curVideo = $video.get(0).tagName === 'VIDEO' ? $video.get(0) : null; } // fire Modal Dialog //------------------------------------------ fireModalDialog( __( curModalID ), { height : dataH, width : dataW, speed : modalSpeed, btn : obj, lightbox : dataLightbox, autoClose : dataCloseTime, closeOnlyBtn : dataCloseOnlyBtn }); } createTrigger(tagName, classes, content, dataID, dataCloseOnlyBtn, dataAutoClose, dataWidth, dataHeight, dataAutoOpen, dataLightbox) { switch (tagName) { case 'a': return ( <> <a role="button" href="#" className={classes} data-modal-width={dataWidth} data-modal-height={dataHeight} data-modal-auto-open={dataAutoOpen} data-modal-id={dataID} data-modal-close-onlybtn={dataCloseOnlyBtn} data-modal-close-time={dataAutoClose} data-modal-lightbox={dataLightbox}>{content}</a> </> ) case 'button': return ( <> <button type="button" className={classes} data-modal-width={dataWidth} data-modal-height={dataHeight} data-modal-auto-open={dataAutoOpen} data-modal-id={dataID} data-modal-close-onlybtn={dataCloseOnlyBtn} data-modal-close-time={dataAutoClose} data-modal-lightbox={dataLightbox}>{content}</button> </> ) case 'div': return ( <> <div role="button" className={classes} data-modal-width={dataWidth} data-modal-height={dataHeight} data-modal-auto-open={dataAutoOpen} data-modal-id={dataID} data-modal-close-onlybtn={dataCloseOnlyBtn} data-modal-close-time={dataAutoClose} data-modal-lightbox={dataLightbox}>{content}</div> </> ) case 'span': return ( <> <span role="button" className={classes} data-modal-width={dataWidth} data-modal-height={dataHeight} data-modal-auto-open={dataAutoOpen} data-modal-id={dataID} data-modal-close-onlybtn={dataCloseOnlyBtn} data-modal-close-time={dataAutoClose} data-modal-lightbox={dataLightbox}>{content}</span> </> ) } } //Returns the dimensions of a video asynchrounsly. getVideoDimensions(url) { return new Promise(function (resolve) { // create the video element let video = document.createElement('video'); // place a listener on it video.addEventListener("loadedmetadata", function () { // retrieve dimensions let height = this.videoHeight; let width = this.videoWidth; // send back result resolve({ height: height, width: width }); }, false); // start download meta-datas video.src = url; }); } componentDidMount() { const self = this; window.curVideo = null; __( document ).ready( () => { //Add modal mask to stage if (__('.poemkit-modal-mask').len() == 0) { __('body').prepend('<div class="poemkit-modal-mask"></div>'); } const btnClose = '.poemkit-modal-box [data-modal-close-trigger], .poemkit-modal-mask:not(.js-poemkit-disabled)'; __( btnClose ).off( 'click' ).on( 'click', function (this: any, e: any) { self.closeWin(e); }); // Move HTML templates to tag end body </body> Array.prototype.forEach.call(document.querySelectorAll('.poemkit-modal-box:not(.is-loaded)'), (node) => { node.classList.add( 'is-loaded' ); document.body.appendChild(node); }); //click to open Modal Dialog const btnOpen = '[data-modal-id]'; __( btnOpen ).off( 'click' ).on( 'click', function (this: any, e: any) { self.openWin(e, __( this )); }); //automatically open Modal Dialog __( btnOpen ).each(function (this: any) { let dataAutoOpen = __( this ).data('modal-auto-open'); if (dataAutoOpen === null) dataAutoOpen = false; if (dataAutoOpen) self.openAction(__( this )); }); }); } /** Remove the global list of events, especially as scroll and interval. */ componentWillUnmount() { clearAllBodyScrollLocks(); // Kill all aniamtions TweenMax.killAll(); // Cancels a timeout previously established by calling setTimeout(). clearTimeout( window.setCloseModalDialog ); // Remove all moved elements Array.prototype.forEach.call(document.querySelectorAll('.poemkit-modal-box.is-loaded'), (node) => { node.remove(); }); } render() { const { height, width, lightbox, autoClose, closeOnlyBtn, fullscreen, heading, triggerTagName, triggerClassName, triggerContent, autoOpen, enableVideo, id, children } = this.props; const cid = id || this.uniqueID; const fullClassName = fullscreen ? 'is-fullscreen' : ''; const lightboxEnabled = (lightbox === null || lightbox === undefined) ? true : lightbox; return ( <> {this.createTrigger(triggerTagName, triggerClassName, triggerContent, cid, closeOnlyBtn, autoClose, width, height, autoOpen, lightboxEnabled)} {!enableVideo ? ( <div className={`poemkit-modal-box ${fullClassName}`} role="dialog" tabIndex={-1} aria-hidden="true" id={cid}> <button type="button" className="poemkit-modal-box__close" data-modal-close-trigger="true"></button> <div className="poemkit-modal-box__content" role="document"> <div className="poemkit-modal-box__head"> {heading || ''} </div> <div className="poemkit-modal-box__body"> <div role="note"> {/*<!-- //////// content begin //////// -->*/} {children} {/*<!-- //////// content end //////// -->*/} </div> </div> </div> </div> ) : ( <div className="poemkit-modal-box is-fullscreen is-video" role="dialog" tabIndex={-1} aria-hidden="true" id={cid}> <button type="button" className="poemkit-modal-box__close" data-modal-close-trigger="true"></button> <div className="poemkit-modal-box__content" role="document"> <div className="poemkit-modal-box__video-waiting"></div> <div className="poemkit-modal-box__video-container"> <div className="embed-responsive embed-responsive-16by9"> {/*<!-- //////// content begin //////// -->*/} {children} {/*<!-- //////// content end //////// -->*/} </div> </div> </div> </div> )} </> ) } }
the_stack
import * as THREE from 'three'; import { EffectComposer } from 'postprocessing'; import type { Scene, Vector3, WebGL1Renderer } from 'three'; import Camera from './Camera'; import { KeplerParticles } from './KeplerParticles'; import { NaturalSatellites } from './EphemPresets'; import { ShapeObject } from './ShapeObject'; import { Skybox } from './Skybox'; import { SpaceObject } from './SpaceObject'; import { SphereObject } from './SphereObject'; import { StaticParticles } from './StaticParticles'; import { Stars } from './Stars'; import type { Coordinate3d } from './Coordinates'; export interface SimulationObject { update: (jd: number, force: boolean) => void; get3jsObjects(): THREE.Object3D[]; getId(): string; } interface CameraOptions { initialPosition?: Coordinate3d; enableDrift?: boolean; } interface DebugOptions { showAxes?: boolean; showGrid?: boolean; showStats?: boolean; } interface SpacekitOptions { basePath: string; startDate?: Date; jd?: number; jdDelta?: number; jdPerSecond?: number; unitsPerAu?: number; startPaused?: boolean; maxNumParticles?: number; particleTextureUrl?: string; particleDefaultSize?: number; camera?: CameraOptions; debug?: DebugOptions; } export interface SimulationContext { simulation: Simulation; options: SpacekitOptions; objects: { renderer: WebGL1Renderer; camera: Camera; scene: Scene; particles: KeplerParticles; composer?: EffectComposer; }; container: { width: number; height: number; }; } /** * The main entrypoint of a visualization. * * This class wraps a THREE.js scene, controls, skybox, etc in an animated * Simulation. * * @example * ``` * const sim = new Spacekit.Simulation(document.getElementById('my-container'), { * basePath: '../path/to/assets', * startDate: Date.now(), * jd: 0.0, * jdDelta: 10.0, * jdPerSecond: 100.0, // overrides jdDelta * startPaused: false, * unitsPerAu: 1.0, * maxNumParticles: 2**16, * camera: { * initialPosition: [0, -10, 5], * enableDrift: false, * }, * debug: { * showAxes: false, * showGrid: false, * showStats: false, * }, * }); * ``` */ export declare class Simulation { onTick?: () => void; private simulationElt; private options; private jd; private jdDelta?; private jdPerSecond; private isPaused; private enableCameraDrift; private cameraDefaultPos; private camera; private useLightSources; private lightPosition?; private subscribedObjects; private particles; private stats?; private fps; private lastUpdatedTime; private lastStaticCameraUpdateTime; private lastResizeUpdateTime; private renderEnabled; private initialRenderComplete; private scene; private renderer; private composer?; /** * @param {HTMLCanvasElement} simulationElt The container for this simulation. * @param {Object} options for simulation * @param {String} options.basePath Path to simulation assets and data * @param {Date} options.startDate The start date and time for this * simulation. * @param {Number} options.jd The JD date of this simulation. * Defaults to 0 * @param {Number} options.jdDelta The number of JD to add every tick of * the simulation. * @param {Number} options.jdPerSecond The number of jd to add every second. * Use this instead of `jdDelta` for constant motion that does not vary with * framerate. Defaults to 100. * @param {Number} options.unitsPerAu The number of "position" units in the * simulation that represent an AU. This is an optional setting that you may * use if the default (1 unit = 1 AU) is too small for your simulation (e.g. * if you are representing a planetary system). Depending on your graphics * card, you may begin to notice inaccuracies at fractional scales of GL * units, so it becomes necessary to scale the whole visualization. Defaults * to 1.0. * @param {boolean} options.startPaused Whether the simulation should start * in a paused state. * @param {Number} options.maxNumParticles The maximum number of particles in * the visualization. Try choosing a number that is larger than your * particles, but not too much larger. It's usually good enough to choose the * next highest power of 2. If you're not showing many particles (tens of * thousands+), you don't need to worry about this. * @param {String} options.particleTextureUrl The texture for the default * particle system. * @param {Number} options.particleDefaultSize The default size for the * particle system. * @param {Object} options.camera Options for camera * @param {Array.<Number>} options.camera.initialPosition Initial X, Y, Z * coordinates of the camera. Defaults to [0, -10, 5]. * @param {boolean} options.camera.enableDrift Set true to have the camera * float around slightly. False by default. * @param {Object} options.debug Options dictating debug state. * @param {boolean} options.debug.showAxes Show X, Y, and Z axes * @param {boolean} options.debug.showGrid Show grid on XY plane * @param {boolean} options.debug.showStats Show FPS and other stats * (requires stats.js). */ constructor(simulationElt: HTMLCanvasElement, options: SpacekitOptions); /** * @private */ private init; /** * @private */ private initRenderer; /** * @private */ private initPasses; /** * @private */ private update; /** * Performs a forced update of all elements in the view. This is used for when the system isn't animating but the * objects need to update their data to properly capture things like updated label positions. * @private */ private staticForcedUpdate; /** * @private * Updates the size of the control and forces a refresh of components whenever the control is being resized. */ private resizeUpdate; /** * @private * TODO(ian): Move this into Camera */ private doCameraDrift; /** * @private */ private animate; /** * Add a spacekit object (usually a SpaceObject) to the visualization. * @see SpaceObject * @param {Object} obj Object to add to visualization * @param {boolean} noUpdate Set to true if object does not need to be * animated. */ addObject(obj: SimulationObject, noUpdate?: boolean): void; /** * Removes an object from the visualization. * @param {Object} obj Object to remove */ removeObject(obj: SpaceObject): void; /** * Shortcut for creating a new SpaceObject belonging to this visualization. * Takes any SpaceObject arguments. * @see SpaceObject */ createObject(...args: any[]): SpaceObject; /** * Shortcut for creating a new ShapeObject belonging to this visualization. * Takes any ShapeObject arguments. * @see ShapeObject */ createShape(...args: any[]): ShapeObject; /** * Shortcut for creating a new SphereOjbect belonging to this visualization. * Takes any SphereObject arguments. * @see SphereObject */ createSphere(...args: any[]): SphereObject; /** * Shortcut for creating a new StaticParticles object belonging to this visualization. * Takes any StaticParticles arguments. * @see SphereObject */ createStaticParticles(...args: any[]): StaticParticles; /** * Shortcut for creating a new Skybox belonging to this visualization. Takes * any Skybox arguments. * @see Skybox */ createSkybox(...args: any[]): Skybox; /** * Shortcut for creating a new Stars object belonging to this visualization. * Takes any Stars arguments. * @see Stars */ createStars(...args: any[]): Stars; /** * Creates an ambient light source. This will dimly light everything in the * visualization. * @param {Number} color Color of light, default 0x333333 */ createAmbientLight(color?: number): void; /** * Creates a light source. This will make the shape of your objects visible * and provide some contrast. * @param {Array.<Number>} pos Position of light source. Defaults to moving * with camera. * @param {Number} color Color of light, default 0xFFFFFF */ createLight(pos?: Coordinate3d | undefined, color?: number): void; getLightPosition(): Vector3 | undefined; isUsingLightSources(): boolean; /** * Returns a promise that receives a NaturalSatellites object when it is * resolved. * @return {Promise<NaturalSatellites>} NaturalSatellites object that is * ready to load. * * @see {NaturalSatellites} */ loadNaturalSatellites(): Promise<NaturalSatellites>; /** * Installs a scroll handler that only renders the visualization while it is * in the user's viewport. * * The scroll handler currently binds to the window object only. */ renderOnlyInViewport(): void; /** * Adjust camera position so that the object fits within the viewport. If * applicable, this function will fit around the object's orbit. * @param {SpaceObject} spaceObj Object to fit within viewport. * @param {Number} offset Add some extra room in the viewport. Increase to be * further zoomed out, decrease to be closer. Default 3.0. */ zoomToFit(spaceObj: SpaceObject, offset?: number): Promise<boolean>; /** * @private * Perform the actual zoom to fit behavior. * @param {Object3D} obj Three.js object to fit within viewport. * @param {Number} offset Add some extra room in the viewport. Increase to be * further zoomed out, decrease to be closer. Default 3.0. */ private doZoomToFit; /** * Run the animation */ start(): void; /** * Stop the animation */ stop(): void; /** * Gets the current JD date of the simulation * @return {Number} JD date */ getJd(): number; /** * Sets the JD date of the simulation. * @param {Number} val JD date */ setJd(val: number): void; /** * Get a date object representing local date and time of the simulation. * @return {Date} Date of simulation */ getDate(): Date; /** * Set the local date and time of the simulation. * @param {Date} date Date of simulation */ setDate(date: Date): void; /** * Get the JD per frame of the visualization. */ getJdDelta(): number; /** * Set the JD per frame of the visualization. This will override any * existing "JD per second" setting. * @param {Number} delta JD per frame */ setJdDelta(delta: number): void; /** * Get the JD change per second of the visualization. * @return {Number | undefined} JD per second, undefined if jd per second is * not set. */ getJdPerSecond(): number | undefined; /** * Set the JD change per second of the visualization. * @param {Number} x JD per second */ setJdPerSecond(x: number): void; /** * Get an object that contains useful context for this visualization * @return {Object} Context object */ getContext(): SimulationContext; /** * Get the element containing this simulation * @return {HTMLElement} The html container of this simulation */ getSimulationElement(): HTMLCanvasElement; /** * Get the Camera and CameraControls wrapper object * @return {Camera} The Camera wrapper */ getViewer(): Camera; /** * Get the three.js scene object * @return {THREE.Scene} The THREE.js scene object */ getScene(): THREE.Scene; /** * Get the three.js renderer * @return {THREE.WebGL1Renderer} The THREE.js renderer */ getRenderer(): THREE.WebGL1Renderer; /** * Enable or disable camera drift. * @param {boolean} driftOn True if you want the camera to float around a bit */ setCameraDrift(driftOn: boolean): void; } export default Simulation;
the_stack
* DescribeResourceConfigs返回参数结构体 */ export interface DescribeResourceConfigsResponse { /** * 资源配置描述数组 */ ResourceConfigSet: Array<ResourceConfigItem> /** * 资源配置数量 */ TotalCount: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * CreateResource请求参数结构体 */ export interface CreateResourceRequest { /** * 资源位置 */ ResourceLoc: ResourceLoc /** * 资源名称 */ Name: string /** * 资源类型。目前只支持 JAR,取值为 1 */ ResourceType: number /** * 资源描述 */ Remark?: string /** * 资源版本描述 */ ResourceConfigRemark?: string } /** * CreateJob请求参数结构体 */ export interface CreateJobRequest { /** * 作业名称,允许输入长度小于等于50个字符的中文、英文、数字、-(横线)、_(下划线)、.(点),且符号必须半角字符。注意作业名不能和现有作业同名 */ Name: string /** * 作业的类型,1 表示 SQL 作业,2 表示 JAR 作业 */ JobType: number /** * 集群的类型,1 表示共享集群,2 表示独享集群 */ ClusterType: number /** * 当 ClusterType=2 时,必选,用来指定该作业提交的独享集群 ID */ ClusterId?: string /** * 设置每 CU 的内存规格,单位为 GB,支持 2、4、8、16(需申请开通白名单后使用)。默认为 4,即 1 CU 对应 4 GB 的运行内存 */ CuMem?: number /** * 作业的备注信息,可以随意设置 */ Remark?: string /** * 作业名所属文件夹ID,根目录为"root" */ FolderId?: string /** * 作业运行的Flink版本 */ FlinkVersion?: string } /** * JobConfig引用资源信息 */ export interface ResourceRefDetail { /** * 资源id */ ResourceId: string /** * 资源版本,-1表示使用最新版本 */ Version: number /** * 资源名称 */ Name: string /** * 1: 主资源 */ Type: number /** * 1: 系统内置资源 */ SystemProvide: number } /** * StopJobs请求参数结构体 */ export interface StopJobsRequest { /** * 批量停止作业的描述信息 */ StopJobDescriptions: Array<StopJobDescription> } /** * CreateJob返回参数结构体 */ export interface CreateJobResponse { /** * 作业Id */ JobId: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 资源位置描述 */ export interface ResourceLoc { /** * 资源位置的存储类型,目前只支持1:COS */ StorageType: number /** * 描述资源位置的json */ Param: ResourceLocParam } /** * RunJobs请求参数结构体 */ export interface RunJobsRequest { /** * 批量启动作业的描述信息 */ RunJobDescriptions: Array<RunJobDescription> } /** * 停止作业的描述信息 */ export interface StopJobDescription { /** * 作业Id */ JobId: string /** * 停止类型,1 停止 2 暂停 */ StopType: number } /** * DeleteTableConfig返回参数结构体 */ export interface DeleteTableConfigResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * CreateResourceConfig返回参数结构体 */ export interface CreateResourceConfigResponse { /** * 资源版本ID */ Version?: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * CreateJobConfig请求参数结构体 */ export interface CreateJobConfigRequest { /** * 作业Id */ JobId: string /** * 主类 */ EntrypointClass?: string /** * 主类入参 */ ProgramArgs?: string /** * 备注 */ Remark?: string /** * 资源引用数组 */ ResourceRefs?: Array<ResourceRef> /** * 作业默认并行度 */ DefaultParallelism?: number /** * 系统参数 */ Properties?: Array<Property> /** * 1: 作业配置达到上限之后,自动删除可删除的最早版本 */ AutoDelete?: number /** * 作业使用的 COS 存储桶名 */ COSBucket?: string /** * 是否采集作业日志 */ LogCollect?: boolean /** * JobManager规格 */ JobManagerSpec?: number /** * TaskManager规格 */ TaskManagerSpec?: number } /** * CreateResourceConfig请求参数结构体 */ export interface CreateResourceConfigRequest { /** * 资源ID */ ResourceId: string /** * 位置信息 */ ResourceLoc: ResourceLoc /** * 资源描述信息 */ Remark?: string /** * 1: 资源版本达到上限,自动删除最早可删除的版本 */ AutoDelete?: number } /** * 系统配置属性 */ export interface Property { /** * 系统配置的Key */ Key: string /** * 系统配置的Value */ Value: string } /** * DeleteTableConfig请求参数结构体 */ export interface DeleteTableConfigRequest { /** * 作业ID */ JobId: string /** * 调试作业ID */ DebugId: number /** * 表名 */ TableName: string } /** * 系统资源返回值 */ export interface SystemResourceItem { /** * 资源ID */ ResourceId: string /** * 资源名称 */ Name: string /** * 资源类型。1 表示 JAR 包,目前只支持该值。 */ ResourceType: number /** * 资源备注 */ Remark: string /** * 资源所属地域 */ Region: string /** * 资源的最新版本 */ LatestResourceConfigVersion: number } /** * DescribeResourceRelatedJobs请求参数结构体 */ export interface DescribeResourceRelatedJobsRequest { /** * 资源ID */ ResourceId: string /** * 默认0; 1: 按照作业版本创建时间降序 */ DESCByJobConfigCreateTime?: number /** * 偏移量,默认为0 */ Offset?: number /** * 分页大小,默认为20,最大值为100 */ Limit?: number } /** * DeleteResources返回参数结构体 */ export interface DeleteResourcesResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * CreateJobConfig返回参数结构体 */ export interface CreateJobConfigResponse { /** * 作业配置版本号 */ Version: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 描述资源配置的返回参数 */ export interface ResourceConfigItem { /** * 资源ID */ ResourceId: string /** * 资源类型 */ ResourceType: number /** * 资源所属地域 */ Region: string /** * 资源所属AppId */ AppId: number /** * 主账号Uin */ OwnerUin: string /** * 子账号Uin */ CreatorUin: string /** * 资源位置描述 */ ResourceLoc: ResourceLoc /** * 资源创建时间 */ CreateTime: string /** * 资源版本 */ Version: number /** * 资源描述 */ Remark: string /** * 资源状态:0: 资源同步中,1:资源已就绪 注意:此字段可能返回 null,表示取不到有效值。 */ Status: number /** * 关联作业个数 注意:此字段可能返回 null,表示取不到有效值。 */ RefJobCount: number } /** * DescribeResources请求参数结构体 */ export interface DescribeResourcesRequest { /** * 需要查询的资源ID数组,数量不超过100个。如果填写了该参数则忽略Filters参数。 */ ResourceIds?: Array<string> /** * 偏移量,仅当设置 Limit 参数时有效 */ Offset?: number /** * 条数限制。如果不填,默认返回 20 条 */ Limit?: number /** * <li><strong>ResourceName</strong></li> <p style="padding-left: 30px;">按照资源名字过滤,支持模糊过滤。传入的过滤名字不超过5个</p><p style="padding-left: 30px;">类型: String</p><p style="padding-left: 30px;">必选: 否</p> */ Filters?: Array<Filter> } /** * 资源参数描述 */ export interface ResourceLocParam { /** * 资源bucket */ Bucket: string /** * 资源路径 */ Path: string /** * 资源所在地域,如果不填,则使用Resource的Region 注意:此字段可能返回 null,表示取不到有效值。 */ Region?: string } /** * DeleteResourceConfigs请求参数结构体 */ export interface DeleteResourceConfigsRequest { /** * 资源ID */ ResourceId: string /** * 资源版本数组 */ ResourceConfigVersions: Array<number> } /** * RunJobs返回参数结构体 */ export interface RunJobsResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 查询作业列表时的过滤器 */ export interface Filter { /** * 要过滤的字段 */ Name: string /** * 字段的过滤值 */ Values: Array<string> } /** * DeleteResources请求参数结构体 */ export interface DeleteResourcesRequest { /** * 待删除资源ID列表 */ ResourceIds: Array<string> } /** * DescribeJobs返回参数结构体 */ export interface DescribeJobsResponse { /** * 作业总数 */ TotalCount: number /** * 作业列表 */ JobSet: Array<JobV1> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 资源详细描述 */ export interface ResourceItem { /** * 资源ID */ ResourceId: string /** * 资源名称 */ Name: string /** * 资源类型 */ ResourceType: number /** * 资源位置 */ ResourceLoc: ResourceLoc /** * 资源地域 */ Region: string /** * 应用ID */ AppId: number /** * 主账号Uin */ OwnerUin: string /** * 子账号Uin */ CreatorUin: string /** * 资源创建时间 */ CreateTime: string /** * 资源最后更新时间 */ UpdateTime: string /** * 资源的资源版本ID */ LatestResourceConfigVersion: number /** * 资源备注 注意:此字段可能返回 null,表示取不到有效值。 */ Remark: string /** * 版本个数 注意:此字段可能返回 null,表示取不到有效值。 */ VersionCount: number /** * 关联作业数 注意:此字段可能返回 null,表示取不到有效值。 */ RefJobCount: number } /** * StopJobs返回参数结构体 */ export interface StopJobsResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * CreateResource返回参数结构体 */ export interface CreateResourceResponse { /** * 资源ID */ ResourceId: string /** * 资源版本 */ Version: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeSystemResources请求参数结构体 */ export interface DescribeSystemResourcesRequest { /** * 需要查询的资源ID数组 */ ResourceIds?: Array<string> /** * 偏移量,仅当设置 Limit 参数时有效 */ Offset?: number /** * 条数限制,默认返回 20 条 */ Limit?: number /** * 查询资源配置列表, 如果不填写,返回该 ResourceIds.N 下所有作业配置列表 */ Filters?: Array<Filter> /** * 集群ID */ ClusterId?: string /** * 查询对应Flink版本的内置connector */ FlinkVersion?: string } /** * DescribeJobConfigs请求参数结构体 */ export interface DescribeJobConfigsRequest { /** * 作业Id */ JobId: string /** * 作业配置版本 */ JobConfigVersions?: Array<number> /** * 偏移量,默认0 */ Offset?: number /** * 分页大小,默认20,最大100 */ Limit?: number /** * 过滤条件 */ Filters?: Array<Filter> /** * true 表示只展示草稿 */ OnlyDraft?: boolean } /** * DescribeResources返回参数结构体 */ export interface DescribeResourcesResponse { /** * 资源详细信息集合 */ ResourceSet: Array<ResourceItem> /** * 总数量 */ TotalCount: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 作业启动详情 */ export interface RunJobDescription { /** * 作业Id */ JobId: string /** * 运行类型,1:启动,2:恢复 */ RunType: number /** * 已废弃。旧版 SQL 类型作业启动参数:指定数据源消费起始时间点 */ StartMode?: string /** * 当前作业的某个版本 */ JobConfigVersion?: number } /** * DescribeJobConfigs返回参数结构体 */ export interface DescribeJobConfigsResponse { /** * 总的配置版本数量 */ TotalCount: number /** * 作业配置列表 */ JobConfigSet: Array<JobConfig> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DeleteResourceConfigs返回参数结构体 */ export interface DeleteResourceConfigsResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeResourceRelatedJobs返回参数结构体 */ export interface DescribeResourceRelatedJobsResponse { /** * 总数 */ TotalCount: number /** * 关联作业信息 */ RefJobInfos: Array<ResourceRefJobInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeSystemResources返回参数结构体 */ export interface DescribeSystemResourcesResponse { /** * 资源详细信息集合 */ ResourceSet: Array<SystemResourceItem> /** * 总数量 */ TotalCount: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 资源被Job 引用信息 */ export interface ResourceRefJobInfo { /** * Job id */ JobId: string /** * Job配置版本 */ JobConfigVersion: number /** * 资源版本 */ ResourceVersion: number } /** * 资源引用参数 */ export interface ResourceRef { /** * 资源ID */ ResourceId: string /** * 资源版本ID,-1表示使用最新版本 */ Version: number /** * 引用资源类型,例如主资源设置为1,代表main class所在的jar包 */ Type: number } /** * DescribeJobs请求参数结构体 */ export interface DescribeJobsRequest { /** * 按照一个或者多个作业ID查询。作业ID形如:cql-11112222,每次请求的作业上限为100。参数不支持同时指定JobIds和Filters。 */ JobIds?: Array<string> /** * 过滤条件,支持的 Filter.Name 为:作业名 Name、作业状态 Status、所属集群 ClusterId。每次请求的 Filters 个数的上限为 3,Filter.Values 的个数上限为 5。参数不支持同时指定 JobIds 和 Filters。 */ Filters?: Array<Filter> /** * 偏移量,默认为0 */ Offset?: number /** * 分页大小,默认为20,最大值为100 */ Limit?: number } /** * Job详细信息 */ export interface JobV1 { /** * 作业ID 注意:此字段可能返回 null,表示取不到有效值。 */ JobId: string /** * 地域 注意:此字段可能返回 null,表示取不到有效值。 */ Region: string /** * 可用区 注意:此字段可能返回 null,表示取不到有效值。 */ Zone: string /** * 用户AppId 注意:此字段可能返回 null,表示取不到有效值。 */ AppId: number /** * 用户UIN 注意:此字段可能返回 null,表示取不到有效值。 */ OwnerUin: string /** * 创建者UIN 注意:此字段可能返回 null,表示取不到有效值。 */ CreatorUin: string /** * 作业名字 注意:此字段可能返回 null,表示取不到有效值。 */ Name: string /** * 作业类型,1:sql作业,2:Jar作业 注意:此字段可能返回 null,表示取不到有效值。 */ JobType: number /** * 作业状态,1:未初始化,2:未发布,3:操作中,4:运行中,5:停止,6:暂停,-1:故障 注意:此字段可能返回 null,表示取不到有效值。 */ Status: number /** * 作业创建时间 注意:此字段可能返回 null,表示取不到有效值。 */ CreateTime: string /** * 作业启动时间 注意:此字段可能返回 null,表示取不到有效值。 */ StartTime: string /** * 作业停止时间 注意:此字段可能返回 null,表示取不到有效值。 */ StopTime: string /** * 作业更新时间 注意:此字段可能返回 null,表示取不到有效值。 */ UpdateTime: string /** * 作业累计运行时间 注意:此字段可能返回 null,表示取不到有效值。 */ TotalRunMillis: number /** * 备注信息 注意:此字段可能返回 null,表示取不到有效值。 */ Remark: string /** * 操作错误提示信息 注意:此字段可能返回 null,表示取不到有效值。 */ LastOpResult: string /** * 集群名字 注意:此字段可能返回 null,表示取不到有效值。 */ ClusterName: string /** * 最新配置版本号 注意:此字段可能返回 null,表示取不到有效值。 */ LatestJobConfigVersion: number /** * 已发布的配置版本 注意:此字段可能返回 null,表示取不到有效值。 */ PublishedJobConfigVersion: number /** * 运行的CU数量 注意:此字段可能返回 null,表示取不到有效值。 */ RunningCuNum: number /** * 作业内存规格 注意:此字段可能返回 null,表示取不到有效值。 */ CuMem: number /** * 作业状态描述 注意:此字段可能返回 null,表示取不到有效值。 */ StatusDesc: string /** * 运行状态时表示单次运行时间 注意:此字段可能返回 null,表示取不到有效值。 */ CurrentRunMillis: number /** * 作业所在的集群ID 注意:此字段可能返回 null,表示取不到有效值。 */ ClusterId: string /** * 作业管理WEB UI 入口 注意:此字段可能返回 null,表示取不到有效值。 */ WebUIUrl: string /** * 作业所在集群类型 注意:此字段可能返回 null,表示取不到有效值。 */ SchedulerType: number /** * 作业所在集群状态 注意:此字段可能返回 null,表示取不到有效值。 */ ClusterStatus: number /** * 细粒度下的运行的CU数量 注意:此字段可能返回 null,表示取不到有效值。 */ RunningCu: number /** * 作业运行的 Flink 版本 注意:此字段可能返回 null,表示取不到有效值。 */ FlinkVersion: string } /** * 作业配置详情 */ export interface JobConfig { /** * 作业Id */ JobId: string /** * 主类 注意:此字段可能返回 null,表示取不到有效值。 */ EntrypointClass: string /** * 主类入参 注意:此字段可能返回 null,表示取不到有效值。 */ ProgramArgs: string /** * 备注 注意:此字段可能返回 null,表示取不到有效值。 */ Remark: string /** * 作业配置创建时间 */ CreateTime: string /** * 作业配置的版本号 */ Version: number /** * 作业默认并行度 注意:此字段可能返回 null,表示取不到有效值。 */ DefaultParallelism: number /** * 系统参数 注意:此字段可能返回 null,表示取不到有效值。 */ Properties: Array<Property> /** * 引用资源 注意:此字段可能返回 null,表示取不到有效值。 */ ResourceRefDetails: Array<ResourceRefDetail> /** * 创建者uin 注意:此字段可能返回 null,表示取不到有效值。 */ CreatorUin: string /** * 作业配置上次启动时间 注意:此字段可能返回 null,表示取不到有效值。 */ UpdateTime: string /** * 作业绑定的存储桶 注意:此字段可能返回 null,表示取不到有效值。 */ COSBucket: string /** * 是否启用日志收集,0-未启用,1-已启用,2-历史集群未设置日志集,3-历史集群已开启 注意:此字段可能返回 null,表示取不到有效值。 */ LogCollect: number /** * 作业的最大并行度 注意:此字段可能返回 null,表示取不到有效值。 */ MaxParallelism: number /** * JobManager规格 注意:此字段可能返回 null,表示取不到有效值。 */ JobManagerSpec: number /** * TaskManager规格 注意:此字段可能返回 null,表示取不到有效值。 */ TaskManagerSpec: number } /** * DescribeResourceConfigs请求参数结构体 */ export interface DescribeResourceConfigsRequest { /** * 资源ID */ ResourceId?: string /** * 偏移量,仅当设置 Limit 时该参数有效 */ Offset?: number /** * 返回值大小,不填则返回全量数据 */ Limit?: number /** * 资源配置Versions集合 */ ResourceConfigVersions?: Array<number> /** * 作业配置版本 */ JobConfigVersion?: number /** * 作业ID */ JobId?: string }
the_stack
import { deflate, inflate } from 'pako'; import { decodeUtf8 } from '../../common/utf8'; import MpqArchive from './archive'; import MpqBlock from './block'; import { COMPRESSION_ADPCM_MONO, COMPRESSION_ADPCM_STEREO, COMPRESSION_BZIP2, COMPRESSION_DEFLATE, COMPRESSION_HUFFMAN, COMPRESSION_IMPLODE, FILE_COMPRESSED, FILE_ENCRYPTED, FILE_EXISTS, FILE_IMPLODE, FILE_OFFSET_ADJUSTED_KEY, FILE_SINGLE_UNIT, HASH_ENTRY_DELETED } from './constants'; import MpqCrypto from './crypto'; import explode from './explode'; // import decodeHuffman from './huffman'; import MpqHash from './hash'; import { isArchive } from './isarchive'; /** * A MPQ file. */ export default class MpqFile { archive: MpqArchive; c: MpqCrypto; name: string; nameResolved: boolean; hash: MpqHash; block: MpqBlock; rawBuffer: Uint8Array | null = null; buffer: Uint8Array | null = null; constructor(archive: MpqArchive, hash: MpqHash, block: MpqBlock, rawBuffer: Uint8Array | null, buffer: Uint8Array | null) { const headerOffset = archive.headerOffset; this.archive = archive; this.c = archive.c; this.name = `File${`${hash.blockIndex}`.padStart(8, '0')}`; this.nameResolved = false; this.hash = hash; this.block = block; if (rawBuffer) { this.rawBuffer = rawBuffer.slice(headerOffset + block.offset, headerOffset + block.offset + block.compressedSize); } if (buffer) { this.buffer = buffer; } } /** * Gets this file's data as a Uint8Array. * * An exception will be thrown if the file needs to be decoded, and decoding fails. */ bytes(): Uint8Array { // Decode if needed if (this.buffer === null) { this.decode(); } // If decoding failed, an exception would have been thrown, so buffer is known to exist at this point. return <Uint8Array>this.buffer; } /** * Gets this file's data as an ArrayBuffer. * * An exception will be thrown if the file needs to be decoded, and decoding fails. */ arrayBuffer(): ArrayBuffer { return this.bytes().buffer; } /** * Gets this file's data as a UTF8 string. * * An exception will be thrown if the file needs to be decoded, and decoding fails. */ text(): string { return decodeUtf8(this.bytes()); } /** * Changes the buffer of this file. * * Does nothing if the archive is in readonly mode. */ set(buffer: Uint8Array): boolean { if (this.archive.readonly) { return false; } const hash = this.hash; const block = this.block; // Reset the hash. hash.locale = 0; hash.platform = 0; // Reset the block. block.compressedSize = 0; block.normalSize = buffer.byteLength; block.flags = 0; this.buffer = buffer; this.rawBuffer = null; return true; } /** * Deletes this file. * * Using the file after it was deleted will result in undefined behavior. * * Does nothing if the archive is in readonly mode. */ delete(): boolean { if (this.archive.readonly) { return false; } const archive = this.archive; const hash = this.hash; const blockIndex = hash.blockIndex; hash.delete(); for (const hash of archive.hashTable.entries) { if (hash.blockIndex < HASH_ENTRY_DELETED && hash.blockIndex > blockIndex) { hash.blockIndex -= 1; } } archive.blockTable.entries.splice(blockIndex, 1); archive.files.splice(blockIndex, 1); return true; } /** * Renames this file. * * Note that this sets the current file's hash's status to being deleted, rather than removing it. * This is due to the way the search algorithm works. * * Does nothing if the archive is in readonly mode. */ rename(newName: string): boolean { if (this.archive.readonly) { return false; } const hash = this.hash; const locale = hash.locale; const platform = hash.platform; const blockIndex = hash.blockIndex; // First delete the current hash. // This will allow its entry to be reused in case it's the only empty/deleted entry in the hashtable. hash.delete(); const newHash = <MpqHash>this.archive.hashTable.add(newName, blockIndex); newHash.locale = locale; newHash.platform = platform; this.name = newName; this.nameResolved = true; this.hash = newHash; return true; } /** * Decode this file. */ decode(): void { if (!this.rawBuffer) { throw new Error(`File ${this.name}: Nothing to decode`); } const archive = this.archive; const block = this.block; const c = archive.c; const encryptionKey = c.computeFileKey(this.name, block); const data = this.rawBuffer; const flags = block.flags; // One buffer of raw data. // I don't know why having no flags means it's a chunk of memory rather than sectors. // After all, there is no flag to say there are indeed sectors. if (flags === FILE_EXISTS) { this.buffer = data.slice(0, block.normalSize); } else if (flags & FILE_SINGLE_UNIT) { // One buffer of possibly encrypted and/or compressed data. // Read the sector let sector; // If this block is encrypted, decrypt the sector. if (flags & FILE_ENCRYPTED) { sector = c.decryptBlock(data.slice(0, block.compressedSize), encryptionKey); } else { sector = data.subarray(0, block.compressedSize); } // If this block is compressed, decompress the sector. // Otherwise, copy the sector as-is. if (flags & FILE_COMPRESSED) { sector = this.decompressSector(sector, block.normalSize); } else { sector = sector.slice(); } this.buffer = sector; } else { // One or more sectors of possibly encrypted and/or compressed data. const sectorCount = Math.ceil(block.normalSize / archive.sectorSize); // Alocate a buffer for the uncompressed block size const buffer = new Uint8Array(block.normalSize); // Get the sector offsets let sectorOffsets = new Uint32Array(data.buffer, 0, sectorCount + 1); // If this file is encrypted, copy the sector offsets and decrypt them. if (flags & FILE_ENCRYPTED) { sectorOffsets = c.decryptBlock(sectorOffsets.slice(), encryptionKey - 1); } let start = sectorOffsets[0]; let end = sectorOffsets[1]; let offset = 0; for (let i = 0; i < sectorCount; i++) { let sector; // If this file is encrypted, copy the sector and decrypt it. // Otherwise a view can be used directly. if (flags & FILE_ENCRYPTED) { sector = c.decryptBlock(data.slice(start, end), encryptionKey + i); } else { sector = data.subarray(start, end); } // Decompress the sector if (flags & FILE_COMPRESSED) { let uncompressedSize = archive.sectorSize; // If this is the last sector, its uncompressed size might not be the size of a sector. if (block.normalSize - offset < uncompressedSize) { uncompressedSize = block.normalSize - offset; } sector = this.decompressSector(sector, uncompressedSize); } // Some sectors have this flags instead of the compression flag + algorithm byte. if (flags & FILE_IMPLODE) { sector = explode(sector); } // Add the sector bytes to the buffer buffer.set(sector, offset); offset += sector.byteLength; // Prepare for the next sector if (i < sectorCount) { start = end; end = sectorOffsets[i + 2]; } } this.buffer = buffer; } // If the archive is in read-only mode, the raw buffer isn't needed anymore, so free the memory. if (archive.readonly) { this.rawBuffer = null; } } decompressSector(bytes: Uint8Array, decompressedSize: number): Uint8Array { // If the size of the data is the same as its decompressed size, it's not compressed. if (bytes.byteLength === decompressedSize) { return bytes; } else { const compressionMask = bytes[0]; if (compressionMask & COMPRESSION_BZIP2) { throw new Error(`File ${this.name}: compression type 'bzip2' not supported`); } if (compressionMask & COMPRESSION_IMPLODE) { try { bytes = explode(bytes.subarray(1)); } catch (e) { throw new Error(`File ${this.name}: failed to decompress with 'explode': ${e}`); } } if (compressionMask & COMPRESSION_DEFLATE) { try { bytes = inflate(bytes.subarray(1)); } catch (e) { throw new Error(`File ${this.name}: failed to decompress with 'zlib': ${e}`); } } if (compressionMask & COMPRESSION_HUFFMAN) { // try { // bytes = decodeHuffman(bytes.subarray(1)); // } catch (e) { // throw new Error(`File ${this.name}: failed to decompress with 'huffman': ${e}`); // } throw new Error(`File ${this.name}: compression type 'huffman' not supported`); } if (compressionMask & COMPRESSION_ADPCM_STEREO) { throw new Error(`File ${this.name}: compression type 'adpcm stereo' not supported`); } if (compressionMask & COMPRESSION_ADPCM_MONO) { throw new Error(`File ${this.name}: compression type 'adpcm mono' not supported`); } return bytes; } } /** * Encode this file. * Archives (maps or generic MPQs) are stored uncompressed in one chunk. * Other files are always stored in sectors, except when a file is smaller than a sector. * Sectors themselves are always compressed, except when the result is smaller than the uncompressed data. */ encode(): void { if (this.buffer !== null && this.rawBuffer === null) { const data = this.buffer; if (isArchive(data)) { this.rawBuffer = this.buffer; this.block.compressedSize = this.buffer.byteLength; this.block.flags = FILE_EXISTS; } else { const sectorSize = this.archive.sectorSize; const sectorCount = Math.ceil(data.byteLength / sectorSize); const offsets = new Uint32Array(sectorCount + 1); let offset = offsets.byteLength; const sectors = []; const compression = []; // First offset is right after the offsets list. offsets[0] = offset; for (let i = 0; i < sectorCount; i++) { const sectorOffset = i * sectorSize; let sector = data.subarray(sectorOffset, sectorOffset + sectorSize); let size = sector.byteLength; const compressed = deflate(sector); let isCompressed = false; // If the compressed size of the sector is smaller than the uncompressed, use the compressed data. // +1 because of the compression mask byte. if (compressed.byteLength + 1 < size) { sector = compressed; size = compressed.byteLength + 1; isCompressed = true; } offset += size; offsets[i + 1] = offset; sectors[i] = sector; compression[i] = isCompressed; } // Only use the compressed data if it's actually smaller than the uncompressed data. if (offset < data.byteLength) { const rawBuffer = new Uint8Array(offset); // Write the offsets list. rawBuffer.set(new Uint8Array(offsets.buffer)); offset = offsets.byteLength; for (let i = 0; i < sectorCount; i++) { // If this sector is compressed, set it to zlib. if (compression[i]) { rawBuffer[offset] = 2; offset += 1; } // Write the sector. const sector = sectors[i]; rawBuffer.set(sector, offset); offset += sector.byteLength; } this.rawBuffer = rawBuffer; this.block.compressedSize = rawBuffer.byteLength; this.block.flags = (FILE_EXISTS | FILE_COMPRESSED) >>> 0; } else { this.rawBuffer = this.buffer; this.block.compressedSize = this.buffer.byteLength; this.block.flags = FILE_EXISTS; } } } } /** * Decrypt this file and encrypt it back, with a new offset in the archive. * This is used for files that use FILE_OFFSET_ADJUSTED_KEY, which are encrypted with a key that depends on their offset. */ reEncrypt(offset: number): boolean { if (!this.rawBuffer) { return false; } const archive = this.archive; const block = this.block; const c = archive.c; const bytes = this.rawBuffer; const flags = block.flags; const encryptionKey = c.computeFileKey(this.name, block); block.offset = offset; const newEncryptionKey = c.computeFileKey(this.name, block); if (flags & FILE_SINGLE_UNIT) { // Decrypt the chunk with the old key. c.decryptBlock(bytes, encryptionKey); // Encrypt the chunk with the new key. c.encryptBlock(bytes, newEncryptionKey); } else { const sectorCount = Math.ceil(block.normalSize / archive.sectorSize); // Get the sector offsets const sectorOffsets = new Uint32Array(bytes.buffer, 0, sectorCount + 1); // Decrypt the sector offsets with the old key. c.decryptBlock(sectorOffsets, encryptionKey - 1); let start = sectorOffsets[0]; let end = sectorOffsets[1]; for (let i = 0; i < sectorCount; i++) { const sector = bytes.subarray(start, end); // Decrypt the chunk with the old key. c.decryptBlock(sector, encryptionKey + i); // Encrypt the chunk with the new key. c.encryptBlock(sector, newEncryptionKey + i); // Prepare for the next sector if (i < sectorCount) { start = end; end = sectorOffsets[i + 2]; } } // Encrypt the sector offsets with the new key. c.encryptBlock(sectorOffsets, newEncryptionKey - 1); } return true; } /** * The offset of the file has been recalculated. * If the offset is different, and this file uses FILE_OFFSET_ADJUSTED_KEY encryption, it must be re-encrypted with the new offset. */ offsetChanged(offset: number): boolean { const block = this.block; if (block.offset !== offset && block.flags & FILE_OFFSET_ADJUSTED_KEY) { if (this.nameResolved) { return this.reEncrypt(offset); } return false; } block.offset = offset; return true; } }
the_stack
import mockConsole from 'jest-mock-console'; import { ProxyTree, Branch } from '../../src'; describe('ProxyTree Tests', () => { beforeEach(() => { jest.clearAllMocks(); mockConsole(['error', 'warn']); }); it('should create ProxyTree with passed object', () => { const dummyObject = { a: { b: 'c' }, b: 'c' }; jest.spyOn(ProxyTree.prototype, 'createBranch'); const proxyTree = new ProxyTree(dummyObject); expect(proxyTree.proxy).toStrictEqual(dummyObject); expect(proxyTree.createBranch).toHaveBeenCalledWith(dummyObject); expect(proxyTree.rootBranch.target).toStrictEqual(dummyObject); expect(proxyTree.rootBranch.proxyTree).toStrictEqual(proxyTree); expect(console.error).not.toHaveBeenCalled(); }); it('should create ProxyTree with passed array', () => { const dummyArray = ['a', { a: 'b' }]; jest.spyOn(ProxyTree.prototype, 'createBranch'); const proxyTree = new ProxyTree(dummyArray); expect(proxyTree.proxy).toStrictEqual(dummyArray); expect(proxyTree.createBranch).toHaveBeenCalledWith(dummyArray); expect(proxyTree.rootBranch.target).toStrictEqual(dummyArray); expect(proxyTree.rootBranch.proxyTree).toStrictEqual(proxyTree); expect(console.error).not.toHaveBeenCalled(); }); it("shouldn't create ProxyTree with string", () => { const dummyString = 'hello my name is jeff'; jest.spyOn(ProxyTree.prototype, 'createBranch'); const proxyTree = new ProxyTree(dummyString as any); expect(proxyTree.proxy).toBe(null); expect(proxyTree.createBranch).toHaveBeenCalledWith(dummyString); expect(proxyTree.rootBranch).toBe(null); expect(console.error).toHaveBeenCalledWith( "ProxyTree: The ProxyTree accepts only values from the type 'object' and 'array'! " + "The passed type was 'string'! " + 'Learn more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy' ); }); it("shouldn't create ProxyTree with number", () => { const dummyNumber = 10; jest.spyOn(ProxyTree.prototype, 'createBranch'); const proxyTree = new ProxyTree(dummyNumber as any); expect(proxyTree.proxy).toBe(null); expect(proxyTree.createBranch).toHaveBeenCalledWith(dummyNumber); expect(proxyTree.rootBranch).toBe(null); expect(console.error).toHaveBeenCalledWith( "ProxyTree: The ProxyTree accepts only values from the type 'object' and 'array'! " + "The passed type was 'number'! " + 'Learn more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy' ); }); describe('ProxyTree Function Tests', () => { const original = { a: [{ b: 1 }, { 1000: { a: { b: 1 } } }, '3rd'], b: { c: { d: 'hi' } }, c: { a: 'hi' }, }; let proxyTree: ProxyTree; beforeEach(() => { proxyTree = new ProxyTree(original); }); describe('createBranch function tests', () => { it('should create Branch with a valid object', () => { const branch = proxyTree.createBranch(original); expect(branch).toBeInstanceOf(Branch); expect(branch?.target).toStrictEqual(original); expect(branch?.proxyTree).toBe(proxyTree); expect(console.error).not.toHaveBeenCalled(); }); it("shouldn't create Branch with a not valid object", () => { const branch = proxyTree.createBranch('not valid object' as any); expect(branch).toBe(null); expect(console.error).toHaveBeenCalledWith( "ProxyTree: The ProxyTree accepts only values from the type 'object' and 'array'! " + "The passed type was 'string'! " + 'Learn more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy' ); }); }); describe('transformTreeToBranchObject function tests', () => { it('should transform 2 layer deep accessed object properties', () => { const proxyfiedOrginal = proxyTree.proxy; // Access Properties proxyfiedOrginal.a; proxyfiedOrginal.a[0]; proxyfiedOrginal.c.a; expect(proxyTree.transformTreeToBranchObject()).toStrictEqual({ key: 'root', timesAccessed: 3, branches: [ { key: 'a', timesAccessed: 2, branches: [{ key: '0', timesAccessed: 1, branches: [] }], }, { key: 'c', timesAccessed: 1, branches: [{ key: 'a', timesAccessed: 1, branches: [] }], }, ], }); }); it('should transform 3 layer deep accessed object properties', () => { const proxyfiedOrginal = proxyTree.proxy; // Access Properties proxyfiedOrginal.a; proxyfiedOrginal.a[0]['b']; proxyfiedOrginal.c.a; proxyfiedOrginal.b; expect(proxyTree.transformTreeToBranchObject()).toStrictEqual({ key: 'root', timesAccessed: 4, branches: [ { key: 'a', timesAccessed: 2, branches: [ { key: '0', timesAccessed: 1, branches: [{ key: 'b', timesAccessed: 1, branches: [] }], }, ], }, { key: 'c', timesAccessed: 1, branches: [{ key: 'a', timesAccessed: 1, branches: [] }], }, { key: 'b', timesAccessed: 1, branches: [], }, ], }); }); it('should transform 5 layer deep accessed object properties', () => { const proxyfiedOrginal = proxyTree.proxy; // Access Properties proxyfiedOrginal.a; proxyfiedOrginal.a[0]['b']; proxyfiedOrginal.a[1][1000]['a']['b']; proxyfiedOrginal.c.a; proxyfiedOrginal.b; expect(proxyTree.transformTreeToBranchObject()).toStrictEqual({ branches: [ { branches: [ { branches: [ { branches: [], key: 'b', timesAccessed: 1, }, ], key: '0', timesAccessed: 1, }, { branches: [ { branches: [ { branches: [ { branches: [], key: 'b', timesAccessed: 1, }, ], key: 'a', timesAccessed: 1, }, ], key: '1000', timesAccessed: 1, }, ], key: '1', timesAccessed: 1, }, ], key: 'a', timesAccessed: 3, }, { branches: [ { branches: [], key: 'a', timesAccessed: 1, }, ], key: 'c', timesAccessed: 1, }, { branches: [], key: 'b', timesAccessed: 1, }, ], key: 'root', timesAccessed: 5, }); }); it('should track often accessed object properties', () => { const proxyfiedOrginal = proxyTree.proxy; // Access Properties proxyfiedOrginal.a; proxyfiedOrginal.a; proxyfiedOrginal.a[0]; proxyfiedOrginal.a; expect(proxyTree.transformTreeToBranchObject()).toStrictEqual({ key: 'root', timesAccessed: 4, branches: [ { key: 'a', timesAccessed: 4, branches: [{ key: '0', timesAccessed: 1, branches: [] }], }, ], }); }); }); describe('transformTreeToBranchObject function tests', () => { beforeEach(() => { jest.spyOn(proxyTree, 'transformTreeToBranchObject'); }); it('should track 2 layer deep accessed object properties', () => { const proxyfiedOrginal = proxyTree.proxy; // Access Properties proxyfiedOrginal.a; proxyfiedOrginal.a[0]; proxyfiedOrginal.c.a; expect(proxyTree.getUsedRoutes()).toStrictEqual([ ['a', '0'], ['c', 'a'], ['a'], ]); expect(proxyTree.transformTreeToBranchObject).toHaveBeenCalledTimes(1); }); it('should track 3 layer deep accessed object properties', () => { const proxyfiedOrginal = proxyTree.proxy; // Access Properties proxyfiedOrginal.a; proxyfiedOrginal.a[0]['b']; proxyfiedOrginal.c.a; proxyfiedOrginal.b; expect(proxyTree.getUsedRoutes()).toStrictEqual([ ['a', '0', 'b'], ['c', 'a'], ['b'], ['a'], ]); expect(proxyTree.transformTreeToBranchObject).toHaveBeenCalledTimes(1); }); it('should track 5 layer deep accessed object properties', () => { const proxyfiedOrginal = proxyTree.proxy; // Access Properties proxyfiedOrginal.a; proxyfiedOrginal.a[0]['b']; proxyfiedOrginal.a[1][1000]['a']['b']; proxyfiedOrginal.c.a; proxyfiedOrginal.b; expect(proxyTree.getUsedRoutes()).toStrictEqual([ ['a', '0', 'b'], ['a', '1', '1000', 'a', 'b'], ['c', 'a'], ['b'], ['a'], ]); expect(proxyTree.transformTreeToBranchObject).toHaveBeenCalledTimes(1); }); it('should track often accessed object properties multiple times and combine them', () => { const proxyfiedOrginal = proxyTree.proxy; // Access Properties proxyfiedOrginal.a; proxyfiedOrginal.a; proxyfiedOrginal.a; expect(proxyTree.getUsedRoutes()).toStrictEqual([['a']]); expect(proxyTree.transformTreeToBranchObject).toHaveBeenCalledTimes(1); }); it("shouldn't track properties not directly belonging to the object", () => { const proxyfiedOrginal = proxyTree.proxy; // Access Properties proxyfiedOrginal.a.length; proxyfiedOrginal.a.slice(1, 2); proxyfiedOrginal.toString(); proxyfiedOrginal.x; expect(proxyTree.getUsedRoutes()).toStrictEqual([['a', '1'], ['a']]); expect(proxyTree.transformTreeToBranchObject).toHaveBeenCalledTimes(1); }); }); }); });
the_stack
import { DOCUMENT } from '@angular/common'; import { AfterViewInit, Directive, ElementRef, Inject, Input, NgZone, OnDestroy } from '@angular/core'; import { fromEvent, merge as mergeStatic, Subscription } from 'rxjs'; import { tap, throttleTime } from 'rxjs/operators'; import { DragDropService } from '../services/drag-drop.service'; import { Utils } from '../shared/utils'; import { DropScrollAreaOffset, DropScrollDirection, DropScrollEnhanceTimingFunctionGroup, DropScrollOrientation, DropScrollSpeed, DropScrollSpeedFunction, DropScrollTriggerEdge } from './drop-scroll-enhance.type'; @Directive({ selector: '[dDropScrollEnhanced]', exportAs: 'dDropScrollEnhanced' }) export class DropScrollEnhancedDirective implements AfterViewInit, OnDestroy { @Input() minSpeed: DropScrollSpeed = 50; @Input() maxSpeed: DropScrollSpeed = 1000; @Input() responseEdgeWidth: string | ((total: number) => string) = '100px'; @Input() speedFn: DropScrollSpeedFunction = DropScrollEnhanceTimingFunctionGroup.default; @Input() direction: DropScrollDirection = 'v'; @Input() viewOffset: { forward?: DropScrollAreaOffset; // 仅重要边和次要边有效 backward?: DropScrollAreaOffset; }; @Input() dropScrollScope: string | Array<string>; @Input() backSpaceDroppable = true; private forwardScrollArea: HTMLElement; private backwardScrollArea: HTMLElement; private subscription: Subscription = new Subscription(); private forwardScrollFn: (event: DragEvent) => void; private backwardScrollFn: (event: DragEvent) => void; private lastScrollTime; private animationFrameId: number; document: Document; constructor(private el: ElementRef, private zone: NgZone, private dragDropService: DragDropService, @Inject(DOCUMENT) private doc: any) { this.document = this.doc; } ngAfterViewInit() { // 设置父元素 this.el.nativeElement.parentNode.style.position = 'relative'; this.el.nativeElement.parentNode.style.display = 'block'; // 创建后退前进区域和对应的滚动函数 this.forwardScrollArea = this.createScrollArea(this.direction, DropScrollOrientation.forward); this.backwardScrollArea = this.createScrollArea(this.direction, DropScrollOrientation.backward); this.forwardScrollFn = this.createScrollFn(this.direction, DropScrollOrientation.forward, this.speedFn); this.backwardScrollFn = this.createScrollFn(this.direction, DropScrollOrientation.backward, this.speedFn); this.zone.runOutsideAngular(() => { // 拖拽到其上触发滚动 this.subscription.add(fromEvent<DragEvent>(this.forwardScrollArea, 'dragover') .pipe( tap(event => {event.preventDefault(); event.stopPropagation(); }), throttleTime(100, undefined, {leading: true, trailing: false}) ).subscribe(event => this.forwardScrollFn(event))); this.subscription.add(fromEvent<DragEvent>(this.backwardScrollArea, 'dragover') .pipe( tap(event => {event.preventDefault(); event.stopPropagation(); }), throttleTime(100, undefined, {leading: true, trailing: false})) .subscribe(event => this.backwardScrollFn(event))); // 拖拽放置委托 this.subscription.add( mergeStatic( fromEvent<DragEvent>(this.forwardScrollArea, 'drop'), fromEvent<DragEvent>(this.backwardScrollArea, 'drop') ).subscribe(event => this.delegateDropEvent(event))); // 拖拽离开清除参数 this.subscription.add( mergeStatic( fromEvent(this.forwardScrollArea, 'dragleave', {passive: true}), fromEvent(this.backwardScrollArea, 'dragleave', {passive: true}) ).subscribe(event => this.cleanLastScrollTime()) ); // 滚动过程计算区域有效性,滚动条贴到边缘的时候无效,无效的时候设置鼠标事件可用为none this.subscription.add( fromEvent(this.el.nativeElement, 'scroll', {passive: true}) .pipe(throttleTime(300, undefined, {leading: true, trailing: true})) .subscribe(event => { this.toggleScrollToOneEnd(this.el.nativeElement, this.forwardScrollArea, this.direction, DropScrollOrientation.forward); this.toggleScrollToOneEnd(this.el.nativeElement, this.backwardScrollArea, this.direction, DropScrollOrientation.backward); }) ); // 窗口缩放的时候重绘有效性区域 this.subscription.add( fromEvent(window, 'resize', {passive: true}) .pipe(throttleTime(300, undefined, {leading: true, trailing: true})) .subscribe(event => this.resizeArea()) ); // dragstart的时候显示拖拽滚动边缘面板 this.subscription.add( this.dragDropService.dragStartEvent.subscribe(() => { if (!this.allowScroll()) {return; } this.zone.runOutsideAngular(() => { setTimeout(() => { // 立马出现会打断边缘元素的拖拽 this.forwardScrollArea.style.display = 'block'; this.backwardScrollArea.style.display = 'block'; }); }); }) ); // dragEnd或drop的时候结束了拖拽,滚动区域影藏起来 this.subscription.add( mergeStatic(this.dragDropService.dragEndEvent, this.dragDropService.dropEvent) .subscribe(() => { this.forwardScrollArea.style.display = 'none'; this.backwardScrollArea.style.display = 'none'; this.lastScrollTime = undefined; }) ); }); setTimeout(() => { this.resizeArea(); }, 0); } ngOnDestroy() { this.subscription.unsubscribe(); } createScrollFn(direction: DropScrollDirection, orientation: DropScrollOrientation, speedFn: DropScrollSpeedFunction) { if (typeof window === 'undefined') { return; } const scrollAttr = (direction === 'v') ? 'scrollTop' : 'scrollLeft'; const eventAttr = (direction === 'v') ? 'clientY' : 'clientX'; const scrollWidthAttr = (direction === 'v') ? 'scrollHeight' : 'scrollWidth'; const offsetWidthAttr = (direction === 'v') ? 'offsetHeight' : 'offsetWidth'; const clientWidthAttr = (direction === 'v') ? 'clientHeight' : 'clientWidth'; const rectWidthAttr = (direction === 'v') ? 'height' : 'width'; const compareTarget = (orientation === DropScrollOrientation.forward) ? this.forwardScrollArea : this.backwardScrollArea; const targetAttr = this.getCriticalEdge(direction, orientation); const scrollElement = this.el.nativeElement; return (event: DragEvent) => { const compareTargetRect = compareTarget.getBoundingClientRect(); const distance = event[eventAttr] - compareTargetRect[targetAttr]; let speed = speedFn(Math.abs(distance / (compareTargetRect[rectWidthAttr] || 1))); if (speed < this.minSpeed) { speed = this.minSpeed; } if (speed > this.maxSpeed) { speed = this.maxSpeed; } if (distance < 0) { speed = - speed; } if (this.animationFrameId) { window.cancelAnimationFrame(this.animationFrameId); this.animationFrameId = undefined; } this.animationFrameId = requestAnimationFrame(() => { const time = new Date().getTime(); const moveDistance = Math.ceil(speed * (time - (this.lastScrollTime || time)) / 1000); scrollElement[scrollAttr] -= moveDistance; this.lastScrollTime = time; // 判断是不是到尽头 if ((scrollElement[scrollAttr] === 0 && orientation === DropScrollOrientation.backward) || ((scrollElement[scrollAttr] + (scrollElement.getBoundingClientRect())[rectWidthAttr] - scrollElement[offsetWidthAttr] + scrollElement[clientWidthAttr] ) === scrollElement[scrollWidthAttr] && orientation === DropScrollOrientation.forward) ) { compareTarget.style.pointerEvents = 'none'; this.toggleActiveClass(compareTarget, false); } this.animationFrameId = undefined; }); if (this.backSpaceDroppable) { Utils.dispatchEventToUnderElement(event); } }; } delegateDropEvent(event: DragEvent) { if (this.backSpaceDroppable) { const ev = Utils.dispatchEventToUnderElement(event); if (ev.defaultPrevented) { event.preventDefault(); event.stopPropagation(); } } } getCriticalEdge(direction: DropScrollDirection, orientation: DropScrollOrientation): DropScrollTriggerEdge { return (direction === 'v' && orientation === DropScrollOrientation.forward && 'bottom') || (direction === 'v' && orientation === DropScrollOrientation.backward && 'top') || (direction !== 'v' && orientation === DropScrollOrientation.forward && 'right') || (direction !== 'v' && orientation === DropScrollOrientation.backward && 'left') || 'bottom'; } getSecondEdge(direction: DropScrollDirection): DropScrollTriggerEdge { return (direction === 'v' && 'left') || (direction !== 'v' && 'top') || 'left'; } createScrollArea(direction: DropScrollDirection, orientation: DropScrollOrientation) { const area = this.document.createElement('div'); area.className = 'dropover-scroll-area ' + 'dropover-scroll-area-' + this.getCriticalEdge(direction, orientation); // 处理大小 area.classList.add('active'); this.setAreaSize(area, direction, orientation); // 处理位置 area.style.position = 'absolute'; this.setAreaStyleLayout(area, direction, orientation); // 默认不展示 area.style.display = 'none'; // 附着元素 this.el.nativeElement.parentNode.appendChild(area, this.el.nativeElement); return area; } setAreaSize(area: HTMLElement, direction: DropScrollDirection, orientation: DropScrollOrientation) { const rect = this.el.nativeElement.getBoundingClientRect(); const containerAttr = direction === 'v' ? 'height' : 'width'; const responseEdgeWidth = (typeof this.responseEdgeWidth === 'string') ? this.responseEdgeWidth : this.responseEdgeWidth(rect[containerAttr]); const settingOffset = this.viewOffset && (orientation === DropScrollOrientation.forward ? this.viewOffset.forward : this.viewOffset.backward); let width = direction === 'v' ? (rect.width + 'px') : responseEdgeWidth; let height = direction === 'v' ? responseEdgeWidth : (rect.height + 'px'); if (settingOffset) { if (settingOffset.widthOffset) { width = 'calc(' + width + ' + ' + (settingOffset.widthOffset) + 'px)'; } if (settingOffset.heightOffset) { height = 'calc(' + height + ' + ' + (settingOffset.heightOffset) + 'px)'; } } area.style.width = width; area.style.height = height; } setAreaStyleLayout (area: HTMLElement, direction: DropScrollDirection, orientation: DropScrollOrientation) { const target = this.el.nativeElement; const relatedTarget = this.el.nativeElement.parentNode; const defaultOffset = {left: 0, right: 0, top: 0, bottom: 0}; const settingOffset = this.viewOffset && (orientation === DropScrollOrientation.forward ? this.viewOffset.forward : this.viewOffset.backward) || defaultOffset; const criticalEdge = this.getCriticalEdge(direction, orientation); const secondEdge = this.getSecondEdge(direction); [criticalEdge, secondEdge].forEach(edge => { area.style[edge] = this.getRelatedPosition(target, relatedTarget, edge, settingOffset[edge]); }); } getRelatedPosition(target, relatedTarget, edge: DropScrollTriggerEdge, offsetValue?: number) { if (typeof window === 'undefined') { return '0px'; } const relatedComputedStyle = window.getComputedStyle(relatedTarget); const relatedRect = relatedTarget.getBoundingClientRect(); const selfRect = target.getBoundingClientRect(); const helper = { left: ['left', 'Left'], right: ['right', 'Right'], top: ['top', 'Top'], bottom: ['bottom', 'Bottom'], }; let factor = 1; if (edge === 'right' || edge === 'bottom') { factor = -1; } return (selfRect[helper[edge][0]] - relatedRect[helper[edge][0]] + parseInt(relatedComputedStyle['border' + helper[edge][1] + 'Width'], 10)) * factor + (offsetValue || 0) + 'px'; } resizeArea() { [{area: this.forwardScrollArea, orientation: DropScrollOrientation.forward}, {area: this.backwardScrollArea, orientation: DropScrollOrientation.backward} ] .forEach(item => { this.setAreaSize(item.area, this.direction, item.orientation); this.setAreaStyleLayout(item.area, this.direction, item.orientation); }); } toggleScrollToOneEnd(scrollElement: any, toggleElement: HTMLElement, direction: DropScrollDirection, orientation: DropScrollOrientation) { const scrollAttr = (direction === 'v') ? 'scrollTop' : 'scrollLeft'; const scrollWidthAttr = (direction === 'v') ? 'scrollHeight' : 'scrollWidth'; const offsetWidthAttr = (direction === 'v') ? 'offsetHeight' : 'offsetWidth'; const clientWidthAttr = (direction === 'v') ? 'clientHeight' : 'clientWidth'; const rectWidthAttr = (direction === 'v') ? 'height' : 'width'; if ((scrollElement[scrollAttr] === 0 && orientation === DropScrollOrientation.backward) || ( Math.abs( scrollElement[scrollAttr] + (scrollElement.getBoundingClientRect())[rectWidthAttr] - scrollElement[scrollWidthAttr] - scrollElement[offsetWidthAttr] + scrollElement[clientWidthAttr] ) < 1 && orientation === DropScrollOrientation.forward )) { toggleElement.style.pointerEvents = 'none'; this.toggleActiveClass(toggleElement, false); } else { toggleElement.style.pointerEvents = 'auto'; this.toggleActiveClass(toggleElement, true); } } cleanLastScrollTime() { if (this.animationFrameId && typeof window !== 'undefined') { window.cancelAnimationFrame(this.animationFrameId); this.animationFrameId = undefined; } this.lastScrollTime = undefined; } toggleActiveClass(target, active) { if (active) { target.classList.remove('inactive'); target.classList.add('active'); } else { target.classList.remove('active'); target.classList.add('inactive'); } } allowScroll(): boolean { if (!this.dropScrollScope) { return true; } let allowed = false; if (typeof this.dropScrollScope === 'string') { if (typeof this.dragDropService.scope === 'string') { allowed = this.dragDropService.scope === this.dropScrollScope; } if (this.dragDropService.scope instanceof Array) { allowed = this.dragDropService.scope.indexOf(this.dropScrollScope) > -1; } } if (this.dropScrollScope instanceof Array) { if (typeof this.dragDropService.scope === 'string') { allowed = this.dropScrollScope.indexOf(this.dragDropService.scope) > -1; } if (this.dragDropService.scope instanceof Array) { allowed = this.dropScrollScope.filter((item) => { return this.dragDropService.scope.indexOf(item) !== -1; }).length > 0; } } return allowed; } }
the_stack
import { Param, Returns, Transaction } from 'fabric-contract-api'; import { Roles } from '../../constants'; import { EventType, HistoricOrder, IVehicleDetails, Order, OrderStatus, Policy, PolicyType, UsageEvent, Vehicle, VehicleStatus } from '../assets'; // tslint:disable-line:max-line-length import { IOptions } from '../assets/options'; import { Insurer, Manufacturer } from '../organizations'; import { VehicleManufactureNetContext } from '../utils/context'; import { generateId } from '../utils/functions'; import { BaseContract } from './base'; export class VehicleContract extends BaseContract { constructor() { super('vehicles'); } @Transaction() @Returns('Order') public async placeOrder( ctx: VehicleManufactureNetContext, ordererId: string, vehicleDetails: IVehicleDetails, options: IOptions, ): Promise<Order> { const { participant } = ctx.clientIdentity; if (!participant.hasRole(Roles.ORDER_CREATE)) { throw new Error(`Only callers with role ${Roles.ORDER_CREATE} can place orders`); } else if (participant.orgId !== vehicleDetails.makeId) { throw new Error('Callers may only create orders in their organisation'); } const numOrders = await ctx.orderList.count(); const id = generateId(ctx.stub.getTxID(), 'ORDER_' + numOrders); const order = new Order( id, vehicleDetails, OrderStatus.PLACED, options, ordererId, (ctx.stub.getTxTimestamp().getSeconds() as any).toInt() * 1000, ); await ctx.orderList.add(order); ctx.setEvent('PLACE_ORDER', order); return order; } @Transaction(false) @Returns('Order[]') public async getOrders(ctx: VehicleManufactureNetContext): Promise<Order[]> { const { participant, organization } = ctx.clientIdentity; if (!participant.hasRole(Roles.ORDER_READ)) { throw new Error(`Only callers with role ${Roles.ORDER_READ} can read orders`); } let query = {}; if (organization instanceof Manufacturer) { query = { selector: { vehicleDetails: { makeId: organization.id } } }; } return await ctx.orderList.query(query); } @Transaction(false) @Returns('Order') public async getOrder(ctx: VehicleManufactureNetContext, orderId: string): Promise<Order> { const { participant, organization } = ctx.clientIdentity; if (!participant.hasRole(Roles.ORDER_READ)) { throw new Error(`Only callers with role ${Roles.ORDER_READ} can read orders`); } const order = await ctx.orderList.get(orderId); if (organization instanceof Manufacturer && !order.madeByOrg(participant.orgId)) { throw new Error( 'Manufacturers may only read an order made by their organisation', ); } return order; } @Transaction(false) @Returns('HistoricOrder[]') public async getOrderHistory( ctx: VehicleManufactureNetContext, orderId: string, ): Promise<HistoricOrder[]> { await this.getOrder(ctx, orderId); // will error if no order, or user cannot access const history = await ctx.orderList.getHistory(orderId); return history; } @Transaction() @Returns('Order') public async scheduleOrderForManufacture(ctx: VehicleManufactureNetContext, orderId: string): Promise<Order> { const { participant } = ctx.clientIdentity; if (!participant.hasRole(Roles.ORDER_UPDATE)) { throw new Error(`Only callers with role ${Roles.ORDER_UPDATE} can schedule orders for manufacture`); } const order = await ctx.orderList.get(orderId); if (!order.madeByOrg(participant.orgId)) { throw new Error('Callers may only schedule an order in their organisation for manufacture'); } order.orderStatus = OrderStatus.SCHEDULED_FOR_MANUFACTURE; await ctx.orderList.update(order); ctx.setEvent('UPDATE_ORDER', order); return order; } @Transaction() @Returns('Order') public async registerVehicleForOrder( ctx: VehicleManufactureNetContext, orderId: string, vin: string, ): Promise<Order> { const {participant, organization} = ctx.clientIdentity; if ( !participant.hasRole(Roles.ORDER_UPDATE) || !participant.hasRole(Roles.VEHICLE_CREATE) ) { throw new Error( `Only callers with roles ${Roles.ORDER_UPDATE} and ${Roles.VEHICLE_CREATE} can register vehicles for orders` // tslint:disable-line ); } else if (!(organization as Manufacturer).originCode || !(organization as Manufacturer).manufacturerCode) { throw new Error( 'Manufacturer\'s origin and manufacturer code must be set before vehicles can be registered', ); } const order = await ctx.orderList.get(orderId); if (!order.madeByOrg(participant.orgId)) { throw new Error('Callers may only register a vehicle for an order in their organisation'); } const year = new Date((ctx.stub.getTxTimestamp().getSeconds() as any).toInt() * 1000).getFullYear(); if (!Vehicle.validateVin(vin, organization as Manufacturer, year)) { throw new Error('Invalid VIN supplied'); } order.orderStatus = OrderStatus.VIN_ASSIGNED; order.vin = vin; await ctx.orderList.update(order); const vehicle = new Vehicle( vin, order.vehicleDetails, VehicleStatus.OFF_THE_ROAD, (ctx.stub.getTxTimestamp().getSeconds() as any).toInt() * 1000, ); await ctx.vehicleList.add(vehicle); ctx.setEvent('UPDATE_ORDER', order); return order; } @Transaction() @Returns('Order') public async assignOwnershipForOrder(ctx: VehicleManufactureNetContext, orderId: string): Promise<Order> { const { participant } = ctx.clientIdentity; if ( !participant.hasRole(Roles.ORDER_UPDATE) || !participant.hasRole(Roles.VEHICLE_UPDATE) ) { throw new Error( `Only callers with roles ${Roles.ORDER_UPDATE} and ${Roles.VEHICLE_UPDATE} can assign ownership of vehicles of orders` // tslint:disable-line ); } const order = await ctx.orderList.get(orderId); if (!order.madeByOrg(participant.orgId)) { throw new Error('Callers may only assign an owner for a vehicle of an order in their organisation'); } order.orderStatus = OrderStatus.OWNER_ASSIGNED; await ctx.orderList.update(order); const vehicle = await ctx.vehicleList.get(order.vin); vehicle.ownerId = order.ordererId; await ctx.vehicleList.update(vehicle); ctx.setEvent('UPDATE_ORDER', order); return order; } @Transaction() @Returns('Order') public async deliverOrder(ctx: VehicleManufactureNetContext, orderId: string): Promise<Order> { const { participant } = ctx.clientIdentity; if (!participant.hasRole(Roles.ORDER_UPDATE)) { throw new Error(`Only callers with role ${Roles.ORDER_UPDATE} can deliver orders`); } const order = await ctx.orderList.get(orderId); if (!order.madeByOrg(participant.orgId)) { throw new Error('Callers may only deliver an order in their organisation'); } order.orderStatus = OrderStatus.DELIVERED; await ctx.orderList.update(order); const vehicle = await ctx.vehicleList.get(order.vin); vehicle.ownerId = order.ordererId; vehicle.vehicleStatus = VehicleStatus.ACTIVE; await ctx.vehicleList.update(vehicle); ctx.setEvent('UPDATE_ORDER', order); return order; } @Transaction(false) @Returns('Vehicle[]') public async getVehicles(ctx: VehicleManufactureNetContext): Promise<Vehicle[]> { const {participant, organization} = ctx.clientIdentity; if (!participant.hasRole(Roles.VEHICLE_READ)) { throw new Error(`Only callers with role ${Roles.VEHICLE_READ} can get vehicles`); } let query = {}; if (organization instanceof Manufacturer) { query = { selector: { vehicleDetails: { makeId: organization.id } } }; } else if (organization instanceof Insurer) { query = { selector: { id: { $in: (await this.getPolicies(ctx)).map((policy) => policy.vin ) } } }; } const vehicles = await ctx.vehicleList.query(query); return vehicles; } @Transaction(false) @Returns('Vehicle') public async getVehicle(ctx: VehicleManufactureNetContext, vin: string): Promise<Vehicle> { const { participant, organization } = ctx.clientIdentity; if (!participant.hasRole(Roles.VEHICLE_READ)) { throw new Error(`Only callers with role ${Roles.VEHICLE_READ} can get vehicles`); } const vehicle = await ctx.vehicleList.get(vin); if (organization instanceof Manufacturer && !vehicle.madeByOrg(participant.orgId)) { throw new Error('Manufacturers may only get a vehicle produced by their organisation'); } // DON'T LIMIT THE INSURER AS WHEN GIVEN A VIN AS PART OF A REQUEST THEY NEED TO SEE THE CAR // REMEMBER READ ACCESS CONTROL IN HERE IS JUST AS ITS USEFUL TO THE ORGANISATION IT LIMITS. // THEY COULD GET FULL DATA IF THEY WISH AS NO DATA IS PRIVATE return vehicle; } @Transaction() @Param('endDate', 'number', 'end date as timestamp in seconds') @Returns('Policy') public async createPolicy( ctx: VehicleManufactureNetContext, vin: string, holderId: string, policyType: PolicyType, endDate: number, ): Promise<Policy> { const { participant } = ctx.clientIdentity; if (!participant.hasRole(Roles.POLICY_CREATE)) { throw new Error(`Only callers with role ${Roles.POLICY_CREATE} can create policies`); } const vehicle = await ctx.vehicleList.get(vin); if (vehicle.vehicleStatus !== VehicleStatus.ACTIVE) { throw new Error('Cannot insure vehicle which is not active'); } const numPolicies = await ctx.policyList.count(); const id = generateId(ctx.stub.getTxID(), 'POLICY_' + numPolicies); const startDate = (ctx.stub.getTxTimestamp().getSeconds() as any).toInt() * 1000; const policy = new Policy(id, vin, participant.orgId, holderId, policyType, startDate, endDate); await ctx.policyList.add(policy); ctx.setEvent('CREATE_POLICY', policy); return policy; } @Transaction(false) @Returns('Policy[]') public async getPolicies(ctx: VehicleManufactureNetContext) { const { participant, organization } = ctx.clientIdentity; if (!participant.hasRole(Roles.POLICY_READ)) { throw new Error(`Only callers with role ${Roles.POLICY_READ} can read policies`); } let query = {}; if (organization instanceof Insurer) { query = { selector: { insurerId: organization.id } }; } const policies = await ctx.policyList.query(query); return policies; } @Transaction(false) @Returns('Policy') public async getPolicy(ctx: VehicleManufactureNetContext, policyId: string): Promise<Policy> { const {participant, organization} = ctx.clientIdentity; if (!participant.hasRole(Roles.POLICY_READ)) { throw new Error(`Only callers with role ${Roles.POLICY_READ} can read policies`); } const policy = await ctx.policyList.get(policyId); if (organization instanceof Insurer && policy.insurerId !== organization.id) { throw new Error('Only insurers who insure the policy can view it'); } return policy; } @Transaction() @Returns('UsageEvent') public async addUsageEvent( ctx: VehicleManufactureNetContext, vin: string, eventType: EventType, acceleration: number, airTemperature: number, engineTemperature: number, lightLevel: number, pitch: number, roll: number, ): Promise<UsageEvent> { const { participant } = ctx.clientIdentity; if (!participant.hasRole(Roles.USAGE_EVENT_CREATE)) { throw new Error(`Only callers with role ${Roles.USAGE_EVENT_CREATE} can add usage events`); } await this.getVehicle(ctx, vin); const id = generateId(ctx.stub.getTxID(), eventType.toString()); const timestamp = (ctx.stub.getTxTimestamp().getSeconds() as any).toInt() * 1000; const usageEvent = new UsageEvent( id, eventType, acceleration, airTemperature, engineTemperature, lightLevel, pitch, roll, timestamp, vin, ); await ctx.usageList.add(usageEvent); ctx.setEvent('ADD_USAGE_EVENT', usageEvent); return usageEvent; } @Transaction(false) @Returns('UsageEvent[]') public async getUsageEvents(ctx: VehicleManufactureNetContext): Promise<UsageEvent[]> { const { participant} = ctx.clientIdentity; if (!participant.hasRole(Roles.USAGE_EVENT_READ)) { throw new Error(`Only callers with role ${Roles.USAGE_EVENT_READ} can get usage events`); } const vehicles = await this.getVehicles(ctx); const usageEvents: UsageEvent[][] = await Promise.all(vehicles.map((vehicle) => { return this.getVehicleEvents(ctx, vehicle.id); })); return [].concat.apply([], usageEvents); } @Transaction(false) @Returns('UsageEvent[]') public async getVehicleEvents(ctx: VehicleManufactureNetContext, vin: string): Promise<UsageEvent[]> { await this.getVehicle(ctx, vin); const { participant } = ctx.clientIdentity; if (!participant.hasRole(Roles.USAGE_EVENT_READ)) { throw new Error(`Only callers with role ${Roles.USAGE_EVENT_READ} can get usage events`); } const usageEvents = await ctx.usageList.query({selector: {vin}}); return usageEvents; } @Transaction(false) @Returns('UsageEvent[]') public async getPolicyEvents(ctx: VehicleManufactureNetContext, policyId: string): Promise<UsageEvent[]> { const policy = await this.getPolicy(ctx, policyId); await this.getVehicle(ctx, policy.vin); const { participant } = ctx.clientIdentity; if (!participant.hasRole(Roles.USAGE_EVENT_READ)) { throw new Error(`Only callers with role ${Roles.USAGE_EVENT_READ} can get usage events`); } const usageEvents = await ctx.usageList.query({ selector: {vin: policy.vin, timestamp: {$gte: policy.startDate, $lt: policy.endDate }}, }); return usageEvents; } }
the_stack
import * as React from 'react' import { ValueLine, EntityLine, EntityCombo, EntityList, EntityRepeater, EntityTabRepeater, EntityTable, EntityCheckboxList, EnumCheckboxList, EntityDetail, EntityStrip, RenderEntity, MultiValueLine, AutocompleteConfig, } from '@framework/Lines' import { ModifiableEntity, Entity, Lite, isEntity, EntityPack } from '@framework/Signum.Entities' import { classes, Dic } from '@framework/Globals' import { SubTokensOptions } from '@framework/FindOptions' import { SearchControl, ValueSearchControlLine, FindOptionsParsed, ResultTable, SearchControlLoaded } from '@framework/Search' import { TypeInfo, MemberInfo, getTypeInfo, tryGetTypeInfos, PropertyRoute, isTypeEntity, Binding, IsByAll, getAllTypes } from '@framework/Reflection' import * as AppContext from '@framework/AppContext' import * as Navigator from '@framework/Navigator' import { TypeContext, ButtonBarElement } from '@framework/TypeContext' import { EntityTableColumn } from '@framework/Lines/EntityTable' import { DynamicViewValidationMessage } from '../Signum.Entities.Dynamic' import { ExpressionOrValueComponent, FieldComponent } from './Designer' import { ExpressionOrValue, Expression, bindExpr, toCodeEx, withClassNameEx, DesignerNode } from './NodeUtils' import { FindOptionsLine, QueryTokenLine, ViewNameComponent, FetchQueryDescription } from './FindOptionsComponent' import { HtmlAttributesLine } from './HtmlAttributesComponent' import { StyleOptionsLine } from './StyleOptionsComponent' import * as NodeUtils from './NodeUtils' import { registeredCustomContexts, API } from '../DynamicViewClient' import { toFindOptions, FindOptionsExpr } from './FindOptionsExpression' import { toHtmlAttributes, HtmlAttributesExpression, withClassName } from './HtmlAttributesExpression' import { toStyleOptions, StyleOptionsExpression } from './StyleOptionsExpression' import { FileLine } from "../../Files/FileLine"; import { MultiFileLine } from "../../Files/MultiFileLine"; import { DownloadBehaviour } from "../../Files/FileDownloader"; import { registerSymbol } from "@framework/Reflection"; import { BsColor, BsSize } from '@framework/Components'; import { Tab, Tabs, Button } from 'react-bootstrap'; import { FileImageLine } from '../../Files/FileImageLine'; import { FileEntity, FilePathEntity, FileEmbedded, FilePathEmbedded } from '../../Files/Signum.Entities.Files'; import { ColorTypeahead } from '../../Basics/Templates/ColorTypeahead'; import { IconTypeahead, parseIcon } from '../../Basics/Templates/IconTypeahead'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { EntityOperationContext } from '@framework/Operations'; import { OperationButton } from '@framework/Operations/EntityOperations'; import { useAPI } from '@framework/Hooks'; import { ValueLineController } from '@framework/Lines/ValueLine' export interface BaseNode { ref?: Expression<any>; kind: string; visible?: ExpressionOrValue<boolean>; } export interface ContainerNode extends BaseNode { children: BaseNode[] } export interface DivNode extends ContainerNode { kind: "Div", field?: string; styleOptions?: StyleOptionsExpression; htmlAttributes?: HtmlAttributesExpression; } NodeUtils.register<DivNode>({ kind: "Div", group: "Container", order: 0, isContainer: true, renderTreeNode: NodeUtils.treeNodeKind, renderCode: (node, cc) => cc.elementCodeWithChildrenSubCtx("div", node.htmlAttributes, node), render: (dn, parentCtx) => NodeUtils.withChildrensSubCtx(dn, parentCtx, <div {...toHtmlAttributes(dn, parentCtx, dn.node.htmlAttributes)} />), renderDesigner: dn => (<div> <FieldComponent dn={dn} binding={Binding.create(dn.node, n => n.field)} /> <StyleOptionsLine dn={dn} binding={Binding.create(dn.node, n => n.styleOptions)} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.htmlAttributes)} /> </div>), }); export interface RowNode extends ContainerNode { kind: "Row", field?: string; styleOptions?: StyleOptionsExpression; htmlAttributes?: HtmlAttributesExpression; } NodeUtils.register<RowNode>({ kind: "Row", group: "Container", order: 1, isContainer: true, validChild: "Column", renderTreeNode: NodeUtils.treeNodeKind, validate: (dn, parentCtx) => parentCtx && dn.node.children.filter(c => c.kind == "Column").map(col => (NodeUtils.evaluate(dn, parentCtx, col, f => (f as ColumnNode).width) ?? 0) + (NodeUtils.evaluate(dn, parentCtx, col, f => (f as ColumnNode).offset) ?? 0) ).sum() > 12 ? "Sum of Column.width/offset should <= 12" : null, renderCode: (node, cc) => cc.elementCodeWithChildrenSubCtx("div", withClassNameEx(node.htmlAttributes, "row"), node), render: (dn, parentCtx) => NodeUtils.withChildrensSubCtx(dn, parentCtx, <div {...withClassName(toHtmlAttributes(dn, parentCtx, dn.node.htmlAttributes), "row")} />), renderDesigner: dn => (<div> <FieldComponent dn={dn} binding={Binding.create(dn.node, n => n.field)} /> <StyleOptionsLine dn={dn} binding={Binding.create(dn.node, n => n.styleOptions)} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.htmlAttributes)} /> </div>), }); export interface ColumnNode extends ContainerNode { kind: "Column"; field?: string; styleOptions?: StyleOptionsExpression; htmlAttributes?: HtmlAttributesExpression; width: ExpressionOrValue<number>; offset: ExpressionOrValue<number>; } NodeUtils.register<ColumnNode>({ kind: "Column", group: null, order: null, isContainer: true, avoidHighlight: true, validParent: "Row", validate: dn => NodeUtils.mandatory(dn, n => n.width), initialize: dn => dn.width = 6, renderTreeNode: NodeUtils.treeNodeKind, renderCode: (node, cc) => { const className = node.offset == null ? bindExpr(column => "col-sm-" + column, node.width) : bindExpr((column, offset) => classes("col-sm-" + column, offset != undefined && "col-sm-offset-" + offset), node.width, node.offset); return cc.elementCodeWithChildrenSubCtx("div", withClassNameEx(node.htmlAttributes, className), node); }, render: (dn, parentCtx) => { const column = NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.width, NodeUtils.isNumber); const offset = NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.offset, NodeUtils.isNumberOrNull); const className = classes("col-sm-" + column, offset != undefined && "col-sm-offset-" + offset) return NodeUtils.withChildrensSubCtx(dn, parentCtx, <div {...withClassName(toHtmlAttributes(dn, parentCtx, dn.node.htmlAttributes), className)} />); }, renderDesigner: (dn) => (<div> <FieldComponent dn={dn} binding={Binding.create(dn.node, n => n.field)} /> <StyleOptionsLine dn={dn} binding={Binding.create(dn.node, n => n.styleOptions)} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.htmlAttributes)} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.width)} type="number" options={[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]} defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.offset)} type="number" options={[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]} defaultValue={null} /> </div>), }); export interface TabsNode extends ContainerNode { kind: "Tabs"; field?: string; styleOptions?: StyleOptionsExpression; id: ExpressionOrValue<string>; defaultActiveKey?: ExpressionOrValue<string>; unmountOnExit?: ExpressionOrValue<boolean>; } NodeUtils.register<TabsNode>({ kind: "Tabs", group: "Container", order: 2, isContainer: true, validChild: "Tab", initialize: dn => dn.id = "tabs", renderTreeNode: NodeUtils.treeNodeKind, renderCode: (node, cc) => cc.elementCodeWithChildrenSubCtx("Tabs", { id: { __code__: cc.ctxName + ".compose(" + toCodeEx(node.id) + ")" } as Expression<string>, defaultActiveKey: node.defaultActiveKey, unmountOnExit: node.unmountOnExit, }, node), render: (dn, parentCtx) => { return NodeUtils.withChildrensSubCtx(dn, parentCtx, <Tabs id={parentCtx.getUniqueId(NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.id, NodeUtils.isString)!)} defaultActiveKey={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.defaultActiveKey, NodeUtils.isStringOrNull)} unmountOnExit={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.unmountOnExit, NodeUtils.isBooleanOrNull)} />); }, renderDesigner: (dn) => (<div> <FieldComponent dn={dn} binding={Binding.create(dn.node, n => n.field)} /> <StyleOptionsLine dn={dn} binding={Binding.create(dn.node, n => n.styleOptions)} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.id)} type="string" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.defaultActiveKey)} type="string" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.unmountOnExit)} type="boolean" defaultValue={false} /> </div>), }); export interface TabNode extends ContainerNode { kind: "Tab"; field?: string; styleOptions?: StyleOptionsExpression; title: ExpressionOrValue<string>; eventKey: string; } NodeUtils.register<TabNode>({ kind: "Tab", group: null, order: null, isContainer: true, avoidHighlight: true, validParent: "Tabs", initialize: (n, parentNode) => { let byName = (parentNode.node.children.map(a => parseInt((a as TabNode).eventKey.tryAfter("tab") ?? "")).filter(s => isFinite(s)).max() ?? 0) + 1; let byPosition = parentNode.node.children.length + 1; let index = Math.max(byName, byPosition); n.title = "My Tab " + index; n.eventKey = "tab" + index; }, renderTreeNode: dn => <span><small>{dn.node.kind}:</small> <strong>{typeof dn.node.title == "string" ? dn.node.title : dn.node.eventKey}</strong></span>, validate: dn => NodeUtils.mandatory(dn, n => n.eventKey), renderCode: (node, cc) => cc.elementCodeWithChildrenSubCtx("Tab", { title: node.title, eventKey: node.eventKey }, node), render: (dn, parentCtx) => { return NodeUtils.withChildrensSubCtx(dn, parentCtx, <Tab title={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.title, NodeUtils.isString)} eventKey={dn.node.eventKey!} />); }, renderDesigner: (dn) => (<div> <FieldComponent dn={dn} binding={Binding.create(dn.node, n => n.field)} /> <StyleOptionsLine dn={dn} binding={Binding.create(dn.node, n => n.styleOptions)} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.eventKey)} type="string" defaultValue={null} allowsExpression={false} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.title)} type="string" defaultValue={null} /> </div>), }); export interface FieldsetNode extends ContainerNode { kind: "Fieldset"; field?: string; styleOptions?: StyleOptionsExpression; htmlAttributes?: HtmlAttributesExpression; legendHtmlAttributes?: HtmlAttributesExpression; legend?: ExpressionOrValue<string>; } NodeUtils.register<FieldsetNode>({ kind: "Fieldset", group: "Container", order: 3, isContainer: true, initialize: dn => dn.legend = "My Fieldset", renderTreeNode: NodeUtils.treeNodeKind, renderCode: (node, cc) => cc.elementCode("fieldset", node.htmlAttributes, node.legend && cc.elementCode("legend", node.legendHtmlAttributes, toCodeEx(node.legend)), cc.elementCodeWithChildrenSubCtx("div", null, node) ), render: (dn, parentCtx) => { return ( <fieldset {...toHtmlAttributes(dn, parentCtx, dn.node.htmlAttributes)}> {dn.node.legend && <legend {...toHtmlAttributes(dn, parentCtx, dn.node.legendHtmlAttributes)}> {NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.legend, NodeUtils.isStringOrNull)} </legend>} {NodeUtils.withChildrensSubCtx(dn, parentCtx, <div />)} </fieldset> ) }, renderDesigner: (dn) => (<div> <FieldComponent dn={dn} binding={Binding.create(dn.node, n => n.field)} /> <StyleOptionsLine dn={dn} binding={Binding.create(dn.node, n => n.styleOptions)} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.htmlAttributes)} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.legend)} type="string" defaultValue={null} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.legendHtmlAttributes)} /> </div>), }); export interface TextNode extends BaseNode { kind: "Text", htmlAttributes?: HtmlAttributesExpression; breakLines?: ExpressionOrValue<boolean> tagName?: ExpressionOrValue<string>; message: ExpressionOrValue<string>; } NodeUtils.register<TextNode>({ kind: "Text", group: "Container", order: 4, initialize: dn => { dn.message = "My message"; }, renderTreeNode: dn => <span><small>{dn.node.kind}:</small> <strong>{dn.node.message ? (typeof dn.node.message == "string" ? dn.node.message : (dn.node.message.__code__ ?? "")).etc(20) : ""}</strong></span>, renderCode: (node, cc) => cc.elementCode(bindExpr(tagName => tagName ?? "p", node.tagName), node.htmlAttributes, toCodeEx(node.message) ), render: (dn, ctx) => React.createElement( NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.tagName, NodeUtils.isStringOrNull) ?? "p", toHtmlAttributes(dn, ctx, dn.node.htmlAttributes), ...NodeUtils.addBreakLines( NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.breakLines, NodeUtils.isBooleanOrNull) || false, NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.message, NodeUtils.isString)!), ), renderDesigner: dn => (<div> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.tagName)} type="string" defaultValue={"p"} options={["p", "span", "div", "pre", "code", "strong", "em", "del", "sub", "sup", "ins", "h1", "h2", "h3", "h4", "h5"]} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.message)} type="textArea" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.breakLines)} type="boolean" defaultValue={false} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.htmlAttributes)} /> </div>), }); export interface ImageNode extends BaseNode { kind: "Image", htmlAttributes?: HtmlAttributesExpression; src?: ExpressionOrValue<string>; } NodeUtils.register<ImageNode>({ kind: "Image", group: "Container", order: 5, initialize: dn => { dn.src = "~/images/logo.png"; }, renderTreeNode: dn => <span><small>{dn.node.kind}:</small> <strong>{dn.node.src ? (typeof dn.node.src == "string" ? dn.node.src : (dn.node.src.__code__ ?? "")).etc(20) : ""}</strong></span>, renderCode: (node, cc) => cc.elementCode("img", node.htmlAttributes && { src: node.src }), render: (dn, ctx) => <img {...toHtmlAttributes(dn, ctx, dn.node.htmlAttributes)} src={AppContext.toAbsoluteUrl(NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.src, NodeUtils.isString) as string)} />, renderDesigner: dn => (<div> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.src)} type="string" defaultValue={null} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.htmlAttributes)} /> </div>), }); export interface RenderEntityNode extends ContainerNode { kind: "RenderEntity"; field?: string; viewName?: ExpressionOrValue<string | ((mod: ModifiableEntity) => string | Navigator.ViewPromise<ModifiableEntity>)>; styleOptions?: StyleOptionsExpression; onEntityLoaded?: Expression<() => void>; extraProps?: Expression<{}>; } NodeUtils.register<RenderEntityNode>({ kind: "RenderEntity", group: "Container", order: 5, isContainer: true, hasEntity: true, validate: (dn, ctx) => dn.node.field && NodeUtils.validateField(dn as DesignerNode<LineBaseNode>), renderTreeNode: dn => <span><small>{dn.node.kind}:</small> <strong>{dn.node.field || (typeof dn.node.viewName == "string" ? dn.node.viewName : "")}</strong></span>, renderCode: (node, cc) => cc.elementCode("RenderEntity", { ctx: cc.subCtxCode(node.field, node.styleOptions), getComponent: cc.getGetComponentEx(node, true), getViewName: NodeUtils.toFunctionCode(node.viewName), onEntityLoaded: node.onEntityLoaded, }), render: (dn, ctx) => { var styleOptions = toStyleOptions(dn, ctx, dn.node.styleOptions); var sctx = dn.node.field ? ctx.subCtx(dn.node.field, styleOptions) : styleOptions ? ctx.subCtx(styleOptions) : ctx; return ( <RenderEntity ctx={sctx} getComponent={NodeUtils.getGetComponent(dn)} getViewPromise={NodeUtils.toFunction(NodeUtils.evaluateAndValidate(dn, sctx, dn.node, n => n.viewName, NodeUtils.isFunctionOrStringOrNull))} onEntityLoaded={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.onEntityLoaded, NodeUtils.isFunctionOrNull)} extraProps={NodeUtils.evaluateAndValidate(dn, sctx, dn.node, n => n.extraProps, NodeUtils.isObjectOrNull)} /> ); }, renderDesigner: dn => <div> <FieldComponent dn={dn} binding={Binding.create(dn.node, n => n.field)} /> <StyleOptionsLine dn={dn} binding={Binding.create(dn.node, n => n.styleOptions)} /> <ViewNameComponent dn={dn} binding={Binding.create(dn.node, n => n.viewName)} typeName={dn.route && dn.route.typeReference().name} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.onEntityLoaded)} type={null} defaultValue={null} exampleExpression={"() => { /* do something here... */ }"} /> <ExtraPropsComponent dn={dn} /> </div>, }); function ExtraPropsComponent({ dn }: { dn: DesignerNode<RenderEntityNode> }) { const typeName = dn.route && dn.route.typeReference().name; const fixedViewName = dn.route && dn.node.viewName && typeof dn.node.viewName == "string" ? dn.node.viewName : undefined; if (typeName && fixedViewName) { const es = Navigator.getSettings(typeName); const staticViews = ["STATIC"].concat((es?.namedViews && Dic.getKeys(es.namedViews)) ?? []); if (!staticViews.contains(fixedViewName)) { const viewProps = useAPI(signal => API.getDynamicViewProps(typeName, fixedViewName), [typeName, fixedViewName]); if (viewProps && viewProps.length > 0) return <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.extraProps)} type={null} defaultValue={null} exampleExpression={"({\r\n" + viewProps!.map(p => ` ${p.name}: null`).join(', \r\n') + "\r\n})"} /> } } return <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.extraProps)} type={null} defaultValue={null} />; } export interface CustomContextNode extends ContainerNode { kind: "CustomContext", typeContext: string; } NodeUtils.register<CustomContextNode>({ kind: "CustomContext", group: "Container", order: 6, isContainer: true, validate: dn => NodeUtils.mandatory(dn, n => n.typeContext) || (!registeredCustomContexts[dn.node.typeContext] ? `${dn.node.typeContext} not found` : undefined), renderTreeNode: dn => <span><small > {dn.node.kind}:</small > <strong>{dn.node.typeContext}</strong></span >, renderCode: (node, cc) => { const ncc = registeredCustomContexts[node.typeContext].getCodeContext(cc); var childrensCode = node.children.map(c => NodeUtils.renderCode(c, ncc)); return ncc.elementCode("div", null, ...childrensCode); }, render: (dn, parentCtx) => { const nctx = registeredCustomContexts[dn.node.typeContext].getTypeContext(parentCtx); if (!nctx) return undefined; return NodeUtils.withChildrensSubCtx(dn, nctx, <div />); }, renderDesigner: dn => (<div> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.typeContext)} allowsExpression={false} type="string" options={Dic.getKeys(registeredCustomContexts)} defaultValue={null} /> </div>), }); export interface TypeIsNode extends ContainerNode { kind: "TypeIs", typeName: string; } NodeUtils.register<TypeIsNode>({ kind: "TypeIs", group: "Container", order: 7, isContainer: true, validate: dn => NodeUtils.mandatory(dn, n => n.typeName) || (!getTypeInfo(dn.node.typeName) ? `Type '${dn.node.typeName}' not found` : undefined), renderTreeNode: dn => <span><small> {dn.node.kind}:</small > <strong>{dn.node.typeName}</strong></span>, renderCode: (node, cc) => { const ncc = cc.createNewContext("ctx" + (cc.usedNames.length + 1)); cc.assignments[ncc.ctxName] = `${node.typeName}Entity.isInstanceOf(${cc.ctxName}.value) ? ${cc.ctxName}.cast(${node.typeName}) : null`; var childrensCode = node.children.map(c => NodeUtils.renderCode(c, ncc)); return "{" + ncc.ctxName + " && " + ncc.elementCode("div", null, ...childrensCode) + "}"; }, render: (dn, parentCtx) => { if (!isEntity(parentCtx.value) || parentCtx.value.Type != dn.node.typeName) return undefined; const nctx = TypeContext.root(parentCtx.value, undefined, parentCtx); return NodeUtils.withChildrensSubCtx(dn, nctx, <div />); }, renderDesigner: dn => (<div> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.typeName)} allowsExpression={false} type="string" options={getTypes(dn.route)} defaultValue={null} /> </div>), }); function getTypes(route: PropertyRoute | undefined): string[] | ((query: string) => string[]) { if (route == undefined) return []; var tr = route.typeReference(); if (tr.name == IsByAll) return autoCompleteType; var types = tryGetTypeInfos(tr); if (types.length == 0 || types[0] == undefined) return []; return types.map(a => a!.name); } function autoCompleteType(query: string): string[] { return getAllTypes() .filter(ti => ti.kind == "Entity" && ti.name.toLowerCase().contains(query.toLowerCase())) .map(a => a.name) .orderBy(a => a.length) .filter((k, i) => i < 5); } export interface LineBaseNode extends BaseNode { labelText?: ExpressionOrValue<string>; field: string; styleOptions?: StyleOptionsExpression; readOnly?: ExpressionOrValue<boolean>; onChange?: Expression<() => void>; labelHtmlAttributes?: HtmlAttributesExpression; formGroupHtmlAttributes?: HtmlAttributesExpression; mandatory?: ExpressionOrValue<boolean>; } export interface ValueLineNode extends LineBaseNode { kind: "ValueLine", textArea?: ExpressionOrValue<string>; unitText?: ExpressionOrValue<string>; formatText?: ExpressionOrValue<string>; autoTrim?: ExpressionOrValue<boolean>; inlineCheckbox?: ExpressionOrValue<boolean>; valueHtmlAttributes?: HtmlAttributesExpression; comboBoxItems?: Expression<string[]>; } NodeUtils.register<ValueLineNode>({ kind: "ValueLine", group: "Property", order: -1, validate: (dn) => NodeUtils.validateFieldMandatory(dn), renderTreeNode: NodeUtils.treeNodeKindField, renderCode: (node, cc) => cc.elementCode("ValueLine", { ref: node.ref, ctx: cc.subCtxCode(node.field, node.styleOptions), labelText: node.labelText, labelHtmlAttributes: node.labelHtmlAttributes, formGroupHtmlAttributes: node.formGroupHtmlAttributes, valueHtmlAttributes: node.valueHtmlAttributes, unitText: node.unitText, formatText: node.formatText, readOnly: node.readOnly, mandatory: node.mandatory, inlineCheckbox: node.inlineCheckbox, valueLineType: node.textArea && bindExpr(ta => ta ? "TextArea" : undefined, node.textArea), comboBoxItems: node.comboBoxItems, autoTrim: node.autoTrim, onChange: node.onChange }), render: (dn, ctx) => (<ValueLine //ref={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.ref, NodeUtils.isObjectOrFunctionOrNull)} ctx={ctx.subCtx(dn.node.field, toStyleOptions(dn, ctx, dn.node.styleOptions))} labelText={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.labelText, NodeUtils.isStringOrNull)} labelHtmlAttributes={toHtmlAttributes(dn, ctx, dn.node.labelHtmlAttributes)} formGroupHtmlAttributes={toHtmlAttributes(dn, ctx, dn.node.formGroupHtmlAttributes)} valueHtmlAttributes={toHtmlAttributes(dn, ctx, dn.node.valueHtmlAttributes)} unitText={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.unitText, NodeUtils.isStringOrNull)} formatText={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.formatText, NodeUtils.isStringOrNull)} readOnly={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.readOnly, NodeUtils.isBooleanOrNull)} mandatory={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.mandatory, NodeUtils.isBooleanOrNull)} inlineCheckbox={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.inlineCheckbox, NodeUtils.isBooleanOrNull)} valueLineType={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.textArea, NodeUtils.isBooleanOrNull) ? "TextArea" : undefined} optionItems={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.comboBoxItems, NodeUtils.isArrayOrNull)} autoFixString={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.autoTrim, NodeUtils.isBooleanOrNull)} onChange={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.onChange, NodeUtils.isFunctionOrNull)} />), renderDesigner: (dn) => { const m = dn.route && dn.route.member; return (<div> {/*<ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.ref)} type={null} defaultValue={true} />*/} <FieldComponent dn={dn} binding={Binding.create(dn.node, n => n.field)} /> <StyleOptionsLine dn={dn} binding={Binding.create(dn.node, n => n.styleOptions)} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.labelText)} type="string" defaultValue={m?.niceName ?? ""} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.labelHtmlAttributes)} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.formGroupHtmlAttributes)} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.valueHtmlAttributes)} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.unitText)} type="string" defaultValue={m?.unit ?? ""} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.formatText)} type="string" defaultValue={m?.format ?? ""} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.readOnly)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.mandatory)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.inlineCheckbox)} type="boolean" defaultValue={false} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.textArea)} type="boolean" defaultValue={false} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.comboBoxItems)} type={null} defaultValue={null} exampleExpression={`["item1", ...]`} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.autoTrim)} type="boolean" defaultValue={true} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.onChange)} type={null} defaultValue={false} exampleExpression={"/* you must declare 'forceUpdate' in locals */ \r\n() => locals.forceUpdate()"} /> </div>) }, }); export interface MultiValueLineNode extends LineBaseNode { kind: "MultiValueLine", onRenderItem?: ExpressionOrValue<(ctx: TypeContext<any>) => React.ReactElement<any>>; onCreate?: ExpressionOrValue<() => Promise<any[] | any | undefined>>; addValueText?: ExpressionOrValue<string>; } NodeUtils.register<MultiValueLineNode>({ kind: "MultiValueLine", group: "Property", hasCollection: true, hasEntity: false, order: 0, validate: (dn) => NodeUtils.validateFieldMandatory(dn), renderTreeNode: NodeUtils.treeNodeKindField, renderCode: (node, cc) => cc.elementCode("MultiValueLine", { ref: node.ref, ctx: cc.subCtxCode(node.field, node.styleOptions), onRenderItem: node.onRenderItem, onCreate: node.onCreate, addValueText: node.addValueText, labelText: node.labelText, labelHtmlAttributes: node.labelHtmlAttributes, formGroupHtmlAttributes: node.formGroupHtmlAttributes, readOnly: node.readOnly, onChange: node.onChange, }), render: (dn, ctx) => ( <MultiValueLine //ref={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.ref, NodeUtils.isObjectOrFunctionOrNull)} ctx={ctx.subCtx(dn.node.field, toStyleOptions(dn, ctx, dn.node.styleOptions))} onRenderItem={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.onRenderItem, NodeUtils.isFunctionOrNull)} onCreate={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.onCreate, NodeUtils.isFunctionOrNull)} addValueText={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.addValueText, NodeUtils.isStringOrNull)} labelText={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.labelText, NodeUtils.isStringOrNull)} labelHtmlAttributes={toHtmlAttributes(dn, ctx, dn.node.labelHtmlAttributes)} formGroupHtmlAttributes={toHtmlAttributes(dn, ctx, dn.node.formGroupHtmlAttributes)} readOnly={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.readOnly, NodeUtils.isBooleanOrNull)} onChange={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.onChange, NodeUtils.isFunctionOrNull)} /> ), renderDesigner: (dn) => { const m = dn.route && dn.route.member; return (<div> {/*<ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.ref)} type={null} defaultValue={true} />*/} <FieldComponent dn={dn} binding={Binding.create(dn.node, n => n.field)} /> <StyleOptionsLine dn={dn} binding={Binding.create(dn.node, n => n.styleOptions)} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.onRenderItem)} type={null} defaultValue={null} exampleExpression={"mctx => modules.React.createElement(ValueLine, {ctx: mctx})"} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.onCreate)} type={null} defaultValue={null} exampleExpression={"() => Promise.resolve(null)"} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.addValueText)} type="string" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.labelText)} type="string" defaultValue={m?.niceName ?? ""} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.labelHtmlAttributes)} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.formGroupHtmlAttributes)} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.readOnly)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.onChange)} type={null} defaultValue={false} exampleExpression={"/* you must declare 'forceUpdate' in locals */ \r\n() => locals.forceUpdate()"} /> </div>) }, }); export interface EntityBaseNode extends LineBaseNode, ContainerNode { createOnFind?: ExpressionOrValue<boolean>; create?: ExpressionOrValue<boolean>; onCreate?: Expression<() => Promise<ModifiableEntity | Lite<Entity> | undefined> | undefined>; find?: ExpressionOrValue<boolean>; onFind?: Expression<() => Promise<ModifiableEntity | Lite<Entity> | undefined> | undefined>; remove?: ExpressionOrValue<boolean | ((item: ModifiableEntity | Lite<Entity>) => boolean)>; onRemove?: Expression<(remove: ModifiableEntity | Lite<Entity>) => Promise<boolean>>; view?: ExpressionOrValue<boolean | ((item: ModifiableEntity | Lite<Entity>) => boolean)>; onView?: Expression<(entity: ModifiableEntity | Lite<Entity>, pr: PropertyRoute) => Promise<ModifiableEntity | undefined> | undefined>; viewOnCreate?: ExpressionOrValue<boolean>; findOptions?: FindOptionsExpr; viewName?: ExpressionOrValue<string | ((mod: ModifiableEntity) => string | Navigator.ViewPromise<ModifiableEntity>)>; } export interface EntityLineNode extends EntityBaseNode { kind: "EntityLine", autoComplete?: ExpressionOrValue<AutocompleteConfig<unknown> | null>; itemHtmlAttributes?: HtmlAttributesExpression; } NodeUtils.register<EntityLineNode>({ kind: "EntityLine", group: "Property", order: 1, isContainer: true, hasEntity: true, validate: (dn, ctx) => NodeUtils.validateEntityBase(dn, ctx), renderTreeNode: NodeUtils.treeNodeKindField, renderCode: (node, cc) => cc.elementCode("EntityLine", cc.getEntityBasePropsEx(node, { showAutoComplete: true })), render: (dn, ctx) => (<EntityLine {...NodeUtils.getEntityBaseProps(dn, ctx, { showAutoComplete: true, isEntityLine: true })} />), renderDesigner: dn => NodeUtils.designEntityBase(dn, { showAutoComplete: true, isEntityLine: true }), }); export interface EntityComboNode extends EntityBaseNode { kind: "EntityCombo", } NodeUtils.register<EntityComboNode>({ kind: "EntityCombo", group: "Property", order: 2, isContainer: true, hasEntity: true, validate: (dn, ctx) => NodeUtils.validateEntityBase(dn, ctx), renderTreeNode: NodeUtils.treeNodeKindField, renderCode: (node, cc) => cc.elementCode("EntityCombo", cc.getEntityBasePropsEx(node, {})), render: (dn, ctx) => (<EntityCombo {...NodeUtils.getEntityBaseProps(dn, ctx, {})} />), renderDesigner: dn => NodeUtils.designEntityBase(dn, {}), }); export interface EntityDetailNode extends EntityBaseNode, ContainerNode { kind: "EntityDetail", avoidFieldSet?: ExpressionOrValue<boolean>; onEntityLoaded?: Expression<() => void>; } NodeUtils.register<EntityDetailNode>({ kind: "EntityDetail", group: "Property", order: 3, isContainer: true, hasEntity: true, validate: (dn, ctx) => NodeUtils.validateEntityBase(dn, ctx), renderTreeNode: NodeUtils.treeNodeKindField, renderCode: (node, cc) => cc.elementCode("EntityDetail", { ctx: cc.getEntityBasePropsEx(node, {}), avoidFieldSet: node.avoidFieldSet, onEntityLoaded: node.onEntityLoaded, }), render: (dn, ctx) => (<EntityDetail avoidFieldSet={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.avoidFieldSet, NodeUtils.isBooleanOrNull)} onEntityLoaded={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.onEntityLoaded, NodeUtils.isFunctionOrNull)} {...NodeUtils.getEntityBaseProps(dn, ctx, {})} />), renderDesigner: dn => <div> {NodeUtils.designEntityBase(dn, {})} <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.avoidFieldSet)} type="boolean" defaultValue={false} allowsExpression={false} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.onEntityLoaded)} type={null} defaultValue={null} exampleExpression={"() => { /* do something here... */ }"} /> </div> }); export interface FileLineNode extends EntityBaseNode { kind: "FileLine", download?: ExpressionOrValue<DownloadBehaviour>; dragAndDrop?: ExpressionOrValue<boolean>; dragAndDropMessage?: ExpressionOrValue<string>; fileType?: ExpressionOrValue<string>; accept?: ExpressionOrValue<string>; maxSizeInBytes?: ExpressionOrValue<number>; } const DownloadBehaviours: DownloadBehaviour[] = ["SaveAs", "View", "None"]; NodeUtils.register<FileLineNode>({ kind: "FileLine", group: "Property", order: 4, isContainer: false, hasEntity: true, validate: (dn, ctx) => NodeUtils.validateFieldMandatory(dn), renderTreeNode: NodeUtils.treeNodeKindField, renderCode: (node, cc) => cc.elementCode("FileLine", { ref: node.ref, ctx: cc.subCtxCode(node.field, node.styleOptions), labelText: node.labelText, labelHtmlAttributes: node.labelHtmlAttributes, formGroupHtmlAttributes: node.formGroupHtmlAttributes, visible: node.visible, readOnly: node.readOnly, remove: node.remove, download: node.download, dragAndDrop: node.dragAndDrop, dragAndDropMessage: node.dragAndDropMessage, fileType: bindExpr(key => registerSymbol("FileType", key), node.fileType), accept: node.accept, maxSizeInBytes: node.maxSizeInBytes, onChange: node.onChange }), render: (dn, parentCtx) => (<FileLine //ref={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.ref, NodeUtils.isObjectOrFunctionOrNull)} ctx={parentCtx.subCtx(dn.node.field, toStyleOptions(dn, parentCtx, dn.node.styleOptions))} labelText={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.labelText, NodeUtils.isStringOrNull)} labelHtmlAttributes={toHtmlAttributes(dn, parentCtx, dn.node.labelHtmlAttributes)} formGroupHtmlAttributes={toHtmlAttributes(dn, parentCtx, dn.node.formGroupHtmlAttributes)} visible={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.visible, NodeUtils.isBooleanOrNull)} readOnly={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.readOnly, NodeUtils.isBooleanOrNull)} remove={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.remove, NodeUtils.isBooleanOrNull)} download={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.download, a => NodeUtils.isInListOrNull(a, DownloadBehaviours))} dragAndDrop={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.dragAndDrop, NodeUtils.isBooleanOrNull)} dragAndDropMessage={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.dragAndDropMessage, NodeUtils.isStringOrNull)} fileType={toFileTypeSymbol(NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.fileType, NodeUtils.isStringOrNull))} accept={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.accept, NodeUtils.isStringOrNull)} maxSizeInBytes={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.maxSizeInBytes, NodeUtils.isNumberOrNull)} onChange={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.onChange, NodeUtils.isFunctionOrNull)} />), renderDesigner: dn => { const m = dn.route && dn.route.member; return ( <div> {/*<ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.ref)} type={null} defaultValue={true} />*/} <FieldComponent dn={dn} binding={Binding.create(dn.node, n => n.field)} /> <StyleOptionsLine dn={dn} binding={Binding.create(dn.node, n => n.styleOptions)} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.labelText)} type="string" defaultValue={m?.niceName ?? ""} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.labelHtmlAttributes)} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.formGroupHtmlAttributes)} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.readOnly)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.remove)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.download)} type="string" defaultValue={null} options={DownloadBehaviours} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.dragAndDrop)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.dragAndDropMessage)} type="string" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.fileType)} type="string" defaultValue={null} options={getFileTypes()} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.accept)} type="string" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.maxSizeInBytes)} type="number" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.onChange)} type={null} defaultValue={null} exampleExpression={"/* you must declare 'forceUpdate' in locals */ \r\n() => locals.forceUpdate()"} /> </div> ); } }); export interface FileImageLineNode extends EntityBaseNode { kind: "FileImageLine", dragAndDrop?: ExpressionOrValue<boolean>; dragAndDropMessage?: ExpressionOrValue<string>; fileType?: ExpressionOrValue<string>; accept?: ExpressionOrValue<string>; maxSizeInBytes?: ExpressionOrValue<number>; imageHtmlAttributes?: HtmlAttributesExpression; } NodeUtils.register<FileImageLineNode>({ kind: "FileImageLine", group: "Property", order: 5, isContainer: false, hasEntity: true, validate: (dn, ctx) => NodeUtils.validateFieldMandatory(dn), renderTreeNode: NodeUtils.treeNodeKindField, renderCode: (node, cc) => cc.elementCode("FileImageLine", { ref: node.ref, ctx: cc.subCtxCode(node.field, node.styleOptions), labelText: node.labelText, labelHtmlAttributes: node.labelHtmlAttributes, formGroupHtmlAttributes: node.formGroupHtmlAttributes, visible: node.visible, readOnly: node.readOnly, remove: node.remove, dragAndDrop: node.dragAndDrop, dragAndDropMessage: node.dragAndDropMessage, fileType: bindExpr(key => registerSymbol("FileType", key), node.fileType), accept: node.accept, maxSizeInBytes: node.maxSizeInBytes, onChange: node.onChange }), render: (dn, parentCtx) => (<FileImageLine //ref={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.ref, NodeUtils.isObjectOrFunctionOrNull)} ctx={parentCtx.subCtx(dn.node.field, toStyleOptions(dn, parentCtx, dn.node.styleOptions))} labelText={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.labelText, NodeUtils.isStringOrNull)} labelHtmlAttributes={toHtmlAttributes(dn, parentCtx, dn.node.labelHtmlAttributes)} formGroupHtmlAttributes={toHtmlAttributes(dn, parentCtx, dn.node.formGroupHtmlAttributes)} imageHtmlAttributes={toHtmlAttributes(dn, parentCtx, dn.node.imageHtmlAttributes)} visible={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.visible, NodeUtils.isBooleanOrNull)} readOnly={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.readOnly, NodeUtils.isBooleanOrNull)} remove={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.remove, NodeUtils.isBooleanOrNull)} dragAndDrop={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.dragAndDrop, NodeUtils.isBooleanOrNull)} dragAndDropMessage={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.dragAndDropMessage, NodeUtils.isStringOrNull)} fileType={toFileTypeSymbol(NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.fileType, NodeUtils.isStringOrNull))} accept={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.accept, NodeUtils.isStringOrNull)} maxSizeInBytes={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.maxSizeInBytes, NodeUtils.isNumberOrNull)} onChange={NodeUtils.evaluateAndValidate(dn, parentCtx, dn.node, n => n.onChange, NodeUtils.isFunctionOrNull)} />), renderDesigner: dn => { const m = dn.route && dn.route.member; return ( <div> {/*<ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.ref)} type={null} defaultValue={true} />*/} <FieldComponent dn={dn} binding={Binding.create(dn.node, n => n.field)} /> <StyleOptionsLine dn={dn} binding={Binding.create(dn.node, n => n.styleOptions)} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.labelText)} type="string" defaultValue={m?.niceName ?? ""} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.labelHtmlAttributes)} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.formGroupHtmlAttributes)} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.imageHtmlAttributes)} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.readOnly)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.remove)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.dragAndDrop)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.dragAndDropMessage)} type="string" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.fileType)} type="string" defaultValue={null} options={getFileTypes()} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.accept)} type="string" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.maxSizeInBytes)} type="number" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.onChange)} type={null} defaultValue={null} exampleExpression={"/* you must declare 'forceUpdate' in locals */ \r\n() => locals.forceUpdate()"} /> </div> ); } }); export interface MultiFileLineNode extends LineBaseNode { kind: "MultiFileLine", download?: ExpressionOrValue<DownloadBehaviour>; dragAndDrop?: ExpressionOrValue<boolean>; dragAndDropMessage?: ExpressionOrValue<string>; fileType?: ExpressionOrValue<string>; accept?: ExpressionOrValue<string>; maxSizeInBytes?: ExpressionOrValue<number>; } NodeUtils.register<MultiFileLineNode>({ kind: "MultiFileLine", group: "Property", hasCollection: true, hasEntity: true, order: 6, validate: (dn) => NodeUtils.validateFieldMandatory(dn), renderTreeNode: NodeUtils.treeNodeKindField, renderCode: (node, cc) => cc.elementCode("MultiFileLine", { ref: node.ref, ctx: cc.subCtxCode(node.field, node.styleOptions), labelText: node.labelText, labelHtmlAttributes: node.labelHtmlAttributes, formGroupHtmlAttributes: node.formGroupHtmlAttributes, readOnly: node.readOnly, download: node.download, dragAndDrop: node.dragAndDrop, dragAndDropMessage: node.dragAndDropMessage, fileType: bindExpr(key => registerSymbol("FileType", key), node.fileType), accept: node.accept, maxSizeInBytes: node.maxSizeInBytes, onChange: node.onChange, }), render: (dn, ctx) => ( <MultiFileLine //ref={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.ref, NodeUtils.isObjectOrFunctionOrNull)} ctx={ctx.subCtx(dn.node.field, toStyleOptions(dn, ctx, dn.node.styleOptions))} labelText={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.labelText, NodeUtils.isStringOrNull)} labelHtmlAttributes={toHtmlAttributes(dn, ctx, dn.node.labelHtmlAttributes)} formGroupHtmlAttributes={toHtmlAttributes(dn, ctx, dn.node.formGroupHtmlAttributes)} readOnly={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.readOnly, NodeUtils.isBooleanOrNull)} download={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.download, a => NodeUtils.isInListOrNull(a, DownloadBehaviours))} dragAndDrop={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.dragAndDrop, NodeUtils.isBooleanOrNull)} dragAndDropMessage={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.dragAndDropMessage, NodeUtils.isStringOrNull)} fileType={toFileTypeSymbol(NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.fileType, NodeUtils.isStringOrNull))} accept={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.accept, NodeUtils.isStringOrNull)} maxSizeInBytes={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.maxSizeInBytes, NodeUtils.isNumberOrNull)} onChange={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.onChange, NodeUtils.isFunctionOrNull)} /> ), renderDesigner: (dn) => { const m = dn.route && dn.route.member; return (<div> {/*<ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.ref)} type={null} defaultValue={true} />*/} <FieldComponent dn={dn} binding={Binding.create(dn.node, n => n.field)} /> <StyleOptionsLine dn={dn} binding={Binding.create(dn.node, n => n.styleOptions)} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.labelText)} type="string" defaultValue={m?.niceName ?? ""} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.labelHtmlAttributes)} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.formGroupHtmlAttributes)} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.readOnly)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.download)} type="string" defaultValue={null} options={DownloadBehaviours} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.dragAndDrop)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.dragAndDropMessage)} type="string" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.fileType)} type="string" defaultValue={null} options={getFileTypes()} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.accept)} type="string" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.maxSizeInBytes)} type="number" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.onChange)} type={null} defaultValue={false} exampleExpression={"/* you must declare 'forceUpdate' in locals */ \r\n() => locals.forceUpdate()"} /> </div>) }, }); function getFileTypes() { return getAllTypes() .filter(a => a.kind == "SymbolContainer" && a.name.endsWith("FileType")) .flatMap(t => Dic.getValues(t.members).map(m => t.name + "." + m.name)); } function toFileTypeSymbol(fileTypeKey?: string) { if (fileTypeKey == undefined) return undefined; return registerSymbol("FileType", fileTypeKey); } export interface EnumCheckboxListNode extends LineBaseNode { kind: "EnumCheckboxList", columnCount?: ExpressionOrValue<number>; columnWidth?: ExpressionOrValue<number>; avoidFieldSet?: ExpressionOrValue<boolean>; } NodeUtils.register<EnumCheckboxListNode>({ kind: "EnumCheckboxList", group: "Collection", order: 0, hasCollection: true, validate: (dn) => NodeUtils.validateFieldMandatory(dn), renderTreeNode: NodeUtils.treeNodeKindField, renderCode: (node, cc) => cc.elementCode("EnumCheckboxList", { ref: node.ref, ctx: cc.subCtxCode(node.field, node.styleOptions), labelText: node.labelText, avoidFieldSet: node.avoidFieldSet, readOnly: node.readOnly, columnCount: node.columnCount, columnWidth: node.columnWidth, onChange: node.onChange, }), render: (dn, ctx) => (<EnumCheckboxList //ref={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.ref, NodeUtils.isObjectOrFunctionOrNull)} ctx={ctx.subCtx(dn.node.field, toStyleOptions(dn, ctx, dn.node.styleOptions))} labelText={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.labelText, NodeUtils.isStringOrNull)} avoidFieldSet={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.avoidFieldSet, NodeUtils.isBooleanOrNull)} readOnly={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.readOnly, NodeUtils.isBooleanOrNull)} columnCount={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.columnCount, NodeUtils.isNumberOrNull)} columnWidth={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.columnWidth, NodeUtils.isNumberOrNull)} onChange={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.onChange, NodeUtils.isFunctionOrNull)} />), renderDesigner: (dn) => { const m = dn.route && dn.route.member; return (<div> {/*<ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.ref)} type={null} defaultValue={true} />*/} <FieldComponent dn={dn} binding={Binding.create(dn.node, n => n.field)} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.labelText)} type="string" defaultValue={m?.niceName ?? ""} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.avoidFieldSet)} type="boolean" defaultValue={false} allowsExpression={false} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.readOnly)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.columnCount)} type="number" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.columnWidth)} type="number" defaultValue={200} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.onChange)} type={null} defaultValue={null} exampleExpression={"/* you must declare 'forceUpdate' in locals */ \r\n() => locals.forceUpdate()"} /> </div>) }, }); export interface EntityListBaseNode extends EntityBaseNode { move?: ExpressionOrValue<boolean | ((item: ModifiableEntity | Lite<Entity>) => boolean)>; onFindMany?: Expression<() => Promise<(ModifiableEntity | Lite<Entity>)[] | undefined> | undefined>; filterRows?: Expression<(ctxs: TypeContext<any /*T*/>[]) => TypeContext<any /*T*/>[]>; } export interface EntityCheckboxListNode extends EntityListBaseNode { kind: "EntityCheckboxList", columnCount?: ExpressionOrValue<number>; columnWidth?: ExpressionOrValue<number>; avoidFieldSet?: ExpressionOrValue<boolean>; } NodeUtils.register<EntityCheckboxListNode>({ kind: "EntityCheckboxList", group: "Collection", order: 1, hasEntity: true, hasCollection: true, validate: (dn, ctx) => NodeUtils.validateEntityBase(dn, ctx), renderTreeNode: NodeUtils.treeNodeKindField, renderCode: (node, cc) => cc.elementCode("EntityCheckboxList", { ...cc.getEntityBasePropsEx(node, { showMove: false, filterRows: true }), columnCount: node.columnCount, columnWidth: node.columnWidth, avoidFieldSet: node.avoidFieldSet, }), render: (dn, ctx) => (<EntityCheckboxList {...NodeUtils.getEntityBaseProps(dn, ctx, { showMove: false, filterRows: true })} columnCount={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.columnCount, NodeUtils.isNumberOrNull)} columnWidth={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.columnWidth, NodeUtils.isNumberOrNull)} avoidFieldSet={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.avoidFieldSet, NodeUtils.isBooleanOrNull)} />), renderDesigner: dn => <div> {NodeUtils.designEntityBase(dn, { filterRows: true })} <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.columnCount)} type="number" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.columnWidth)} type="number" defaultValue={200} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.avoidFieldSet)} type="boolean" defaultValue={false} allowsExpression={false} /> </div> }); export interface EntityListNode extends EntityListBaseNode { kind: "EntityList", } NodeUtils.register<EntityListNode>({ kind: "EntityList", group: "Collection", order: 2, isContainer: true, hasEntity: true, hasCollection: true, validate: (dn, ctx) => NodeUtils.validateEntityBase(dn, ctx), renderTreeNode: NodeUtils.treeNodeKindField, renderCode: (node, cc) => cc.elementCode("EntityList", cc.getEntityBasePropsEx(node, { findMany: true, showMove: true, filterRows: true })), render: (dn, ctx) => (<EntityList {...NodeUtils.getEntityBaseProps(dn, ctx, { findMany: true, showMove: true, filterRows: true })} />), renderDesigner: dn => NodeUtils.designEntityBase(dn, { findMany: true, showMove: true, filterRows: true }) }); export interface EntityStripNode extends EntityListBaseNode { kind: "EntityStrip", autoComplete?: ExpressionOrValue<AutocompleteConfig<unknown> | null>; iconStart?: boolean; vertical?: boolean; } NodeUtils.register<EntityStripNode>({ kind: "EntityStrip", group: "Collection", order: 3, isContainer: true, hasEntity: true, hasCollection: true, validate: (dn, ctx) => NodeUtils.validateEntityBase(dn, ctx), renderTreeNode: NodeUtils.treeNodeKindField, renderCode: (node, cc) => cc.elementCode("EntityStrip", { ...cc.getEntityBasePropsEx(node, { showAutoComplete: true, findMany: true, showMove: true, filterRows: true }), iconStart: node.iconStart, vertical: node.vertical, }), render: (dn, ctx) => (<EntityStrip {...NodeUtils.getEntityBaseProps(dn, ctx, { showAutoComplete: true, findMany: true, showMove: true, filterRows: true })} iconStart={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.iconStart, NodeUtils.isBooleanOrNull)} vertical={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.vertical, NodeUtils.isBooleanOrNull)} />), renderDesigner: dn => <div> {NodeUtils.designEntityBase(dn, { showAutoComplete: true, findMany: true, showMove: true, filterRows: true })} <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.iconStart)} type="boolean" defaultValue={false} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.vertical)} type="boolean" defaultValue={false} /> </div> }); export interface EntityRepeaterNode extends EntityListBaseNode { kind: "EntityRepeater", avoidFieldSet?: ExpressionOrValue<boolean>; } NodeUtils.register<EntityRepeaterNode>({ kind: "EntityRepeater", group: "Collection", order: 4, isContainer: true, hasEntity: true, hasCollection: true, validate: (dn, ctx) => NodeUtils.validateEntityBase(dn, ctx), renderTreeNode: NodeUtils.treeNodeKindField, renderCode: (node, cc) => cc.elementCode("EntityRepeater", { ...cc.getEntityBasePropsEx(node, { findMany: true, showMove: true, filterRows: true }), avoidFieldSet: node.avoidFieldSet }), render: (dn, ctx) => (<EntityRepeater {...NodeUtils.getEntityBaseProps(dn, ctx, { findMany: true, showMove: true, filterRows: true })} avoidFieldSet={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.avoidFieldSet, NodeUtils.isBooleanOrNull)} />), renderDesigner: dn => <div> {NodeUtils.designEntityBase(dn, { findMany: true, showMove: true, filterRows: true })} <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.avoidFieldSet)} type="boolean" defaultValue={false} allowsExpression={false} /> </div> }); export interface EntityTabRepeaterNode extends EntityListBaseNode { kind: "EntityTabRepeater", avoidFieldSet?: ExpressionOrValue<boolean>; } NodeUtils.register<EntityTabRepeaterNode>({ kind: "EntityTabRepeater", group: "Collection", order: 5, isContainer: true, hasEntity: true, hasCollection: true, validate: (dn, ctx) => NodeUtils.validateEntityBase(dn, ctx), renderTreeNode: NodeUtils.treeNodeKindField, renderCode: (node, cc) => cc.elementCode("EntityTabRepeater", { ...cc.getEntityBasePropsEx(node, { findMany: true, showMove: true, filterRows: true }), avoidFieldSet: node.avoidFieldSet }), render: (dn, ctx) => (<EntityTabRepeater {...NodeUtils.getEntityBaseProps(dn, ctx, { findMany: true, showMove: true, filterRows: true })} avoidFieldSet={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.avoidFieldSet, NodeUtils.isBooleanOrNull)} />), renderDesigner: dn => <div> {NodeUtils.designEntityBase(dn, { findMany: true, showMove: true, filterRows: true })} <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.avoidFieldSet)} type="boolean" defaultValue={false} allowsExpression={false} /> </div> }); export interface EntityTableNode extends EntityListBaseNode { kind: "EntityTable", avoidFieldSet?: ExpressionOrValue<boolean>; scrollable?: ExpressionOrValue<boolean>; maxResultsHeight?: Expression<number | string>; } NodeUtils.register<EntityTableNode>({ kind: "EntityTable", group: "Collection", order: 6, isContainer: true, hasEntity: true, hasCollection: true, validChild: "EntityTableColumn", validate: (dn, ctx) => NodeUtils.validateEntityBase(dn, ctx), renderTreeNode: NodeUtils.treeNodeKindField, renderCode: (node, cc) => cc.elementCode("EntityTable", { ...cc.getEntityBasePropsEx(node, { findMany: true, showMove: true, avoidGetComponent: true, filterRows: true }), avoidFieldSet: node.avoidFieldSet, scrollable: node.scrollable, maxResultsHeight: node.maxResultsHeight, columns: ({ __code__: "EntityTable.typedColumns<YourEntityHere>(" + cc.stringifyObject(node.children.map(col => ({ __code__: NodeUtils.renderCode(col as EntityTableColumnNode, cc) }))) + ")" }) }), render: (dn, ctx) => (<EntityTable columns={dn.node.children.length == 0 ? undefined : dn.node.children.filter(c => (c.visible == undefined || NodeUtils.evaluateAndValidate(dn, ctx, c, n => n.visible, NodeUtils.isBooleanOrNull)) && NodeUtils.validate(dn.createChild(c), ctx) == null).map(col => NodeUtils.render(dn.createChild(col as EntityTableColumnNode), ctx) as any)} {...NodeUtils.getEntityBaseProps(dn, ctx, { findMany: true, showMove: true, avoidGetComponent: true, filterRows: true })} avoidFieldSet={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.avoidFieldSet, NodeUtils.isBooleanOrNull)} scrollable={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.scrollable, NodeUtils.isBooleanOrNull)} maxResultsHeight={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.maxResultsHeight, NodeUtils.isNumberOrStringOrNull)} />), renderDesigner: dn => <div> {NodeUtils.designEntityBase(dn, { findMany: true, showMove: true, filterRows: true })} <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.avoidFieldSet)} type="boolean" defaultValue={false} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.scrollable)} type="boolean" defaultValue={false} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.maxResultsHeight)} type={null} defaultValue={null} /> </div> }); export interface EntityTableColumnNode extends ContainerNode { kind: "EntityTableColumn", property?: string; header?: string; headerHtmlAttributes?: HtmlAttributesExpression, cellHtmlAttributes?: HtmlAttributesExpression, } NodeUtils.register<EntityTableColumnNode>({ kind: "EntityTableColumn", group: null, order: null, isContainer: true, avoidHighlight: true, validParent: "EntityTable", validate: (dn) => dn.node.property ? undefined : NodeUtils.mandatory(dn, n => n.header), renderTreeNode: NodeUtils.treeNodeTableColumnProperty, renderCode: (node, cc) => cc.stringifyObject({ property: node.property && { __code__: "a => a." + node.property }, header: node.header, headerHtmlAttributes: node.headerHtmlAttributes, cellHtmlAttributes: node.cellHtmlAttributes, template: cc.getGetComponentEx(node, false) }), render: (dn, ctx) => ({ property: dn.node.property && NodeUtils.asFieldFunction(dn.node.property), header: NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.header, NodeUtils.isStringOrNull), headerHtmlAttributes: toHtmlAttributes(dn, ctx, dn.node.headerHtmlAttributes), cellHtmlAttributes: toHtmlAttributes(dn, ctx, dn.node.cellHtmlAttributes), template: NodeUtils.getGetComponent(dn) }) as EntityTableColumn<ModifiableEntity, any> as any, //HACK renderDesigner: dn => <div> <FieldComponent dn={dn} binding={Binding.create(dn.node, n => n.property)} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.header)} type="string" defaultValue={null} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.headerHtmlAttributes)} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.cellHtmlAttributes)} /> </div> }); export interface SearchControlNode extends BaseNode { kind: "SearchControl", findOptions?: FindOptionsExpr; searchOnLoad?: ExpressionOrValue<boolean>; showContextMenu?: Expression<(fop: FindOptionsParsed) => boolean | "Basic">; extraButtons?: Expression<(searchControl: SearchControlLoaded) => (ButtonBarElement | null | undefined | false)[]>; viewName?: ExpressionOrValue<string | ((mod: ModifiableEntity) => string | Navigator.ViewPromise<ModifiableEntity>)>; showHeader?: ExpressionOrValue<boolean>; showFilters?: ExpressionOrValue<boolean>; showFilterButton?: ExpressionOrValue<boolean>; showFooter?: ExpressionOrValue<boolean>; showGroupButton?: ExpressionOrValue<boolean>; showBarExtension?: ExpressionOrValue<boolean>; showChartButton?: ExpressionOrValue<boolean>; showExcelMenu?: ExpressionOrValue<boolean>; showUserQuery?: ExpressionOrValue<boolean>; showWordReport?: ExpressionOrValue<boolean>; hideFullScreenButton?: ExpressionOrValue<boolean>; allowSelection?: ExpressionOrValue<boolean>; allowChangeColumns?: ExpressionOrValue<boolean>; create?: ExpressionOrValue<boolean>; onCreate?: Expression<() => Promise<undefined | EntityPack<any> | ModifiableEntity | "no_change">>; navigate?: ExpressionOrValue<boolean>; deps?: Expression<React.DependencyList | undefined>; maxResultsHeight?: Expression<number | string>; onSearch?: Expression<(fo: FindOptionsParsed, dataChange: boolean) => void>; onResult?: Expression<(table: ResultTable, dataChange: boolean) => void>; } NodeUtils.register<SearchControlNode>({ kind: "SearchControl", group: "Search", order: 1, validate: (dn, ctx) => NodeUtils.mandatory(dn, n => n.findOptions) || dn.node.findOptions && NodeUtils.validateFindOptions(dn.node.findOptions, ctx), renderTreeNode: dn => <span><small>SearchControl:</small> <strong>{dn.node.findOptions?.queryName ?? " - "}</strong></span>, renderCode: (node, cc) => cc.elementCode("SearchControl", { ref: node.ref, findOptions: node.findOptions, searchOnLoad: node.searchOnLoad, showContextMenu: node.showContextMenu, extraButtons: node.extraButtons, getViewPromise: NodeUtils.toFunctionCode(node.viewName), showHeader: node.showHeader, showFilters: node.showFilters, showFilterButton: node.showFilterButton, showFooter: node.showFooter, showGroupButton: node.showGroupButton, showBarExtension: node.showBarExtension, showChartButton: node.showChartButton, showExcelMenu: node.showExcelMenu, showUserQuery: node.showUserQuery, showWordReport: node.showWordReport, hideFullScreenButton: node.hideFullScreenButton, allowSelection: node.allowSelection, allowChangeColumns: node.allowChangeColumns, create: node.create, onCreate: node.onCreate, navigate: node.navigate, deps: node.deps, maxResultsHeight: node.maxResultsHeight, onSearch: node.onSearch, onResult: node.onResult, }), render: (dn, ctx) => <SearchControl ref={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.ref, NodeUtils.isObjectOrFunctionOrNull)} findOptions={toFindOptions(dn, ctx, dn.node.findOptions!)} getViewPromise={NodeUtils.toFunction(NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.viewName, NodeUtils.isFunctionOrStringOrNull))} searchOnLoad={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.searchOnLoad, NodeUtils.isBooleanOrNull)} showContextMenu={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.showContextMenu, NodeUtils.isFunctionOrNull)} extraButtons={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.extraButtons, NodeUtils.isFunctionOrNull)} showHeader={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.showHeader, NodeUtils.isBooleanOrNull)} showFilters={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.showFilters, NodeUtils.isBooleanOrNull)} showFilterButton={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.showFilterButton, NodeUtils.isBooleanOrNull)} showFooter={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.showFooter, NodeUtils.isBooleanOrNull)} showGroupButton={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.showGroupButton, NodeUtils.isBooleanOrNull)} showBarExtension={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.showBarExtension, NodeUtils.isBooleanOrNull)} showBarExtensionOption={{ showChartButton: NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.showChartButton, NodeUtils.isBooleanOrNull), showExcelMenu: NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.showExcelMenu, NodeUtils.isBooleanOrNull), showUserQuery: NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.showUserQuery, NodeUtils.isBooleanOrNull), showWordReport: NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.showWordReport, NodeUtils.isBooleanOrNull), }} hideFullScreenButton={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.hideFullScreenButton, NodeUtils.isBooleanOrNull)} allowSelection={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.allowSelection, NodeUtils.isBooleanOrNull)} allowChangeColumns={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.allowChangeColumns, NodeUtils.isBooleanOrNull)} create={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.create, NodeUtils.isBooleanOrNull)} onCreate={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.onCreate, NodeUtils.isFunctionOrNull)} view={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.navigate, NodeUtils.isBooleanOrNull)} deps={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.deps, NodeUtils.isNumberOrStringOrNull)} maxResultsHeight={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.maxResultsHeight, NodeUtils.isNumberOrStringOrNull)} onSearch={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.onSearch, NodeUtils.isFunctionOrNull)} onResult={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.onResult, NodeUtils.isFunctionOrNull)} />, renderDesigner: dn => <div> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.ref)} type={null} defaultValue={true} /> <FindOptionsLine dn={dn} binding={Binding.create(dn.node, a => a.findOptions)} /> <FetchQueryDescription queryName={dn.node.findOptions && dn.node.findOptions.queryName} > {qd => <ViewNameComponent dn={dn} binding={Binding.create(dn.node, n => n.viewName)} typeName={qd?.columns["Entity"].type.name} />} </FetchQueryDescription> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.searchOnLoad)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.showContextMenu)} type={null} defaultValue={null} exampleExpression={"fop => \"Basic\""} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.extraButtons)} type={null} defaultValue={null} exampleExpression={`sc => [ { order: -1.1, button: modules.React.createElement("button", { className: "btn btn-light", title: "Setting", onClick: e => alert(e) }, modules.React.createElement(modules.FontAwesomeIcon, { icon: "cog", color: "green" }), " ", "Setting") }, ]`} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.showHeader)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.showFilters)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.showFilterButton)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.showFooter)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.showGroupButton)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.showBarExtension)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.showChartButton)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.showExcelMenu)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.showUserQuery)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.showWordReport)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.hideFullScreenButton)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.allowSelection)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.allowChangeColumns)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.create)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.onCreate)} type={null} defaultValue={null} exampleExpression={`() => { modules.Constructor.construct("YourTypeHere").then(pack => { if (pack == undefined) return; /* Set entity properties here... */ /* pack.entity.[propertyName] = ... */ modules.Navigator.view(pack).done(); }).done(); }`} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.navigate)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.deps)} type={null} defaultValue={null} exampleExpression={"ctx.frame.refreshCount"} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.maxResultsHeight)} type={null} defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.onSearch)} type={null} defaultValue={null} exampleExpression={"(fop, dataChange) => {}"} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.onResult)} type={null} defaultValue={null} exampleExpression={"(table, dataChange) => dataChange && ctx.frame.onReload()"} /> </div> }); export interface ValueSearchControlLineNode extends BaseNode { kind: "ValueSearchControlLine", findOptions?: FindOptionsExpr; valueToken?: string; labelText?: ExpressionOrValue<string>; labelHtmlAttributes?: HtmlAttributesExpression; isBadge?: ExpressionOrValue<boolean>; isLink?: ExpressionOrValue<boolean>; isFormControl?: ExpressionOrValue<boolean>; findButton?: ExpressionOrValue<boolean>; viewEntityButton?: ExpressionOrValue<boolean>; deps?: Expression<React.DependencyList | undefined>; formGroupHtmlAttributes?: HtmlAttributesExpression; } NodeUtils.register<ValueSearchControlLineNode>({ kind: "ValueSearchControlLine", group: "Search", order: 1, validate: (dn, ctx) => { if (!dn.node.findOptions && !dn.node.valueToken) return DynamicViewValidationMessage.Member0IsMandatoryFor1.niceToString("findOptions (or valueToken)", dn.node.kind); if (dn.node.findOptions) { const error = NodeUtils.validateFindOptions(dn.node.findOptions, ctx); if (error) return error; } if (dn.node.valueToken && !dn.node.findOptions) { if (ctx) { var name = ctx.propertyRoute!.typeReference().name; if (!isTypeEntity(name)) return DynamicViewValidationMessage.ValueTokenCanNotBeUseFor0BecauseIsNotAnEntity.niceToString(name); } } return null; }, renderTreeNode: dn => <span><small>ValueSearchControlLine:</small> <strong>{ dn.node.valueToken ? dn.node.valueToken : dn.node.findOptions ? dn.node.findOptions.queryName : " - " }</strong></span>, renderCode: (node, cc) => cc.elementCode("ValueSearchControlLine", { ref: node.ref, ctx: cc.subCtxCode(), findOptions: node.findOptions, valueToken: node.valueToken, labelText: node.labelText, isBadge: node.isBadge, isLink: node.isLink, isFormControl: node.isFormControl, findButton: node.findButton, viewEntityButton: node.viewEntityButton, labelHtmlAttributes: node.labelHtmlAttributes, formGroupHtmlAttributes: node.formGroupHtmlAttributes, deps: node.deps, }), render: (dn, ctx) => <ValueSearchControlLine ctx={ctx} ref={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.ref, NodeUtils.isObjectOrFunctionOrNull)} findOptions={dn.node.findOptions && toFindOptions(dn, ctx, dn.node.findOptions!)} valueToken={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.valueToken, NodeUtils.isStringOrNull)} labelText={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.labelText, NodeUtils.isStringOrNull)} isBadge={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.isBadge, NodeUtils.isBooleanOrNull)} isLink={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.isLink, NodeUtils.isBooleanOrNull)} isFormControl={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.isFormControl, NodeUtils.isBooleanOrNull)} findButton={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.findButton, NodeUtils.isBooleanOrNull)} viewEntityButton={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.viewEntityButton, NodeUtils.isBooleanOrNull)} labelHtmlAttributes={toHtmlAttributes(dn, ctx, dn.node.labelHtmlAttributes)} formGroupHtmlAttributes={toHtmlAttributes(dn, ctx, dn.node.formGroupHtmlAttributes)} deps={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, f => f.deps, NodeUtils.isNumberOrStringOrNull)} />, renderDesigner: dn => { return (<div> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.ref)} type={null} defaultValue={true} /> <QueryTokenLine dn={dn} binding={Binding.create(dn.node, a => a.valueToken)} queryKey={dn.node.findOptions && dn.node.findOptions.queryName || (isTypeEntity(dn.route!.typeReference().name) ? dn.route!.typeReference().name : dn.route!.findRootType().name)} subTokenOptions={SubTokensOptions.CanAggregate | SubTokensOptions.CanElement} /> <FindOptionsLine dn={dn} binding={Binding.create(dn.node, a => a.findOptions)} onQueryChanged={() => dn.node.valueToken = undefined} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.labelHtmlAttributes)} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.labelText)} type="string" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.isBadge)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.isLink)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.isFormControl)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.findButton)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.viewEntityButton)} type="boolean" defaultValue={null} /> <HtmlAttributesLine dn={dn} binding={Binding.create(dn.node, n => n.formGroupHtmlAttributes)} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, f => f.deps)} type={null} defaultValue={null} exampleExpression={"ctx.frame.refreshCount"} /> </div>); } }); export interface ButtonNode extends BaseNode { kind: "Button", name: string; operationName?: string; onOperationClick?: ExpressionOrValue<(e: EntityOperationContext<any>) => void>; canExecute?: ExpressionOrValue<string>; text?: ExpressionOrValue<string>; active?: ExpressionOrValue<boolean>; color?: ExpressionOrValue<string>; icon?: ExpressionOrValue<string>; iconColor?: ExpressionOrValue<string>; disabled?: ExpressionOrValue<boolean>; outline?: ExpressionOrValue<boolean>; onClick?: ExpressionOrValue<(e: React.MouseEvent<any>) => void>; size?: ExpressionOrValue<string>; className?: ExpressionOrValue<string>; } NodeUtils.register<ButtonNode>({ kind: "Button", group: "Simple", hasCollection: false, hasEntity: false, order: 0, renderTreeNode: dn => <span><small>Button:</small> <strong>{dn.node.name}</strong></span>, renderCode: (node, cc) => cc.elementCode(node.operationName ? "OperationButton" : "Button", { ref: node.ref, eoc: node.operationName ? { __code__: `EntityOperationContext.fromTypeContext(${cc.subCtxCode().__code__}, ${node.operationName}))` } : undefined, onOperationClick: node.onOperationClick, canExecute: node.canExecute, active: node.active, color: node.color, icon: node.icon, iconColor: node.iconColor, disabled: node.disabled, outline: node.outline, onClick: node.onClick, size: node.size, className: node.className, }), render: (dn, ctx) => { var icon = NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.icon, NodeUtils.isStringOrNull); var pIcon = parseIcon(icon); var iconColor = NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.iconColor, NodeUtils.isStringOrNull); var children = pIcon || iconColor ? <> {pIcon && <FontAwesomeIcon icon={pIcon} color={iconColor} className="me-2" />} {NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.text, NodeUtils.isStringOrNull)} </> : undefined; if (dn.node.operationName) { const eoc = EntityOperationContext.fromTypeContext(ctx as TypeContext<Entity>, dn.node.operationName); return ( <OperationButton eoc={eoc} canExecute={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.canExecute, NodeUtils.isStringOrNull)} onOperationClick={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.onOperationClick, NodeUtils.isFunctionOrNull)} disabled={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.disabled, NodeUtils.isBooleanOrNull)} className={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.className, NodeUtils.isStringOrNull)} variant={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.color, NodeUtils.isStringOrNull) as BsColor} size={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.size, NodeUtils.isStringOrNull) as BsSize as any} children={children} /> ); } return ( <Button active={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.active, NodeUtils.isBooleanOrNull)} disabled={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.disabled, NodeUtils.isBooleanOrNull)} onClick={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.onClick, NodeUtils.isFunctionOrNull)} className={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.className, NodeUtils.isStringOrNull)} variant={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.color, NodeUtils.isStringOrNull) as BsColor} size={NodeUtils.evaluateAndValidate(dn, ctx, dn.node, n => n.size, NodeUtils.isStringOrNull) as BsSize as any} children={children} /> ); }, renderDesigner: (dn) => { var ti = dn.route && getTypeInfo(dn.route.typeReference().name); var operations = (ti?.operations && Dic.getValues(ti.operations).map(o => o.key)) ?? []; return (<div> {/*<ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.ref)} type={null} defaultValue={true} />*/} <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.name)} type="string" defaultValue={null} allowsExpression={false} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.operationName)} type="string" defaultValue={null} allowsExpression={false} options={operations} refreshView={() => { if (dn.node.operationName == null) { delete dn.node.canExecute; delete dn.node.onOperationClick; } dn.context.refreshView(); }} /> {dn.node.operationName && <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.canExecute)} type="string" defaultValue={null} />} {dn.node.operationName && <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.onOperationClick)} type={null} defaultValue={false} exampleExpression={"(eoc) => eoc.defaultClick()"} />} <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.text)} type="string" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.color)} type="string" defaultValue={null} options={["primary", "secondary", "success", "danger", "warning", "info", "light", "dark"] as BsColor[]} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.size)} type="string" defaultValue={null} options={["lg", "md", "sm", "xs"] as BsSize[]} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.icon)} type="string" defaultValue={null} onRenderValue={(val, e) => <IconTypeahead icon={val as string | null | undefined} formControlClass="form-control form-control-xs" onChange={newIcon => e.updateValue(newIcon)} />} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.iconColor)} type="string" defaultValue={null} onRenderValue={(val, e) => <ColorTypeahead color={val as string | null | undefined} formControlClass="form-control form-control-xs" onChange={newColor => e.updateValue(newColor)} />} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.active)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.disabled)} type="boolean" defaultValue={null} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.onClick)} type={null} defaultValue={false} exampleExpression={"/* you must declare 'forceUpdate' in locals */ \r\n(e) => locals.forceUpdate()"} /> <ExpressionOrValueComponent dn={dn} binding={Binding.create(dn.node, n => n.className)} type="string" defaultValue={null} /> </div>) }, }); export namespace NodeConstructor { export function createDefaultNode(ti: TypeInfo) { return { kind: "Div", children: createSubChildren(PropertyRoute.root(ti)) } as DivNode; } export function createEntityTableSubChildren(pr: PropertyRoute): BaseNode[] { const subMembers = pr.subMembers(); return Dic.map(subMembers, (field, mi) => ({ kind: "EntityTableColumn", property: field, children: [] }) as BaseNode).filter(a => (a as any).property != "Id"); } export function createSubChildren(pr: PropertyRoute): BaseNode[] { const subMembers = pr.subMembers(); return Dic.map(subMembers, (field, mi) => appropiateComponent(mi, field)).filter(a => !!a).map(a => a!); } export const specificComponents: { [typeName: string]: (mi: MemberInfo, field: string) => BaseNode | undefined; } = {}; export var appropiateComponent = (mi: MemberInfo, field: string): BaseNode | undefined => { if (mi.name == "Id" || mi.notVisible == true) return undefined; const tr = mi.type; const sc = specificComponents[tr.name]; if (sc) { const result = sc(mi, field); if (result) return result; } const tis = tryGetTypeInfos(tr); const ti = tis.firstOrNull(); if (tr.isCollection) { if (tr.name == "[ALL]") return { kind: "EntityStrip", field, children: [] } as EntityStripNode; else if (!ti && !tr.isEmbedded) return { kind: "MultiValueLine", field, children: [] } as MultiValueLineNode; else if (tr.isEmbedded || ti!.entityKind == "Part" || ti!.entityKind == "SharedPart") return { kind: "EntityTable", field, children: [] } as EntityTableNode; else if (ti!.isLowPopulation) return { kind: "EntityCheckboxList", field, children: [] } as EntityCheckboxListNode; else return { kind: "EntityStrip", field, children: [] } as EntityStripNode; } if (tr.name == "[ALL]") return { kind: "EntityLine", field, children: [] } as EntityLineNode; if (ti) { if (ti.kind == "Enum") return { kind: "ValueLine", field } as ValueLineNode; if (tr.name == FilePathEntity.typeName && mi.defaultFileTypeInfo && mi.defaultFileTypeInfo.onlyImages) return { kind: "FileImageLine", field } as FileImageLineNode; if (ti.name == FileEntity.typeName || ti.name == FilePathEntity.typeName) return { kind: "FileLine", field } as FileLineNode; if (ti.entityKind == "Part" || ti.entityKind == "SharedPart") return { kind: "EntityDetail", field, children: [] } as EntityDetailNode; if (ti.isLowPopulation) return { kind: "EntityCombo", field, children: [] } as EntityComboNode; return { kind: "EntityLine", field, children: [] } as EntityLineNode; } if (tr.isEmbedded) { if (tr.name == FilePathEmbedded.typeName && mi.defaultFileTypeInfo && mi.defaultFileTypeInfo.onlyImages) return { kind: "FileImageLine", field } as FileImageLineNode; if (tr.name == FileEmbedded.typeName || tr.name == FilePathEmbedded.typeName) return { kind: "FileLine", field } as FileLineNode; return { kind: "EntityDetail", field, children: [] } as EntityDetailNode; } if (ValueLineController.getValueLineType(tr) != undefined) return { kind: "ValueLine", field } as ValueLineNode; return undefined; } }
the_stack
import { Client } from "matrix-org-irc"; import * as promiseutil from "../promiseutil"; import Scheduler from "./Scheduler"; import * as logging from "../logging"; import Bluebird from "bluebird"; import { Defer } from "../promiseutil"; import { IrcServer } from "./IrcServer"; const log = logging.get("client-connection"); export interface IrcMessage { command?: string; args: string[]; rawCommand: string; prefix: string; } // The time we're willing to wait for a connect callback when connecting to IRC. const CONNECT_TIMEOUT_MS = 30 * 1000; // 30s // The delay between messages when there are >1 messages to send. const FLOOD_PROTECTION_DELAY_MS = 700; // The max amount of time we should wait for the server to ping us before reconnecting. // Servers ping infrequently (2-3mins) so this should be high enough to allow up // to 2 pings to lapse before reconnecting (5-6mins). const THROTTLE_WAIT_MS = 20 * 1000; // String reply of any CTCP Version requests const CTCP_VERSION = 'matrix-appservice-irc, part of the Matrix.org Network'; const CONN_LIMIT_MESSAGES = [ "too many host connections", // ircd-seven "no more connections allowed in your connection class", "this server is full", // unrealircd ]; // Log an Error object to stderr function logError(err: Error) { if (!err || !err.message) { return; } log.error(err.message); } export interface ConnectionOpts { localAddress?: string; password?: string; realname: string; username?: string; nick: string; secure?: { ca?: string; }; encodingFallback: string; } export type InstanceDisconnectReason = "throttled"|"irc_error"|"net_error"|"timeout"|"raw_error"| "toomanyconns"|"banned"|"killed"|"idle"|"limit_reached"| "iwanttoreconnect"; export class ConnectionInstance { public dead = false; private state: "created"|"connecting"|"connected" = "created"; private pingRateTimerId: NodeJS.Timer|null = null; private clientSidePingTimeoutTimerId: NodeJS.Timer|null = null; private connectDefer: Defer<ConnectionInstance>; public onDisconnect?: (reason: string) => void; /** * Create an IRC connection instance. Wraps the node-irc library to handle * connections correctly. * @constructor * @param {IrcClient} ircClient The new IRC client. * @param {string} domain The domain (for logging purposes) * @param {string} nick The nick (for logging purposes) */ constructor (public readonly client: Client, private readonly domain: string, private nick: string, private pingOpts: { pingRateMs: number; pingTimeoutMs: number; }) { this.listenForErrors(); this.listenForPings(); this.listenForCTCPVersions(); this.connectDefer = promiseutil.defer(); } /** * Connect this client to the server. There are zero guarantees this will ever * connect. * @return {Promise} Resolves if connected; rejects if failed to connect. */ public connect(): Promise<ConnectionInstance> { if (this.dead) { throw new Error("connect() called on dead client: " + this.nick); } this.state = "connecting"; let gotConnectedCallback = false; setTimeout(() => { if (!gotConnectedCallback && !this.dead) { log.error( "%s@%s still not connected after %sms. Killing connection.", this.nick, this.domain, CONNECT_TIMEOUT_MS ); this.disconnect("timeout").catch(logError); } }, CONNECT_TIMEOUT_MS); this.client.connect(1, () => { gotConnectedCallback = true; this.state = "connected"; this.resetPingSendTimer(); this.connectDefer.resolve(this); }); return this.connectDefer.promise; } /** * Blow away the connection. You MUST destroy this object afterwards. * @param {string} reason - Reason to reject with. One of: * throttled|irc_error|net_error|timeout|raw_error|toomanyconns|banned */ public disconnect(reason: InstanceDisconnectReason, ircReason?: string) { if (this.dead) { return Bluebird.resolve(); } ircReason = ircReason || reason; log.info( "disconnect()ing %s@%s - %s", this.nick, this.domain, reason ); this.dead = true; return new Bluebird((resolve) => { // close the connection this.client.disconnect(ircReason, () => { /* This is needed for tests */ }); // remove timers if (this.pingRateTimerId) { clearTimeout(this.pingRateTimerId); this.pingRateTimerId = null; } if (this.clientSidePingTimeoutTimerId) { clearTimeout(this.clientSidePingTimeoutTimerId); this.clientSidePingTimeoutTimerId = null; } if (this.state !== "connected") { // we never resolved this defer, so reject it. this.connectDefer.reject(new Error(reason)); } if (this.state === "connected" && this.onDisconnect) { // we only invoke onDisconnect once we've had a successful connect. // Connection *attempts* are managed by the create() function so if we // call this now it would potentially invoke this 3 times (once per // connection instance!). Each time would have dead=false as they are // separate objects. this.onDisconnect(reason); } resolve(); }); } // eslint-disable-next-line @typescript-eslint/no-explicit-any public addListener(eventName: string, fn: (...args: Array<any>) => void) { // eslint-disable-next-line @typescript-eslint/no-explicit-any this.client.addListener(eventName, (...args: unknown[]) => { if (this.dead) { log.error( "%s@%s RECV a %s event for a dead connection", this.nick, this.domain, eventName ); return; } // do the callback // eslint-disable-next-line @typescript-eslint/no-explicit-any fn.apply(fn, args as any); }); } private listenForErrors() { this.client.addListener("error", (err?: IrcMessage) => { log.error("Server: %s (%s) Error: %s", this.domain, this.nick, JSON.stringify(err)); // We should disconnect the client for some but not all error codes. This // list is a list of codes which we will NOT disconnect the client for. const failCodes = [ "err_nosuchchannel", "err_toomanychannels", "err_channelisfull", "err_inviteonlychan", "err_bannedfromchan", "err_badchannelkey", "err_needreggednick", "err_nosuchnick", "err_cannotsendtochan", "err_toomanychannels", "err_erroneusnickname", "err_usernotinchannel", "err_notonchannel", "err_useronchannel", "err_notregistered", "err_alreadyregistred", "err_noprivileges", "err_chanoprivsneeded", "err_banonchan", "err_nickcollision", "err_nicknameinuse", "err_erroneusnickname", "err_nonicknamegiven", "err_eventnickchange", "err_nicktoofast", "err_unknowncommand", "err_unavailresource", "err_umodeunknownflag", "err_nononreg", "err_nooperhost", "err_passwdmismatch", ]; if (err && err.command) { if (failCodes.includes(err.command)) { return; // don't disconnect for these error codes. } } if (err && err.command === "err_yourebannedcreep") { this.disconnect("banned").catch(logError); return; } this.disconnect("irc_error").catch(logError); }); this.client.addListener("netError", (err: unknown) => { log.error( "Server: %s (%s) Network Error: %s", this.domain, this.nick, JSON.stringify(err, undefined, 2) ); this.disconnect("net_error").catch(logError); }); this.client.addListener("abort", () => { log.error( "Server: %s (%s) Connection Aborted", this.domain, this.nick ); this.disconnect("net_error").catch(logError); }); this.client.addListener("raw", (msg?: {command?: string; rawCommand: string; args?: string[]}) => { if (logging.isVerbose()) { log.debug( "%s@%s: %s", this.nick, this.domain, JSON.stringify(msg) ); } if (msg && (msg.command === "ERROR" || msg.rawCommand === "ERROR")) { log.error( "%s@%s: %s", this.nick, this.domain, JSON.stringify(msg) ); let wasThrottled = false; if (!msg.args) { this.disconnect("raw_error").catch(logError); return; } // E.g. 'Closing Link: gateway/shell/matrix.org/session (Bad user info)' // ircd-seven doc link: https://git.io/JvxEs if (msg.args[0]?.match(/Closing Link: .+\(Bad user info\)/)) { log.error( `User ${this.nick} was X:LINED!` ); this.disconnect("banned").catch(logError); return; } let errText = ("" + msg.args[0]) || ""; errText = errText.toLowerCase(); wasThrottled = errText.includes("throttl"); if (wasThrottled) { this.disconnect("throttled").catch(logError); return; } const wasBanned = errText.includes("banned") || errText.includes("k-lined"); if (wasBanned) { this.disconnect("banned").catch(logError); return; } const tooManyHosts = CONN_LIMIT_MESSAGES.find((connLimitMsg) => { return errText.includes(connLimitMsg); }) !== undefined; if (tooManyHosts) { this.disconnect("toomanyconns").catch(logError); return; } this.disconnect("raw_error").catch(logError); } }); } private listenForPings() { // BOTS-65 : A client can get ping timed out and not reconnect. // ------------------------------------------------------------ // The client is doing IRC ping/pongs, but there is no check to say // "hey, the server hasn't pinged me in a while, it's probably dead". The // RFC for pings states that pings are sent "if no other activity detected // from a connection." so we need to count anything we shove down the wire // as a ping refresh. const keepAlivePing = () => { // refresh the ping timer if (this.clientSidePingTimeoutTimerId) { clearTimeout(this.clientSidePingTimeoutTimerId); } this.clientSidePingTimeoutTimerId = setTimeout(() => { log.info( "Ping timeout: knifing connection for %s on %s", this.domain, this.nick, ); // Just emit an netError which clients need to handle anyway. this.client.emit("netError", { msg: "Client-side ping timeout" }); }, this.pingOpts.pingTimeoutMs); } this.client.on("ping", (svr: string) => { log.debug("Received ping from %s directed at %s", svr, this.nick); keepAlivePing(); }); // decorate client.send to refresh the timer const realSend = this.client.send; // eslint-disable-next-line @typescript-eslint/no-explicit-any this.client.send = (...args: string[]) => { keepAlivePing(); this.resetPingSendTimer(); // sending a message counts as a ping return realSend.apply(this.client, args); }; } private listenForCTCPVersions() { this.client.addListener("ctcp-version", (from: string) => { if (from) { // Ensure the sender is valid before we try to respond this.client.ctcp(from, 'reply', `VERSION ${CTCP_VERSION}`); } }); } private resetPingSendTimer() { // reset the ping rate timer if (this.pingRateTimerId) { clearTimeout(this.pingRateTimerId); } this.pingRateTimerId = setTimeout(() => { if (this.dead) { return; } // Do what XChat does this.client.send("PING", "LAG" + Date.now()); // keep doing it. this.resetPingSendTimer(); }, this.pingOpts.pingRateMs); } /** * Create an IRC client connection and connect to it. * @param {IrcServer} server The server to connect to. * @param {Object} opts Options for this connection. * @param {string} opts.nick The nick to use. * @param {string} opts.username The username to use. * @param {string} opts.realname The real name of the user. * @param {string} opts.password The password to give NickServ. * @param {string} opts.localAddress The local address to bind to when connecting. * @param {Function} onCreatedCallback Called with the client when created. * @return {Promise} Resolves to an ConnectionInstance or rejects. */ public static async create (server: IrcServer, opts: ConnectionOpts, onCreatedCallback?: (inst: ConnectionInstance) => void): Promise<ConnectionInstance> { if (!opts.nick || !server) { throw new Error("Bad inputs. Nick: " + opts.nick); } const connectionOpts = { userName: opts.username, realName: opts.realname, password: opts.password, localAddress: opts.localAddress, autoConnect: false, autoRejoin: false, floodProtection: true, floodProtectionDelay: FLOOD_PROTECTION_DELAY_MS, port: server.getPort(), selfSigned: server.useSslSelfSigned(), certExpired: server.allowExpiredCerts(), retryCount: 0, family: (server.getIpv6Prefix() || server.getIpv6Only() ? 6 : null) as 6|null, bustRfc3484: true, sasl: opts.password ? server.useSasl() : false, secure: server.useSsl() ? server.getSecureOptions() : undefined, encodingFallback: opts.encodingFallback }; // Returns: A promise which resolves to a ConnectionInstance const retryConnection = () => { const nodeClient = new Client( server.randomDomain(), opts.nick, connectionOpts ); const inst = new ConnectionInstance( nodeClient, server.domain, opts.nick, { pingRateMs: server.pingRateMs, pingTimeoutMs: server.pingTimeout, } ); if (onCreatedCallback) { onCreatedCallback(inst); } return inst.connect(); }; let connAttempts = 0; let retryTimeMs = 0; const BASE_RETRY_TIME_MS = 1000; while (true) { try { if (server.getReconnectIntervalMs() > 0) { // wait until scheduled return (await Scheduler.reschedule( server, retryTimeMs, retryConnection, opts.nick )) as ConnectionInstance; } // Try to connect immediately: we'll wait if we fail. return await retryConnection(); } catch (err) { connAttempts += 1; log.error( `ConnectionInstance.connect failed after ${connAttempts} attempts (${err.message})` ); if (err.message === "throttled") { retryTimeMs += THROTTLE_WAIT_MS; } if (err.message === "banned") { log.error( `${opts.nick} is banned from ${server.domain}, ` + `throwing` ); throw new Error("User is banned from the network."); // If the user is banned, we should part them from any rooms. } if (err.message === "toomanyconns") { log.error( `User ${opts.nick} was ILINED. This may be the network limiting us!` ); throw new Error("Connection was ILINED. We cannot retry this."); } // always set a staggered delay here to avoid thundering herd // problems on mass-disconnects const delay = (BASE_RETRY_TIME_MS * Math.random())+ retryTimeMs + Math.round((connAttempts * 1000) * Math.random()); log.info(`Retrying connection for ${opts.nick} on ${server.domain} `+ `in ${delay}ms (attempts ${connAttempts})`); await Bluebird.delay(delay); } } } }
the_stack
import { GenSuggestionOptionsStrict, SuggestionOptions } from './genSuggestionsOptions'; import { parseDictionary } from './SimpleDictionaryParser'; import * as Sug from './suggestAStar'; import { SuggestionCollector, suggestionCollector, SuggestionCollectorOptions } from './suggestCollector'; import { Trie } from './trie'; import { CompoundWordsMethod } from './walker'; const defaultOptions: SuggestionCollectorOptions = { numSuggestions: 10, ignoreCase: undefined, changeLimit: undefined, includeTies: true, timeout: undefined, }; const stopHere = true; describe('Validate Suggest', () => { const changeLimit = 3; // cspell:ignore joyfullwalk test('Tests suggestions for valid word talks', () => { const trie = Trie.create(sampleWords); const results = Sug.suggest(trie.root, 'talks', { changeLimit: changeLimit }); expect(results).toEqual([ { cost: 0, word: 'talks' }, { cost: 100, word: 'talk' }, { cost: 125, word: 'walks' }, { cost: 200, word: 'talked' }, { cost: 200, word: 'talker' }, { cost: 225, word: 'walk' }, ]); }); test('Tests suggestions for valid word', () => { const trie = Trie.create(sampleWords); const results = Sug.suggest(trie.root, 'talks', { changeLimit: changeLimit }); const suggestions = results.map((s) => s.word); expect(suggestions).toEqual(expect.arrayContaining(['talks'])); expect(suggestions).toEqual(expect.arrayContaining(['talk'])); expect(suggestions[0]).toBe('talks'); expect(suggestions[1]).toBe('talk'); expect(suggestions).toEqual(['talks', 'talk', 'walks', 'talked', 'talker', 'walk']); }); test('Tests suggestions for invalid word', () => { const trie = Trie.create(sampleWords); // cspell:ignore tallk const results = Sug.suggest(trie.root, 'tallk', {}); const suggestions = results.map((s) => s.word); expect(suggestions).toEqual(expect.arrayContaining(['talks'])); expect(suggestions).toEqual(expect.arrayContaining(['talk'])); expect(suggestions[1]).toBe('talks'); expect(suggestions[0]).toBe('talk'); expect(suggestions).toEqual(['talk', 'talks', 'walk', 'talked', 'talker', 'walks']); }); // cspell:ignore jernals test('Tests suggestions jernals', () => { const trie = Trie.create(sampleWords); const results = Sug.suggest(trie.root, 'jernals', {}); const suggestions = results.map((s) => s.word); expect(suggestions).toEqual(['journals', 'journal']); }); // cspell:ignore juornals test('Tests suggestions for `juornals` (reduced cost for swap)', () => { const trie = Trie.create(sampleWords); const results = Sug.suggest(trie.root, 'juornals', { changeLimit: changeLimit }); const suggestions = results.map((s) => s.word); expect(suggestions).toEqual(['journals', 'journal', 'journalism', 'journalist']); }); test('Tests suggestions for joyfull', () => { const trie = Trie.create(sampleWords); const results = Sug.suggest(trie.root, 'joyfull', { changeLimit: changeLimit }); const suggestions = results.map((s) => s.word); expect(suggestions).toEqual(['joyful', 'joyfully', 'joyfuller', 'joyous', 'joyfullest']); }); test('Tests suggestions', () => { const trie = Trie.create(sampleWords); const results = Sug.suggest(trie.root, '', {}); const suggestions = results.map((s) => s.word); expect(suggestions).toEqual([]); }); // cspell:ignore joyfull test('Tests suggestions with low max num', () => { const trie = Trie.create(sampleWords); const results = Sug.suggest(trie.root, 'joyfull', { numSuggestions: 2 }); const suggestions = results.map((s) => s.word); expect(suggestions).toEqual(['joyful', 'joyfully']); }); test('Tests genSuggestions', () => { const trie = Trie.create(sampleWords); const collector = suggestionCollector( 'joyfull', sugOpts({ numSuggestions: 3, filter: (word) => word !== 'joyfully', }) ); collector.collect(Sug.genSuggestions(trie.root, collector.word, sugGenOptsFromCollector(collector))); const suggestions = collector.suggestions.map((s) => s.word); expect(suggestions).toEqual(expect.not.arrayContaining(['joyfully'])); // We get 4 because they are tied expect(suggestions).toEqual(['joyful', 'joyfuller', 'joyous', 'joyfullest']); expect(collector.changeLimit).toBeLessThanOrEqual(300); }); test('Tests genSuggestions wanting 0', () => { const trie = Trie.create(sampleWords); const collector = suggestionCollector('joyfull', sugOptsMaxNum(0)); collector.collect(Sug.genSuggestions(trie.root, collector.word, sugGenOptsFromCollector(collector))); const suggestions = collector.suggestions.map((s) => s.word); expect(suggestions).toHaveLength(0); }); test('Tests genSuggestions wanting -10', () => { const trie = Trie.create(sampleWords); const collector = suggestionCollector('joyfull', sugOptsMaxNum(-10)); collector.collect(Sug.genSuggestions(trie.root, collector.word, sugGenOptsFromCollector(collector))); const suggestions = collector.suggestions.map((s) => s.word); expect(suggestions).toHaveLength(0); }); // cspell:ignore wålk test('that accents are closer', () => { const trie = Trie.create(sampleWords); const collector = suggestionCollector('wålk', sugOptsMaxNum(3)); collector.collect( Sug.genCompoundableSuggestions( trie.root, collector.word, sugGenOptsFromCollector(collector, CompoundWordsMethod.JOIN_WORDS) ) ); const suggestions = collector.suggestions.map((s) => s.word); expect(suggestions).toEqual(['walk', 'walks', 'talk']); }); // cspell:ignore wâlkéd test('that multiple accents are closer', () => { const trie = Trie.create(sampleWords); const collector = suggestionCollector('wâlkéd', sugOptsMaxNum(3)); collector.collect( Sug.genCompoundableSuggestions( trie.root, collector.word, sugGenOptsFromCollector(collector, CompoundWordsMethod.JOIN_WORDS) ) ); const suggestions = collector.suggestions.map((s) => s.word); expect(suggestions).toEqual(['walked', 'walker', 'talked']); }); // cspell:ignore walkingtalkingjoy test('Tests compound suggestions', () => { const trie = Trie.create(sampleWords); const opts: SuggestionOptions = { numSuggestions: 1, compoundMethod: CompoundWordsMethod.SEPARATE_WORDS }; const results = Sug.suggest(trie.root, 'walkingtalkingjoy', opts); const suggestions = results.map((s) => s.word); expect(suggestions).toEqual(['walking talking joy']); }); // cspell:ignore joyfullwalk test('Tests genSuggestions with compounds SEPARATE_WORDS', () => { const trie = Trie.create(sampleWords); const ops = sugOpts(sugOptsMaxNum(4), { changeLimit: 4 }); const collector = suggestionCollector('joyfullwalk', ops); collector.collect( Sug.genCompoundableSuggestions( trie.root, collector.word, sugGenOptsFromCollector(collector, CompoundWordsMethod.SEPARATE_WORDS) ) ); expect(collector.suggestions).toEqual([ { cost: 129, word: 'joyful walk' }, { cost: 229, word: 'joyful talk' }, { cost: 229, word: 'joyful walks' }, { cost: 325, word: 'joyfully' }, ]); }); // cspell:ignore joyfullwalk joyfulwalk joyfulwalks joyfullywalk, joyfullywalks test('Tests genSuggestions with compounds JOIN_WORDS', () => { const trie = Trie.create(sampleWords); const collector = suggestionCollector('joyfullwalk', sugOptsMaxNum(3)); collector.collect( Sug.genCompoundableSuggestions( trie.root, collector.word, sugGenOptsFromCollector(collector, CompoundWordsMethod.JOIN_WORDS) ) ); const suggestions = collector.suggestions.map((s) => s.word); // expect(suggestions).toEqual(['joyful+walk', 'joyful+talk', 'joyful+walks', 'joyfully+walk']); expect(suggestions).toEqual(['joyful+walk', 'joyful+talk', 'joyful+walks']); expect(collector.changeLimit).toBeLessThan(300); }); // cspell:ignore walkingtree talkingtree test.each` word | expected ${'walkingstick'} | ${expect.arrayContaining([{ word: 'walkingstick', cost: 99 }])} ${'walkingtree'} | ${expect.arrayContaining([])} `('that forbidden words are not included (collector)', ({ word, expected }) => { const trie = parseDictionary(` walk walking* *stick talking* *tree !walkingtree `); const r = Sug.suggest(trie.root, word, { numSuggestions: 1 }); expect(r).toEqual(expected); }); if (stopHere) return; }); function sugOpts(...opts: Partial<SuggestionCollectorOptions>[]): SuggestionCollectorOptions { return Object.assign({}, defaultOptions, ...opts); } function sugOptsMaxNum(maxNumSuggestions: number): SuggestionCollectorOptions { return sugOpts({ numSuggestions: maxNumSuggestions }); } function sugGenOptsFromCollector(collector: SuggestionCollector, compoundMethod?: CompoundWordsMethod) { const { ignoreCase, changeLimit } = collector; const ops: GenSuggestionOptionsStrict = { compoundMethod, ignoreCase, changeLimit, }; return ops; } const sampleWords = [ 'walk', 'walked', 'walker', 'walking', 'walks', 'talk', 'talks', 'talked', 'talker', 'talking', 'lift', 'lifts', 'lifted', 'lifter', 'lifting', 'journal', 'journals', 'journalism', 'journalist', 'journalistic', 'journey', 'journeyer', 'journeyman', 'journeymen', 'joust', 'jouster', 'jousting', 'jovial', 'joviality', 'jowl', 'jowly', 'joy', 'joyful', 'joyfuller', 'joyfullest', 'joyfully', 'joyfulness', 'joyless', 'joylessness', 'joyous', 'joyousness', 'joyridden', 'joyride', 'joyrider', 'joyriding', 'joyrode', 'joystick', ];
the_stack
import { Chain, Chain1, Chain2, Chain2C, Chain3, Chain3C, Chain4 } from './Chain' import { Either, URI as EURI } from './Either' import { flow, Lazy } from './function' import { HKT2, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import * as _ from './internal' import { NaturalTransformation12C, NaturalTransformation13C, NaturalTransformation14C, NaturalTransformation21, NaturalTransformation22, NaturalTransformation22C, NaturalTransformation23, NaturalTransformation23C, NaturalTransformation24 } from './NaturalTransformation' import { Option, URI as OURI } from './Option' import { Predicate } from './Predicate' import { Refinement } from './Refinement' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category type classes * @since 2.10.0 */ export interface FromEither<F> { readonly URI: F readonly fromEither: <E, A>(e: Either<E, A>) => HKT2<F, E, A> } /** * @category type classes * @since 2.11.0 */ export interface FromEither1<F extends URIS> { readonly URI: F readonly fromEither: NaturalTransformation21<EURI, F> } /** * @category type classes * @since 2.10.0 */ export interface FromEither2<F extends URIS2> { readonly URI: F readonly fromEither: NaturalTransformation22<EURI, F> } /** * @category type classes * @since 2.10.0 */ export interface FromEither2C<F extends URIS2, E> { readonly URI: F readonly _E: E readonly fromEither: NaturalTransformation22C<EURI, F, E> } /** * @category type classes * @since 2.10.0 */ export interface FromEither3<F extends URIS3> { readonly URI: F readonly fromEither: NaturalTransformation23<EURI, F> } /** * @category type classes * @since 2.10.0 */ export interface FromEither3C<F extends URIS3, E> { readonly URI: F readonly _E: E readonly fromEither: NaturalTransformation23C<EURI, F, E> } /** * @category type classes * @since 2.10.0 */ export interface FromEither4<F extends URIS4> { readonly URI: F readonly fromEither: NaturalTransformation24<EURI, F> } // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category constructors * @since 2.10.0 */ export function fromOption<F extends URIS4>( F: FromEither4<F> ): <E>(onNone: Lazy<E>) => NaturalTransformation14C<OURI, F, E> export function fromOption<F extends URIS3>( F: FromEither3<F> ): <E>(onNone: Lazy<E>) => NaturalTransformation13C<OURI, F, E> export function fromOption<F extends URIS3, E>( F: FromEither3C<F, E> ): (onNone: Lazy<E>) => NaturalTransformation13C<OURI, F, E> export function fromOption<F extends URIS2>( F: FromEither2<F> ): <E>(onNone: Lazy<E>) => NaturalTransformation12C<OURI, F, E> export function fromOption<F extends URIS2, E>( F: FromEither2C<F, E> ): (onNone: Lazy<E>) => NaturalTransformation12C<OURI, F, E> export function fromOption<F>(F: FromEither<F>): <E>(onNone: Lazy<E>) => <A>(ma: Option<A>) => HKT2<F, E, A> export function fromOption<F>(F: FromEither<F>): <E>(onNone: Lazy<E>) => <A>(ma: Option<A>) => HKT2<F, E, A> { return (onNone) => (ma) => F.fromEither(_.isNone(ma) ? _.left(onNone()) : _.right(ma.value)) } /** * @category constructors * @since 2.10.0 */ export function fromPredicate<F extends URIS4>( F: FromEither4<F> ): { <A, B extends A, E>(refinement: Refinement<A, B>, onFalse: (a: A) => E): <S, R>(a: A) => Kind4<F, S, R, E, B> <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E): <S, R, B extends A>(b: B) => Kind4<F, S, R, E, B> <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E): <S, R>(a: A) => Kind4<F, S, R, E, A> } export function fromPredicate<F extends URIS3>( F: FromEither3<F> ): { <A, B extends A, E>(refinement: Refinement<A, B>, onFalse: (a: A) => E): <R>(a: A) => Kind3<F, R, E, B> <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E): <R, B extends A>(b: B) => Kind3<F, R, E, B> <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E): <R>(a: A) => Kind3<F, R, E, A> } export function fromPredicate<F extends URIS3, E>( F: FromEither3C<F, E> ): { <A, B extends A>(refinement: Refinement<A, B>, onFalse: (a: A) => E): <R>(a: A) => Kind3<F, R, E, B> <A>(predicate: Predicate<A>, onFalse: (a: A) => E): <R, B extends A>(b: B) => Kind3<F, R, E, B> <A>(predicate: Predicate<A>, onFalse: (a: A) => E): <R>(a: A) => Kind3<F, R, E, A> } export function fromPredicate<F extends URIS2>( F: FromEither2<F> ): { <A, B extends A, E>(refinement: Refinement<A, B>, onFalse: (a: A) => E): (a: A) => Kind2<F, E, B> <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E): <B extends A>(b: B) => Kind2<F, E, B> <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E): (a: A) => Kind2<F, E, A> } export function fromPredicate<F extends URIS2, E>( F: FromEither2C<F, E> ): { <A, B extends A>(refinement: Refinement<A, B>, onFalse: (a: A) => E): (a: A) => Kind2<F, E, B> <A>(predicate: Predicate<A>, onFalse: (a: A) => E): <B extends A>(b: B) => Kind2<F, E, B> <A>(predicate: Predicate<A>, onFalse: (a: A) => E): (a: A) => Kind2<F, E, A> } export function fromPredicate<F>( F: FromEither<F> ): { <A, B extends A, E>(refinement: Refinement<A, B>, onFalse: (a: A) => E): (a: A) => HKT2<F, E, B> <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E): <B extends A>(b: B) => HKT2<F, E, B> <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E): (a: A) => HKT2<F, E, A> } export function fromPredicate<F>( F: FromEither<F> ): { <A, B extends A, E>(refinement: Refinement<A, B>, onFalse: (a: A) => E): (a: A) => HKT2<F, E, B> <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E): <B extends A>(b: B) => HKT2<F, E, B> <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E): (a: A) => HKT2<F, E, A> } { return <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E) => (a: A) => F.fromEither(predicate(a) ? _.right(a) : _.left(onFalse(a))) } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @category combinators * @since 2.10.0 */ export function fromOptionK<F extends URIS4>( F: FromEither4<F> ): <E>( onNone: Lazy<E> ) => <A extends ReadonlyArray<unknown>, B>(f: (...a: A) => Option<B>) => <S, R>(...a: A) => Kind4<F, S, R, E, B> export function fromOptionK<F extends URIS3>( F: FromEither3<F> ): <E>( onNone: Lazy<E> ) => <A extends ReadonlyArray<unknown>, B>(f: (...a: A) => Option<B>) => <R>(...a: A) => Kind3<F, R, E, B> export function fromOptionK<F extends URIS3, E>( F: FromEither3C<F, E> ): ( onNone: Lazy<E> ) => <A extends ReadonlyArray<unknown>, B>(f: (...a: A) => Option<B>) => <R>(...a: A) => Kind3<F, R, E, B> export function fromOptionK<F extends URIS2>( F: FromEither2<F> ): <E>( onNone: Lazy<E> ) => <A extends ReadonlyArray<unknown>, B>(f: (...a: A) => Option<B>) => (...a: A) => Kind2<F, E, B> export function fromOptionK<F extends URIS2, E>( F: FromEither2C<F, E> ): (onNone: Lazy<E>) => <A extends ReadonlyArray<unknown>, B>(f: (...a: A) => Option<B>) => (...a: A) => Kind2<F, E, B> export function fromOptionK<F>( F: FromEither<F> ): <E>( onNone: Lazy<E> ) => <A extends ReadonlyArray<unknown>, B>(f: (...a: A) => Option<B>) => (...a: A) => HKT2<F, E, B> export function fromOptionK<F>( F: FromEither<F> ): <E>( onNone: Lazy<E> ) => <A extends ReadonlyArray<unknown>, B>(f: (...a: A) => Option<B>) => (...a: A) => HKT2<F, E, B> { const fromOptionF = fromOption(F) return (onNone) => { const from = fromOptionF(onNone) return (f) => flow(f, from) } } /** * @category combinators * @since 2.10.0 */ export function chainOptionK<F extends URIS4>( F: FromEither4<F>, M: Chain4<F> ): <E>(onNone: Lazy<E>) => <A, B>(f: (a: A) => Option<B>) => <S, R>(ma: Kind4<F, S, R, E, A>) => Kind4<F, S, R, E, B> export function chainOptionK<F extends URIS3>( F: FromEither3<F>, M: Chain3<F> ): <E>(onNone: Lazy<E>) => <A, B>(f: (a: A) => Option<B>) => <R>(ma: Kind3<F, R, E, A>) => Kind3<F, R, E, B> export function chainOptionK<F extends URIS3, E>( F: FromEither3C<F, E>, M: Chain3C<F, E> ): (onNone: Lazy<E>) => <A, B>(f: (a: A) => Option<B>) => <R>(ma: Kind3<F, R, E, A>) => Kind3<F, R, E, B> export function chainOptionK<F extends URIS2>( F: FromEither2<F>, M: Chain2<F> ): <E>(onNone: Lazy<E>) => <A, B>(f: (a: A) => Option<B>) => (ma: Kind2<F, E, A>) => Kind2<F, E, B> export function chainOptionK<F extends URIS2, E>( F: FromEither2C<F, E>, M: Chain2C<F, E> ): (onNone: Lazy<E>) => <A, B>(f: (a: A) => Option<B>) => (ma: Kind2<F, E, A>) => Kind2<F, E, B> export function chainOptionK<F>( F: FromEither<F>, M: Chain<F> ): <E>(onNone: Lazy<E>) => <A, B>(f: (a: A) => Option<B>) => (ma: HKT2<F, E, A>) => HKT2<F, E, B> export function chainOptionK<F extends URIS2>( F: FromEither2<F>, M: Chain2<F> ): <E>(onNone: Lazy<E>) => <A, B>(f: (a: A) => Option<B>) => (ma: Kind2<F, E, A>) => Kind2<F, E, B> { const fromOptionKF = fromOptionK(F) return (onNone) => { const from = fromOptionKF(onNone) return (f) => (ma) => M.chain(ma, from(f)) } } /** * @category combinators * @since 2.10.0 */ export function fromEitherK<F extends URIS4>( F: FromEither4<F> ): <A extends ReadonlyArray<unknown>, E, B>(f: (...a: A) => Either<E, B>) => <S, R>(...a: A) => Kind4<F, S, R, E, B> export function fromEitherK<F extends URIS3>( F: FromEither3<F> ): <A extends ReadonlyArray<unknown>, E, B>(f: (...a: A) => Either<E, B>) => <R>(...a: A) => Kind3<F, R, E, B> export function fromEitherK<F extends URIS3, E>( F: FromEither3C<F, E> ): <A extends ReadonlyArray<unknown>, B>(f: (...a: A) => Either<E, B>) => <R>(...a: A) => Kind3<F, R, E, B> export function fromEitherK<F extends URIS2>( F: FromEither2<F> ): <A extends ReadonlyArray<unknown>, E, B>(f: (...a: A) => Either<E, B>) => (...a: A) => Kind2<F, E, B> export function fromEitherK<F extends URIS2, E>( F: FromEither2C<F, E> ): <A extends ReadonlyArray<unknown>, B>(f: (...a: A) => Either<E, B>) => (...a: A) => Kind2<F, E, B> export function fromEitherK<F extends URIS>( F: FromEither1<F> ): <E, A extends ReadonlyArray<unknown>, B>(f: (...a: A) => Either<E, B>) => (...a: A) => Kind<F, B> export function fromEitherK<F>( F: FromEither<F> ): <A extends ReadonlyArray<unknown>, E, B>(f: (...a: A) => Either<E, B>) => (...a: A) => HKT2<F, E, B> export function fromEitherK<F>( F: FromEither<F> ): <A extends ReadonlyArray<unknown>, E, B>(f: (...a: A) => Either<E, B>) => (...a: A) => HKT2<F, E, B> { return (f) => flow(f, F.fromEither) } /** * @category combinators * @since 2.10.0 */ export function chainEitherK<M extends URIS4>( F: FromEither4<M>, M: Chain4<M> ): <A, E, B>(f: (a: A) => Either<E, B>) => <S, R>(ma: Kind4<M, S, R, E, A>) => Kind4<M, S, R, E, B> export function chainEitherK<M extends URIS3>( F: FromEither3<M>, M: Chain3<M> ): <A, E, B>(f: (a: A) => Either<E, B>) => <R>(ma: Kind3<M, R, E, A>) => Kind3<M, R, E, B> export function chainEitherK<M extends URIS3, E>( F: FromEither3C<M, E>, M: Chain3C<M, E> ): <A, B>(f: (a: A) => Either<E, B>) => <R>(ma: Kind3<M, R, E, A>) => Kind3<M, R, E, B> export function chainEitherK<M extends URIS2>( F: FromEither2<M>, M: Chain2<M> ): <A, E, B>(f: (a: A) => Either<E, B>) => (ma: Kind2<M, E, A>) => Kind2<M, E, B> export function chainEitherK<M extends URIS2, E>( F: FromEither2C<M, E>, M: Chain2C<M, E> ): <A, B>(f: (a: A) => Either<E, B>) => (ma: Kind2<M, E, A>) => Kind2<M, E, B> export function chainEitherK<M extends URIS>( F: FromEither1<M>, M: Chain1<M> ): <E, A, B>(f: (a: A) => Either<E, B>) => (ma: Kind<M, A>) => Kind<M, B> export function chainEitherK<M>( F: FromEither<M>, M: Chain<M> ): <A, E, B>(f: (a: A) => Either<E, B>) => (ma: HKT2<M, E, A>) => HKT2<M, E, B> export function chainEitherK<M extends URIS2>( F: FromEither2<M>, M: Chain2<M> ): <A, E, B>(f: (a: A) => Either<E, B>) => (ma: Kind2<M, E, A>) => Kind2<M, E, B> { const fromEitherKF = fromEitherK(F) return (f) => (ma) => M.chain(ma, fromEitherKF(f)) } /** * @category combinators * @since 2.10.0 */ export function filterOrElse<M extends URIS4>( F: FromEither4<M>, M: Chain4<M> ): { <A, B extends A, E>(refinement: Refinement<A, B>, onFalse: (a: A) => E): <S, R>( ma: Kind4<M, S, R, E, A> ) => Kind4<M, S, R, E, B> <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E): <S, R, B extends A>( mb: Kind4<M, S, R, E, B> ) => Kind4<M, S, R, E, B> <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E): <S, R>(ma: Kind4<M, S, R, E, A>) => Kind4<M, S, R, E, A> } export function filterOrElse<M extends URIS3>( F: FromEither3<M>, M: Chain3<M> ): { <A, B extends A, E>(refinement: Refinement<A, B>, onFalse: (a: A) => E): <R>( ma: Kind3<M, R, E, A> ) => Kind3<M, R, E, B> <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E): <R, B extends A>(mb: Kind3<M, R, E, B>) => Kind3<M, R, E, B> <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E): <R>(ma: Kind3<M, R, E, A>) => Kind3<M, R, E, A> } export function filterOrElse<M extends URIS3, E>( F: FromEither3C<M, E>, M: Chain3C<M, E> ): { <A, B extends A>(refinement: Refinement<A, B>, onFalse: (a: A) => E): <R>(ma: Kind3<M, R, E, A>) => Kind3<M, R, E, B> <A>(predicate: Predicate<A>, onFalse: (a: A) => E): <R, B extends A>(mb: Kind3<M, R, E, B>) => Kind3<M, R, E, B> <A>(predicate: Predicate<A>, onFalse: (a: A) => E): <R>(ma: Kind3<M, R, E, A>) => Kind3<M, R, E, A> } export function filterOrElse<M extends URIS2>( F: FromEither2<M>, M: Chain2<M> ): { <A, B extends A, E>(refinement: Refinement<A, B>, onFalse: (a: A) => E): (ma: Kind2<M, E, A>) => Kind2<M, E, B> <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E): <B extends A>(mb: Kind2<M, E, B>) => Kind2<M, E, B> <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E): (ma: Kind2<M, E, A>) => Kind2<M, E, A> } export function filterOrElse<M extends URIS2, E>( F: FromEither2C<M, E>, M: Chain2C<M, E> ): { <A, B extends A>(refinement: Refinement<A, B>, onFalse: (a: A) => E): (ma: Kind2<M, E, A>) => Kind2<M, E, B> <A>(predicate: Predicate<A>, onFalse: (a: A) => E): <B extends A>(mb: Kind2<M, E, B>) => Kind2<M, E, B> <A>(predicate: Predicate<A>, onFalse: (a: A) => E): (ma: Kind2<M, E, A>) => Kind2<M, E, A> } export function filterOrElse<M extends URIS2>( F: FromEither<M>, M: Chain<M> ): { <A, B extends A, E>(refinement: Refinement<A, B>, onFalse: (a: A) => E): (ma: HKT2<M, E, A>) => HKT2<M, E, B> <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E): <B extends A>(mb: HKT2<M, E, B>) => HKT2<M, E, B> <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E): (ma: HKT2<M, E, A>) => HKT2<M, E, A> } export function filterOrElse<M extends URIS2>( F: FromEither2<M>, M: Chain2<M> ): { <A, B extends A, E>(refinement: Refinement<A, B>, onFalse: (a: A) => E): (ma: Kind2<M, E, A>) => Kind2<M, E, B> <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E): <B extends A>(mb: Kind2<M, E, B>) => Kind2<M, E, B> <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E): (ma: Kind2<M, E, A>) => Kind2<M, E, A> } { return <A, E>(predicate: Predicate<A>, onFalse: (a: A) => E) => (ma: Kind2<M, E, A>): Kind2<M, E, A> => M.chain(ma, (a) => F.fromEither(predicate(a) ? _.right(a) : _.left(onFalse(a)))) }
the_stack
import { deserialize, deserializeAs, Deserialize, GenericDeserialize, GenericDeserializeInto, deserializeIndexable } from '../src/serialize'; class T1 { public x : number; public y : number; } class T2 { @deserialize public x : number; @deserialize public y : number; public static OnDeserialized() : void { } } class T3 { @deserializeAs(T2) child : T2; @deserialize x : number; public static OnDeserialized() : void { } } class T4 { @deserializeAs(Date) dateList : Array<Date>; } class T5 { @deserializeAs(Date) date: Date; } class JsonTest { @deserialize public obj : any; constructor() { this.obj = { key1: 1, nestedKey : { key2: 2 } } } } class Fruit { @deserialize public name: string; } class Tree { @deserialize public value: string; @deserializeAs(Fruit) fruits: Array<Fruit>; @deserializeAs(Tree) trees: Array<Tree>; } var DeserializerFn = function(src : any) : any { return 'custom!'; }; var Deserializer = { Deserialize: DeserializerFn }; class CustomDeserializeTest { @deserializeAs(Deserializer) public x : string; } class CustomDeserializeTest2 { @deserializeAs(DeserializerFn) public x : string; } describe('Deserialize', function () { it('should not deserialize if not marked with deserializer', function () { var json = { x: 1, y: 2 }; var instance = Deserialize(json, T1); expect((instance instanceof T1)).toBe(true); expect(instance.x).toBeUndefined(); expect(instance.y).toBeUndefined(); }); it('should deserialize if marked with deserializer', function () { var json = { x: 1, y: 2 }; var instance = Deserialize(json, T2); expect((instance instanceof T2)).toBe(true); expect(instance.x).toBe(1); expect(instance.y).toBe(2); }); it('should deserialize an array', function () { var json = [{ x: 1, y: 1 }, { x: 2, y: 2 }]; var list = Deserialize(json, T2); expect(Array.isArray(list)); expect(list.length).toBe(2); expect(list[0] instanceof T2).toBe(true); expect(list[0].x).toBe(1); expect(list[0].y).toBe(1); expect(list[1] instanceof T2).toBe(true); expect(list[1].x).toBe(2); expect(list[1].y).toBe(2); }); it('should deserialize a primitive', function () { expect(Deserialize(1)).toBe(1); expect(Deserialize(null)).toBe(null); expect(Deserialize(false)).toBe(false); expect(Deserialize(true)).toBe(true); expect(Deserialize('1')).toBe('1'); }); it('should deserialize a date', function () { var d = new Date(); var dateStr = d.toString(); var result = Deserialize(dateStr, Date); expect(result instanceof Date).toBe(true); }); it('should deserialize a date even when it\'s not a string', function () { var d = new Date(); var result = Deserialize(d, Date); expect(result instanceof Date).toBe(true); expect(result.toString()).toEqual(d.toString()) }); it('should deserialize a regex', function () { var r = /hi/; var regexStr = r.toString(); var result = Deserialize(regexStr, RegExp); expect(result instanceof RegExp).toBe(true); }); it('should deserialize a nested object as a type', function () { var t3 = { child: { x: 1, y: 1 }, x: 2 }; var result = Deserialize(t3, T3); expect(result instanceof T3).toBe(true); expect(result.child instanceof T2).toBe(true); expect(result.child.x).toBe(1); expect(result.child.y).toBe(1); expect(result.x).toBe(2); }); it('should deserialize a nested array as a type', function () { var d1 = new Date(); var d2 = new Date(); var d3 = new Date(); var t4 = { dateList: [d1.toString(), d2.toString(), d3] }; var result = Deserialize(t4, T4); expect(result instanceof T4).toBeTruthy(); expect(Array.isArray(result.dateList)).toBe(true); expect(result.dateList[0].toString()).toEqual(d1.toString()); expect(result.dateList[1].toString()).toEqual(d2.toString()); expect(result.dateList[2].toString()).toEqual(d3.toString()); }); it('should deserialize a Date property even if source is a Date object', function () { var t5 = { date: new Date() } var result = Deserialize(t5, T5); expect(result instanceof T5).toBeTruthy(); expect(result.date.toString()).toEqual(t5.date.toString()); }); it('should call OnDeserialize if defined on parent and or child', function () { var json = { child: {x : 1, y: 1}, x: 10 }; spyOn(T3, 'OnDeserialized').and.callThrough(); spyOn(T2, 'OnDeserialized').and.callThrough(); var result = Deserialize(json, T3); expect(T3.OnDeserialized).toHaveBeenCalledWith(result, json); expect(T2.OnDeserialized).toHaveBeenCalledWith(result.child, json.child); }); it('should deserialize js objects tagged with deserialize', function(){ var testJson = new JsonTest(); var result = Deserialize(testJson, JsonTest); expect(result).toBeDefined(); expect(typeof result.obj === "object").toBeTruthy(); expect(result.obj.key1).toBe(1); expect(result.obj.nestedKey.key2).toBe(2); }); it('should deserialize js primitive arrays tagged with deserialize', function() { }); it('should use a custom deserializer', function() { var testJson = { "x": new Date().toString() }; var result = Deserialize(testJson, CustomDeserializeTest); expect(result.x).toBe("custom!"); }); it('should use a custom deserialize function', function() { var testJson = { "x": new Date().toString() }; var result = Deserialize(testJson, CustomDeserializeTest2); expect(result.x).toBe("custom!"); }); it('should cast to primitive array when given a primitive type', function() { class Test { @deserializeAs(String) public arrayOfString: Array<string>; @deserializeAs(Number) public arrayOfNumber: Array<number>; @deserializeAs(Boolean) public arrayOfBoolean: Array<boolean>; } var json = { arrayOfString: ['String1', 'String2'], arrayOfNumber: [1, 2], arrayOfBoolean: [true, false] }; var test : Test = Deserialize(json, Test); expect(Array.isArray(test.arrayOfString)).toBe(true); expect(test.arrayOfString[0]).toBe("String1"); expect(test.arrayOfString[1]).toBe("String2"); expect(Array.isArray(test.arrayOfNumber)).toBe(true); expect(test.arrayOfNumber[0]).toBe(1); expect(test.arrayOfNumber[1]).toBe(2); expect(Array.isArray(test.arrayOfBoolean)).toBe(true); expect(test.arrayOfBoolean[0]).toBe(true); expect(test.arrayOfBoolean[1]).toBe(false); }); it('should cast to primitive type when given a primitive type', function() { class Test { @deserializeAs(String) public str: string; @deserializeAs(Number) public num: number; @deserializeAs(Boolean) public bool: boolean; @deserializeAs(Number) public float: number; } var json = { str: 1, num: "2", bool: 3, float: "3.1415" }; var test : Test = Deserialize(json, Test); expect(test.str).toBe('1'); expect(test.num).toBe(2); expect(test.bool).toBe(true); expect(test.float).toBe(3.1415); }); //contributed by @1ambda it('should deserialize a json including nested empty arrays', function() { var root1 = { trees: new Array<Tree>(), value: "root1" }; var deserialized1 = Deserialize(root1, Tree); expect(deserialized1.trees.length).toBe(0); expect(deserialized1.value).toBe("root1"); /** * `-- root * |-- t1 * `-- t2 * |-- t3 * `-- t4 */ var root2 = { trees: [{ value: "t1" , trees: new Array<Tree>() }, { value: "t2", trees: [{ value: "t3", trees: new Array<Tree>() }, { value: "t4", trees: new Array<Tree>() }] }], value: "root2" }; var deserialized2 = Deserialize(root2, Tree); expect(deserialized2.trees.length).toBe(2); expect(deserialized2.trees[0].trees.length).toBe(0); /* t1 includes empty trees */ expect(deserialized2.trees[1].trees.length).toBe(2); /* t2 includes 2 trees (t3, t4) */ }); it("should deserialize custom objects into an array", function() { // class Item { } }) it("should deserialize empty json into an empty string") it('should deserialize a json including nested, multiple empty arrays', function() { var root1 = { fruits: new Array<Fruit>(), trees: new Array<Tree>(), value: "root1" }; var deserialized1 = Deserialize(root1, Tree); expect(deserialized1.trees.length).toBe(0); expect(deserialized1.value).toBe("root1"); expect(deserialized1.fruits.length).toBe(0); /** * `-- root * |-- t1 including f1 * `-- t2 * |-- t3 including f3 * `-- t4 */ var root2 = { trees: [{ value: "t1" , trees: new Array<Tree>(), fruits: new Array<Fruit>(), }, { value: "t2", trees: [{ value: "t3", trees: new Array<Tree>(), fruits: new Array<Fruit>(), }, { value: "t4", trees: new Array<Tree>() }] }], value: "root2" }; var deserialized2 = Deserialize(root2, Tree); expect(deserialized2.trees.length).toBe(2); expect(deserialized2.trees[0].trees.length).toBe(0); /* t1 includes empty trees */ expect(deserialized2.trees[0].fruits.length).toBe(0); /* t1 includes empty fruits */ expect(deserialized2.trees[1].trees.length).toBe(2); /* t2 includes 2 trees (t3, t4) */ expect(deserialized2.trees[1].trees[0].trees.length).toBe(0); /* t3 includes empty trees */ expect(deserialized2.trees[1].trees[0].fruits.length).toBe(0); /* t3 includes fruits trees */ expect(deserialized2.trees[1].trees[1].trees.length).toBe(0); /* t4 includes empty trees */ expect(deserialized2.trees[1].trees[1].fruits).toBeUndefined(); /* t4 has no fruits */ }); it("Should deserialize indexable object", function () { class Y { @deserialize thing : string; } class X { @deserializeIndexable(Y) yMap : any; } var map : any = { yMap: { 1: { thing: '1' }, 2: { thing: '2' } } }; var x : X = Deserialize(map, X); expect(x.yMap[1] instanceof(Y)).toBe(true); expect(x.yMap[2] instanceof(Y)).toBe(true); }); }); describe('Deserialize generics', function () { it('should handle a generic deserialize', function () { var tree = GenericDeserialize({value: "someValue"}, Tree); expect((tree instanceof Tree)).toBe(true); expect(tree.value).toBe("someValue"); }); it('should handle a generic deserializeInto', function () { var tree = new Tree(); tree.value = 'hello'; var tree2 = GenericDeserializeInto({value: "someValue"}, Tree, tree); expect((tree2 instanceof Tree)).toBe(true); expect(tree2).toBe(tree); expect(tree.value).toBe("someValue"); }); }); //rest of file contributed by @1ambda export interface NoParamConstructor<T> { new (): T } export abstract class Deserializable { public static deserialize<T>(ctor: NoParamConstructor<T>, json : any): T { return Deserialize(json, ctor); } public static deserializeArray<T>(ctor: NoParamConstructor<T>, json : any): Array<T> { return Deserialize(json, ctor); } } class Car extends Deserializable { @deserialize public engine: string; @deserialize public wheels: number; } describe("Deserializable", () => { describe("deserialize", () => { it("should parse Car", () => { let json : any = {engine: "M5", wheels: 4}; let c1 = Car.deserialize(Car, json); let c2 = Car.deserialize<Car>(Car, json); // without NoParamConstructor expect(c1.engine).toEqual(json.engine); expect(c1.wheels).toEqual(json.wheels); }); }); });
the_stack
import { Environment, HighestMigrationId } from '@mockoon/commons'; import { expect } from 'chai'; import { promises as fs } from 'fs'; import { resolve } from 'path'; import { Config } from 'src/renderer/app/config'; import { Settings } from 'src/shared/models/settings.model'; import { Tests } from 'test/lib/tests'; describe('Schema validation', () => { describe('Unable to migrate, repair', () => { const tests = new Tests('schema-validation/broken'); it('should fail migration and repair if too broken (route object missing)', async () => { await tests.helpers.checkToastDisplayed( 'warning', 'Migration of environment "Missing route object" failed. The environment was automatically repaired and migrated to the latest version.' ); await tests.helpers.waitForAutosave(); await tests.helpers.verifyObjectPropertyInFile( './tmp/storage/environment-0.json', [ 'lastMigration', // indirectly verify that it's an array 'routes.0' ], [HighestMigrationId, undefined] ); }); }); describe('Generic (test with Settings)', () => { const genericTestCases = [ { path: 'schema-validation/empty-file', describeTitle: 'Empty file', testTitle: 'should fix empty file', preTest: async (fileContent) => { expect(() => { JSON.parse(fileContent); }).to.throw('Unexpected end of JSON input'); } }, { path: 'schema-validation/null-content', describeTitle: 'Null content', testTitle: 'should fix null content', preTest: async (fileContent) => { expect(JSON.parse(fileContent)).to.equal(null); } }, { path: 'schema-validation/empty-object', describeTitle: 'Empty object', testTitle: 'should fix empty object', preTest: async (fileContent) => { expect(JSON.parse(fileContent)).to.be.an('object'); } }, { path: 'schema-validation/corrupted-content', describeTitle: 'Corrupted content', testTitle: 'should fix corrupted content', preTest: async (fileContent) => { expect(JSON.parse(fileContent)).to.be.an('object'); } } ]; genericTestCases.forEach((genericTestCase) => { describe(genericTestCase.describeTitle, () => { const tests = new Tests(genericTestCase.path, true, true, false); it(genericTestCase.testTitle, async () => { const fileContent = ( await fs.readFile('./tmp/storage/settings.json') ).toString(); genericTestCase.preTest(fileContent); await tests.helpers.waitForAutosave(); await tests.helpers.verifyObjectPropertyInFile( './tmp/storage/settings.json', 'welcomeShown', false ); }); }); }); }); describe('Settings', () => { const tests = new Tests('schema-validation/settings', true, true, false); it('should verify initial properties (missing, invalid, unknown)', async () => { const fileContent: Settings = JSON.parse( (await fs.readFile('./tmp/storage/settings.json')).toString() ); expect(fileContent.logsMenuSize).to.be.undefined; expect(fileContent.bannerDismissed).to.be.undefined; expect((fileContent as any).unknown).to.equal(true); expect(fileContent.environments).to.include.members([null, 'unknown']); expect(fileContent.environments[2]).to.include({ uuid: '', path: '/home/username/file1.json' }); }); it('should verify saved properties (missing, invalid, unknown)', async () => { await tests.helpers.waitForAutosave(); const fileContent: Settings = JSON.parse( (await fs.readFile('./tmp/storage/settings.json')).toString() ); // add missing properties with default expect(fileContent.logsMenuSize).to.equal(150); expect(fileContent.bannerDismissed) .to.be.an('array') .that.have.lengthOf(0); // remove unknown values expect((fileContent as any).unknown).to.be.undefined; // remove invalid values expect(fileContent.environments).to.be.an('array').that.have.lengthOf(0); }); }); describe('Environments', () => { const tests = new Tests('schema-validation/environments'); it('should verify initial properties (missing, invalid, unknown)', async () => { const fileContent: Environment = JSON.parse( (await fs.readFile('./tmp/storage/environment-0.json')).toString() ); expect(fileContent.routes[0].uuid).to.equal('non-uuid'); expect(fileContent.name).to.be.undefined; expect(fileContent.routes[0].responses[0].rulesOperator).to.equal( 'DUMMY' ); expect(fileContent.routes[0].enabled).to.equal(null); expect(fileContent.routes[0].responses[0].statusCode).to.equal(99); // allow empty body expect(fileContent.routes[0].responses[0].body).to.equal(''); // allow enum in target expect(fileContent.routes[0].responses[0].rules[1].target).to.equal( 'invalid' ); // invalid array item expect(fileContent.routes[0].responses[0].headers) .to.be.an('array') .that.have.lengthOf(2); expect( (fileContent.routes[0].responses[0].headers[0] as any).unknown ).to.equal(true); }); it('should verify saved properties (missing, invalid, unknown)', async () => { await tests.helpers.waitForAutosave(); const fileContent: Environment = JSON.parse( (await fs.readFile('./tmp/storage/environment-0.json')).toString() ); expect(fileContent.routes[0].uuid).to.be.a.uuid('v4'); expect(fileContent.name).to.equal('New environment'); expect(fileContent.routes[0].responses[0].rulesOperator).to.equal('OR'); expect(fileContent.routes[0].enabled).to.equal(true); expect(fileContent.routes[0].responses[0].statusCode).to.equal(200); // allow empty body expect(fileContent.routes[0].responses[0].body).to.equal(''); // allow enum in target expect(fileContent.routes[0].responses[0].rules[1].target).to.equal( 'body' ); // strip invalid array item expect(fileContent.routes[0].responses[0].headers) .to.be.an('array') .that.have.lengthOf(1); expect(fileContent.routes[0].responses[0].headers[0].key).to.equal( 'Content-Type' ); }); }); describe('Route', () => { const tests = new Tests( 'schema-validation/broken-route', true, true, false ); it('Should import the broken route and fix the schema', async () => { const fileContent = await fs.readFile( './test/data/schema-validation/broken-route/route-export-broken.json', 'utf-8' ); tests.app.electron.clipboard.writeText( fileContent.replace('##appVersion##', Config.appVersion) ); tests.helpers.mockDialog('showSaveDialog', [ resolve('./tmp/storage/new-environment.json') ]); tests.helpers.selectMenuEntry('IMPORT_CLIPBOARD'); await tests.app.client.pause(500); await tests.helpers.countEnvironments(1); await tests.helpers.countRoutes(1); await tests.helpers.waitForAutosave(); const envFileContent: Environment = JSON.parse( (await fs.readFile('./tmp/storage/new-environment.json')).toString() ); // verify that properties exists expect(envFileContent.uuid).to.be.a.uuid('v4'); expect(envFileContent.routes[0].uuid).to.be.a.uuid('v4'); expect(envFileContent.routes[0].enabled).to.equal(true); expect(envFileContent.routes[0].responses[0].statusCode).to.equal(200); }); }); describe('UUID deduplication (environment)', () => { const tests = new Tests('schema-validation/uuid-dedup'); const initialUUID = 'a93e9c88-62f9-40a7-be4f-9645e1988d8a'; it('should deduplicate UUIDs at launch', async () => { await tests.helpers.waitForAutosave(); const env0Content: Environment = JSON.parse( (await fs.readFile('./tmp/storage/environment-0.json')).toString() ); const env1Content: Environment = JSON.parse( (await fs.readFile('./tmp/storage/environment-1.json')).toString() ); expect(env0Content.uuid).to.equal(initialUUID); expect(env0Content.routes[0].uuid).to.not.equal(initialUUID); expect(env0Content.routes[0].uuid).to.be.a.uuid('v4'); expect(env0Content.routes[0].responses[0].uuid).to.not.equal(initialUUID); expect(env0Content.routes[0].responses[0].uuid).to.be.a.uuid('v4'); expect(env1Content.uuid).to.not.equal(initialUUID); expect(env1Content.uuid).to.be.a.uuid('v4'); expect(env1Content.routes[0].uuid).to.not.equal(initialUUID); expect(env1Content.routes[0].uuid).to.be.a.uuid('v4'); expect(env1Content.routes[0].responses[0].uuid).to.not.equal(initialUUID); expect(env1Content.routes[0].responses[0].uuid).to.be.a.uuid('v4'); await tests.helpers.verifyObjectPropertyInFile( './tmp/storage/settings.json', ['environments.0.uuid', 'environments.1.uuid'], [initialUUID, env1Content.uuid] ); }); it('should deduplicate UUIDs when opening another environment', async () => { await fs.copyFile( './test/data/schema-validation/uuid-dedup/env-to-load.json', './tmp/storage/env-to-load.json' ); tests.helpers.mockDialog('showOpenDialog', [ resolve('./tmp/storage/env-to-load.json') ]); await tests.helpers.openEnvironment(); await tests.app.client.pause(500); await tests.helpers.countEnvironments(3); await tests.helpers.assertHasActiveEnvironment('uuid dedup load'); await tests.helpers.waitForAutosave(); const envContent: Environment = JSON.parse( (await fs.readFile('./tmp/storage/env-to-load.json')).toString() ); expect(envContent.uuid).to.not.equal(initialUUID); expect(envContent.uuid).to.be.a.uuid('v4'); expect(envContent.routes[0].uuid).to.not.equal(initialUUID); expect(envContent.routes[0].uuid).to.be.a.uuid('v4'); expect(envContent.routes[0].responses[0].uuid).to.not.equal(initialUUID); expect(envContent.routes[0].responses[0].uuid).to.be.a.uuid('v4'); }); it('should deduplicate UUIDs when importing another environment', async () => { tests.helpers.mockDialog('showOpenDialog', [ './test/data/schema-validation/uuid-dedup/env-to-import.json' ]); tests.helpers.mockDialog('showSaveDialog', [ resolve('./tmp/storage/env-to-import.json') ]); tests.helpers.selectMenuEntry('IMPORT_FILE'); await tests.app.client.pause(500); await tests.helpers.countEnvironments(4); await tests.helpers.assertHasActiveEnvironment('uuid dedup import'); await tests.helpers.waitForAutosave(); const envContent: Environment = JSON.parse( (await fs.readFile('./tmp/storage/env-to-import.json')).toString() ); expect(envContent.uuid).to.not.equal(initialUUID); expect(envContent.uuid).to.be.a.uuid('v4'); expect(envContent.routes[0].uuid).to.not.equal(initialUUID); expect(envContent.routes[0].uuid).to.be.a.uuid('v4'); expect(envContent.routes[0].responses[0].uuid).to.not.equal(initialUUID); expect(envContent.routes[0].responses[0].uuid).to.be.a.uuid('v4'); }); }); describe('Mockoon format identifier', () => { const tests = new Tests( 'schema-validation/missing-identifier', true, true, false ); it('should prompt before opening an environment where identifier (lastmigration) is missing', async () => { await fs.copyFile( './test/data/schema-validation/missing-identifier/env-to-load.json', './tmp/storage/env-to-load.json' ); tests.helpers.mockDialog('showOpenDialog', [ resolve('./tmp/storage/env-to-load.json') ]); await tests.helpers.openEnvironment(); await tests.app.client.waitUntilTextExists( '.modal-title', 'Confirm file opening' ); }); it('should not open the file if cancel is clicked', async () => { await tests.helpers.elementClick('.modal-footer .btn:last-of-type'); await tests.helpers.countEnvironments(0); }); it('should open the file and fix the schema if confirm is clicked', async () => { tests.helpers.mockDialog('showOpenDialog', [ resolve('./tmp/storage/env-to-load.json') ]); await tests.helpers.openEnvironment(); await tests.app.client.waitUntilTextExists( '.modal-title', 'Confirm file opening' ); await tests.helpers.elementClick('.modal-footer .btn:first-of-type'); await tests.helpers.countEnvironments(1); await tests.helpers.assertActiveEnvironmentName('missing identifier'); await tests.helpers.waitForAutosave(); await tests.helpers.verifyObjectPropertyInFile( './tmp/storage/env-to-load.json', ['lastMigration'], [HighestMigrationId] ); }); }); });
the_stack
import { BentleyError, Id64String } from "@itwin/core-bentley"; import { Angle, AngleSweep, Arc3d, BSplineCurve3d, CurveCollection, CurveFactory, CurvePrimitive, FrameBuilder, Geometry, GeometryQuery, IModelJson, InterpolationCurve3d, InterpolationCurve3dOptions, InterpolationCurve3dProps, LineString3d, Loop, Matrix3d, Path, Plane3dByOriginAndUnitNormal, Point3d, PointString3d, Ray3d, RegionOps, Transform, Vector3d, YawPitchRollAngles } from "@itwin/core-geometry"; import { Code, ColorDef, ElementGeometry, ElementGeometryInfo, FlatBufferGeometryStream, GeometricElementProps, GeometryParams, GeometryStreamProps, isPlacement3dProps, JsonGeometryStream, LinePixels, PlacementProps } from "@itwin/core-common"; import { AccuDrawHintBuilder, AngleDescription, BeButton, BeButtonEvent, BeModifierKeys, CoreTools, DecorateContext, DynamicsContext, EventHandled, GraphicType, HitDetail, IModelApp, LengthDescription, NotifyMessageDetails, OutputMessagePriority, SnapDetail, TentativeOrAccuSnap, ToolAssistance, ToolAssistanceImage, ToolAssistanceInputMethod, ToolAssistanceInstruction, ToolAssistanceSection } from "@itwin/core-frontend"; import { BasicManipulationCommandIpc, editorBuiltInCmdIds } from "@itwin/editor-common"; import { computeChordToleranceFromPoint, CreateElementTool, DynamicGraphicsProvider } from "./CreateElementTool"; import { EditTools } from "./EditTool"; import { DialogItem, DialogProperty, DialogPropertySyncItem, EnumerationChoice, PropertyDescriptionHelper, PropertyEditorParamTypes, RangeEditorParams } from "@itwin/appui-abstract"; /** @alpha Values for [[CreateOrContinueTool.createCurvePhase] to support join and closure. */ export enum CreateCurvePhase { /** Current tool phase changes CurvePrimitive startPoint. * ex. Arc defined by center, start would return this when accepted length is 1. */ DefineStart, /** Current tool phase changes CurvePrimitive endPoint. * ex. Arc defined by start, end, mid would return this when accepted length is 1. */ DefineEnd, /** Current tool phase does NOT change CurvePrimitive startPoint or endPoint. * ex. When defining arc mid point, or start and end tangents for a bcurve return this. */ DefineOther, } /** @alpha Base class for creating open and closed paths. */ export abstract class CreateOrContinuePathTool extends CreateElementTool { protected readonly accepted: Point3d[] = []; protected current?: CurvePrimitive; protected continuationData?: { props: GeometricElementProps, path: Path, params: GeometryParams }; protected isClosed = false; protected isConstruction = false; // Sub-classes can set in createNewCurvePrimitive to bypass creating element graphics... protected _graphicsProvider?: DynamicGraphicsProvider; protected _snapGeomId?: Id64String; protected _startedCmd?: string; protected async startCommand(): Promise<string> { if (undefined !== this._startedCmd) return this._startedCmd; return EditTools.startCommand<string>(editorBuiltInCmdIds.cmdBasicManipulation, this.iModel.key); } public static callCommand<T extends keyof BasicManipulationCommandIpc>(method: T, ...args: Parameters<BasicManipulationCommandIpc[T]>): ReturnType<BasicManipulationCommandIpc[T]> { return EditTools.callCommand(method, ...args) as ReturnType<BasicManipulationCommandIpc[T]>; } protected override get wantAccuSnap(): boolean { return true; } protected override get wantDynamics(): boolean { return true; } protected get allowJoin(): boolean { return this.isControlDown; } protected get allowClosure(): boolean { return this.isControlDown; } protected get allowSimplify(): boolean { return true; } protected get wantSmartRotation(): boolean { return this.isContinueExistingPath || this.isControlDown; } protected get wantPickableDynamics(): boolean { return false; } protected get wantJoin(): boolean { return this.allowJoin; } protected get wantClosure(): boolean { return this.isContinueExistingPath && this.allowClosure; } protected get wantSimplify(): boolean { return this.allowSimplify; } protected get showCurveConstructions(): boolean { return false; } protected get showJoin(): boolean { return this.isContinueExistingPath && CreateCurvePhase.DefineStart === this.createCurvePhase; } protected get showClosure(): boolean { return this.isClosed && CreateCurvePhase.DefineEnd === this.createCurvePhase; } /** Sub-classes should override unless first point changes startPoint and last point changes endPoint. */ protected get createCurvePhase(): CreateCurvePhase { return (0 === this.accepted.length ? CreateCurvePhase.DefineStart : CreateCurvePhase.DefineEnd); } /** Implemented by sub-classes to create the new curve or construction curve for placement dynamics. * @param ev The current button event from a click or motion event. * @param isDynamics true when called for dynamics and the point from ev should be included in the result curve. * @internal */ protected abstract createNewCurvePrimitive(ev: BeButtonEvent, isDynamics: boolean): CurvePrimitive | undefined; protected getCurrentRotation(ev: BeButtonEvent): Matrix3d { const matrix = (undefined !== ev.viewport ? AccuDrawHintBuilder.getCurrentRotation(ev.viewport, true, true) : undefined); return (undefined !== matrix ? matrix : Matrix3d.createIdentity()); } protected getUpVector(ev: BeButtonEvent): Vector3d { return this.getCurrentRotation(ev).getColumn(2); } protected async updateCurveAndContinuationData(ev: BeButtonEvent, isDynamics: boolean, phase: CreateCurvePhase): Promise<void> { this.isConstruction = false; this.current = this.createNewCurvePrimitive(ev, isDynamics); if (CreateCurvePhase.DefineStart === phase) await this.isValidForJoin(); // Updates this.continuationData... else if (CreateCurvePhase.DefineEnd === phase) await this.isValidForClosure(); // Updates this.isClosed... } protected get isContinueExistingPath(): boolean { return undefined !== this.continuationData; } protected async isValidForContinue(snap: SnapDetail): Promise<{ props: GeometricElementProps, path: Path, params: GeometryParams } | undefined> { if (!snap.isElementHit) return; const snapCurve = snap.getCurvePrimitive(); if (undefined === snapCurve) return; const curveS = snapCurve.startPoint(); const curveE = snapCurve.endPoint(); if (curveS.isAlmostEqual(curveE)) return; // Reject snap to single physically closed curve primitive... const snapPt = snap.adjustedPoint; if (!(snapPt.isAlmostEqual(curveS) || snapPt.isAlmostEqual(curveE))) return; // No point to further checks if snap wasn't to endpoint of curve primitive... try { this._startedCmd = await this.startCommand(); const info = await CreateOrContinuePathTool.callCommand("requestElementGeometry", snap.sourceId, { maxDisplayable: 1, geometry: { curves: true, surfaces: false, solids: false } }); if (undefined === info) return; const data = CreateOrContinuePathTool.isSingleOpenPath(info); if (undefined === data) return; const props = await this.iModel.elements.loadProps(snap.sourceId) as GeometricElementProps; if (undefined === props) return; return { props, path: data.path, params: data.params }; } catch (err) { IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Error, BentleyError.getErrorMessage(err) || "An unknown error occurred.")); return; } } protected async isValidForJoin(): Promise<boolean> { this.continuationData = undefined; if (!this.wantJoin) return false; if (undefined === this.current) return false; const snap = TentativeOrAccuSnap.getCurrentSnap(); if (undefined === snap) return false; const data = await this.isValidForContinue(snap); if (undefined === data) return false; if (!CreateOrContinuePathTool.isPathEndPoint(this.current, data.path)) return false; this.continuationData = data; return true; } protected async isValidForClosure(): Promise<boolean> { this.isClosed = false; if (!this.wantClosure) return false; if (undefined === this.current) return false; return (this.isClosed = CreateOrContinuePathTool.isPathClosurePoint(this.current, this.continuationData?.path)); } public static isSingleOpenPath(info: ElementGeometryInfo): { path: Path, params: GeometryParams } | undefined { const it = new ElementGeometry.Iterator(info); it.requestWorldCoordinates(); for (const entry of it) { const geom = entry.toGeometryQuery(); if (undefined === geom) return; if ("curvePrimitive" === geom.geometryCategory) { const curve = geom as CurvePrimitive; const curveS = curve.startPoint(); const curveE = curve.endPoint(); if (curveS.isAlmostEqual(curveE)) return; // Reject zero length lines, physically closed arcs, linestrings, etc... return { path: Path.create(curve), params: entry.geomParams }; } else if ("curveCollection" === geom.geometryCategory) { const curves = geom as CurveCollection; if (!curves.isOpenPath) return; const path = curves as Path; const curveS = path.children[0].startPoint(); const curveE = path.children[path.children.length - 1].endPoint(); if (curveS.isAlmostEqual(curveE)) return; // Reject physically closed path... return { path, params: entry.geomParams }; } break; } return; } public static isPathEndPoint(curve: CurvePrimitive, path: Path): boolean { const curveS = curve.startPoint(); const pathS = path.children[0].startPoint(); const pathE = path.children[path.children.length - 1].endPoint(); if (!(curveS.isAlmostEqual(pathS) || curveS.isAlmostEqual(pathE))) return false; return true; } public static isPathClosurePoint(curve: CurvePrimitive, path?: Path): boolean { const length = curve.quickLength(); if (length < Geometry.smallMetricDistance) return false; const curveS = curve.startPoint(); const curveE = curve.endPoint(); if (undefined === path) { if (!curveS.isAlmostEqual(curveE)) return false; const curveLocalToWorld = FrameBuilder.createRightHandedFrame(undefined, curve); if (undefined === curveLocalToWorld) return false; // Don't create a Loop unless new CurvePrimitive is planar... const curvePlane = Plane3dByOriginAndUnitNormal.create(curveLocalToWorld.getOrigin(), curveLocalToWorld.matrix.getColumn(2)); return (undefined !== curvePlane && curve.isInPlane(curvePlane)); } const pathS = path.children[0].startPoint(); const pathE = path.children[path.children.length - 1].endPoint(); if (!(curveS.isAlmostEqual(pathS) && curveE.isAlmostEqual(pathE) || curveS.isAlmostEqual(pathE) && curveE.isAlmostEqual(pathS))) return false; const pathLocalToWorld = FrameBuilder.createRightHandedFrame(undefined, [curve, path]); if (undefined === pathLocalToWorld) return false; // Don't create a Loop unless new CurvePrimitive + existing Path is planar... const pathPlane = Plane3dByOriginAndUnitNormal.create(pathLocalToWorld.getOrigin(), pathLocalToWorld.matrix.getColumn(2)); if (undefined === pathPlane) return false; if (!curve.isInPlane(pathPlane)) return false; for (const child of path.children) { if (!child.isInPlane(pathPlane)) return false; } return true; } protected clearGraphics(): void { if (undefined === this._graphicsProvider) return; this._graphicsProvider.cleanupGraphic(); this._graphicsProvider = undefined; } protected async createGraphics(ev: BeButtonEvent): Promise<void> { await this.updateCurveAndContinuationData(ev, true, this.createCurvePhase); if (!IModelApp.viewManager.inDynamicsMode || this.isConstruction) return; // Don't need to create graphic if dynamics aren't yet active... const placement = this.getPlacementProps(); if (undefined === placement) return; const geometry = this.getGeometryProps(placement); if (undefined === geometry) return; if (undefined === this._graphicsProvider) this._graphicsProvider = new DynamicGraphicsProvider(this.iModel, this.toolId); // Set chord tolerance for non-linear curve primitives... if (ev.viewport) this._graphicsProvider.chordTolerance = computeChordToleranceFromPoint(ev.viewport, ev.point); await this._graphicsProvider.createGraphic(this.targetCategory, placement, geometry); } protected addConstructionGraphics(curve: CurvePrimitive, showCurve: boolean, context: DynamicsContext): void { if (!showCurve) { switch (curve.curvePrimitiveType) { case "arc": case "bsplineCurve": case "interpolationCurve": break; default: return; } } const builder = context.createGraphic({ type: GraphicType.WorldOverlay }); builder.setSymbology(context.viewport.getContrastToBackgroundColor(), ColorDef.black, 1, LinePixels.Code2); if (showCurve) builder.addPath(Path.create(curve)); switch (curve.curvePrimitiveType) { case "arc": { const arc = curve as Arc3d; const start = arc.startPoint(); const end = arc.endPoint(); builder.addLineString([arc.center, start]); if (!start.isAlmostEqual(end)) builder.addLineString([arc.center, end]); builder.setSymbology(context.viewport.getContrastToBackgroundColor(), ColorDef.black, 5); builder.addPointString([arc.center]); break; } case "bsplineCurve": { const bcurve = curve as BSplineCurve3d; const poles: Point3d[] = []; for (let iPole = 0; iPole < bcurve.numPoles; ++iPole) { const polePt = bcurve.getPolePoint3d(iPole); if (undefined !== polePt) poles.push(polePt); } builder.addLineString(poles); builder.setSymbology(context.viewport.getContrastToBackgroundColor(), ColorDef.black, 5); builder.addPointString(poles); break; } case "interpolationCurve": { const fitCurve = curve as InterpolationCurve3d; builder.setSymbology(context.viewport.getContrastToBackgroundColor(), ColorDef.black, 5); builder.addPointString(fitCurve.options.fitPoints); // deep copy shoulnd't be necessary... break; } default: break; } context.addGraphic(builder.finish()); } protected showConstructionGraphics(_ev: BeButtonEvent, context: DynamicsContext): boolean { if (undefined === this.current) return false; if (!this.isConstruction) { if (this.showCurveConstructions) this.addConstructionGraphics(this.current, false, context); return false; } this.addConstructionGraphics(this.current, true, context); return true; } public override onDynamicFrame(ev: BeButtonEvent, context: DynamicsContext): void { if (this.showConstructionGraphics(ev, context)) return; // Don't display element graphics... if (undefined !== this._graphicsProvider) this._graphicsProvider.addGraphic(context); } public override async onMouseMotion(ev: BeButtonEvent): Promise<void> { return this.createGraphics(ev); } protected showJoinIndicator(context: DecorateContext, pt: Point3d): void { const lengthX = Math.floor(context.viewport.pixelsFromInches(0.08)) + 0.5; const lengthY = Math.floor(lengthX * 0.6) + 0.5; const offsetX = lengthX * 3; const offsetY = lengthY * 3; const position = context.viewport.worldToView(pt); position.x = Math.floor(position.x - offsetX) + 0.5; position.y = Math.floor(position.y + offsetY) + 0.5; const drawDecoration = (ctx: CanvasRenderingContext2D) => { ctx.beginPath(); ctx.strokeStyle = "rgba(0,0,0,.8)"; ctx.lineWidth = 3; ctx.lineCap = "round"; ctx.moveTo(-lengthX, lengthY); ctx.lineTo(0, lengthY); ctx.lineTo(0, -lengthY); ctx.lineTo(lengthX, -lengthY); ctx.stroke(); ctx.beginPath(); ctx.strokeStyle = "rgba(255,255,255,.8)"; ctx.lineWidth = 1; ctx.moveTo(-lengthX, lengthY); ctx.lineTo(0, lengthY); ctx.lineTo(0, -lengthY); ctx.lineTo(lengthX, -lengthY); ctx.stroke(); ctx.beginPath(); ctx.strokeStyle = "rgba(0,0,0,.8)"; ctx.fillStyle = "rgba(0,255,255,.8)"; ctx.arc(0, -lengthY, 2.5, 0, 2 * Math.PI); ctx.fill(); ctx.stroke(); }; context.addCanvasDecoration({ position, drawDecoration }, true); } protected showClosureIndicator(context: DecorateContext, pt: Point3d): void { const radius = Math.floor(context.viewport.pixelsFromInches(0.06)) + 0.5; const offset = radius * 2.5; const position = context.viewport.worldToView(pt); position.x = Math.floor(position.x - offset) + 0.5; position.y = Math.floor(position.y + offset) + 0.5; const drawDecoration = (ctx: CanvasRenderingContext2D) => { ctx.beginPath(); ctx.strokeStyle = "rgba(255,255,255,.8)"; ctx.lineWidth = 1; ctx.fillStyle = "rgba(0,0,255,.2)"; ctx.arc(0, 0, radius, 0, 2 * Math.PI); ctx.fill(); ctx.stroke(); ctx.beginPath(); ctx.strokeStyle = "rgba(0,0,0,.8)"; ctx.arc(0, 0, radius + 1, 0, 2 * Math.PI); ctx.stroke(); ctx.beginPath(); ctx.strokeStyle = "rgba(0,0,0,.8)"; ctx.fillStyle = "rgba(0,255,255,.8)"; ctx.arc(-radius, 0, 2.5, 0, 2 * Math.PI); ctx.fill(); ctx.stroke(); }; context.addCanvasDecoration({ position, drawDecoration }, true); } public override testDecorationHit(id: Id64String): boolean { return id === this._snapGeomId; } public override async getToolTip(hit: HitDetail): Promise<HTMLElement | string> { if (this.testDecorationHit(hit.sourceId)) return this.description; return super.getToolTip(hit); } protected getSnapGeometry(): GeometryQuery | undefined { if (this.accepted.length < 2) return; // Treat accepted points as linear segments by default... return LineString3d.create(this.accepted); } public override getDecorationGeometry(_hit: HitDetail): GeometryStreamProps | undefined { const geomQuery = this.getSnapGeometry(); if (undefined === geomQuery) return; const geomJson = IModelJson.Writer.toIModelJson(geomQuery); return geomJson ? [geomJson] : undefined; } protected addPickableGraphics(context: DecorateContext): void { const geomQuery = this.getSnapGeometry(); if (undefined === geomQuery) return; if (undefined === this._snapGeomId) this._snapGeomId = this.iModel.transientIds.next; const builder = context.createGraphic({ type: GraphicType.WorldDecoration, pickable: { id: this._snapGeomId, locateOnly: true } }); builder.setSymbology(ColorDef.white, ColorDef.white, 1); switch (geomQuery.geometryCategory) { case "pointCollection": { const pointString = geomQuery as PointString3d; builder.addPointString(pointString.points); break; } case "curvePrimitive": { const curvePrimitive = geomQuery as CurvePrimitive; switch (curvePrimitive.curvePrimitiveType) { case "lineString": { const lineString = geomQuery as LineString3d; builder.addLineString(lineString.points); break; } default: return; // Don't need to support other types of CurvePrimitive currently... } break; } default: return; // Don't need to support other types of GeometryQuery currently... } context.addDecorationFromBuilder(builder); } public override decorate(context: DecorateContext): void { if (this.wantPickableDynamics) this.addPickableGraphics(context); if (undefined === this.current) return; if (this.showJoin) this.showJoinIndicator(context, this.current.startPoint()); else if (this.showClosure) this.showClosureIndicator(context, this.current.endPoint()); } public override async onModifierKeyTransition(_wentDown: boolean, modifier: BeModifierKeys, _event: KeyboardEvent): Promise<EventHandled> { if (BeModifierKeys.Control !== modifier) return EventHandled.No; // Update display for join/closure change w/o waiting for a motion event... return EventHandled.Yes; } protected getPlacementProps(): PlacementProps | undefined { if (undefined !== this.continuationData) return this.continuationData.props.placement; if (undefined === this.current) return; const vp = this.targetView; if (undefined === vp) return; const matrix = AccuDrawHintBuilder.getCurrentRotation(vp, true, true); const localToWorld = FrameBuilder.createRightHandedFrame(matrix?.getColumn(2), this.current); if (undefined === localToWorld) return; const origin = localToWorld.getOrigin(); const angles = new YawPitchRollAngles(); YawPitchRollAngles.createFromMatrix3d(localToWorld.matrix, angles); if (vp.view.is3d()) return { origin, angles }; return { origin, angle: angles.yaw }; } protected createNewPath(placement: PlacementProps): JsonGeometryStream | FlatBufferGeometryStream | undefined { if (undefined === this.current) return; const builder = new ElementGeometry.Builder(); builder.setLocalToWorldFromPlacement(placement); const geometry = (this.isClosed ? Loop.create(this.current) : this.current); if (!builder.appendGeometryQuery(geometry)) return; return { format: "flatbuffer", data: builder.entries }; } protected continueExistingPath(placement: PlacementProps): JsonGeometryStream | FlatBufferGeometryStream | undefined { if (undefined === this.current || undefined === this.continuationData) return; const length = this.current.quickLength(); if (length < Geometry.smallMetricDistance) return; const curveS = this.current.startPoint(); const pathS = this.continuationData.path.children[0].startPoint(); const pathE = this.continuationData.path.children[this.continuationData.path.children.length - 1].endPoint(); const append = pathE.isAlmostEqual(curveS); if (!append && !pathS.isAlmostEqual(curveS)) return; const continuePath = this.continuationData.path.clone() as Path; if (undefined === continuePath) return; const current = this.current.clone(); if (undefined === current) return; if (append) { continuePath.tryAddChild(current); } else { current.reverseInPlace(); continuePath.children.splice(0, 0, current); } const geometry = (this.isClosed ? Loop.create(...continuePath.children) : continuePath); if (this.wantSimplify) RegionOps.consolidateAdjacentPrimitives(geometry); const builder = new ElementGeometry.Builder(); builder.setLocalToWorldFromPlacement(placement); builder.appendGeometryParamsChange(this.continuationData.params); if (!builder.appendGeometryQuery(geometry)) return; return { format: "flatbuffer", data: builder.entries }; } protected getGeometryProps(placement: PlacementProps): JsonGeometryStream | FlatBufferGeometryStream | undefined { if (this.isContinueExistingPath) return this.continueExistingPath(placement); return this.createNewPath(placement); } protected getElementProps(placement: PlacementProps): GeometricElementProps | undefined { if (undefined !== this.continuationData) return this.continuationData.props; const model = this.targetModelId; const category = this.targetCategory; if (isPlacement3dProps(placement)) return { classFullName: "Generic:PhysicalObject", model, category, code: Code.createEmpty(), placement }; return { classFullName: "BisCore:DrawingGraphic", model, category, code: Code.createEmpty(), placement }; } protected async createElement(): Promise<void> { const placement = this.getPlacementProps(); if (undefined === placement) return; const geometry = this.getGeometryProps(placement); if (undefined === geometry) return; const elemProps = this.getElementProps(placement); if (undefined === elemProps) return; let data; if ("flatbuffer" === geometry.format) { data = { entryArray: geometry.data }; delete elemProps.geom; // Leave unchanged until replaced by flatbuffer geometry... } else { elemProps.geom = geometry.data; } try { this._startedCmd = await this.startCommand(); if (undefined === elemProps.id) await CreateOrContinuePathTool.callCommand("insertGeometricElement", elemProps, data); else await CreateOrContinuePathTool.callCommand("updateGeometricElement", elemProps, data); await this.saveChanges(); } catch (err) { IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Error, BentleyError.getErrorMessage(err) || "An unknown error occurred.")); } } protected setupAccuDraw(): void { const nPts = this.accepted.length; if (0 === nPts) return; const hints = new AccuDrawHintBuilder(); if (this.wantSmartRotation) hints.enableSmartRotation = true; // Rotate AccuDraw to last segment... if (nPts > 1 && !this.accepted[nPts - 1].isAlmostEqual(this.accepted[nPts - 2])) hints.setXAxis(Vector3d.createStartEnd(this.accepted[nPts - 2], this.accepted[nPts - 1])); hints.setOrigin(this.accepted[nPts - 1]); hints.sendHints(); } protected override setupAndPromptForNextAction(): void { this.setupAccuDraw(); super.setupAndPromptForNextAction(); } protected async acceptPoint(ev: BeButtonEvent): Promise<boolean> { const phase = this.createCurvePhase; this.accepted.push(ev.point.clone()); await this.updateCurveAndContinuationData(ev, false, phase); return true; } protected async cancelPoint(_ev: BeButtonEvent): Promise<boolean> { return true; } public override async onDataButtonDown(ev: BeButtonEvent): Promise<EventHandled> { if (!await this.acceptPoint(ev)) return EventHandled.Yes; return super.onDataButtonDown(ev); } public override async onResetButtonUp(ev: BeButtonEvent): Promise<EventHandled> { if (!await this.cancelPoint(ev)) return EventHandled.Yes; return super.onResetButtonUp(ev); } public override async onUndoPreviousStep(): Promise<boolean> { if (0 === this.accepted.length) return false; this.accepted.pop(); if (0 === this.accepted.length) await this.onReinitialize(); else this.setupAndPromptForNextAction(); return true; } public override async onCleanup() { this.clearGraphics(); return super.onCleanup(); } } /** @alpha Creates a line string or shape. Uses model and category from [[BriefcaseConnection.editorToolSettings]]. */ export class CreateLineStringTool extends CreateOrContinuePathTool { public static override toolId = "CreateLineString"; public static override iconSpec = "icon-snaps"; // Need better icon... protected override get wantPickableDynamics(): boolean { return true; } // Allow snapping to accepted segments... protected override provideToolAssistance(_mainInstrText?: string, _additionalInstr?: ToolAssistanceInstruction[]): void { const nPts = this.accepted.length; const mainMsg = CoreTools.translate(0 === nPts ? "ElementSet.Prompts.StartPoint" : (1 === nPts ? "ElementSet.Prompts.EndPoint" : "ElementSet.Inputs.AdditionalPoint")); const leftMsg = CoreTools.translate("ElementSet.Inputs.AcceptPoint"); const rightMsg = CoreTools.translate(nPts > 1 ? "ElementSet.Inputs.Complete" : "ElementSet.Inputs.Cancel"); const mouseInstructions: ToolAssistanceInstruction[] = []; const touchInstructions: ToolAssistanceInstruction[] = []; if (!ToolAssistance.createTouchCursorInstructions(touchInstructions)) touchInstructions.push(ToolAssistance.createInstruction(ToolAssistanceImage.OneTouchTap, leftMsg, false, ToolAssistanceInputMethod.Touch)); mouseInstructions.push(ToolAssistance.createInstruction(ToolAssistanceImage.LeftClick, leftMsg, false, ToolAssistanceInputMethod.Mouse)); touchInstructions.push(ToolAssistance.createInstruction(ToolAssistanceImage.TwoTouchTap, rightMsg, false, ToolAssistanceInputMethod.Touch)); mouseInstructions.push(ToolAssistance.createInstruction(ToolAssistanceImage.RightClick, rightMsg, false, ToolAssistanceInputMethod.Mouse)); const sections: ToolAssistanceSection[] = []; sections.push(ToolAssistance.createSection(mouseInstructions, ToolAssistance.inputsLabel)); sections.push(ToolAssistance.createSection(touchInstructions, ToolAssistance.inputsLabel)); const mainInstruction = ToolAssistance.createInstruction(this.iconSpec, mainMsg); const instructions = ToolAssistance.createInstructions(mainInstruction, sections); IModelApp.notifications.setToolAssistance(instructions); } protected override get wantClosure(): boolean { // A linestring can support physical closure when creating a new path... return this.allowClosure; } protected override isComplete(ev: BeButtonEvent): boolean { // Accept on reset with at least 2 points... if (BeButton.Reset === ev.button) return (this.accepted.length > 1); // Allow data to complete on physical closure (creates Loop)... return this.isClosed; } protected createNewCurvePrimitive(ev: BeButtonEvent, isDynamics: boolean): CurvePrimitive | undefined { const numRequired = (isDynamics ? 1 : 2); if (this.accepted.length < numRequired) { this.isConstruction = true; // Create zero length line as construction geometry to support join... const pt = (0 !== this.accepted.length ? this.accepted[0] : ev.point); return LineString3d.create([pt, pt]); } const pts = (isDynamics ? [...this.accepted, ev.point] : this.accepted); return LineString3d.create(pts); } protected override async cancelPoint(ev: BeButtonEvent): Promise<boolean> { // NOTE: Starting another tool will not create element...require reset or closure... if (this.isComplete(ev)) { await this.updateCurveAndContinuationData(ev, false, CreateCurvePhase.DefineEnd); await this.createElement(); } return true; } public async onRestartTool() { const tool = new CreateLineStringTool(); if (!await tool.run()) return this.exitTool(); } } /** @alpha */ export enum ArcMethod { CenterStart = 0, StartCenter = 1, StartMidEnd = 2, StartEndMid = 3, } /** @alpha Creates an arc. Uses model and category from [[BriefcaseConnection.editorToolSettings]]. */ export class CreateArcTool extends CreateOrContinuePathTool { public static override toolId = "CreateArc"; public static override iconSpec = "icon-three-points-circular-arc"; public static override get minArgs() { return 0; } public static override get maxArgs() { return 3; } // method, radius, sweep - zero value unlocks associated "use" toggle... protected override get showCurveConstructions(): boolean { return true; } // Display lines from center to start/end... protected override provideToolAssistance(mainInstrText?: string, additionalInstr?: ToolAssistanceInstruction[]): void { const nPts = this.accepted.length; switch (this.method) { case ArcMethod.CenterStart: mainInstrText = (0 === nPts ? EditTools.translate("CreateArc.Prompts.CenterPoint") : (1 === nPts ? CoreTools.translate("ElementSet.Prompts.StartPoint") : CoreTools.translate("ElementSet.Prompts.EndPoint"))); break; case ArcMethod.StartCenter: mainInstrText = (0 === nPts ? CoreTools.translate("ElementSet.Prompts.StartPoint") : (1 === nPts ? EditTools.translate("CreateArc.Prompts.CenterPoint") : CoreTools.translate("ElementSet.Prompts.EndPoint"))); break; case ArcMethod.StartMidEnd: mainInstrText = (0 === nPts ? CoreTools.translate("ElementSet.Prompts.StartPoint") : (1 === nPts ? EditTools.translate("CreateArc.Prompts.MidPoint") : CoreTools.translate("ElementSet.Prompts.EndPoint"))); break; case ArcMethod.StartEndMid: mainInstrText = (0 === nPts ? CoreTools.translate("ElementSet.Prompts.StartPoint") : (1 === nPts ? CoreTools.translate("ElementSet.Prompts.EndPoint") : EditTools.translate("CreateArc.Prompts.MidPoint"))); break; } super.provideToolAssistance(mainInstrText, additionalInstr); } protected override setupAccuDraw(): void { const nPts = this.accepted.length; if (0 === nPts) return; const hints = new AccuDrawHintBuilder(); if (this.wantSmartRotation) hints.enableSmartRotation = true; switch (this.accepted.length) { case 1: hints.setOrigin(this.accepted[0]); if (ArcMethod.CenterStart !== this.method) break; hints.setOriginFixed = true; hints.setModePolar(); break; case 2: switch (this.method) { case ArcMethod.CenterStart: if (!this.accepted[0].isAlmostEqual(this.accepted[1])) hints.setXAxis(Vector3d.createStartEnd(this.accepted[0], this.accepted[1])); // Rotate AccuDraw to major axis... break; case ArcMethod.StartCenter: let center = this.accepted[1]; const start = this.accepted[0]; const vector0 = center.unitVectorTo(start); if (undefined === vector0) break; if (this.useRadius) center = start.plusScaled(vector0, -this.radius); hints.setOrigin(center); hints.setOriginFixed = true; hints.setModePolar(); hints.setXAxis(vector0); break; default: hints.setOrigin(this.accepted[1]); break; } break; } hints.sendHints(); } private static methodMessage(str: string) { return EditTools.translate(`CreateArc.Method.${str}`); } private static getMethodChoices = (): EnumerationChoice[] => { return [ { label: CreateArcTool.methodMessage("CenterStart"), value: ArcMethod.CenterStart }, { label: CreateArcTool.methodMessage("StartCenter"), value: ArcMethod.StartCenter }, { label: CreateArcTool.methodMessage("StartMidEnd"), value: ArcMethod.StartMidEnd }, { label: CreateArcTool.methodMessage("StartEndMid"), value: ArcMethod.StartEndMid }, ]; }; private _methodProperty: DialogProperty<number> | undefined; public get methodProperty() { if (!this._methodProperty) this._methodProperty = new DialogProperty<number>(PropertyDescriptionHelper.buildEnumPicklistEditorDescription( "arcMethod", EditTools.translate("CreateArc.Label.Method"), CreateArcTool.getMethodChoices()), ArcMethod.StartCenter as number); return this._methodProperty; } public get method(): ArcMethod { return this.methodProperty.value as ArcMethod; } public set method(method: ArcMethod) { this.methodProperty.value = method; } private _useRadiusProperty: DialogProperty<boolean> | undefined; public get useRadiusProperty() { if (!this._useRadiusProperty) this._useRadiusProperty = new DialogProperty<boolean>(PropertyDescriptionHelper.buildLockPropertyDescription("useArcRadius"), false); return this._useRadiusProperty; } public get useRadius(): boolean { return this.useRadiusProperty.value; } public set useRadius(value: boolean) { this.useRadiusProperty.value = value; } private _radiusProperty: DialogProperty<number> | undefined; public get radiusProperty() { if (!this._radiusProperty) this._radiusProperty = new DialogProperty<number>(new LengthDescription("arcRadius", EditTools.translate("CreateArc.Label.Radius")), 0.1, undefined, !this.useRadius); return this._radiusProperty; } public get radius(): number { return this.radiusProperty.value; } public set radius(value: number) { this.radiusProperty.value = value; } private _useSweepProperty: DialogProperty<boolean> | undefined; public get useSweepProperty() { if (!this._useSweepProperty) this._useSweepProperty = new DialogProperty<boolean>(PropertyDescriptionHelper.buildLockPropertyDescription("useArcSweep"), false); return this._useSweepProperty; } public get useSweep(): boolean { return this.useSweepProperty.value; } public set useSweep(value: boolean) { this.useSweepProperty.value = value; } private _sweepProperty: DialogProperty<number> | undefined; public get sweepProperty() { if (!this._sweepProperty) this._sweepProperty = new DialogProperty<number>(new AngleDescription("arcSweep", EditTools.translate("CreateArc.Label.Sweep")), Math.PI / 2.0, undefined, !this.useSweep); return this._sweepProperty; } public get sweep(): number { return this.sweepProperty.value; } public set sweep(value: number) { this.sweepProperty.value = value; } protected override isComplete(_ev: BeButtonEvent): boolean { return (3 === this.accepted.length); } protected override get createCurvePhase(): CreateCurvePhase { switch (this.accepted.length) { case 0: return ArcMethod.CenterStart === this.method ? CreateCurvePhase.DefineOther : CreateCurvePhase.DefineStart; case 1: if (ArcMethod.CenterStart === this.method) return CreateCurvePhase.DefineStart; else if (ArcMethod.StartEndMid === this.method) return CreateCurvePhase.DefineEnd; else return CreateCurvePhase.DefineOther; default: return ArcMethod.StartEndMid === this.method ? CreateCurvePhase.DefineOther : CreateCurvePhase.DefineEnd; } } protected createConstructionCurve(ev: BeButtonEvent, isDynamics: boolean): CurvePrimitive | undefined { switch (this.accepted.length) { case 0: { if (ArcMethod.CenterStart === this.method) return undefined; return LineString3d.create([ev.point, ev.point]); } case 1: { const pt1 = this.accepted[0]; const pt2 = (isDynamics ? ev.point : pt1); switch (this.method) { case ArcMethod.CenterStart: case ArcMethod.StartCenter: { if (pt1.isAlmostEqual(pt2)) return (ArcMethod.StartCenter === this.method ? LineString3d.create([pt1, pt2]) : undefined); let center = (ArcMethod.CenterStart === this.method ? pt1 : pt2); const start = (ArcMethod.CenterStart === this.method ? pt2 : pt1); const normal = this.getUpVector(ev); const vector0 = Vector3d.createStartEnd(center, start); const vector90 = normal.crossProduct(vector0); const radius = (this.useRadius ? this.radius : vector0.magnitude()); if (this.useRadius) { if (ArcMethod.StartCenter === this.method) { vector0.normalizeInPlace(); center = start.plusScaled(vector0, -radius); } } else { this.radius = radius; this.syncToolSettingsRadiusAndSweep(); } vector0.scaleToLength(radius, vector0); vector90.scaleToLength(radius, vector90); return Arc3d.create(center, vector0, vector90); } case ArcMethod.StartMidEnd: case ArcMethod.StartEndMid: { return LineString3d.create([pt1, pt2]); } default: return undefined; } } case 2: { switch (this.method) { case ArcMethod.CenterStart: return LineString3d.create([this.accepted[1], this.accepted[0]]); case ArcMethod.StartCenter: case ArcMethod.StartMidEnd: case ArcMethod.StartEndMid: return LineString3d.create([this.accepted[0], this.accepted[1]]); default: return undefined; } } default: return undefined; } } protected createNewCurvePrimitive(ev: BeButtonEvent, isDynamics: boolean): CurvePrimitive | undefined { const numRequired = (isDynamics ? 2 : 3); if (this.accepted.length < numRequired) { this.isConstruction = true; // Create construction geometry to support join... return this.createConstructionCurve(ev, isDynamics); } const final = (isDynamics ? ev.point : this.accepted[2]); const start = (ArcMethod.CenterStart === this.method ? this.accepted[1] : this.accepted[0]); const end = (ArcMethod.StartEndMid === this.method ? this.accepted[1] : final); switch (this.method) { case ArcMethod.CenterStart: case ArcMethod.StartCenter: let center = (ArcMethod.CenterStart === this.method ? this.accepted[0] : this.accepted[1]); if (center.isAlmostEqual(start)) return undefined; // Don't create 0 radius arc... const vector0 = Vector3d.createStartEnd(center, start); const vector90 = Vector3d.create(); const radius = (this.useRadius ? this.radius : vector0.magnitude()); const sweep = Angle.createRadians(this.useSweep ? this.sweep : Angle.pi2Radians); if (this.useRadius) { if (ArcMethod.StartCenter === this.method) { vector0.normalizeInPlace(); center = start.plusScaled(vector0, -radius); } } else { this.radius = radius; } let defaultArc = (undefined !== this.current && "arc" === this.current.curvePrimitiveType ? this.current as Arc3d : undefined); if (undefined === defaultArc) { this.getUpVector(ev).crossProduct(vector0, vector90); vector0.scaleToLength(radius, vector0); vector90.scaleToLength(radius, vector90); // Create default arc that follows continuation path start/end tangent... if (undefined !== this.continuationData) { const pathS = this.continuationData.path.children[0].startPoint(); if (start.isAlmostEqual(pathS)) { const tangentS = this.continuationData.path.children[0].fractionToPointAndUnitTangent(0.0); if (vector90.dotProduct(tangentS.direction) > 0.0) sweep.setRadians(-sweep.radians); } else { const tangentE = this.continuationData.path.children[this.continuationData.path.children.length - 1].fractionToPointAndUnitTangent(1.0); if (vector90.dotProduct(tangentE.direction) < 0.0) sweep.setRadians(-sweep.radians); } } defaultArc = Arc3d.create(center, vector0, vector90, AngleSweep.create(sweep)); } // Don't have well defined minor axis, continue using previous or default arc... if (start.isAlmostEqual(end)) return defaultArc; const prevSweep = Angle.createRadians(defaultArc.sweep.sweepRadians); Vector3d.createStartEnd(center, end, vector90); sweep.setFrom(vector0.planarAngleTo(vector90, defaultArc.perpendicularVector)); defaultArc.perpendicularVector.crossProduct(vector0, vector90); vector0.scaleToLength(radius, vector0); vector90.scaleToLength(radius, vector90); if (Math.abs(sweep.radians) < Angle.createDegrees(30.0).radians && prevSweep.isFullCircle && ((sweep.radians < 0.0 && prevSweep.radians > 0.0) || (sweep.radians > 0.0 && prevSweep.radians < 0.0))) prevSweep.setRadians(-prevSweep.radians); // Reverse direction... if (sweep.isAlmostZero) sweep.setDegrees(prevSweep.radians < 0.0 ? -360.0 : 360.0); // Create full sweep... if (this.useSweep) { if ((sweep.radians < 0.0 && this.sweep > 0.0) || (sweep.radians > 0.0 && this.sweep < 0.0)) sweep.setRadians(-this.sweep); else sweep.setRadians(this.sweep); } else { if (sweep.radians < 0.0 && prevSweep.radians > 0.0) sweep.setRadians(Angle.pi2Radians + sweep.radians); else if (sweep.radians > 0.0 && prevSweep.radians < 0.0) sweep.setRadians(-(Angle.pi2Radians - sweep.radians)); this.sweep = sweep.radians; } if (!this.useRadius || !this.useSweep) this.syncToolSettingsRadiusAndSweep(); return Arc3d.create(center, vector0, vector90, AngleSweep.create(sweep)); case ArcMethod.StartMidEnd: case ArcMethod.StartEndMid: const mid = (ArcMethod.StartEndMid === this.method ? final : this.accepted[1]); return Arc3d.createCircularStartMiddleEnd(start, mid, end); } } private syncToolSettingsRadiusAndSweep(): void { switch (this.method) { case ArcMethod.CenterStart: case ArcMethod.StartCenter: if (this.useRadius && this.useSweep) return; break; default: return; } const syncData: DialogPropertySyncItem[] = []; if (!this.useRadius) syncData.push(this.radiusProperty.syncItem); if (!this.useSweep) syncData.push(this.sweepProperty.syncItem); if (0 !== syncData.length) this.syncToolSettingsProperties(syncData); } protected override getToolSettingPropertyLocked(property: DialogProperty<any>): DialogProperty<any> | undefined { if (property === this.useRadiusProperty) return this.radiusProperty; else if (property === this.useSweepProperty) return this.sweepProperty; return undefined; } public override async applyToolSettingPropertyChange(updatedValue: DialogPropertySyncItem): Promise<boolean> { if (!this.changeToolSettingPropertyValue(updatedValue)) return false; if (this.methodProperty.name === updatedValue.propertyName) await this.onReinitialize(); else if (updatedValue.propertyName === this.radiusProperty.name && ArcMethod.StartCenter === this.method && this.useRadius && 2 === this.accepted.length) await this.onUndoPreviousStep(); // If radius is changed when creating arc by start/center after center has been defined, back up a step to defined a new center point... return true; } public override supplyToolSettingsProperties(): DialogItem[] | undefined { const toolSettings = new Array<DialogItem>(); toolSettings.push(this.methodProperty.toDialogItem({ rowPriority: 1, columnIndex: 0 })); if (ArcMethod.CenterStart === this.method || ArcMethod.StartCenter === this.method) { // ensure controls are enabled/disabled base on current lock property state this.radiusProperty.isDisabled = !this.useRadius; this.sweepProperty.isDisabled = !this.useSweep; const useRadiusLock = this.useRadiusProperty.toDialogItem({ rowPriority: 2, columnIndex: 0 }); const useSweepLock = this.useSweepProperty.toDialogItem({ rowPriority: 3, columnIndex: 0 }); toolSettings.push(this.radiusProperty.toDialogItem({ rowPriority: 2, columnIndex: 1 }, useRadiusLock)); toolSettings.push(this.sweepProperty.toDialogItem({ rowPriority: 3, columnIndex: 1 }, useSweepLock)); } return toolSettings; } public async onRestartTool(): Promise<void> { const tool = new CreateArcTool(); if (!await tool.run()) return this.exitTool(); } public override async onInstall(): Promise<boolean> { if (!await super.onInstall()) return false; // Setup initial values here instead of supplyToolSettingsProperties to support keyin args w/o appui-react... this.initializeToolSettingPropertyValues([this.methodProperty, this.radiusProperty, this.useRadiusProperty, this.sweepProperty, this.useSweepProperty]); if (!this.radius) this.useRadius = false; if (!this.sweep) this.useSweep = false; return true; } /** The keyin takes the following arguments, all of which are optional: * - `method=0|1|2|3` How arc will be defined. 0 for center/start, 1 for start/center, 2 for start/mid/end, and 3 for start/end/mid. * - `radius=number` Arc radius for start/center or center/start, 0 to define by points. * - `sweep=number` Arc sweep angle in degrees for start/center or center/start, 0 to define by points. */ public override async parseAndRun(...inputArgs: string[]): Promise<boolean> { let arcMethod; let arcRadius; let arcSweep; for (const arg of inputArgs) { const parts = arg.split("="); if (2 !== parts.length) continue; if (parts[0].toLowerCase().startsWith("me")) { const method = Number.parseInt(parts[1], 10); if (!Number.isNaN(method)) { switch (method) { case 0: arcMethod = ArcMethod.CenterStart; break; case 1: arcMethod = ArcMethod.StartCenter; break; case 2: arcMethod = ArcMethod.StartMidEnd; break; case 3: arcMethod = ArcMethod.StartEndMid; break; } } } else if (parts[0].toLowerCase().startsWith("ra")) { const radius = Number.parseFloat(parts[1]); if (!Number.isNaN(radius)) { arcRadius = radius; } } else if (parts[0].toLowerCase().startsWith("sw")) { const sweep = Number.parseFloat(parts[1]); if (!Number.isNaN(sweep)) { arcSweep = Angle.createDegrees(sweep).radians; } } } // Update current session values so keyin args are picked up for tool settings/restart... if (undefined !== arcMethod) this.saveToolSettingPropertyValue(this.methodProperty, { value: arcMethod }); if (undefined !== arcRadius) { if (0.0 !== arcRadius) this.saveToolSettingPropertyValue(this.radiusProperty, { value: arcRadius }); this.saveToolSettingPropertyValue(this.useRadiusProperty, { value: 0.0 !== arcRadius }); } if (undefined !== arcSweep) { if (0.0 !== arcSweep) this.saveToolSettingPropertyValue(this.sweepProperty, { value: arcSweep }); this.saveToolSettingPropertyValue(this.useSweepProperty, { value: 0.0 !== arcSweep }); } return this.run(); } } /** @alpha */ export enum CircleMethod { Center = 0, Edge = 1, } /** @alpha Creates a circle. Uses model and category from [[BriefcaseConnection.editorToolSettings]]. */ export class CreateCircleTool extends CreateOrContinuePathTool { public static override toolId = "CreateCircle"; public static override iconSpec = "icon-circle"; public static override get minArgs() { return 0; } public static override get maxArgs() { return 2; } // method, radius - zero value unlocks associated "use" toggle... protected override get showCurveConstructions(): boolean { return !(CircleMethod.Center === this.method && this.useRadius); } protected override get createCurvePhase(): CreateCurvePhase { return CreateCurvePhase.DefineOther; } // No join or closure checks... protected override provideToolAssistance(mainInstrText?: string, additionalInstr?: ToolAssistanceInstruction[]): void { const nPts = this.accepted.length; switch (this.method) { case CircleMethod.Center: mainInstrText = EditTools.translate(0 === nPts ? "CreateCircle.Prompts.CenterPoint" : "CreateCircle.Prompts.EdgePoint"); break; case CircleMethod.Edge: mainInstrText = EditTools.translate(0 === nPts ? "CreateCircle.Prompts.EdgePoint" : "CreateCircle.Prompts.CenterPoint"); break; } super.provideToolAssistance(mainInstrText, additionalInstr); } protected override setupAccuDraw(): void { const nPts = this.accepted.length; if (0 === nPts) return; const hints = new AccuDrawHintBuilder(); if (this.wantSmartRotation) hints.enableSmartRotation = true; if (CircleMethod.Center === this.method && 1 === this.accepted.length) { hints.setOrigin(this.accepted[0]); hints.setOriginFixed = true; hints.setModePolar(); } hints.sendHints(); } private static methodMessage(str: string) { return EditTools.translate(`CreateCircle.Method.${str}`); } private static getMethodChoices = (): EnumerationChoice[] => { return [ { label: CreateCircleTool.methodMessage("Center"), value: CircleMethod.Center }, { label: CreateCircleTool.methodMessage("Edge"), value: CircleMethod.Edge }, ]; }; private _methodProperty: DialogProperty<number> | undefined; public get methodProperty() { if (!this._methodProperty) this._methodProperty = new DialogProperty<number>(PropertyDescriptionHelper.buildEnumPicklistEditorDescription( "circleMethod", EditTools.translate("CreateCircle.Label.Method"), CreateCircleTool.getMethodChoices()), CircleMethod.Center as number); return this._methodProperty; } public get method(): CircleMethod { return this.methodProperty.value as CircleMethod; } public set method(method: CircleMethod) { this.methodProperty.value = method; } private _useRadiusProperty: DialogProperty<boolean> | undefined; public get useRadiusProperty() { if (!this._useRadiusProperty) this._useRadiusProperty = new DialogProperty<boolean>(PropertyDescriptionHelper.buildLockPropertyDescription("useCircleRadius"), false); return this._useRadiusProperty; } public get useRadius(): boolean { return this.useRadiusProperty.value; } public set useRadius(value: boolean) { this.useRadiusProperty.value = value; } private _radiusProperty: DialogProperty<number> | undefined; public get radiusProperty() { if (!this._radiusProperty) this._radiusProperty = new DialogProperty<number>(new LengthDescription("circleRadius", EditTools.translate("CreateCircle.Label.Radius")), 0.1, undefined, !this.useRadius); return this._radiusProperty; } public get radius(): number { return this.radiusProperty.value; } public set radius(value: number) { this.radiusProperty.value = value; } protected override isComplete(_ev: BeButtonEvent): boolean { if (CircleMethod.Center === this.method && this.useRadius) return (this.accepted.length >= 1); // Could be 2 if radius locked after 1st data point... return (2 === this.accepted.length); } protected createNewCurvePrimitive(ev: BeButtonEvent, isDynamics: boolean): CurvePrimitive | undefined { this.isClosed = true; // Always closed... const numRequired = (isDynamics ? 1 : 2); if (this.accepted.length < numRequired) { if (CircleMethod.Center === this.method && this.useRadius) return Arc3d.createCenterNormalRadius(isDynamics ? ev.point : this.accepted[0], this.getUpVector(ev), this.radius); return undefined; } const pt1 = this.accepted[0]; const pt2 = (isDynamics ? ev.point : this.accepted[1]); let center = (CircleMethod.Center === this.method ? pt1 : pt2); const edge = (CircleMethod.Center === this.method ? pt2 : pt1); const normal = this.getUpVector(ev); const vector0 = Vector3d.createStartEnd(center, edge); const vector90 = normal.crossProduct(vector0); const radius = (this.useRadius ? this.radius : vector0.magnitude()); if (this.useRadius) { if (CircleMethod.Edge === this.method) { vector0.normalizeInPlace(); center = edge.plusScaled(vector0, -radius); } } else { this.radius = radius; this.syncToolSettingsRadius(); } vector0.scaleToLength(radius, vector0); vector90.scaleToLength(radius, vector90); return Arc3d.create(center, vector0, vector90); } protected override async cancelPoint(_ev: BeButtonEvent): Promise<boolean> { if (CircleMethod.Center === this.method && this.useRadius) { // Exit instead of restarting to avoid having circle "stuck" on cursor... await this.exitTool(); return false; } return true; } private syncToolSettingsRadius(): void { if (this.useRadius) return; this.syncToolSettingsProperties([this.radiusProperty.syncItem]); } protected override getToolSettingPropertyLocked(property: DialogProperty<any>): DialogProperty<any> | undefined { return (property === this.useRadiusProperty ? this.radiusProperty : undefined); } public override async applyToolSettingPropertyChange(updatedValue: DialogPropertySyncItem): Promise<boolean> { if (!this.changeToolSettingPropertyValue(updatedValue)) return false; if (this.methodProperty.name === updatedValue.propertyName) await this.onReinitialize(); else if (updatedValue.propertyName === this.useRadiusProperty.name && CircleMethod.Center === this.method && this.useRadius && 0 === this.accepted.length) await this.onReinitialize(); return true; } public override supplyToolSettingsProperties(): DialogItem[] | undefined { const toolSettings = new Array<DialogItem>(); toolSettings.push(this.methodProperty.toDialogItem({ rowPriority: 1, columnIndex: 0 })); // ensure controls are enabled/disabled base on current lock property state this.radiusProperty.isDisabled = !this.useRadius; const useRadiusLock = this.useRadiusProperty.toDialogItem({ rowPriority: 2, columnIndex: 0 }); toolSettings.push(this.radiusProperty.toDialogItem({ rowPriority: 2, columnIndex: 1 }, useRadiusLock)); return toolSettings; } public async onRestartTool(): Promise<void> { const tool = new CreateCircleTool(); if (!await tool.run()) return this.exitTool(); } public override async onReinitialize(): Promise<void> { if (CircleMethod.Center === this.method && this.useRadius) { // Don't install a new tool instance, we want to preserve current AccuDraw state... this.accepted.length = 0; this.setupAndPromptForNextAction(); this.beginDynamics(); return; } return super.onReinitialize(); } public override async onPostInstall() { await super.onPostInstall(); if (CircleMethod.Center === this.method && this.useRadius) { // Start dynamics before 1st data point when placing by center w/locked radius value. // Require the user to explicitly enable AccuDraw so that the compass location can be adjusted for changes // to locks or view ACS (as opposed to appearing at it's previous or default location). AccuDrawHintBuilder.deactivate(); this.beginDynamics(); } } public override async onInstall(): Promise<boolean> { if (!await super.onInstall()) return false; // Setup initial values here instead of supplyToolSettingsProperties to support keyin args w/o appui-react... this.initializeToolSettingPropertyValues([this.methodProperty, this.radiusProperty, this.useRadiusProperty]); if (!this.radius) this.useRadius = false; return true; } /** The keyin takes the following arguments, all of which are optional: * - `method=0|1` How circle will be defined. 0 for center, 1 for edge. * - `radius=number` Circle radius, 0 to define by points. */ public override async parseAndRun(...inputArgs: string[]): Promise<boolean> { let circleMethod; let circleRadius; for (const arg of inputArgs) { const parts = arg.split("="); if (2 !== parts.length) continue; if (parts[0].toLowerCase().startsWith("me")) { const method = Number.parseInt(parts[1], 10); if (!Number.isNaN(method)) { switch (method) { case 0: circleMethod = CircleMethod.Center; break; case 1: circleMethod = CircleMethod.Edge; break; } } } else if (parts[0].toLowerCase().startsWith("ra")) { const radius = Number.parseFloat(parts[1]); if (!Number.isNaN(radius)) { circleRadius = radius; } } } // Update current session values so keyin args are picked up for tool settings/restart... if (undefined !== circleMethod) this.saveToolSettingPropertyValue(this.methodProperty, { value: circleMethod }); if (undefined !== circleRadius) { if (0.0 !== circleRadius) this.saveToolSettingPropertyValue(this.radiusProperty, { value: circleRadius }); this.saveToolSettingPropertyValue(this.useRadiusProperty, { value: 0.0 !== circleRadius }); } return this.run(); } } /** @alpha Creates an ellipse. Uses model and category from [[BriefcaseConnection.editorToolSettings]]. */ export class CreateEllipseTool extends CreateOrContinuePathTool { public static override toolId = "CreateEllipse"; public static override iconSpec = "icon-ellipse"; protected override isComplete(_ev: BeButtonEvent): boolean { return (3 === this.accepted.length); } protected override get createCurvePhase(): CreateCurvePhase { return CreateCurvePhase.DefineOther; } // No join or closure checks... protected override provideToolAssistance(mainInstrText?: string, additionalInstr?: ToolAssistanceInstruction[]): void { const nPts = this.accepted.length; switch (nPts) { case 0: mainInstrText = EditTools.translate("CreateEllipse.Prompts.CenterPoint"); break; case 1: mainInstrText = EditTools.translate("CreateEllipse.Prompts.MajorAxis"); break; case 2: mainInstrText = EditTools.translate("CreateEllipse.Prompts.MinorAxis"); break; } super.provideToolAssistance(mainInstrText, additionalInstr); } protected override setupAccuDraw(): void { const nPts = this.accepted.length; if (0 === nPts) return; const hints = new AccuDrawHintBuilder(); if (this.wantSmartRotation) hints.enableSmartRotation = true; switch (nPts) { case 1: hints.setOrigin(this.accepted[0]); hints.setOriginFixed = true; break; case 2: hints.setXAxis(Vector3d.createStartEnd(this.accepted[0], this.accepted[1])); hints.setLockX = true; break; } hints.sendHints(); } protected createNewCurvePrimitive(ev: BeButtonEvent, isDynamics: boolean): CurvePrimitive | undefined { const numRequired = (isDynamics ? 2 : 3); if (this.accepted.length < numRequired) { if (this.accepted.length < (numRequired - 1)) return undefined; this.isConstruction = true; // Create construction geometry to show major axis... return LineString3d.create([this.accepted[0], (isDynamics ? ev.point : this.accepted[1])]); } this.isClosed = true; // Always closed... const center = this.accepted[0]; const major = this.accepted[1]; const normal = this.getUpVector(ev); const vector0 = Vector3d.createStartEnd(center, major); const vector90 = normal.crossProduct(vector0); const dir = Ray3d.create(center, vector90); const minor = dir.projectPointToRay(isDynamics ? ev.point : this.accepted[2]); vector90.scaleToLength(center.distance(minor), vector90); return Arc3d.create(center, vector0, vector90); } public async onRestartTool(): Promise<void> { const tool = new CreateEllipseTool(); if (!await tool.run()) return this.exitTool(); } } /** @alpha Creates a rectangle by corner points. Uses model and category from [[BriefcaseConnection.editorToolSettings]]. */ export class CreateRectangleTool extends CreateOrContinuePathTool { public static override toolId = "CreateRectangle"; public static override iconSpec = "icon-rectangle"; protected localToWorld = Transform.createIdentity(); protected originLocal?: Point3d; protected cornerLocal?: Point3d; public static override get minArgs() { return 0; } public static override get maxArgs() { return 1; } // radius - zero value unlocks associated "use" toggle... protected override provideToolAssistance(mainInstrText?: string, additionalInstr?: ToolAssistanceInstruction[]): void { mainInstrText = CoreTools.translate(0 === this.accepted.length ? "ElementSet.Prompts.StartCorner" : "ElementSet.Prompts.OppositeCorner"); super.provideToolAssistance(mainInstrText, additionalInstr); } protected override setupAccuDraw(): void { const nPts = this.accepted.length; if (0 === nPts) return; const hints = new AccuDrawHintBuilder(); if (this.wantSmartRotation) hints.enableSmartRotation = true; hints.setOrigin(this.accepted[0]); hints.sendHints(); } private _useRadiusProperty: DialogProperty<boolean> | undefined; public get useRadiusProperty() { if (!this._useRadiusProperty) this._useRadiusProperty = new DialogProperty<boolean>(PropertyDescriptionHelper.buildLockPropertyDescription("useCornerRadius"), false); return this._useRadiusProperty; } public get useRadius(): boolean { return this.useRadiusProperty.value; } public set useRadius(value: boolean) { this.useRadiusProperty.value = value; } private _radiusProperty: DialogProperty<number> | undefined; public get radiusProperty() { if (!this._radiusProperty) this._radiusProperty = new DialogProperty<number>(new LengthDescription("cornerRadius", EditTools.translate("CreateRectangle.Label.CornerRadius")), 0.1, undefined, !this.useRadius); return this._radiusProperty; } public get radius(): number { return this.radiusProperty.value; } public set radius(value: number) { this.radiusProperty.value = value; } protected override isComplete(_ev: BeButtonEvent): boolean { return (2 === this.accepted.length); } protected override get createCurvePhase(): CreateCurvePhase { return CreateCurvePhase.DefineOther; } // No join or closure checks... protected createNewCurvePrimitive(ev: BeButtonEvent, isDynamics: boolean): CurvePrimitive | undefined { const numRequired = (isDynamics ? 1 : 2); if (this.accepted.length < numRequired) return undefined; const origin = this.accepted[0]; const corner = (isDynamics ? ev.point : this.accepted[1]); const matrix = this.getCurrentRotation(ev); Transform.createOriginAndMatrix(Point3d.createZero(), matrix, this.localToWorld); this.originLocal = this.localToWorld.multiplyInversePoint3d(origin); this.cornerLocal = this.localToWorld.multiplyInversePoint3d(corner); if (undefined === this.originLocal || undefined === this.cornerLocal) return undefined; const shapePts: Point3d[] = []; shapePts[0] = Point3d.create(this.originLocal.x, this.originLocal.y, this.originLocal.z); shapePts[1] = Point3d.create(this.cornerLocal.x, this.originLocal.y, this.cornerLocal.z); shapePts[2] = Point3d.create(this.cornerLocal.x, this.cornerLocal.y, this.cornerLocal.z); shapePts[3] = Point3d.create(this.originLocal.x, this.cornerLocal.y, this.originLocal.z); shapePts[4] = shapePts[0].clone(); this.localToWorld.multiplyPoint3dArrayInPlace(shapePts); this.isClosed = true; // Always closed... return LineString3d.create(shapePts); } protected override createNewPath(placement: PlacementProps): JsonGeometryStream | FlatBufferGeometryStream | undefined { if (!this.useRadius || 0.0 === this.radius || undefined === this.originLocal || undefined === this.cornerLocal) return super.createNewPath(placement); const builder = new ElementGeometry.Builder(); builder.setLocalToWorldFromPlacement(placement); const loop = CurveFactory.createRectangleXY(this.originLocal.x, this.originLocal.y, this.cornerLocal.x, this.cornerLocal.y, this.originLocal.z, this.radius); loop.tryTransformInPlace(this.localToWorld); if (!builder.appendGeometryQuery(loop)) return; return { format: "flatbuffer", data: builder.entries }; } protected override getToolSettingPropertyLocked(property: DialogProperty<any>): DialogProperty<any> | undefined { return (property === this.useRadiusProperty ? this.radiusProperty : undefined); } public override async applyToolSettingPropertyChange(updatedValue: DialogPropertySyncItem): Promise<boolean> { return this.changeToolSettingPropertyValue(updatedValue); } public override supplyToolSettingsProperties(): DialogItem[] | undefined { const toolSettings = new Array<DialogItem>(); // ensure controls are enabled/disabled base on current lock property state this.radiusProperty.isDisabled = !this.useRadius; const useRadiusLock = this.useRadiusProperty.toDialogItem({ rowPriority: 1, columnIndex: 0 }); toolSettings.push(this.radiusProperty.toDialogItem({ rowPriority: 1, columnIndex: 1 }, useRadiusLock)); return toolSettings; } public async onRestartTool(): Promise<void> { const tool = new CreateRectangleTool(); if (!await tool.run()) return this.exitTool(); } public override async onInstall(): Promise<boolean> { if (!await super.onInstall()) return false; // Setup initial values here instead of supplyToolSettingsProperties to support keyin args w/o appui-react... this.initializeToolSettingPropertyValues([this.radiusProperty, this.useRadiusProperty]); if (!this.radius) this.useRadius = false; return true; } /** The keyin takes the following arguments, all of which are optional: * - `radius=number` Corner radius, 0 for sharp corners. */ public override async parseAndRun(...inputArgs: string[]): Promise<boolean> { let cornerRadius; for (const arg of inputArgs) { const parts = arg.split("="); if (2 !== parts.length) continue; if (parts[0].toLowerCase().startsWith("ra")) { const radius = Number.parseFloat(parts[1]); if (!Number.isNaN(radius)) { cornerRadius = radius; } } } // Update current session values so keyin args are picked up for tool settings/restart... if (undefined !== cornerRadius) { if (0.0 !== cornerRadius) this.saveToolSettingPropertyValue(this.radiusProperty, { value: cornerRadius }); this.saveToolSettingPropertyValue(this.useRadiusProperty, { value: 0.0 !== cornerRadius }); } return this.run(); } } /** @alpha */ export enum BCurveMethod { ControlPoints = 0, ThroughPoints = 1, } /** @alpha Creates a bspline curve by poles or through points. Uses model and category from [[BriefcaseConnection.editorToolSettings]]. */ export class CreateBCurveTool extends CreateOrContinuePathTool { public static override toolId = "CreateBCurve"; public static override iconSpec = "icon-snaps-nearest"; // Need better icon... protected _isPhysicallyClosedOrComplete = false; protected _tangentPhase = CreateCurvePhase.DefineOther; public static override get minArgs() { return 0; } public static override get maxArgs() { return 3; } // method, order, tangents... protected override get wantPickableDynamics(): boolean { return true; } // Allow snapping to control polygon or through points... protected override get showCurveConstructions(): boolean { return true; } // Display control polygon or through points... protected override provideToolAssistance(_mainInstrText?: string, _additionalInstr?: ToolAssistanceInstruction[]): void { const nPts = this.accepted.length; let mainMsg; if (CreateCurvePhase.DefineOther === this._tangentPhase) mainMsg = CoreTools.translate(0 === nPts ? "ElementSet.Prompts.StartPoint" : "ElementSet.Inputs.AdditionalPoint"); else mainMsg = EditTools.translate(CreateCurvePhase.DefineStart === this._tangentPhase ? "CreateBCurve.Prompts.StartTangent" : "CreateBCurve.Prompts.EndTangent") ; const leftMsg = CoreTools.translate("ElementSet.Inputs.AcceptPoint"); const rightMsg = CoreTools.translate(CreateCurvePhase.DefineOther === this._tangentPhase && nPts >= this.requiredPointCount ? "ElementSet.Inputs.Complete" : "ElementSet.Inputs.Cancel"); const mouseInstructions: ToolAssistanceInstruction[] = []; const touchInstructions: ToolAssistanceInstruction[] = []; if (!ToolAssistance.createTouchCursorInstructions(touchInstructions)) touchInstructions.push(ToolAssistance.createInstruction(ToolAssistanceImage.OneTouchTap, leftMsg, false, ToolAssistanceInputMethod.Touch)); mouseInstructions.push(ToolAssistance.createInstruction(ToolAssistanceImage.LeftClick, leftMsg, false, ToolAssistanceInputMethod.Mouse)); touchInstructions.push(ToolAssistance.createInstruction(ToolAssistanceImage.TwoTouchTap, rightMsg, false, ToolAssistanceInputMethod.Touch)); mouseInstructions.push(ToolAssistance.createInstruction(ToolAssistanceImage.RightClick, rightMsg, false, ToolAssistanceInputMethod.Mouse)); const sections: ToolAssistanceSection[] = []; sections.push(ToolAssistance.createSection(mouseInstructions, ToolAssistance.inputsLabel)); sections.push(ToolAssistance.createSection(touchInstructions, ToolAssistance.inputsLabel)); const mainInstruction = ToolAssistance.createInstruction(this.iconSpec, mainMsg); const instructions = ToolAssistance.createInstructions(mainInstruction, sections); IModelApp.notifications.setToolAssistance(instructions); } private static methodMessage(str: string) { return EditTools.translate(`CreateBCurve.Method.${str}`); } private static getMethodChoices = (): EnumerationChoice[] => { return [ { label: CreateBCurveTool.methodMessage("ControlPoints"), value: BCurveMethod.ControlPoints }, { label: CreateBCurveTool.methodMessage("ThroughPoints"), value: BCurveMethod.ThroughPoints }, ]; }; private _methodProperty: DialogProperty<number> | undefined; public get methodProperty() { if (!this._methodProperty) this._methodProperty = new DialogProperty<number>(PropertyDescriptionHelper.buildEnumPicklistEditorDescription( "bcurveMethod", EditTools.translate("CreateBCurve.Label.Method"), CreateBCurveTool.getMethodChoices()), BCurveMethod.ControlPoints as number); return this._methodProperty; } public get method(): BCurveMethod { return this.methodProperty.value as BCurveMethod; } public set method(method: BCurveMethod) { this.methodProperty.value = method; } private _orderProperty: DialogProperty<number> | undefined; public get orderProperty() { if (!this._orderProperty) this._orderProperty = new DialogProperty<number>( PropertyDescriptionHelper.buildNumberEditorDescription("bcurveOrder", EditTools.translate("CreateBCurve.Label.Order"), { type: PropertyEditorParamTypes.Range, minimum: this.minOrder, maximum: this.maxOrder } as RangeEditorParams), 3); return this._orderProperty; } public get order(): number { return this.orderProperty.value; } public set order(value: number) { this.orderProperty.value = value; } protected get minOrder(): number { return 2; } protected get maxOrder(): number { return 16; } private _tangentsProperty: DialogProperty<boolean> | undefined; public get tangentsProperty() { if (!this._tangentsProperty) this._tangentsProperty = new DialogProperty<boolean>( PropertyDescriptionHelper.buildToggleDescription("bcurveTangents", EditTools.translate("CreateBCurve.Label.Tangents")), false); return this._tangentsProperty; } public get tangents(): boolean { return this.tangentsProperty.value; } public set tangents(value: boolean) { this.tangentsProperty.value = value; } protected override get wantClosure(): boolean { // A bcurve can support physical closure when creating a new path... return this.allowClosure; } protected get requiredPointCount(): number { if (BCurveMethod.ThroughPoints === this.method) return 3; // Interpolation curve is always order 4 with 3 point minimum... return this.order; } protected override get createCurvePhase(): CreateCurvePhase { if (CreateCurvePhase.DefineOther !== this._tangentPhase) return CreateCurvePhase.DefineOther; return super.createCurvePhase; } protected override isComplete(ev: BeButtonEvent): boolean { // Accept on reset with sufficient points... if (BeButton.Reset === ev.button) return (this.accepted.length >= this.requiredPointCount); // Allow data to complete on physical closure... return this.isClosed || this._isPhysicallyClosedOrComplete; } protected override showConstructionGraphics(ev: BeButtonEvent, context: DynamicsContext): boolean { if (CreateCurvePhase.DefineOther !== this._tangentPhase && this.current) { const fitCurve = this.current as InterpolationCurve3d; const builder = context.createGraphic({ type: GraphicType.WorldOverlay }); const color = context.viewport.getContrastToBackgroundColor(); builder.setSymbology(color, ColorDef.black, 1, LinePixels.Code2); builder.addLineString([ev.point, fitCurve.options.fitPoints[CreateCurvePhase.DefineStart === this._tangentPhase ? 0 : fitCurve.options.fitPoints.length-1]]); builder.setSymbology(color, ColorDef.black, 8); builder.addPointString([ev.point]); context.addGraphic(builder.finish()); } return super.showConstructionGraphics(ev, context); } protected createNewCurvePrimitive(ev: BeButtonEvent, isDynamics: boolean): CurvePrimitive | undefined { if (CreateCurvePhase.DefineOther !== this._tangentPhase && this.current) { const fitCurve = this.current as InterpolationCurve3d; if (CreateCurvePhase.DefineStart === this._tangentPhase) { const tangentS = Vector3d.createStartEnd(ev.point, fitCurve.options.fitPoints[0]); if (tangentS.magnitude() > Geometry.smallMetricDistance) fitCurve.options.startTangent = tangentS; } else { const tangentE = Vector3d.createStartEnd(ev.point, fitCurve.options.fitPoints[fitCurve.options.fitPoints.length-1]); if (tangentE.magnitude() > Geometry.smallMetricDistance) fitCurve.options.endTangent = tangentE; } return fitCurve; } // Don't include current point if it's the same as the last accepted point, want dynamics to show an accurate preview of what reset will accept... const includeCurrPt = (isDynamics && (0 === this.accepted.length || !ev.point.isAlmostEqual(this.accepted[this.accepted.length - 1]))); const pts = (includeCurrPt ? [...this.accepted, ev.point] : this.accepted); const numRequired = this.requiredPointCount; if (pts.length < numRequired) { // Create point/linestring construction geometry to support join... this.isConstruction = true; return LineString3d.create(1 === pts.length ? [pts[0], pts[0]] : pts); } // Create periodic-looking curve on physical closure with sufficient points even when not creating a loop/surface... this._isPhysicallyClosedOrComplete = (undefined === this.continuationData && pts[0].isAlmostEqual(pts[pts.length -1])); if (BCurveMethod.ControlPoints === this.method) { if (this._isPhysicallyClosedOrComplete && this.order > 2) { const tmpPts = pts.slice(undefined, -1); // Don't include closure point... return BSplineCurve3d.createPeriodicUniformKnots(tmpPts, this.order); } return BSplineCurve3d.createUniformKnots(pts, this.order); } const interpProps: InterpolationCurve3dProps = { fitPoints: pts, closed: this._isPhysicallyClosedOrComplete, isChordLenKnots: 1, isColinearTangents: 1 }; // Create interpolation curve tangent to continuation curve... if (undefined !== this.continuationData && this.tangents) { const tangentS = this.continuationData.path.children[0].fractionToPointAndUnitTangent(0.0); const tangentE = this.continuationData.path.children[this.continuationData.path.children.length - 1].fractionToPointAndUnitTangent(1.0); if (pts[0].isAlmostEqual(tangentS.origin)) interpProps.startTangent = tangentS.direction.scale(-1); else if (pts[0].isAlmostEqual(tangentE.origin)) interpProps.startTangent = tangentE.direction; if (pts[pts.length - 1].isAlmostEqual(tangentS.origin)) interpProps.endTangent = tangentS.direction.scale(-1); else if (pts[pts.length - 1].isAlmostEqual(tangentE.origin)) interpProps.endTangent = tangentE.direction; this._isPhysicallyClosedOrComplete = (undefined !== interpProps.startTangent && undefined !== interpProps.endTangent); } const interpOpts = InterpolationCurve3dOptions.create(interpProps); return InterpolationCurve3d.createCapture(interpOpts); } protected override getSnapGeometry(): GeometryQuery | undefined { // Only snap to through points... if (BCurveMethod.ThroughPoints === this.method) return (this.accepted.length > 1 ? PointString3d.create(this.accepted) : undefined); return super.getSnapGeometry(); } protected override async acceptPoint(ev: BeButtonEvent): Promise<boolean> { switch (this._tangentPhase) { case CreateCurvePhase.DefineOther: return super.acceptPoint(ev); case CreateCurvePhase.DefineStart: this._tangentPhase = CreateCurvePhase.DefineEnd; break; case CreateCurvePhase.DefineEnd: this._isPhysicallyClosedOrComplete = true; break; } await this.updateCurveAndContinuationData(ev, false, CreateCurvePhase.DefineOther); return true; } protected override async cancelPoint(ev: BeButtonEvent): Promise<boolean> { // NOTE: Starting another tool will not create element...require reset or closure... if (this.isComplete(ev)) { if (BCurveMethod.ThroughPoints === this.method && this.tangents && this.current) { const fitCurve = this.current as InterpolationCurve3d; switch (this._tangentPhase) { case CreateCurvePhase.DefineOther: await this.updateCurveAndContinuationData(ev, false, CreateCurvePhase.DefineEnd); this._tangentPhase = (undefined === fitCurve.options.startTangent ? CreateCurvePhase.DefineStart : CreateCurvePhase.DefineEnd); IModelApp.toolAdmin.updateDynamics(); this.setupAndPromptForNextAction(); return false; case CreateCurvePhase.DefineStart: fitCurve.options.startTangent = undefined; // Not accepted, compute default start tangent... this._tangentPhase = CreateCurvePhase.DefineEnd; IModelApp.toolAdmin.updateDynamics(); this.setupAndPromptForNextAction(); return false; case CreateCurvePhase.DefineEnd: fitCurve.options.endTangent = undefined; // Not accepted, compute default end tangent... await this.createElement(); return true; } } await this.updateCurveAndContinuationData(ev, false, CreateCurvePhase.DefineEnd); await this.createElement(); } return true; } public override async applyToolSettingPropertyChange(updatedValue: DialogPropertySyncItem): Promise<boolean> { if (!this.changeToolSettingPropertyValue(updatedValue)) return false; if (this.methodProperty.name === updatedValue.propertyName) await this.onReinitialize(); return true; } public override supplyToolSettingsProperties(): DialogItem[] | undefined { const toolSettings = new Array<DialogItem>(); toolSettings.push(this.methodProperty.toDialogItem({ rowPriority: 1, columnIndex: 0 })); if (BCurveMethod.ThroughPoints === this.method) toolSettings.push(this.tangentsProperty.toDialogItem({ rowPriority: 2, columnIndex: 0 })); else toolSettings.push(this.orderProperty.toDialogItem({ rowPriority: 2, columnIndex: 1 })); return toolSettings; } public async onRestartTool(): Promise<void> { const tool = new CreateBCurveTool(); if (!await tool.run()) return this.exitTool(); } public override async onInstall(): Promise<boolean> { if (!await super.onInstall()) return false; // Setup initial values here instead of supplyToolSettingsProperties to support keyin args w/o appui-react... this.initializeToolSettingPropertyValues([this.methodProperty, this.orderProperty, this.tangentsProperty]); return true; } /** The keyin takes the following arguments, all of which are optional: * - `method=0|1` How bcurve will be defined. 0 for control points, 1 for through points. * - `order=number` bcurve order from 2 to 16. * - 'tangents=0|1 Whether to specify start/end tangents for through points construction. */ public override async parseAndRun(...inputArgs: string[]): Promise<boolean> { let bcurveMethod; let bcurveOrder; let bcurveTangents; for (const arg of inputArgs) { const parts = arg.split("="); if (2 !== parts.length) continue; if (parts[0].toLowerCase().startsWith("me")) { const method = Number.parseInt(parts[1], 10); if (!Number.isNaN(method)) { switch (method) { case 0: bcurveMethod = BCurveMethod.ControlPoints; break; case 1: bcurveMethod = BCurveMethod.ThroughPoints; break; } } } else if (parts[0].toLowerCase().startsWith("or")) { const order = Number.parseInt(parts[1], 10); if (order >= this.minOrder && order <= this.maxOrder) { bcurveOrder = order; } } else if (parts[0].toLowerCase().startsWith("ta")) { const tangents = Number.parseInt(parts[1], 10); bcurveTangents = (0 !== tangents); } } // Update current session values so keyin args are picked up for tool settings/restart... if (undefined !== bcurveMethod) this.saveToolSettingPropertyValue(this.methodProperty, { value: bcurveMethod }); if (undefined !== bcurveOrder) this.saveToolSettingPropertyValue(this.orderProperty, { value: bcurveOrder }); if (undefined !== bcurveTangents) this.saveToolSettingPropertyValue(this.tangentsProperty, { value: bcurveTangents }); return this.run(); } }
the_stack
import { HttpResponse, HttpEvent } from '@angular/common/http'; import { Observable } from 'rxjs';import { HttpOptions } from '../../types'; import * as models from '../../models'; export interface GistsAPIClientInterface { /** * Arguments object for method `getGists`. */ getGistsParams?: { /** * Timestamp in ISO 8601 format YYYY-MM-DDTHH:MM:SSZ. * Only gists updated at or after this time are returned. * */ since?: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List the authenticated user's gists or if called anonymously, this will * return all public gists. * * Response generated for [ 200 ] HTTP response code. */ getGists( args?: GistsAPIClientInterface['getGistsParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Gists>; getGists( args?: GistsAPIClientInterface['getGistsParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Gists>>; getGists( args?: GistsAPIClientInterface['getGistsParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Gists>>; /** * Arguments object for method `postGists`. */ postGistsParams?: { /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.PostGist, }; /** * Create a gist. * Response generated for [ 201 ] HTTP response code. */ postGists( args: Exclude<GistsAPIClientInterface['postGistsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Gist>; postGists( args: Exclude<GistsAPIClientInterface['postGistsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Gist>>; postGists( args: Exclude<GistsAPIClientInterface['postGistsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Gist>>; /** * Arguments object for method `getGistsPublic`. */ getGistsPublicParams?: { /** * Timestamp in ISO 8601 format YYYY-MM-DDTHH:MM:SSZ. * Only gists updated at or after this time are returned. * */ since?: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List all public gists. * Response generated for [ 200 ] HTTP response code. */ getGistsPublic( args?: GistsAPIClientInterface['getGistsPublicParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Gists>; getGistsPublic( args?: GistsAPIClientInterface['getGistsPublicParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Gists>>; getGistsPublic( args?: GistsAPIClientInterface['getGistsPublicParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Gists>>; /** * Arguments object for method `getGistsStarred`. */ getGistsStarredParams?: { /** * Timestamp in ISO 8601 format YYYY-MM-DDTHH:MM:SSZ. * Only gists updated at or after this time are returned. * */ since?: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List the authenticated user's starred gists. * Response generated for [ 200 ] HTTP response code. */ getGistsStarred( args?: GistsAPIClientInterface['getGistsStarredParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Gists>; getGistsStarred( args?: GistsAPIClientInterface['getGistsStarredParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Gists>>; getGistsStarred( args?: GistsAPIClientInterface['getGistsStarredParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Gists>>; /** * Arguments object for method `deleteGistsId`. */ deleteGistsIdParams?: { /** Id of gist. */ id: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Delete a gist. * Response generated for [ 204 ] HTTP response code. */ deleteGistsId( args: Exclude<GistsAPIClientInterface['deleteGistsIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteGistsId( args: Exclude<GistsAPIClientInterface['deleteGistsIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteGistsId( args: Exclude<GistsAPIClientInterface['deleteGistsIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getGistsId`. */ getGistsIdParams?: { /** Id of gist. */ id: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a single gist. * Response generated for [ 200 ] HTTP response code. */ getGistsId( args: Exclude<GistsAPIClientInterface['getGistsIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Gist>; getGistsId( args: Exclude<GistsAPIClientInterface['getGistsIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Gist>>; getGistsId( args: Exclude<GistsAPIClientInterface['getGistsIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Gist>>; /** * Arguments object for method `patchGistsId`. */ patchGistsIdParams?: { /** Id of gist. */ id: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.PatchGist, }; /** * Edit a gist. * Response generated for [ 200 ] HTTP response code. */ patchGistsId( args: Exclude<GistsAPIClientInterface['patchGistsIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Gist>; patchGistsId( args: Exclude<GistsAPIClientInterface['patchGistsIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Gist>>; patchGistsId( args: Exclude<GistsAPIClientInterface['patchGistsIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Gist>>; /** * Arguments object for method `getGistsIdComments`. */ getGistsIdCommentsParams?: { /** Id of gist. */ id: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List comments on a gist. * Response generated for [ 200 ] HTTP response code. */ getGistsIdComments( args: Exclude<GistsAPIClientInterface['getGistsIdCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Comments>; getGistsIdComments( args: Exclude<GistsAPIClientInterface['getGistsIdCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Comments>>; getGistsIdComments( args: Exclude<GistsAPIClientInterface['getGistsIdCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Comments>>; /** * Arguments object for method `postGistsIdComments`. */ postGistsIdCommentsParams?: { /** Id of gist. */ id: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.CommentBody, }; /** * Create a commen * Response generated for [ 201 ] HTTP response code. */ postGistsIdComments( args: Exclude<GistsAPIClientInterface['postGistsIdCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Comment>; postGistsIdComments( args: Exclude<GistsAPIClientInterface['postGistsIdCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Comment>>; postGistsIdComments( args: Exclude<GistsAPIClientInterface['postGistsIdCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Comment>>; /** * Arguments object for method `deleteGistsIdCommentsCommentId`. */ deleteGistsIdCommentsCommentIdParams?: { /** Id of gist. */ id: number, /** Id of comment. */ commentId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Delete a comment. * Response generated for [ 204 ] HTTP response code. */ deleteGistsIdCommentsCommentId( args: Exclude<GistsAPIClientInterface['deleteGistsIdCommentsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteGistsIdCommentsCommentId( args: Exclude<GistsAPIClientInterface['deleteGistsIdCommentsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteGistsIdCommentsCommentId( args: Exclude<GistsAPIClientInterface['deleteGistsIdCommentsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getGistsIdCommentsCommentId`. */ getGistsIdCommentsCommentIdParams?: { /** Id of gist. */ id: number, /** Id of comment. */ commentId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a single comment. * Response generated for [ 200 ] HTTP response code. */ getGistsIdCommentsCommentId( args: Exclude<GistsAPIClientInterface['getGistsIdCommentsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Comment>; getGistsIdCommentsCommentId( args: Exclude<GistsAPIClientInterface['getGistsIdCommentsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Comment>>; getGistsIdCommentsCommentId( args: Exclude<GistsAPIClientInterface['getGistsIdCommentsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Comment>>; /** * Arguments object for method `patchGistsIdCommentsCommentId`. */ patchGistsIdCommentsCommentIdParams?: { /** Id of gist. */ id: number, /** Id of comment. */ commentId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.Comment, }; /** * Edit a comment. * Response generated for [ 200 ] HTTP response code. */ patchGistsIdCommentsCommentId( args: Exclude<GistsAPIClientInterface['patchGistsIdCommentsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Comment>; patchGistsIdCommentsCommentId( args: Exclude<GistsAPIClientInterface['patchGistsIdCommentsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Comment>>; patchGistsIdCommentsCommentId( args: Exclude<GistsAPIClientInterface['patchGistsIdCommentsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Comment>>; /** * Arguments object for method `postGistsIdForks`. */ postGistsIdForksParams?: { /** Id of gist. */ id: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Fork a gist. * Response generated for [ 204 ] HTTP response code. */ postGistsIdForks( args: Exclude<GistsAPIClientInterface['postGistsIdForksParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; postGistsIdForks( args: Exclude<GistsAPIClientInterface['postGistsIdForksParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; postGistsIdForks( args: Exclude<GistsAPIClientInterface['postGistsIdForksParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `deleteGistsIdStar`. */ deleteGistsIdStarParams?: { /** Id of gist. */ id: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Unstar a gist. * Response generated for [ 204 ] HTTP response code. */ deleteGistsIdStar( args: Exclude<GistsAPIClientInterface['deleteGistsIdStarParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteGistsIdStar( args: Exclude<GistsAPIClientInterface['deleteGistsIdStarParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteGistsIdStar( args: Exclude<GistsAPIClientInterface['deleteGistsIdStarParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getGistsIdStar`. */ getGistsIdStarParams?: { /** Id of gist. */ id: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Check if a gist is starred. * Response generated for [ 204 ] HTTP response code. */ getGistsIdStar( args: Exclude<GistsAPIClientInterface['getGistsIdStarParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getGistsIdStar( args: Exclude<GistsAPIClientInterface['getGistsIdStarParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getGistsIdStar( args: Exclude<GistsAPIClientInterface['getGistsIdStarParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `putGistsIdStar`. */ putGistsIdStarParams?: { /** Id of gist. */ id: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Star a gist. * Response generated for [ 204 ] HTTP response code. */ putGistsIdStar( args: Exclude<GistsAPIClientInterface['putGistsIdStarParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; putGistsIdStar( args: Exclude<GistsAPIClientInterface['putGistsIdStarParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; putGistsIdStar( args: Exclude<GistsAPIClientInterface['putGistsIdStarParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; }
the_stack
import { client, dataKey, portal } from "."; import { ExecuteRequestError, genKeyPairAndSeed, getEntryLink, JsonData, JSONResponse, SkynetClient, URI_SKYNET_PREFIX, } from "../src"; import { hashDataKey } from "../src/crypto"; import { decodeSkylinkBase64 } from "../src/utils/encoding"; import { toHexString } from "../src/utils/string"; describe(`SkyDB end to end integration tests for portal '${portal}'`, () => { // Sleep for a second before each test to try to avoid rate limiter. beforeEach(async () => { await new Promise((r) => setTimeout(r, 1000)); }); it("Should get existing SkyDB data", async () => { const publicKey = "89e5147864297b80f5ddf29711ba8c093e724213b0dcbefbc3860cc6d598cc35"; const dataKey = "dataKey1"; const expectedDataLink = `${URI_SKYNET_PREFIX}AACDPHoC2DCV_kLGUdpdRJr3CcxCmKadLGPi6OAMl7d48w`; const expectedData = { message: "hi there" }; const { data: received, dataLink } = await client.db.getJSON(publicKey, dataKey); expect(expectedData).toEqual(received); expect(dataLink).toEqual(expectedDataLink); }); it("Should get existing SkyDB data using entry link", async () => { const publicKey = "89e5147864297b80f5ddf29711ba8c093e724213b0dcbefbc3860cc6d598cc35"; const dataKey = "dataKey3"; const expectedJson = { message: "hi there!" }; const expectedData = { _data: expectedJson }; const expectedEntryLink = `${URI_SKYNET_PREFIX}AQAZ1R-KcL4NO_xIVf0q8B1ngPVd6ec-Pu54O0Cto387Nw`; const expectedDataLink = `${URI_SKYNET_PREFIX}AAAVyJktMuK-7WRCNUvYcYq7izvhCbgDLXlT4YgechblJw`; const entryLink = getEntryLink(publicKey, dataKey); expect(entryLink).toEqual(expectedEntryLink); const { data } = await client.getFileContent(entryLink); expect(data).toEqual(expect.objectContaining(expectedData)); const { data: json, dataLink } = await client.db.getJSON(publicKey, dataKey); expect(dataLink).toEqual(expectedDataLink); expect(json).toEqual(expectedJson); }); it("getRawBytes should perform a lookup but not a skylink GET if the cachedDataLink is a hit for existing data", async () => { const publicKey = "89e5147864297b80f5ddf29711ba8c093e724213b0dcbefbc3860cc6d598cc35"; const dataKey = "dataKey3"; const expectedDataLink = `${URI_SKYNET_PREFIX}AAAVyJktMuK-7WRCNUvYcYq7izvhCbgDLXlT4YgechblJw`; const { data: returnedData, dataLink } = await client.db.getRawBytes(publicKey, dataKey, { cachedDataLink: expectedDataLink, }); expect(returnedData).toBeNull(); expect(dataLink).toEqual(expectedDataLink); }); it("Should get existing SkyDB data with unicode data key", async () => { const publicKey = "4a964fa1cb329d066aedcf7fc03a249eeea3cf2461811090b287daaaec37ab36"; const dataKey = "dataKeyż"; const expected = { message: "Hello" }; const { data: received } = await client.db.getJSON(publicKey, dataKey); expect(expected).toEqual(received); }); it("Should return null for an inexistent entry", async () => { const { publicKey } = genKeyPairAndSeed(); // Try getting an inexistent entry. const { data, dataLink } = await client.db.getJSON(publicKey, "foo"); expect(data).toBeNull(); expect(dataLink).toBeNull(); }); it("Should set and get new entries", async () => { const { publicKey, privateKey } = genKeyPairAndSeed(); const json = { data: "thisistext" }; const json2 = { data: "foo2" }; // Set the file in SkyDB. await client.db.setJSON(privateKey, dataKey, json); // Get the file in SkyDB. const { data, dataLink } = await client.db.getJSON(publicKey, dataKey); expect(data).toEqual(json); expect(dataLink).toBeTruthy(); // Set the file again. await client.db.setJSON(privateKey, dataKey, json2); // Get the file again, should have been updated. const { data: data2, dataLink: dataLink2 } = await client.db.getJSON(publicKey, dataKey); expect(data2).toEqual(json2); expect(dataLink2).toBeTruthy(); }); // Regression test: Use some strange data keys that have failed in previous versions. const dataKeys = [".", "..", "http://localhost:8000/", ""]; it.each(dataKeys)("Should set and get new entry with dataKey '%s'", async (dataKey) => { const { publicKey, privateKey } = genKeyPairAndSeed(); const json = { data: "thisistext" }; await client.db.setJSON(privateKey, dataKey, json); const { data, dataLink } = await client.db.getJSON(publicKey, dataKey); expect(data).toEqual(json); expect(dataLink).toBeTruthy(); }); it("Should be able to delete an existing entry", async () => { const { publicKey, privateKey } = genKeyPairAndSeed(); const json = { data: "thisistext" }; await client.db.setJSON(privateKey, dataKey, json); const { data, dataLink } = await client.db.getJSON(publicKey, dataKey); expect(data).toEqual(json); expect(dataLink).toBeTruthy(); await client.db.deleteJSON(privateKey, dataKey); const { data: data2, dataLink: dataLink2 } = await client.db.getJSON(publicKey, dataKey); expect(data2).toBeNull(); expect(dataLink2).toBeNull(); }); it("Should be able to set a new entry as deleted and then write over it", async () => { const { publicKey, privateKey } = genKeyPairAndSeed(); await client.db.deleteJSON(privateKey, dataKey); // Get the entry link. const entryLink = getEntryLink(publicKey, dataKey); // Downloading the entry link should return a 404. // TODO: Should getFileContent return `null` on 404? try { await client.getFileContent(entryLink); throw new Error("'getFileContent' should not have succeeded"); } catch (err) { // Assert the type and that instanceof behaves as expected. expect(err).toBeInstanceOf(ExecuteRequestError); expect((err as ExecuteRequestError).responseStatus).toEqual(404); } // The SkyDB entry should be null. const { data, dataLink } = await client.db.getJSON(publicKey, dataKey); expect(data).toBeNull(); expect(dataLink).toBeNull(); // Write to the entry. const json = { data: "thisistext" }; await client.db.setJSON(privateKey, dataKey, json); // The entry should be readable. const { data: data2, dataLink: dataLink2 } = await client.db.getJSON(publicKey, dataKey); expect(data2).toEqual(json); expect(dataLink2).toBeTruthy(); }); it("Should correctly set a data link", async () => { const { publicKey, privateKey } = genKeyPairAndSeed(); const dataLink = "AAAVyJktMuK-7WRCNUvYcYq7izvhCbgDLXlT4YgechblJw"; const dataLinkBytes = decodeSkylinkBase64(dataLink); await client.db.setDataLink(privateKey, dataKey, dataLink); const { entry: returnedEntry } = await client.registry.getEntry(publicKey, dataKey); expect(returnedEntry).not.toBeNull(); expect(returnedEntry).toEqual(expect.objectContaining({})); // @ts-expect-error TS still thinks returnedEntry can be null expect(returnedEntry.data).toEqualUint8Array(dataLinkBytes); }); it("should set and get entry data", async () => { const { publicKey, privateKey } = genKeyPairAndSeed(); const data = new Uint8Array([1, 2, 3]); // Set the entry data. await client.db.setEntryData(privateKey, dataKey, data); // Get the entry data. const { data: returnedData } = await client.db.getEntryData(publicKey, dataKey); // Assert the returned data equals the original data. expect(returnedData).toEqualUint8Array(data); }); it("should set and delete entry data", async () => { const { publicKey, privateKey } = genKeyPairAndSeed(); const data = new Uint8Array([1, 2, 3]); // Set the entry data. await client.db.setEntryData(privateKey, dataKey, data); // Delete the entry data. await client.db.deleteEntryData(privateKey, dataKey); // Trying to get the deleted data should result in null. const { data: returnedData } = await client.db.getEntryData(publicKey, dataKey); expect(returnedData).toBeNull(); }); it("should be able to delete a new entry and then write over it", async () => { const data = new Uint8Array([1, 2, 3]); const { publicKey, privateKey } = genKeyPairAndSeed(); // Delete the entry data. await client.db.deleteEntryData(privateKey, dataKey); // Trying to fetch the entry should result in null. const { data: returnedData } = await client.db.getEntryData(publicKey, dataKey); expect(returnedData).toBeNull(); // Write to the entry. await client.db.setEntryData(privateKey, dataKey, data); // The entry should be readable. const { data: returnedData2 } = await client.db.getEntryData(publicKey, dataKey); expect(returnedData2).toEqual(data); }); it("Should correctly handle the hashedDataKeyHex option", async () => { const { publicKey, privateKey } = genKeyPairAndSeed(); const dataKey = "test"; const hashedDataKeyHex = toHexString(hashDataKey(dataKey)); const json = { message: "foo" }; // Set JSON using the hashed data key hex. await client.db.setJSON(privateKey, hashedDataKeyHex, json, { hashedDataKeyHex: true }); // Get JSON using the original data key. const { data } = await client.db.getJSON(publicKey, dataKey, { hashedDataKeyHex: false }); expect(data).toEqual(json); }); it("Should update the revision number cache", async () => { const { publicKey, privateKey } = genKeyPairAndSeed(); const json = { message: 1 }; await client.db.setJSON(privateKey, dataKey, json); const cachedRevisionEntry = await client.db.revisionNumberCache.getRevisionAndMutexForEntry(publicKey, dataKey); expect(cachedRevisionEntry.revision.toString()).toEqual("0"); await client.db.setJSON(privateKey, dataKey, json); expect(cachedRevisionEntry.revision.toString()).toEqual("1"); await client.db.getJSON(publicKey, dataKey); expect(cachedRevisionEntry.revision.toString()).toEqual("1"); }); // REGRESSION TESTS: By creating a gap between setJSON and getJSON, a user // could call getJSON, get outdated data, then call setJSON, and overwrite // more up to date data with outdated data, but still use a high enough // revision number. // // The fix is that you cannot retrieve the revision number while calling // setJSON. You have to use the same revision number that you had when you // called getJSON. describe("getJSON/setJSON data race regression integration tests", () => { const jsonOld = { message: 1 }; const jsonNew = { message: 2 }; const delays = [0, 10, 100, 500]; const concurrentAccessError = "Concurrent access prevented in SkyDB"; const registryUpdateError = "Unable to update the registry"; const getJSONWithDelay = async function ( client: SkynetClient, delay: number, publicKey: string, dataKey: string ): Promise<JSONResponse> { await new Promise((r) => setTimeout(r, delay)); return await client.db.getJSON(publicKey, dataKey); }; const setJSONWithDelay = async function ( client: SkynetClient, delay: number, privateKey: string, dataKey: string, data: JsonData ) { await new Promise((r) => setTimeout(r, delay)); return await client.db.setJSON(privateKey, dataKey, data); }; it.each(delays)( "should not get old data when getJSON is called after setJSON on a single client with a '%s' ms delay and getJSON doesn't fail", async (delay) => { const { publicKey, privateKey } = genKeyPairAndSeed(); // Set the data. await client.db.setJSON(privateKey, dataKey, jsonOld); // Try to invoke the data race. let receivedJson; try { // Get the data while also calling setJSON. [{ data: receivedJson }] = await Promise.all([ getJSONWithDelay(client, delay, publicKey, dataKey), setJSONWithDelay(client, 0, privateKey, dataKey, jsonNew), ]); } catch (e) { if ((e as Error).message.includes(concurrentAccessError)) { // The data race condition has been prevented and we received the // expected error. Return from test early. // // NOTE: I've manually confirmed that both code paths (no error, and // return on expected error) are hit. return; } // Unexpected error, throw. throw e; } // Data race did not occur, getJSON should have latest JSON. expect(receivedJson).toEqual(jsonNew); } ); // NOTE: We can't guarantee that data won't be lost if two (or more) actors // write to the registry at the same time, but we can guarantee that the // final state will be the desired final state by at least one of the // actors. One of the two clients will lose, but the other will win and be // consistent, so the data won't be corrupt, it'll just be missing one // update. it.each(delays)( "should get either old or new data when getJSON is called after setJSON on two different clients with a '%s' ms delay", async (delay) => { // Create two new clients with a fresh revision cache. const client1 = new SkynetClient(portal); const client2 = new SkynetClient(portal); const { publicKey, privateKey } = genKeyPairAndSeed(); // Get revision entry cache handles. const cachedRevisionEntry1 = await client1.db.revisionNumberCache.getRevisionAndMutexForEntry( publicKey, dataKey ); const cachedRevisionEntry2 = await client2.db.revisionNumberCache.getRevisionAndMutexForEntry( publicKey, dataKey ); // Set the initial data. { await client1.db.setJSON(privateKey, dataKey, jsonOld); expect(cachedRevisionEntry1.revision.toString()).toEqual("0"); expect(cachedRevisionEntry2.revision.toString()).toEqual("-1"); } // Call getJSON and setJSON concurrently on different clients -- both // should succeeed. { // Get the data while also calling setJSON. const [_, { data: receivedJson }] = await Promise.all([ setJSONWithDelay(client1, 0, privateKey, dataKey, jsonNew), getJSONWithDelay(client2, delay, publicKey, dataKey), ]); // See if we got the new or old data. expect(receivedJson).not.toBeNull(); expect(cachedRevisionEntry1.revision.toString()).toEqual("1"); if (receivedJson?.message === jsonNew.message) { expect(cachedRevisionEntry2.revision.toString()).toEqual("1"); // Return if we got the new data -- both clients are in sync. // // NOTE: I've manually confirmed that both code paths (old data and // new data) are hit. return; } // client2 should have old data and cached revision at this point. expect(receivedJson).toEqual(jsonOld); expect(cachedRevisionEntry2.revision.toString()).toEqual("0"); } // If we got old data and an old revision from getJSON, the client may // still be able to write to that entry, overwriting the new data. // // Try to update the entry with client2 which has the old revision. const updatedJson = { message: 3 }; let expectedJson: JsonData; try { await client2.db.setJSON(privateKey, dataKey, updatedJson); expectedJson = updatedJson; } catch (e) { // Catches both "doesn't have enough pow" and "provided revision number // is already registered" errors. if ((e as Error).message.includes(registryUpdateError)) { // NOTE: I've manually confirmed that both code paths (no error, and // return on expected error) are hit. expectedJson = jsonNew; } else { // Unexpected error, throw. throw e; } } // The entry should have the overriden, updated data at this point. await Promise.all([ async () => { const { data: receivedJson } = await client1.db.getJSON(publicKey, dataKey); expect(cachedRevisionEntry1.revision.toString()).toEqual("1"); expect(receivedJson).toEqual(expectedJson); }, async () => { const { data: receivedJson } = await client2.db.getJSON(publicKey, dataKey); expect(cachedRevisionEntry2.revision.toString()).toEqual("1"); expect(receivedJson).toEqual(expectedJson); }, ]); } ); it.each(delays)( "should make sure that two concurrent setJSON calls on a single client with a '%s' ms delay either fail with the right error or succeed ", async (delay) => { const { publicKey, privateKey } = genKeyPairAndSeed(); // Try to invoke two concurrent setJSON calls. try { await Promise.all([ setJSONWithDelay(client, delay, privateKey, dataKey, jsonNew), setJSONWithDelay(client, 0, privateKey, dataKey, jsonOld), ]); } catch (e) { if ((e as Error).message.includes(concurrentAccessError)) { // The data race condition has been prevented and we received the // expected error. Return from test early. // // NOTE: I've manually confirmed that both code paths (no error, and // return on expected error) are hit. return; } // Unexpected error, throw. throw e; } // Data race did not occur, getJSON should get latest JSON. const { data: receivedJson } = await client.db.getJSON(publicKey, dataKey); expect(receivedJson).toEqual(jsonNew); } ); it.each(delays)( "should make sure that two concurrent setJSON calls on different clients with a '%s' ms delay fail with the right error or succeed", async (delay) => { // Create two new clients with a fresh revision cache. const client1 = new SkynetClient(portal); const client2 = new SkynetClient(portal); const { publicKey, privateKey } = genKeyPairAndSeed(); // Try to invoke two concurrent setJSON calls. try { await Promise.all([ setJSONWithDelay(client2, delay, privateKey, dataKey, jsonNew), setJSONWithDelay(client1, 0, privateKey, dataKey, jsonOld), ]); } catch (e) { if ((e as Error).message.includes(registryUpdateError)) { // The data race condition has been prevented and we received the // expected error. Return from test early. // // NOTE: I've manually confirmed that both code paths (no error, and // return on expected error) are hit. return; } // Unexpected error, throw. throw e; } // Data race did not occur, getJSON should get one of the JSON values. let client3; if (Math.random() < 0.5) { client3 = client1; } else { client3 = client2; } const { data: receivedJson } = await client3.db.getJSON(publicKey, dataKey); expect([jsonOld, jsonNew]).toContainEqual(receivedJson); } ); }); });
the_stack
import { RepoRef } from "@atomist/automation-client/lib/operations/common/RepoId"; import { File } from "@atomist/automation-client/lib/project/File"; import { GitProject } from "@atomist/automation-client/lib/project/git/GitProject"; import { InMemoryProject } from "@atomist/automation-client/lib/project/mem/InMemoryProject"; import { Project } from "@atomist/automation-client/lib/project/Project"; import * as assert from "power-assert"; import { LoggingProgressLog } from "../../../../lib/api-helper/log/LoggingProgressLog"; import { fakeGoalInvocation } from "../../../../lib/api-helper/testsupport/fakeGoalInvocation"; import { fakePush } from "../../../../lib/api-helper/testsupport/fakePush"; import { GoalInvocation, GoalProjectListenerEvent, GoalProjectListenerRegistration, } from "../../../../lib/api/goal/GoalInvocation"; import { pushTest } from "../../../../lib/api/mapping/PushTest"; import { AnyPush } from "../../../../lib/api/mapping/support/commonPushTests"; import { cachePut, cacheRemove, cacheRestore, GoalCache, GoalCacheOptions, resolveClassifierPath, sanitizeClassifier, } from "../../../../lib/core/goal/cache/goalCaching"; class TestGoalArtifactCache implements GoalCache { private id: RepoRef; private cacheFiles: File[]; private classifier: string; public async put(gi: GoalInvocation, project: Project, files: string[], classifier: string = "default"): Promise<string> { this.id = gi.id; this.cacheFiles = await Promise.all(files.map(async f => project.getFile(f))); this.classifier = classifier; return undefined; } public async empty(): Promise<void> { this.id = undefined; this.cacheFiles = undefined; this.classifier = undefined; } public async remove(gi: GoalInvocation): Promise<void> { if (this.id === gi.id) { this.id = undefined; this.cacheFiles = undefined; this.classifier = undefined; } else { throw Error("Wrong id!"); } } public async retrieve(gi: GoalInvocation, project: Project, classifier: string = "default"): Promise<void> { if (this.id === gi.id && this.classifier === classifier) { if (this.cacheFiles === undefined) { throw Error("No cache"); } this.cacheFiles.forEach(f => project.add(f)); } else { throw Error("Wrong id!"); } } } const ErrorProjectListenerRegistration: GoalProjectListenerRegistration = { name: "Error", listener: async () => { throw Error("Test cache miss"); }, pushTest: AnyPush, }; describe("goalCaching", () => { describe("sanitizeClassifier", () => { it("should do nothing successfully", () => { ["", "simple", "foo.bar", "foo..bar"].forEach(c => { const s = sanitizeClassifier(c); assert(s === c); }); }); it("should unhide paths", () => { [ { c: ".foo", e: "foo" }, { c: "..foo", e: "foo" }, { c: "._foo", e: "_foo" }, { c: "./.", e: "_." }, { c: "././.", e: "_._." }, { c: "./.././", e: "_.._._" }, { c: "..", e: "" }, { c: "../../..", e: "_.._.." }, { c: "../../../", e: "_.._.._" }, { c: "../../../foo", e: "_.._.._foo" }, ].forEach(ce => { const s = sanitizeClassifier(ce.c); assert(s === ce.e); const b = ce.c.replace(/\//g, "\\"); const t = sanitizeClassifier(b); assert(t === ce.e); }); }); it("should replace invalid characters", () => { [ { c: "/", e: "_" }, { c: "///", e: "___" }, { c: "/foo", e: "_foo" }, { c: "///foo", e: "___foo" }, { c: "//foo//", e: "__foo__" }, { c: "/../../../foo", e: "_.._.._.._foo" }, { c: "_foo", e: "_foo" }, { c: "__foo", e: "__foo" }, { c: "foo.", e: "foo." }, { c: "foo..", e: "foo.." }, { c: "foo/", e: "foo_" }, { c: "foo////", e: "foo____" }, { c: "foo/..", e: "foo_.." }, { c: "foo/.././..", e: "foo_.._._.." }, { c: "foo/././././", e: "foo_._._._._" }, { c: "foo/../../../..", e: "foo_.._.._.._.." }, { c: "foo/../../../../", e: "foo_.._.._.._.._" }, { c: "foo/./bar", e: "foo_._bar" }, { c: "foo/././bar", e: "foo_._._bar" }, { c: "foo/././././bar", e: "foo_._._._._bar" }, { c: "foo/../bar", e: "foo_.._bar" }, { c: "foo/../../bar", e: "foo_.._.._bar" }, { c: "foo/../../../../bar", e: "foo_.._.._.._.._bar" }, { c: "foo/./.././../bar", e: "foo_._.._._.._bar" }, { c: "foo/.././.././bar", e: "foo_.._._.._._bar" }, { c: "foo/..///.//../bar", e: "foo_..___.__.._bar" }, { c: "foo/.././/.././bar/../././//..//./baz", e: "foo_.._.__.._._bar_.._._.___..__._baz" }, { c: "foo/.../bar", e: "foo_..._bar" }, { c: "foo/..../bar", e: "foo_...._bar" }, { c: "foo/.bar", e: "foo_.bar" }, { c: "foo/..bar", e: "foo_..bar" }, { c: "foo/...bar", e: "foo_...bar" }, { c: "foo/.bar/.baz", e: "foo_.bar_.baz" }, { c: "foo/..bar/..baz", e: "foo_..bar_..baz" }, { c: "foo/.../bar/.../baz", e: "foo_..._bar_..._baz" }, { c: "foo/....bar.baz", e: "foo_....bar.baz" }, { c: "foo/.../.bar.baz", e: "foo_..._.bar.baz" }, { c: "foo/....bar.baz/.qux.", e: "foo_....bar.baz_.qux." }, ].forEach(ce => { const s = sanitizeClassifier(ce.c); assert(s === ce.e); const b = ce.c.replace(/\//g, "\\"); const t = sanitizeClassifier(b); assert(t === ce.e); }); }); it("should handle the diabolical", () => { const c = "../.././...////....foo//.bar.baz/./..//...///...qux./quux...quuz/./../corge//...///./."; const s = sanitizeClassifier(c); const e = "_.._._...____....foo__.bar.baz_._..__...___...qux._quux...quuz_._.._corge__...___._."; assert(s === e); }); }); describe("resolveClassifierPath", () => { const gi: any = { configuration: { sdm: { docker: { registry: "kinks/bigsky", }, }, }, context: { workspaceId: "TH3K1NK5", }, goalEvent: { branch: "preservation/society", repo: { name: "village-green", owner: "TheKinks", providerId: "PyeReprise", }, sha: "9932791f7adfd854b576125b058e9eb45b3da8b9", }, }; it("should return the workspace ID", async () => { for (const c of [undefined, ""]) { const r = await resolveClassifierPath(c, gi); assert(r === "TH3K1NK5"); } }); it("should prepend the workspace ID", async () => { for (const c of ["simple", "foo.bar", "foo..bar"]) { const r = await resolveClassifierPath(c, gi); assert(r === `TH3K1NK5/${c}`); } }); it("should replace placeholders", async () => { // tslint:disable-next-line:no-invalid-template-strings const c = "star-struck_${repo.providerId}_${repo.owner}_${repo.name}_${sha}_PhenomenalCat"; const r = await resolveClassifierPath(c, gi); const e = "TH3K1NK5/star-struck_PyeReprise_TheKinks_village-green_9932791f7adfd854b576125b058e9eb45b3da8b9_PhenomenalCat"; assert(r === e); }); it("should replace placeholders and provide defaults", async () => { // tslint:disable-next-line:no-invalid-template-strings const c = "star-struck_${repo.providerId}_${repo.owner}_${repo.name}_${brunch:hunch}_PhenomenalCat"; const r = await resolveClassifierPath(c, gi); const e = "TH3K1NK5/star-struck_PyeReprise_TheKinks_village-green_hunch_PhenomenalCat"; assert(r === e); }); it("should replace nested placeholders", async () => { // tslint:disable-next-line:no-invalid-template-strings const c = "star-struck_${repo.providerId}_${repo.owner}_${repo.name}_${brunch:${sha}}_PhenomenalCat"; const r = await resolveClassifierPath(c, gi); const e = "TH3K1NK5/star-struck_PyeReprise_TheKinks_village-green_9932791f7adfd854b576125b058e9eb45b3da8b9_PhenomenalCat"; assert(r === e); }); it("should replace and sanitize placeholders", async () => { // tslint:disable-next-line:no-invalid-template-strings const c = "star-struck_${sdm.docker.registry}_${repo.owner}_${repo.name}_${branch}_PhenomenalCat"; const r = await resolveClassifierPath(c, gi); const e = "TH3K1NK5/star-struck_kinks_bigsky_TheKinks_village-green_preservation_society_PhenomenalCat"; assert(r === e); }); }); describe("goalCaching", () => { let project; const testCache = new TestGoalArtifactCache(); let fakePushId; let fakeGoal; beforeEach(() => { project = InMemoryProject.of({ path: "test.txt", content: "Test" }, { path: "dirtest/test.txt", content: "", }); fakePushId = fakePush().id; fakeGoal = fakeGoalInvocation(fakePushId); fakeGoal.progressLog = new LoggingProgressLog("test", "debug"); fakeGoal.configuration.sdm.cache = { enabled: true, store: testCache, }; }); it("should cache and retrieve", async () => { const options: GoalCacheOptions = { entries: [{ classifier: "default", pattern: { globPattern: "**/*.txt" } }], onCacheMiss: ErrorProjectListenerRegistration, }; fakeGoal.goalEvent.data = JSON.stringify({ foo: "bar" }); await cachePut(options) .listener(project, fakeGoal, GoalProjectListenerEvent.after); // it should find it in the cache const emptyProject = InMemoryProject.of(); assert(!await emptyProject.hasFile("test.txt")); await cacheRestore(options) .listener(emptyProject as any as GitProject, fakeGoal, GoalProjectListenerEvent.before); assert(await emptyProject.hasFile("test.txt")); const data = JSON.parse(fakeGoal.goalEvent.data); assert.deepStrictEqual(data["@atomist/sdm/input"], [{ classifier: "default" }]); assert.deepStrictEqual(data["@atomist/sdm/output"], options.entries); assert.deepStrictEqual(data.foo, "bar"); }); it("should call fallback on cache miss", async () => { // when cache something const fallback: GoalProjectListenerRegistration = { name: "fallback", listener: async p => { await p.addFile("test2.txt", "test"); }, }; const options: GoalCacheOptions = { entries: [{ classifier: "default", pattern: { globPattern: "**/*.txt" } }], onCacheMiss: fallback, }; await cachePut(options) .listener(project, fakeGoal, GoalProjectListenerEvent.after); // and clearing the cache await cacheRemove(options) .listener(project, fakeGoal, GoalProjectListenerEvent.after); // it should not find it in the cache and call fallback const emptyProject = InMemoryProject.of(); assert(!await emptyProject.hasFile("test2.txt")); await cacheRestore(options) .listener(emptyProject as any as GitProject, fakeGoal, GoalProjectListenerEvent.before); assert(await emptyProject.hasFile("test2.txt")); }); it("should call multiple fallbacks on cache miss", async () => { // when cache something const fallback: GoalProjectListenerRegistration = { name: "fallback", listener: async p => { await p.addFile("test2.txt", "test"); }, }; const fallback2: GoalProjectListenerRegistration = { name: "fallback", listener: async p => { if (await p.hasFile("test2.txt")) { await p.addFile("test3.txt", "test"); } }, }; const options: GoalCacheOptions = { entries: [{ classifier: "default", pattern: { globPattern: "**/*.txt" } }], onCacheMiss: [fallback, fallback2], }; await cachePut(options) .listener(project, fakeGoal, GoalProjectListenerEvent.after); // and clearing the cache await cacheRemove(options) .listener(project, fakeGoal, GoalProjectListenerEvent.after); // it should not find it in the cache and call fallback const emptyProject = InMemoryProject.of(); await cacheRestore(options) .listener(emptyProject as any as GitProject, fakeGoal, GoalProjectListenerEvent.before); assert(await emptyProject.hasFile("test2.txt")); assert(await emptyProject.hasFile("test3.txt")); }); it("shouldn't call fallback with failing pushtest on cache miss", async () => { // when cache something const NoPushMatches = pushTest("never", async () => false); const fallback: GoalProjectListenerRegistration = { name: "fallback", listener: async p => { await p.addFile("test.txt", "test"); }, }; const fallback2: GoalProjectListenerRegistration = { name: "fallback", listener: async p => { await p.addFile("test2.txt", "test"); }, pushTest: NoPushMatches, }; const fallback3: GoalProjectListenerRegistration = { name: "fallback", listener: async p => { await p.addFile("test3.txt", "test"); }, }; const options: GoalCacheOptions = { entries: [{ classifier: "default", pattern: { globPattern: "**/*.txt" } }], onCacheMiss: [fallback, fallback2, fallback3], }; await cachePut(options) .listener(project, fakeGoal, GoalProjectListenerEvent.after); // and clearing the cache await cacheRemove(options) .listener(project, fakeGoal, GoalProjectListenerEvent.after); // it should not find it in the cache and call fallback const emptyProject = InMemoryProject.of(); await cacheRestore(options) .listener(emptyProject as any as GitProject, fakeGoal, GoalProjectListenerEvent.before); assert(await emptyProject.hasFile("test.txt")); assert(!await emptyProject.hasFile("test2.txt")); assert(await emptyProject.hasFile("test3.txt")); }); it("shouldn't call fallback with wrong event on cache miss", async () => { // when cache something const NoPushMatches = pushTest("never", async () => false); const fallback: GoalProjectListenerRegistration = { name: "fallback", listener: async p => { await p.addFile("test.txt", "test"); }, }; const fallback2: GoalProjectListenerRegistration = { name: "fallback", listener: async p => { await p.addFile("test2.txt", "test"); }, pushTest: NoPushMatches, }; const fallback3: GoalProjectListenerRegistration = { name: "fallback", listener: async p => { await p.addFile("test3.txt", "test"); }, events: [GoalProjectListenerEvent.after], }; const options: GoalCacheOptions = { entries: [{ classifier: "default", pattern: { globPattern: "**/*.txt" } }], onCacheMiss: [fallback, fallback2, fallback3], }; await cachePut(options) .listener(project, fakeGoal, GoalProjectListenerEvent.after); // and clearing the cache await cacheRemove(options) .listener(project, fakeGoal, GoalProjectListenerEvent.after); // it should not find it in the cache and call fallback const emptyProject = InMemoryProject.of(); await cacheRestore(options) .listener(emptyProject as any as GitProject, fakeGoal, GoalProjectListenerEvent.before); assert(await emptyProject.hasFile("test.txt")); assert(!await emptyProject.hasFile("test2.txt")); assert(!await emptyProject.hasFile("test3.txt")); }); it("should default to NoOpGoalCache", async () => { fakeGoal.configuration.sdm.cache.store = undefined; const fallback: GoalProjectListenerRegistration = { name: "fallback", listener: async p => { await p.addFile("fallback.txt", "test"); }, }; const options: GoalCacheOptions = { entries: [{ classifier: "default", pattern: { globPattern: "**/*.txt" } }], onCacheMiss: fallback, }; await cachePut(options) .listener(project, fakeGoal, GoalProjectListenerEvent.after); const emptyProject = InMemoryProject.of(); await cacheRestore(options) .listener(emptyProject as any as GitProject, fakeGoal, GoalProjectListenerEvent.before); assert(await emptyProject.hasFile("fallback.txt")); }); }); });
the_stack
import sinon = require('sinon'); import {expect} from 'chai'; import * as Long from 'long'; import {Channel, Client, Endorser, Eventer, EventInfo, IdentityContext} from 'fabric-common'; import * as fabproto6 from 'fabric-protos'; import {BlockEvent, ContractEvent, ContractListener, ListenerOptions} from '../../../src/events'; import {NetworkImpl} from '../../../src/network'; import * as testUtils from '../../testutils'; import {StubEventService} from './stubeventservice'; import {Contract, ContractImpl} from '../../../src/contract'; import {Gateway} from '../../../src/gateway'; import {StubCheckpointer} from './stubcheckpointer'; import {EventServiceManager} from '../../../src/impl/event/eventservicemanager'; interface StubContractListener extends ContractListener { completePromise: Promise<ContractEvent[]>; } describe('contract event listener', () => { let eventService: StubEventService; let gateway: sinon.SinonStubbedInstance<Gateway>; let network: NetworkImpl; let channel: sinon.SinonStubbedInstance<Channel>; let listener: StubContractListener; let spyListener: sinon.SinonSpy<[ContractEvent], Promise<void>>; let contract: Contract; const eventName = 'eventName'; const chaincodeId = 'bourbons'; const eventPayload = 'payload'; beforeEach(() => { eventService = new StubEventService('stub'); gateway = sinon.createStubInstance(Gateway); gateway.identityContext = sinon.createStubInstance(IdentityContext); gateway.getIdentity.returns({ mspId: 'mspId', type: 'stub' }); channel = sinon.createStubInstance(Channel); channel.newEventService.returns(eventService); const endorser = sinon.createStubInstance(Endorser); (endorser as any).name = 'endorser'; channel.getEndorsers.returns([endorser]); const client = sinon.createStubInstance(Client); const eventer = sinon.createStubInstance(Eventer); client.newEventer.returns(eventer); (channel as any).client = client; network = new NetworkImpl(gateway as unknown as Gateway, channel); listener = testUtils.newAsyncListener<ContractEvent>(); spyListener = sinon.spy(listener); const namespace = 'biscuitContract'; contract = new ContractImpl(network, chaincodeId, namespace); }); afterEach(() => { sinon.restore(); }); // Following functions required to populate a real event info structure from fabric-protos function newEvent(blockNumber: number): EventInfo { return { eventService, blockNumber: Long.fromNumber(blockNumber), block: newFullBlock() }; } function newPrivateEvent(blockNumber: number): EventInfo { return Object.assign(newEvent(blockNumber), { privateData: [ 'PRIVATE_DATA' ] }); } function newFullBlock(): fabproto6.common.Block { const block = new fabproto6.common.Block(); block.data = new fabproto6.common.BlockData(); block.metadata = new fabproto6.common.BlockMetadata(); block.metadata.metadata = []; block.metadata.metadata[fabproto6.common.BlockMetadataIndex.TRANSACTIONS_FILTER] = new Uint8Array(10); return block; } function addTransaction(event: any, transaction:any, statusCode: number = fabproto6.protos.TxValidationCode.VALID, index = 0, transactionId?: string): void { event.block.data.data.push(newEnvelope(transaction, transactionId)); event.block.metadata.metadata[fabproto6.common.BlockMetadataIndex.TRANSACTIONS_FILTER][index] = statusCode; } function newEnvelope(transaction: any, transactionId?: string): any { const channelHeader = new fabproto6.common.ChannelHeader(); channelHeader.type = fabproto6.common.HeaderType.ENDORSER_TRANSACTION; channelHeader.tx_id = transactionId; const payload = new fabproto6.common.Payload(); payload.header = new fabproto6.common.Header(); payload.header.channel_header = channelHeader as unknown as Buffer; payload.data = transaction; const envelope:any = {}; envelope.payload = payload; return envelope; } function newTransaction(ccId: string = contract.chaincodeId): any { const transaction = new fabproto6.protos.Transaction(); transaction.actions.push(newTransactionAction(ccId)); return transaction; } function newTransactionAction(ccId: string): any { const transactionAction = new fabproto6.protos.TransactionAction(); transactionAction.payload = newChaincodeActionPayload(ccId); return transactionAction; } function newChaincodeActionPayload(ccId: string): any { const chaincodeActionPayload = new fabproto6.protos.ChaincodeActionPayload(); chaincodeActionPayload.action = newChaincodeEndorsedAction(ccId); return chaincodeActionPayload; } function newChaincodeEndorsedAction(ccId: string): any { const endorsedAction = new fabproto6.protos.ChaincodeEndorsedAction(); endorsedAction.proposal_response_payload = newProposalResponsePayload(ccId); return endorsedAction; } function newProposalResponsePayload(ccId: string): any { const proposalResponsePayload = new fabproto6.protos.ProposalResponsePayload(); proposalResponsePayload.extension = newChaincodeAction(ccId); return proposalResponsePayload; } function newChaincodeAction(ccId: string): any { const chaincodeAction = new fabproto6.protos.ChaincodeAction(); chaincodeAction.events = newChaincodeEvent(ccId); return chaincodeAction; } function newChaincodeEvent(ccId: string): any { const chaincodeEvent = new fabproto6.protos.ChaincodeEvent(); chaincodeEvent.chaincode_id = ccId; chaincodeEvent.event_name = eventName; chaincodeEvent.payload = Buffer.from(eventPayload, 'utf8'); return chaincodeEvent; } function newFilteredEvent(blockNumber: number): EventInfo { return { eventService, blockNumber: new Long(blockNumber), filteredBlock: newFilteredBlock(blockNumber) }; } function newFilteredBlock(blockNumber: number): fabproto6.protos.FilteredBlock { const filteredBlock = new fabproto6.protos.FilteredBlock(); filteredBlock.number = blockNumber; filteredBlock.filtered_transactions = []; return filteredBlock; } function addFilteredTransaction(event: EventInfo, filteredTransaction: fabproto6.protos.FilteredTransaction): void { event.filteredBlock.filtered_transactions.push(filteredTransaction); } function newFilteredTransaction(ccId: string = contract.chaincodeId): fabproto6.protos.FilteredTransaction { const filteredTransaction = new fabproto6.protos.FilteredTransaction(); filteredTransaction.tx_validation_code = fabproto6.protos.TxValidationCode.VALID; filteredTransaction.transaction_actions = newFilteredTransactionAction(ccId); return filteredTransaction; } function newFilteredTransactionAction(ccId: string): any { const filteredTransactionAction = new fabproto6.protos.FilteredTransactionActions(); filteredTransactionAction.chaincode_actions = [newFilteredChaincodeAction(ccId)]; return filteredTransactionAction; } function newFilteredChaincodeAction(ccId: string): any { const filteredChaincodeAction = new fabproto6.protos.FilteredChaincodeAction(); filteredChaincodeAction.chaincode_event = newChaincodeEvent(ccId); return filteredChaincodeAction; } function assertCanNavigateEvents(contractEvent: ContractEvent) { const transactionEvent = contractEvent.getTransactionEvent(); expect(transactionEvent).to.exist; expect(transactionEvent.getContractEvents()).to.contain(contractEvent); const blockEvent = transactionEvent.getBlockEvent(); expect(blockEvent).to.exist; expect(blockEvent.getTransactionEvents()).to.contain(transactionEvent); } it('add listener returns the listener', async () => { const result = await contract.addContractListener(listener); expect(result).to.equal(listener); }); it('listener not called if block contains no chaincode events', async () => { const event = newEvent(1); // Block event with no chaincode events const blockListener = testUtils.newAsyncListener<BlockEvent>(); await contract.addContractListener(spyListener); await network.addBlockListener(blockListener); eventService.sendEvent(event); await blockListener.completePromise; sinon.assert.notCalled(spyListener); }); it('listener receives events', async () => { const event = newEvent(1); addTransaction(event, newTransaction()); await contract.addContractListener(spyListener); eventService.sendEvent(event); await listener.completePromise; sinon.assert.calledOnceWithExactly(spyListener, sinon.match({chaincodeId, eventName})); }); it('stops listening for events after the listener has been removed', async () => { const event = newEvent(1); addTransaction(event, newTransaction()); const blockListener = testUtils.newAsyncListener<BlockEvent>(); await contract.addContractListener(spyListener); contract.removeContractListener(spyListener); await network.addBlockListener(blockListener); eventService.sendEvent(event); await blockListener.completePromise; sinon.assert.notCalled(spyListener); }); it('listener is invoked for each contract event in a block', async () => { listener = testUtils.newAsyncListener<ContractEvent>(2); spyListener = sinon.spy(listener); const event = newEvent(1); const transaction = newTransaction(); addTransaction(event, transaction); addTransaction(event, transaction); await contract.addContractListener(spyListener); eventService.sendEvent(event); await listener.completePromise; sinon.assert.calledWith(spyListener.getCall(0), sinon.match({chaincodeId, eventName})); sinon.assert.calledWith(spyListener.getCall(1), sinon.match({chaincodeId, eventName})); }); it('listener only receives events matching its chaincode id', async () => { const badEvent = newEvent(1); addTransaction(badEvent, newTransaction('fabCar')); // Event for another contract const goodEvent = newEvent(2); addTransaction(goodEvent, newTransaction()); await contract.addContractListener(spyListener); eventService.sendEvent(badEvent); eventService.sendEvent(goodEvent); await listener.completePromise; sinon.assert.calledOnceWithExactly(spyListener, sinon.match({chaincodeId, eventName})); }); it('error thrown by listener does not disrupt other listeners', async () => { listener = testUtils.newAsyncListener<ContractEvent>(2); spyListener = sinon.spy(listener); const errorListener = sinon.fake.rejects(new Error('LISTENER_ERROR')); const transaction = newTransaction(); const event1 = newEvent(1); addTransaction(event1, transaction); const event2 = newEvent(2); addTransaction(event1, transaction); await contract.addContractListener(errorListener); await contract.addContractListener(spyListener); eventService.sendEvent(event1); eventService.sendEvent(event2); await listener.completePromise; sinon.assert.calledTwice(spyListener); }); it('error thrown by listener does not prevent subsequent contract events being processed', async () => { listener = testUtils.newAsyncListener<ContractEvent>(2); const fake = sinon.fake(async (e) => { await listener(e); throw new Error('LISTENER_ERROR'); }); const event = newEvent(1); const transaction = newTransaction(); addTransaction(event, transaction); addTransaction(event, transaction); await contract.addContractListener(fake); eventService.sendEvent(event); await listener.completePromise; sinon.assert.calledTwice(fake); }); it('replay contract listener does not receive events earlier than start block', async () => { const transaction = newTransaction(); const event1 = newEvent(1); addTransaction(event1, transaction); const event2 = newEvent(2); addTransaction(event2, transaction); const options: ListenerOptions = { startBlock: 2 }; await contract.addContractListener(listener, options); eventService.sendEvent(event1); eventService.sendEvent(event2); const args = await listener.completePromise; const blockNumber = args[0].getTransactionEvent().getBlockEvent().blockNumber.toNumber(); expect(blockNumber).to.equal(options.startBlock); }); it('listener defaults to full blocks', async () => { const eventServiceManager = (network as any).eventServiceManager as EventServiceManager; const stub = sinon.stub(eventServiceManager, 'startEventService'); await contract.addContractListener(listener); sinon.assert.calledOnceWithExactly(stub, sinon.match.any, sinon.match.has('blockType', 'full')); }); it('listener can receive filtered blocks', async () => { const eventServiceManager = (network as any).eventServiceManager as EventServiceManager; const stub = sinon.stub(eventServiceManager, 'startEventService'); const event = newFilteredEvent(1); addFilteredTransaction(event, newFilteredTransaction()); const options: ListenerOptions = { type: 'filtered' }; await contract.addContractListener(listener, options); eventService.sendEvent(event); await listener.completePromise; sinon.assert.calledOnceWithExactly(stub, sinon.match.any, sinon.match.has('blockType', options.type)); }); it('listener can receive private blocks', async () => { const eventServiceManager = (network as any).eventServiceManager as EventServiceManager; const stub = sinon.stub(eventServiceManager, 'startEventService'); const event = newPrivateEvent(1); addTransaction(event, newTransaction()); const options: ListenerOptions = { type: 'private' }; await contract.addContractListener(listener, options); eventService.sendEvent(event); await listener.completePromise; sinon.assert.calledOnceWithExactly(stub, sinon.match.any, sinon.match.has('blockType', options.type)); }); it('listener does not receive events for invalid transactions', async () => { const badEvent = newEvent(1); addTransaction(badEvent, newTransaction(), fabproto6.protos.TxValidationCode.MVCC_READ_CONFLICT, 0); const goodEvent = newEvent(2); addTransaction(badEvent, newTransaction()); await contract.addContractListener(listener); eventService.sendEvent(badEvent); eventService.sendEvent(goodEvent); const contractEvents = await listener.completePromise; expect(contractEvents[0].getTransactionEvent()).to.include({isValid: true}); }); it('filtered events do not contain payload', async () => { const event = newFilteredEvent(1); addFilteredTransaction(event, newFilteredTransaction()); const options: ListenerOptions = { type: 'filtered' }; await contract.addContractListener(listener, options); eventService.sendEvent(event); const contractEvents = await listener.completePromise; expect(contractEvents[0].payload).to.be.undefined; }); it('full events contain payload', async () => { const event = newEvent(1); addTransaction(event, newTransaction()); const options: ListenerOptions = { type: 'full' }; await contract.addContractListener(listener, options); eventService.sendEvent(event); const contractEvents = await listener.completePromise; expect(contractEvents[0].payload?.toString()).to.equal(eventPayload); }); it('can navigate event hierarchy for filtered events', async () => { const event = newFilteredEvent(1); addFilteredTransaction(event, newFilteredTransaction()); const options: ListenerOptions = { type: 'filtered' }; await contract.addContractListener(listener, options); eventService.sendEvent(event); const [contractEvent] = await listener.completePromise; assertCanNavigateEvents(contractEvent); }); it('can navigate event hierarchy for full events', async () => { const event = newEvent(1); addTransaction(event, newTransaction()); const options: ListenerOptions = { type: 'full' }; await contract.addContractListener(listener, options); eventService.sendEvent(event); const [contractEvent] = await listener.completePromise; assertCanNavigateEvents(contractEvent); }); it('can navigate event hierarchy for private events', async () => { const event = newPrivateEvent(1); addTransaction(event, newTransaction()); const options: ListenerOptions = { type: 'private' }; await contract.addContractListener(listener, options); eventService.sendEvent(event); const [contractEvent] = await listener.completePromise; assertCanNavigateEvents(contractEvent); expect(contractEvent.getTransactionEvent().privateData).to.equal(event.privateData[0]); }); describe('checkpoint', () => { it('new checkpoint listener receives events', async () => { const checkpointer = new StubCheckpointer(); const event = newEvent(1); addTransaction(event, newTransaction()); const options: ListenerOptions = { checkpointer }; await contract.addContractListener(spyListener, options); eventService.sendEvent(event); await listener.completePromise; sinon.assert.calledOnceWithExactly(spyListener, sinon.match({chaincodeId, eventName})); }); it('checkpoint listener receives events from checkpoint block number', async () => { const checkpointer = new StubCheckpointer(); await checkpointer.setBlockNumber(Long.fromNumber(2)); const transaction = newTransaction(); const event1 = newEvent(1); addTransaction(event1, transaction); const event2 = newEvent(2); addTransaction(event2, transaction); const options: ListenerOptions = { checkpointer }; await contract.addContractListener(listener, options); eventService.sendEvent(event1); eventService.sendEvent(event2); const [args] = await listener.completePromise; const blockNumber = args.getTransactionEvent().getBlockEvent().blockNumber.toNumber(); expect(blockNumber).to.equal(2); }); it('checkpointer records block numbers', async () => { listener = testUtils.newAsyncListener<ContractEvent>(2); const checkpointer = new StubCheckpointer(); const transaction = newTransaction(); const event1 = newEvent(1); addTransaction(event1, transaction); const event2 = newEvent(2); addTransaction(event2, transaction); const options: ListenerOptions = { checkpointer }; await contract.addContractListener(listener, options); eventService.sendEvent(event1); eventService.sendEvent(event2); await listener.completePromise; const blockNumber = await checkpointer.getBlockNumber(); expect(blockNumber.toNumber()).to.be.oneOf([1, 2]); }); it('checkpointer records transaction IDs', async () => { listener = testUtils.newAsyncListener<ContractEvent>(2); const checkpointer = new StubCheckpointer(); const spy = sinon.spy(checkpointer, 'addTransactionId'); const transaction = newTransaction(); const event1 = newEvent(1); addTransaction(event1, transaction, undefined, 0, 'TX1'); const event2 = newEvent(2); addTransaction(event2, transaction, undefined, 0, 'TX2'); const options: ListenerOptions = { checkpointer }; await contract.addContractListener(listener, options); eventService.sendEvent(event1); eventService.sendEvent(event2); await listener.completePromise; sinon.assert.calledWith(spy, 'TX1'); }); }); });
the_stack
namespace pxtblockly { export interface FieldGridPickerToolTipConfig { yOffset?: number; xOffset?: number; } export interface FieldGridPickerOptions extends Blockly.FieldCustomDropdownOptions { columns?: string; maxRows?: string; width?: string; tooltips?: string; tooltipsXOffset?: string; tooltipsYOffset?: string; hasSearchBar?: boolean; hideRect?: boolean; } export class FieldGridPicker extends Blockly.FieldDropdown implements Blockly.FieldCustom { public isFieldCustom_ = true; // Width in pixels private width_: number; // Columns in grid private columns_: number; // Number of rows to display (if there are extra rows, the picker will be scrollable) private maxRows_: number; protected backgroundColour_: string; protected borderColour_: string; private tooltipConfig_: FieldGridPickerToolTipConfig; private gridTooltip_: HTMLElement; private firstItem_: HTMLElement; private hasSearchBar_: boolean; private hideRect_: boolean; private observer: IntersectionObserver; private selectedItemDom: HTMLElement; private closeModal_: boolean; // Selected bar private selectedBar_: HTMLElement; private selectedImg_: HTMLImageElement; private selectedBarText_: HTMLElement; private selectedBarValue_: string; private static DEFAULT_IMG = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='; constructor(text: string, options: FieldGridPickerOptions, validator?: Function) { super(options.data); this.columns_ = parseInt(options.columns) || 4; this.maxRows_ = parseInt(options.maxRows) || 0; this.width_ = parseInt(options.width) || 200; this.backgroundColour_ = pxtblockly.parseColour(options.colour); this.borderColour_ = pxt.toolbox.fadeColor(this.backgroundColour_, 0.4, false); let tooltipCfg: FieldGridPickerToolTipConfig = { xOffset: parseInt(options.tooltipsXOffset) || 15, yOffset: parseInt(options.tooltipsYOffset) || -10 } this.tooltipConfig_ = tooltipCfg; this.hasSearchBar_ = !!options.hasSearchBar || false; this.hideRect_ = !!options.hideRect || false; } /** * When disposing the grid picker, make sure the tooltips are disposed too. * @public */ public dispose() { super.dispose(); this.disposeTooltip(); this.disposeIntersectionObserver(); } private createTooltip_() { if (this.gridTooltip_) return; // Create tooltip this.gridTooltip_ = document.createElement('div'); this.gridTooltip_.className = 'goog-tooltip blocklyGridPickerTooltip'; this.gridTooltip_.style.position = 'absolute'; this.gridTooltip_.style.display = 'none'; this.gridTooltip_.style.visibility = 'hidden'; document.body.appendChild(this.gridTooltip_); } /** * Create blocklyGridPickerRows and add them to table container * @param options * @param tableContainer */ private populateTableContainer(options: (Object | String[])[], tableContainer: HTMLElement, scrollContainer: HTMLElement) { pxsim.U.removeChildren(tableContainer); if (options.length == 0) { this.firstItem_ = undefined } for (let i = 0; i < options.length / this.columns_; i++) { let row = this.populateRow(i, options, tableContainer); tableContainer.appendChild(row); } } /** * Populate a single row and add it to table container * @param row * @param options * @param tableContainer */ private populateRow(row: number, options: (Object | string[])[], tableContainer: HTMLElement): HTMLElement { const columns = this.columns_; const rowContent = document.createElement('div'); rowContent.className = 'blocklyGridPickerRow'; for (let i = (columns * row); i < Math.min((columns * row) + columns, options.length); i++) { let content = (options[i] as any)[0]; // Human-readable text or image. const value = (options[i] as any)[1]; // Language-neutral value. const menuItem = document.createElement('div'); menuItem.className = 'goog-menuitem goog-option'; menuItem.setAttribute('id', ':' + i); // For aria-activedescendant menuItem.setAttribute('role', 'menuitem'); menuItem.style.userSelect = 'none'; menuItem.title = content['alt'] || content; menuItem.setAttribute('data-value', value); const menuItemContent = document.createElement('div'); menuItemContent.setAttribute('class', 'goog-menuitem-content'); menuItemContent.title = content['alt'] || content; menuItemContent.setAttribute('data-value', value); const hasImages = typeof content == 'object'; // Set colour let backgroundColour = this.backgroundColour_; if (value == this.getValue()) { // This option is selected menuItem.setAttribute('aria-selected', 'true'); pxt.BrowserUtils.addClass(menuItem, 'goog-option-selected'); backgroundColour = (this.sourceBlock_ as Blockly.BlockSvg).getColourTertiary(); // Save so we can scroll to it later this.selectedItemDom = menuItem; if (hasImages && !this.shouldShowTooltips()) { this.updateSelectedBar_(content, value); } } menuItem.style.backgroundColor = backgroundColour; menuItem.style.borderColor = this.borderColour_; if (hasImages) { // An image, not text. const buttonImg = new Image(content['width'], content['height']); buttonImg.setAttribute('draggable', 'false'); if (!('IntersectionObserver' in window)) { // No intersection observer support, set the image url immediately buttonImg.src = content['src']; } else { buttonImg.src = FieldGridPicker.DEFAULT_IMG; buttonImg.setAttribute('data-src', content['src']); this.observer.observe(buttonImg); } buttonImg.alt = content['alt'] || ''; buttonImg.setAttribute('data-value', value); menuItemContent.appendChild(buttonImg); } else { // text menuItemContent.textContent = content; } if (this.shouldShowTooltips()) { Blockly.bindEvent_(menuItem, 'click', this, this.buttonClickAndClose_); // Setup hover tooltips const xOffset = (this.sourceBlock_.RTL ? -this.tooltipConfig_.xOffset : this.tooltipConfig_.xOffset); const yOffset = this.tooltipConfig_.yOffset; Blockly.bindEvent_(menuItem, 'mousemove', this, (e: MouseEvent) => { if (hasImages) { this.gridTooltip_.style.top = `${e.clientY + yOffset}px`; this.gridTooltip_.style.left = `${e.clientX + xOffset}px`; // Set tooltip text const touchTarget = document.elementFromPoint(e.clientX, e.clientY); const title = (touchTarget as any).title || (touchTarget as any).alt; this.gridTooltip_.textContent = title; // Show the tooltip this.gridTooltip_.style.visibility = title ? 'visible' : 'hidden'; this.gridTooltip_.style.display = title ? '' : 'none'; } pxt.BrowserUtils.addClass(menuItem, 'goog-menuitem-highlight'); tableContainer.setAttribute('aria-activedescendant', menuItem.id); }); Blockly.bindEvent_(menuItem, 'mouseout', this, (e: MouseEvent) => { if (hasImages) { // Hide the tooltip this.gridTooltip_.style.visibility = 'hidden'; this.gridTooltip_.style.display = 'none'; } pxt.BrowserUtils.removeClass(menuItem, 'goog-menuitem-highlight'); tableContainer.removeAttribute('aria-activedescendant'); }); } else { if (hasImages) { // Show the selected bar this.selectedBar_.style.display = ''; // Show the selected item (in the selected bar) Blockly.bindEvent_(menuItem, 'click', this, (e: MouseEvent) => { if (this.closeModal_) { this.buttonClick_(e); } else { // Clear all current hovers. const currentHovers = tableContainer.getElementsByClassName('goog-menuitem-highlight'); for (let i = 0; i < currentHovers.length; i++) { pxt.BrowserUtils.removeClass(currentHovers[i] as HTMLElement, 'goog-menuitem-highlight'); } // Set hover on current item pxt.BrowserUtils.addClass(menuItem, 'goog-menuitem-highlight'); this.updateSelectedBar_(content, value); } }); } else { Blockly.bindEvent_(menuItem, 'click', this, this.buttonClickAndClose_); Blockly.bindEvent_(menuItem, 'mouseup', this, this.buttonClickAndClose_); } } menuItem.appendChild(menuItemContent); rowContent.appendChild(menuItem); if (i == 0) { this.firstItem_ = menuItem; } } return rowContent; } /** * Callback for when a button is clicked inside the drop-down. * Should be bound to the FieldIconMenu. * @param {Event} e DOM event for the click/touch * @private */ protected buttonClick_ = function (e: any) { let value = e.target.getAttribute('data-value'); if (value !== null) { this.setValue(value); // Close the picker if (this.closeModal_) { this.close(); this.closeModal_ = false; } } }; protected buttonClickAndClose_ = function (e: any) { this.closeModal_ = true; this.buttonClick_(e); }; /** * Whether or not to show a box around the dropdown menu. * @return {boolean} True if we should show a box (rect) around the dropdown menu. Otherwise false. * @private */ shouldShowRect_() { return !this.hideRect_ ? !this.sourceBlock_.isShadow() : false; } doClassValidation_(newValue: string) { return newValue; } /** * Closes the gridpicker. */ private close() { this.disposeTooltip(); Blockly.WidgetDiv.hideIfOwner(this); Blockly.Events.setGroup(false); } /** * Getter method */ private getFirstItem() { return this.firstItem_; } /** * Highlight first item in menu, de-select and de-highlight all others */ private highlightFirstItem(tableContainerDom: HTMLElement) { let menuItemsDom = tableContainerDom.childNodes; if (menuItemsDom.length && menuItemsDom[0].childNodes) { for (let row = 0; row < menuItemsDom.length; ++row) { let rowLength = menuItemsDom[row].childNodes.length for (let col = 0; col < rowLength; ++col) { const menuItem = menuItemsDom[row].childNodes[col] as HTMLElement pxt.BrowserUtils.removeClass(menuItem, "goog-menuitem-highlight"); pxt.BrowserUtils.removeClass(menuItem, "goog-option-selected"); } } let firstItem = menuItemsDom[0].childNodes[0] as HTMLElement; firstItem.className += " goog-menuitem-highlight" } } /** * Scroll menu to item that equals current value of gridpicker */ private highlightAndScrollSelected(tableContainerDom: HTMLElement, scrollContainerDom: HTMLElement) { if (!this.selectedItemDom) return; goog.style.scrollIntoContainerView(this.selectedItemDom, scrollContainerDom, true); } /** * Create a dropdown menu under the text. * @private */ public showEditor_() { Blockly.WidgetDiv.show(this, this.sourceBlock_.RTL, () => { this.onClose_(); }); this.setupIntersectionObserver_(); this.createTooltip_(); const tableContainer = document.createElement("div"); this.positionMenu_(tableContainer); } private positionMenu_(tableContainer: HTMLElement) { // Record viewport dimensions before adding the dropdown. const viewportBBox = Blockly.utils.getViewportBBox(); const anchorBBox = this.getAnchorDimensions_(); const { paddingContainer, scrollContainer } = this.createWidget_(tableContainer); const containerSize = { width: paddingContainer.offsetWidth, height: paddingContainer.offsetHeight }; //goog.style.getSize(paddingContainer); // Set width const windowSize = goog.dom.getViewportSize(); if (this.width_ > windowSize.width) { this.width_ = windowSize.width; } tableContainer.style.width = this.width_ + 'px'; let addedHeight = 0; if (this.hasSearchBar_) addedHeight += 50; // Account for search bar if (this.selectedBar_) addedHeight += 50; // Account for the selected bar // Set height if (this.maxRows_) { // Calculate height const firstRowDom = tableContainer.children[0] as HTMLElement; const rowHeight = firstRowDom.offsetHeight; // Compute maxHeight using maxRows + 0.3 to partially show next row, to hint at scrolling let maxHeight = rowHeight * (this.maxRows_ + 0.3); if (windowSize.height < (maxHeight + addedHeight)) { maxHeight = windowSize.height - addedHeight; } if (containerSize.height > maxHeight) { scrollContainer.style.overflowY = "auto"; goog.style.setHeight(scrollContainer, maxHeight); containerSize.height = maxHeight; } } containerSize.height += addedHeight; if (this.sourceBlock_.RTL) { (Blockly.utils as any).uiMenu.adjustBBoxesForRTL(viewportBBox, anchorBBox, containerSize); } // Position the menu. Blockly.WidgetDiv.positionWithAnchor(viewportBBox, anchorBBox, containerSize, this.sourceBlock_.RTL); // (<any>scrollContainer).focus(); this.highlightAndScrollSelected(tableContainer, scrollContainer) }; private shouldShowTooltips() { return !pxt.BrowserUtils.isMobile(); } private getAnchorDimensions_() { const boundingBox = this.getScaledBBox() as any; if (this.sourceBlock_.RTL) { boundingBox.right += Blockly.FieldDropdown.CHECKMARK_OVERHANG; } else { boundingBox.left -= Blockly.FieldDropdown.CHECKMARK_OVERHANG; } return boundingBox; }; private createWidget_(tableContainer: HTMLElement) { const div = Blockly.WidgetDiv.DIV; const options = this.getOptions(); // Container for the menu rows tableContainer.setAttribute("role", "menu"); tableContainer.setAttribute("aria-haspopup", "true"); // Container used to limit the height of the tableContainer, because the tableContainer uses // display: table, which ignores height and maxHeight const scrollContainer = document.createElement("div"); // Needed to correctly style borders and padding around the scrollContainer, because the padding around the // scrollContainer is part of the scrollable area and will not be correctly shown at the top and bottom // when scrolling const paddingContainer = document.createElement("div"); paddingContainer.style.border = `solid 1px ${this.borderColour_}`; tableContainer.style.backgroundColor = this.backgroundColour_; scrollContainer.style.backgroundColor = this.backgroundColour_; paddingContainer.style.backgroundColor = this.backgroundColour_; tableContainer.className = 'blocklyGridPickerMenu'; scrollContainer.className = 'blocklyGridPickerScroller'; paddingContainer.className = 'blocklyGridPickerPadder'; paddingContainer.appendChild(scrollContainer); scrollContainer.appendChild(tableContainer); div.appendChild(paddingContainer); // Search bar if (this.hasSearchBar_) { const searchBar = this.createSearchBar_(tableContainer, scrollContainer, options); paddingContainer.insertBefore(searchBar, paddingContainer.childNodes[0]); } // Selected bar if (!this.shouldShowTooltips()) { this.selectedBar_ = this.createSelectedBar_(); paddingContainer.appendChild(this.selectedBar_); } // Render elements this.populateTableContainer(options, tableContainer, scrollContainer); return { paddingContainer, scrollContainer }; } private createSearchBar_(tableContainer: HTMLElement, scrollContainer: HTMLElement, options: (Object | string[])[]) { const searchBarDiv = document.createElement("div"); searchBarDiv.setAttribute("class", "ui fluid icon input"); const searchIcon = document.createElement("i"); searchIcon.setAttribute("class", "search icon"); const searchBar = document.createElement("input"); searchBar.setAttribute("type", "search"); searchBar.setAttribute("id", "search-bar"); searchBar.setAttribute("class", "blocklyGridPickerSearchBar"); searchBar.setAttribute("placeholder", pxt.Util.lf("Search")); searchBar.addEventListener("click", () => { searchBar.focus(); searchBar.setSelectionRange(0, searchBar.value.length); }); // Search on key change searchBar.addEventListener("keyup", pxt.Util.debounce(() => { let text = searchBar.value; let re = new RegExp(text, "i"); let filteredOptions = options.filter((block) => { const alt = (block as any)[0].alt; // Human-readable text or image. const value = (block as any)[1]; // Language-neutral value. return alt ? re.test(alt) : re.test(value); }) this.populateTableContainer.bind(this)(filteredOptions, tableContainer, scrollContainer); if (text) { this.highlightFirstItem(tableContainer) } else { this.highlightAndScrollSelected(tableContainer, scrollContainer) } // Hide the tooltip this.gridTooltip_.style.visibility = 'hidden'; this.gridTooltip_.style.display = 'none'; }, 300, false)); // Select the first item if the enter key is pressed searchBar.addEventListener("keyup", (e: KeyboardEvent) => { const code = e.which; if (code == 13) { /* Enter key */ // Select the first item in the list const firstRow = tableContainer.childNodes[0] as HTMLElement; if (firstRow) { const firstItem = firstRow.childNodes[0] as HTMLElement; if (firstItem) { this.closeModal_ = true; firstItem.click(); } } } }); searchBarDiv.appendChild(searchBar); searchBarDiv.appendChild(searchIcon); return searchBarDiv; } private createSelectedBar_() { const selectedBar = document.createElement("div"); selectedBar.setAttribute("class", "blocklyGridPickerSelectedBar"); selectedBar.style.display = 'none'; const selectedWrapper = document.createElement("div"); const selectedImgWrapper = document.createElement("div"); selectedImgWrapper.className = 'blocklyGridPickerSelectedImage'; selectedWrapper.appendChild(selectedImgWrapper); this.selectedImg_ = document.createElement("img"); this.selectedImg_.setAttribute('width', '30px'); this.selectedImg_.setAttribute('height', '30px'); this.selectedImg_.setAttribute('draggable', 'false'); this.selectedImg_.style.display = 'none'; this.selectedImg_.src = FieldGridPicker.DEFAULT_IMG; selectedImgWrapper.appendChild(this.selectedImg_); this.selectedBarText_ = document.createElement("span"); this.selectedBarText_.className = 'blocklyGridPickerTooltip'; selectedWrapper.appendChild(this.selectedBarText_); const buttonsWrapper = document.createElement("div"); const buttonsDiv = document.createElement("div"); buttonsDiv.className = 'ui buttons mini'; buttonsWrapper.appendChild(buttonsDiv); const selectButton = document.createElement("button"); selectButton.className = "ui button icon green"; const selectButtonIcon = document.createElement("i"); selectButtonIcon.className = 'icon check'; selectButton.appendChild(selectButtonIcon); Blockly.bindEvent_(selectButton, 'click', this, () => { this.setValue(this.selectedBarValue_); this.close(); }); const cancelButton = document.createElement("button"); cancelButton.className = "ui button icon red"; const cancelButtonIcon = document.createElement("i"); cancelButtonIcon.className = 'icon cancel'; cancelButton.appendChild(cancelButtonIcon); Blockly.bindEvent_(cancelButton, 'click', this, () => { this.close(); }); buttonsDiv.appendChild(selectButton); buttonsDiv.appendChild(cancelButton); selectedBar.appendChild(selectedWrapper); selectedBar.appendChild(buttonsWrapper); return selectedBar; } private updateSelectedBar_(content: any, value: string) { if (content['src']) { this.selectedImg_.src = content['src']; this.selectedImg_.style.display = ''; } this.selectedImg_.alt = content['alt'] || content; this.selectedBarText_.textContent = content['alt'] || content; this.selectedBarValue_ = value; } private setupIntersectionObserver_() { if (!('IntersectionObserver' in window)) return; this.disposeIntersectionObserver(); // setup intersection observer for the image const preloadImage = (el: HTMLImageElement) => { const lazyImageUrl = el.getAttribute('data-src'); if (lazyImageUrl) { el.src = lazyImageUrl; el.removeAttribute('data-src'); } } const config = { // If the image gets within 50px in the Y axis, start the download. rootMargin: '20px 0px', threshold: 0.01 }; const onIntersection: IntersectionObserverCallback = (entries) => { entries.forEach(entry => { // Are we in viewport? if (entry.intersectionRatio > 0) { // Stop watching and load the image this.observer.unobserve(entry.target); preloadImage(entry.target as HTMLImageElement); } }) } this.observer = new IntersectionObserver(onIntersection, config); } private disposeIntersectionObserver() { if (this.observer) { this.observer = null; } } /** * Disposes the tooltip DOM. * @private */ private disposeTooltip() { if (this.gridTooltip_) { pxsim.U.remove(this.gridTooltip_); this.gridTooltip_ = null; } } private onClose_() { this.disposeTooltip(); } } }
the_stack
import EventNode from '../lib/eventLogNode'; import EventLogDataObject from '../lib/eventLogData'; import {EventLogObject} from '../lib/apollo11types'; const dllStructure = new EventLogDataObject(); const dllStructure2 = new EventLogDataObject(); const evtNode1: EventLogObject = { event: { mutation: { kind: 'Document', definitions: [], }, variables: {}, loading: false, error: null, }, type: 'query', eventId: '099087779', }; const eventNode1 = new EventNode(evtNode1); const evtNode2: EventLogObject = { event: { mutation: { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'mutation', name: {kind: 'Name', value: 'newBookTrips'}, variableDefinitions: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: {kind: 'Name', value: 'newbookTrips'}, arguments: [ { kind: 'Argument', name: {kind: 'Name', value: 'newlaunchIds'}, value: { kind: 'Variable', name: {kind: 'Name', value: 'newlaunchIds'}, }, }, ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: {kind: 'Name', value: 'success'}, arguments: [], directives: [], }, { kind: 'Field', name: {kind: 'Name', value: 'message'}, arguments: [], directives: [], }, { kind: 'Field', name: {kind: 'Name', value: 'launches'}, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: {kind: 'Name', value: 'id'}, arguments: [], directives: [], }, { kind: 'Field', name: {kind: 'Name', value: 'isBooked'}, arguments: [], directives: [], }, { kind: 'Field', name: {kind: 'Name', value: '__typename'}, }, ], }, }, { kind: 'Field', name: {kind: 'Name', value: '__typename'}, }, ], }, }, ], }, }, ], // loc: {start: 0, end: 173}, }, variables: {launchIds: ['100']}, loading: false, error: null, }, type: 'mutation', eventId: '099087780', }; const eventNode2 = new EventNode(evtNode2); const evtNode3: EventLogObject = { event: { mutation: { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'mutation', name: {kind: 'Name', value: 'cancel'}, variableDefinitions: [ { kind: 'VariableDefinition', variable: { kind: 'Variable', name: {kind: 'Name', value: 'launchId'}, }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: {kind: 'Name', value: 'ID'}, }, }, directives: [], }, ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: {kind: 'Name', value: 'cancelTrip'}, arguments: [ { kind: 'Argument', name: {kind: 'Name', value: 'launchId'}, value: { kind: 'Variable', name: {kind: 'Name', value: 'launchId'}, }, }, ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: {kind: 'Name', value: 'success'}, arguments: [], directives: [], }, { kind: 'Field', name: {kind: 'Name', value: 'message'}, arguments: [], directives: [], }, { kind: 'Field', name: {kind: 'Name', value: 'launches'}, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: {kind: 'Name', value: 'id'}, arguments: [], directives: [], }, { kind: 'Field', name: {kind: 'Name', value: 'isBooked'}, arguments: [], directives: [], }, { kind: 'Field', name: {kind: 'Name', value: '__typename'}, }, ], }, }, { kind: 'Field', name: {kind: 'Name', value: '__typename'}, }, ], }, }, ], }, }, ], }, variables: {launchId: '101'}, loading: true, error: null, }, type: 'mutation', eventId: '099087787', }; const eventNode3 = new EventNode(evtNode3); const evtNode4: EventLogObject = { event: { mutation: { kind: 'Document', definitions: [], }, variables: {}, loading: false, error: null, }, type: 'query', eventId: '099087793', }; const eventNode4 = new EventNode(evtNode4); const evtNode5: EventLogObject = { event: { mutation: { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'mutation', name: {kind: 'Name', value: 'newBookTrips'}, variableDefinitions: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: {kind: 'Name', value: 'newbookTrips'}, arguments: [ { kind: 'Argument', name: {kind: 'Name', value: 'newlaunchIds'}, value: { kind: 'Variable', name: {kind: 'Name', value: 'newlaunchIds'}, }, }, ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: {kind: 'Name', value: 'success'}, arguments: [], directives: [], }, { kind: 'Field', name: {kind: 'Name', value: 'message'}, arguments: [], directives: [], }, { kind: 'Field', name: {kind: 'Name', value: 'launches'}, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: {kind: 'Name', value: 'id'}, arguments: [], directives: [], }, { kind: 'Field', name: {kind: 'Name', value: 'isBooked'}, arguments: [], directives: [], }, { kind: 'Field', name: {kind: 'Name', value: '__typename'}, }, ], }, }, { kind: 'Field', name: {kind: 'Name', value: '__typename'}, }, ], }, }, ], }, }, ], // loc: {start: 0, end: 173}, }, variables: {launchIds: ['100']}, loading: false, error: null, }, type: 'mutation', eventId: '099087796', }; const eventNode5 = new EventNode(evtNode5); dllStructure.addEventLog(eventNode1); // console.log(dllStructure); dllStructure.addEventLog(eventNode2); // console.log(dllStructure); dllStructure.addEventLog(eventNode3); // console.log(dllStructure); // console.log(dllStructure.map(e => e)); dllStructure2.addEventLog(eventNode4); dllStructure2.addEventLog(eventNode5); // eventNode1: '099087779', // eventNode2: '099087780', // eventNode3: '099087787', // eventNode4: '099087793', // eventNode5: '099087796', console.log('First DLL ::', dllStructure); console.log(dllStructure.debugPrint()); console.log(dllStructure.reverseDebugPrint()); console.log('Second DLL ::', dllStructure2); console.log(dllStructure2.debugPrint()); console.log(dllStructure2.reverseDebugPrint()); dllStructure.append(dllStructure2); console.log('New DLL ::', dllStructure); console.log(dllStructure.debugPrint()); console.log(dllStructure.reverseDebugPrint()); // const allStructures = dllStructure.addEventLog(dllStructure2.eventHead); // const allStructures = dllStructure.insertEventLogAfter( // dllStructure.eventTail, // dllStructure2.eventHead, // ); // console.log('Addition of BOTH'); // console.log(allStructures); // let nde = allStructures.eventHead; // while (nde) { // console.log('NDE :: ', nde); // console.log(nde.content.eventId); // nde = nde.next; // }
the_stack
import { SequenceMultiplicity, SequenceType, ValueType } from '../expressions/dataTypes/Value'; import astHelper, { IAST } from '../parsing/astHelper'; import { annotateArrayConstructor } from './annotateArrayConstructor'; import { annotateArrowExpr } from './annotateArrowExpr'; import { annotateBinOp } from './annotateBinaryOperator'; import { annotateCastableOperator, annotateCastOperator } from './annotateCastOperators'; import { annotateGeneralCompare, annotateNodeCompare, annotateValueCompare, } from './annotateCompareOperator'; import { annotateContextItemExpr } from './annotateContextItemExpr'; import { annotateDynamicFunctionInvocationExpr } from './annotateDynamicFunctionInvocationExpr'; import { annotateFlworExpression } from './annotateFlworExpression'; import { annotateFunctionCall } from './annotateFunctionCall'; import { annotateIfThenElseExpr } from './annotateIfThenElseExpr'; import { annotateInstanceOfExpr } from './annotateInstanceOfExpr'; import { annotateLogicalOperator } from './annotateLogicalOperator'; import { annotateMapConstructor } from './annotateMapConstructor'; import { annotateNamedFunctionRef } from './annotateNamedFunctionRef'; import { annotatePathExpr } from './annotatePathExpr'; import { annotateQuantifiedExpr } from './annotateQuantifiedExpr'; import { annotateRangeSequenceOperator } from './annotateRangeSequenceOperator'; import { annotateSequenceOperator } from './annotateSequenceOperator'; import { annotateSetOperator } from './annotateSetOperators'; import { annotateSimpleMapExpr } from './annotateSimpleMapExpr'; import { annotateStringConcatenateOperator } from './annotateStringConcatenateOperator'; import { annotateTypeSwitchOperator } from './annotateTypeSwitchOperator'; import { annotateUnaryLookup } from './annotateUnaryLookup'; import { annotateUnaryMinus, annotateUnaryPlus } from './annotateUnaryOperator'; import { annotateVarRef } from './annotateVarRef'; import { AnnotationContext } from './AnnotationContext'; /** * Recursively traverse the AST in the depth first, pre-order to infer type and annotate AST; * Annotates as much type information as possible to the AST nodes. * Inserts attribute `type` to the corresponding node if type is inferred. * * @param ast The AST to annotate * @param context The static context used for function lookups */ export default function annotateAst(ast: IAST, context: AnnotationContext) { annotate(ast, context); } export function countQueryBodyAnnotations( ast: IAST, total: number = 0, annotated: number = 0 ): [number, number] { for (let i = 1; i < ast.length; i++) { if (Array.isArray(ast[i])) [total, annotated] = countQueryBodyAnnotations(ast[i] as IAST, total, annotated); } if (annotationFunctions.has(ast[0]) && ast[0] !== 'queryBody') { if (astHelper.getAttribute(ast, 'type')) annotated += 1; total += 1; } return [total, annotated]; } /** * Recursively traverse the AST in the depth first, pre-order to infer type and annotate AST; * Annotates as much type information as possible to the AST nodes. * Inserts attribute `type` to the corresponding node if type is inferred. * * @param ast The AST to annotate. * @param context The static context to use for function lookups. * @throws errors when attempts to annotate fail. * @returns The type of the AST node or `undefined` when the type cannot be annotated. */ function annotate(ast: IAST, context: AnnotationContext): SequenceType | undefined { const astNodeName = ast[0]; const annotationFunction = annotationFunctions.get(astNodeName); if (annotationFunction) { return annotationFunction(ast, context); } // Current node cannot be annotated, but maybe deeper ones can. for (let i = 1; i < ast.length; i++) { if (ast[i]) { annotate(ast[i] as IAST, context); } } return undefined; } /** * The function lambda for annotating binary operators */ const binopAnnotateCb = (ast: IAST, context: AnnotationContext): SequenceType => { const left = annotate(astHelper.getFirstChild(ast, 'firstOperand')[1] as IAST, context); const right = annotate(astHelper.getFirstChild(ast, 'secondOperand')[1] as IAST, context); return annotateBinOp(ast, left, right, ast[0], context); }; /** * The function lambda for annotating logical operators */ const logicOpAnnotateCb = (ast: IAST, context: AnnotationContext): SequenceType => { annotate(astHelper.getFirstChild(ast, 'firstOperand')[1] as IAST, context); annotate(astHelper.getFirstChild(ast, 'secondOperand')[1] as IAST, context); return annotateLogicalOperator(ast); }; /** * The function lambda for annotating set operators */ const setOpAnnotateCb = (ast: IAST, context: AnnotationContext): SequenceType => { annotate(astHelper.getFirstChild(ast, 'firstOperand')[1] as IAST, context); annotate(astHelper.getFirstChild(ast, 'secondOperand')[1] as IAST, context); return annotateSetOperator(ast); }; /** * The function lambda for annotating general compare operators */ const generalCompareAnnotateCb = (ast: IAST, context: AnnotationContext): SequenceType => { annotate(astHelper.getFirstChild(ast, 'firstOperand')[1] as IAST, context); annotate(astHelper.getFirstChild(ast, 'secondOperand')[1] as IAST, context); return annotateGeneralCompare(ast); }; /** * The function lambda for annotating value compare operators */ const valueCompareAnnotateCb = (ast: IAST, context: AnnotationContext): SequenceType => { annotate(astHelper.getFirstChild(ast, 'firstOperand')[1] as IAST, context); annotate(astHelper.getFirstChild(ast, 'secondOperand')[1] as IAST, context); return annotateValueCompare(ast); }; /** * The function lambda for annotating node compare operators */ const nodeCompareAnnotateCb = (ast: IAST, context: AnnotationContext): SequenceType => { annotate(astHelper.getFirstChild(ast, 'firstOperand')[1] as IAST, context); annotate(astHelper.getFirstChild(ast, 'secondOperand')[1] as IAST, context); return annotateNodeCompare(ast); }; /** * A lookup table which stores the AST node name and the annotation function lambda. Converting * this from a switch to a map allows us to get a list of all nodes the current system can annotate * using `Object.keys(annotationFunctions)`. */ const annotationFunctions = new Map< string, (ast: IAST, context: AnnotationContext) => SequenceType >([ [ 'unaryMinusOp', (ast: IAST, context: AnnotationContext): SequenceType => { const minVal = annotate(astHelper.getFirstChild(ast, 'operand')[1] as IAST, context); return annotateUnaryMinus(ast, minVal, context); }, ], [ 'unaryPlusOp', (ast: IAST, context: AnnotationContext): SequenceType => { const plusVal = annotate(astHelper.getFirstChild(ast, 'operand')[1] as IAST, context); return annotateUnaryPlus(ast, plusVal, context); }, // Binary operators ], ['addOp', binopAnnotateCb], ['subtractOp', binopAnnotateCb], ['divOp', binopAnnotateCb], ['idivOp', binopAnnotateCb], ['modOp', binopAnnotateCb], [ 'multiplyOp', binopAnnotateCb, // And + Or operators ], ['andOp', logicOpAnnotateCb], [ 'orOp', logicOpAnnotateCb, // Sequences ], [ 'sequenceExpr', (ast: IAST, context: AnnotationContext): SequenceType => { const children = astHelper.getChildren(ast, '*'); const types = children.map((a) => annotate(a, context)); return annotateSequenceOperator(ast, children.length, children, types); }, // Set operations (union, intersect, except) ], ['unionOp', setOpAnnotateCb], ['intersectOp', setOpAnnotateCb], [ 'exceptOp', setOpAnnotateCb, // String concatentation ], [ 'stringConcatenateOp', (ast: IAST, context: AnnotationContext): SequenceType => { annotate(astHelper.getFirstChild(ast, 'firstOperand')[1] as IAST, context); annotate(astHelper.getFirstChild(ast, 'secondOperand')[1] as IAST, context); return annotateStringConcatenateOperator(ast); }, // Range operator ], [ 'rangeSequenceExpr', (ast: IAST, context: AnnotationContext): SequenceType => { annotate(astHelper.getFirstChild(ast, 'startExpr')[1] as IAST, context); annotate(astHelper.getFirstChild(ast, 'endExpr')[1] as IAST, context); return annotateRangeSequenceOperator(ast); }, // Comparison operators ], ['equalOp', generalCompareAnnotateCb], ['notEqualOp', generalCompareAnnotateCb], ['lessThanOrEqualOp', generalCompareAnnotateCb], ['lessThanOp', generalCompareAnnotateCb], ['greaterThanOrEqualOp', generalCompareAnnotateCb], ['greaterThanOp', generalCompareAnnotateCb], ['eqOp', valueCompareAnnotateCb], ['neOp', valueCompareAnnotateCb], ['ltOp', valueCompareAnnotateCb], ['leOp', valueCompareAnnotateCb], ['gtOp', valueCompareAnnotateCb], ['geOp', valueCompareAnnotateCb], ['isOp', nodeCompareAnnotateCb], ['nodeBeforeOp', nodeCompareAnnotateCb], [ 'nodeAfterOp', nodeCompareAnnotateCb, // Path Expression ], [ 'pathExpr', (ast: IAST, context: AnnotationContext): SequenceType => { const root = astHelper.getFirstChild(ast, 'rootExpr'); if (root && root[1]) annotate(root[1] as IAST, context); astHelper.getChildren(ast, 'stepExpr').map((b) => annotate(b, context)); return annotatePathExpr(ast); }, // Context Item ], [ 'contextItemExpr', (ast, _context) => { return annotateContextItemExpr(ast); }, ], [ 'ifThenElseExpr', (ast: IAST, context: AnnotationContext): SequenceType => { // If clause annotate( astHelper.getFirstChild(astHelper.getFirstChild(ast, 'ifClause'), '*'), context ); const thenClause = annotate( astHelper.getFirstChild(astHelper.getFirstChild(ast, 'thenClause'), '*'), context ); const elseClause = annotate( astHelper.getFirstChild(astHelper.getFirstChild(ast, 'elseClause'), '*'), context ); return annotateIfThenElseExpr(ast, thenClause, elseClause); }, ], [ 'instanceOfExpr', (ast: IAST, context: AnnotationContext): SequenceType => { annotate(astHelper.getFirstChild(ast, 'argExpr'), context); annotate(astHelper.getFirstChild(ast, 'sequenceType'), context); return annotateInstanceOfExpr(ast); }, // Constant expressions ], [ 'integerConstantExpr', (ast: IAST, _context: AnnotationContext): SequenceType => { const integerSequenceType = { type: ValueType.XSINTEGER, mult: SequenceMultiplicity.EXACTLY_ONE, }; astHelper.insertAttribute(ast, 'type', integerSequenceType); return integerSequenceType; }, ], [ 'doubleConstantExpr', (ast: IAST, _context: AnnotationContext): SequenceType => { const doubleSequenceType = { type: ValueType.XSDOUBLE, mult: SequenceMultiplicity.EXACTLY_ONE, }; astHelper.insertAttribute(ast, 'type', doubleSequenceType); return doubleSequenceType; }, ], [ 'decimalConstantExpr', (ast: IAST, _context: AnnotationContext): SequenceType => { const decimalSequenceType = { type: ValueType.XSDECIMAL, mult: SequenceMultiplicity.EXACTLY_ONE, }; astHelper.insertAttribute(ast, 'type', decimalSequenceType); return decimalSequenceType; }, ], [ 'stringConstantExpr', (ast: IAST, _context: AnnotationContext): SequenceType => { const stringSequenceType = { type: ValueType.XSSTRING, mult: SequenceMultiplicity.EXACTLY_ONE, }; astHelper.insertAttribute(ast, 'type', stringSequenceType); return stringSequenceType; }, // Functions ], [ 'functionCallExpr', (ast: IAST, context: AnnotationContext): SequenceType => { const functionArguments = astHelper.getFirstChild(ast, 'arguments'); const argumentTypeNodes = astHelper.getChildren(functionArguments, '*'); argumentTypeNodes.map((x) => annotate(x, context)); return annotateFunctionCall(ast, context); }, ], [ 'arrowExpr', (ast: IAST, context: AnnotationContext): SequenceType => { annotate(astHelper.getFirstChild(ast, 'argExpr')[1] as IAST, context); return annotateArrowExpr(ast, context); }, ], [ 'dynamicFunctionInvocationExpr', (ast: IAST, context: AnnotationContext): SequenceType => { const functionItem: SequenceType = annotate( astHelper.followPath(ast, ['functionItem', '*']), context ); const argNodes = astHelper.getFirstChild(ast, 'arguments'); const args: SequenceType = argNodes ? annotate(argNodes, context) : undefined; return annotateDynamicFunctionInvocationExpr(ast); }, ], [ 'namedFunctionRef', (ast: IAST, context: AnnotationContext): SequenceType => { return annotateNamedFunctionRef(ast, context); }, ], [ 'inlineFunctionExpr', (ast: IAST, context: AnnotationContext): SequenceType => { annotate(astHelper.getFirstChild(ast, 'functionBody')[1] as IAST, context); const type = { type: ValueType.FUNCTION, mult: SequenceMultiplicity.EXACTLY_ONE }; astHelper.insertAttribute(ast, 'type', type); return type; }, // Casting ], [ 'castExpr', (ast: IAST, _context: AnnotationContext): SequenceType => { return annotateCastOperator(ast); }, ], [ 'castableExpr', (ast: IAST, _context: AnnotationContext): SequenceType => { return annotateCastableOperator(ast); }, // Maps ], [ 'simpleMapExpr', (ast: IAST, context: AnnotationContext): SequenceType => { const pathExpressions: IAST[] = astHelper.getChildren(ast, 'pathExpr'); let lastType; for (let i = 0; i < pathExpressions.length; i++) { lastType = annotate(pathExpressions[i], context); } return annotateSimpleMapExpr(ast, context, lastType); }, ], [ 'mapConstructor', (ast: IAST, context: AnnotationContext): SequenceType => { astHelper.getChildren(ast, 'mapConstructorEntry').map((keyValuePair) => ({ key: annotate(astHelper.followPath(keyValuePair, ['mapKeyExpr', '*']), context), value: annotate(astHelper.followPath(keyValuePair, ['mapValueExpr', '*']), context), })); return annotateMapConstructor(ast); }, // Arrays ], [ 'arrayConstructor', (ast: IAST, context: AnnotationContext): SequenceType => { astHelper .getChildren(astHelper.getFirstChild(ast, '*'), 'arrayElem') .map((arrayElem) => annotate(arrayElem, context)); return annotateArrayConstructor(ast); }, // Unary Lookup ], [ 'unaryLookup', (ast: IAST, _context: AnnotationContext): SequenceType => { const ncName = astHelper.getFirstChild(ast, 'NCName'); return annotateUnaryLookup(ast, ncName); }, // TypeSwitch ], [ 'typeswitchExpr', (ast: IAST, context: AnnotationContext): SequenceType => { const argumentType = annotate( astHelper.getFirstChild(ast, 'argExpr')[1] as IAST, context ); const caseClausesReturns = astHelper .getChildren(ast, 'typeswitchExprCaseClause') .map((a) => annotate(astHelper.followPath(a, ['resultExpr'])[1] as IAST, context)); const defaultCaseReturn = annotate( astHelper.followPath(ast, ['typeswitchExprDefaultClause', 'resultExpr'])[1] as IAST, context ); return annotateTypeSwitchOperator( ast, argumentType, caseClausesReturns, defaultCaseReturn ); }, ], [ 'quantifiedExpr', (ast: IAST, context: AnnotationContext): SequenceType => { astHelper.getChildren(ast, '*').map((a) => annotate(a, context)); return annotateQuantifiedExpr(ast); }, ], [ 'x:stackTrace', (ast: IAST, context: AnnotationContext): SequenceType => { const children = astHelper.getChildren(ast, '*'); return annotate(children[0], context); }, ], [ 'queryBody', (ast: IAST, context: AnnotationContext): SequenceType => { const type = annotate(ast[1] as IAST, context); return type; }, ], [ 'flworExpr', (ast: IAST, context: AnnotationContext): SequenceType => { return annotateFlworExpression(ast, context, annotate); }, ], [ 'varRef', (ast: IAST, context: AnnotationContext): SequenceType => { return annotateVarRef(ast as IAST, context); }, ], ]);
the_stack
import { Injectable } from "@angular/core"; import { Delegate } from "ark-ts"; import { Network, NetworkType } from "ark-ts/model"; import * as lodash from "lodash"; import { EMPTY, Observable, Subject, throwError } from "rxjs"; import { debounceTime, map } from "rxjs/operators"; import { v4 as uuid } from "uuid"; import * as constants from "@/app/app.constants"; import { Contact, Profile, Wallet, WalletKeys } from "@/models/model"; import { StoredNetwork } from "@/models/stored-network"; import { TranslatableObject } from "@/models/translate"; import { AuthProvider } from "@/services/auth/auth"; import { ForgeProvider } from "@/services/forge/forge"; import { StorageProvider } from "@/services/storage/storage"; import { UserDataService } from "./user-data.interface"; @Injectable() export class UserDataServiceImpl implements UserDataService { public get isDevNet(): boolean { return ( this.currentNetwork && this.currentNetwork.type === NetworkType.Devnet ); } public get isMainNet(): boolean { return ( this.currentNetwork && this.currentNetwork.type === NetworkType.Mainnet ); } public get defaultNetworks(): Network[] { if (!this._defaultNetworks) { this._defaultNetworks = Network.getAll(); } return this._defaultNetworks; } public profiles: { [key: string]: Profile } = {}; public networks: Record<string, StoredNetwork> = {}; public currentProfile: Profile; public currentNetwork: StoredNetwork; public currentWallet: Wallet; public onActivateNetwork$: Subject<StoredNetwork> = new Subject(); public onUpdateNetwork$: Subject<StoredNetwork> = new Subject(); public onCreateWallet$: Subject<Wallet> = new Subject(); public onUpdateWallet$: Subject<Wallet> = new Subject(); public onSelectProfile$: Subject<Profile> = new Subject(); private _defaultNetworks: Network[]; constructor( private storageProvider: StorageProvider, private authProvider: AuthProvider, private forgeProvider: ForgeProvider, ) { this.loadAllData(); this.onLogin(); this.onClearStorage(); this.onUpdateNetwork$.subscribe( (network) => (this.currentNetwork = network), ); } // this method is required to "migrate" contacts, in the first version of the app the contact's didnt't include an address property private static mapContact = ( contacts: { [address: string]: Contact }, contact: Contact, address: string, ): void => { contact.address = address; contacts[address] = contact; }; addOrUpdateNetwork( network: StoredNetwork, networkId?: string, ): Observable<{ network: Network; id: string }> { if (!networkId) { networkId = this.generateUniqueId(); } const { [networkId]: _, ...networks } = this.networks; networks[networkId] = network; this.networks = networks; return this.storageProvider .set(constants.STORAGE_NETWORKS, this.networks) .pipe( map(() => { return { network: this.networks[networkId], id: networkId, }; }), ); } getNetworkById(networkId: string): StoredNetwork { return this.networks[networkId]; } removeNetworkById(networkId: string) { const { [networkId]: _, ...networks } = this.networks; this.networks = networks; return this.storageProvider.set( constants.STORAGE_NETWORKS, this.networks, ); } addProfile(profile: Profile) { this.profiles[this.generateUniqueId()] = profile; return this.saveProfiles(); } getProfileByName(name: string) { const profile = lodash.find( this.profiles, (id: any) => id.name.toLowerCase() === name.toLowerCase(), ); if (profile) { return new Profile().deserialize(profile); } } getProfileById(profileId: string) { if (this.profiles[profileId]) { return new Profile().deserialize(this.profiles[profileId]); } } removeProfileById(profileId: string) { const { [profileId]: _, ...profiles } = this.profiles; this.profiles = profiles; return this.saveProfiles(); } saveProfiles(profiles = this.profiles) { const currentProfile = this.authProvider.loggedProfileId; if (currentProfile) { this.setCurrentProfile(currentProfile, false); } return this.storageProvider.set(constants.STORAGE_PROFILES, profiles); } encryptSecondPassphrase( wallet: Wallet, pinCode: string, secondPassphrase: string, profileId: string = this.authProvider.loggedProfileId, ) { if (lodash.isUndefined(profileId)) { return; } if (wallet && !wallet.cipherSecondKey) { // wallet.secondBip38 = this.forgeProvider.encryptBip38(secondWif, pinCode, this.currentNetwork); wallet.cipherSecondKey = this.forgeProvider.encrypt( secondPassphrase, pinCode, wallet.address, wallet.iv, ); return this.updateWallet(wallet, profileId, true); } return this.saveProfiles(); } addWallet( wallet: Wallet, passphrase: string, pinCode: string, profileId: string = this.authProvider.loggedProfileId, ) { if (lodash.isUndefined(profileId)) { return throwError("EMPTY_PROFILE_ID"); } const profile = this.getProfileById(profileId); if (!profile) { return throwError("PROFILE_NOT_FOUND"); } if (passphrase) { const iv = this.forgeProvider.generateIv(); wallet.iv = iv; const cipherKey = this.forgeProvider.encrypt( passphrase, pinCode, wallet.address, iv, ); // wallet.bip38 = this.forgeProvider.encryptBip38(wif, pinCode, this.currentNetwork); wallet.cipherKey = cipherKey; } if ( !profile.wallets[wallet.address] || profile.wallets[wallet.address].isWatchOnly ) { this.onCreateWallet$.next(wallet); return this.saveWallet(wallet, profileId, true); } return this.saveProfiles(); } updateWalletEncryption(oldPassword: string, newPassword: string) { for (const profileId in this.profiles) { if (profileId) { const profile = this.profiles[profileId]; for (const walletId in profile.wallets) { if (walletId) { const wallet = profile.wallets[walletId]; if (wallet.isWatchOnly) { continue; } const key = this.forgeProvider.decrypt( wallet.cipherKey, oldPassword, wallet.address, wallet.iv, ); wallet.cipherKey = this.forgeProvider.encrypt( key, newPassword, wallet.address, wallet.iv, ); // wallet.bip38 = this.forgeProvider.encryptBip38(wif, newPassword, this.currentNetwork); if (wallet.cipherSecondKey) { const secondKey = this.forgeProvider.decrypt( wallet.cipherSecondKey, oldPassword, wallet.address, wallet.iv, ); wallet.cipherSecondKey = this.forgeProvider.encrypt( secondKey, newPassword, wallet.address, wallet.iv, ); // wallet.secondBip38 = this.forgeProvider.encryptBip38(secondWif, newPassword, this.currentNetwork); } this.updateWallet(wallet, profileId); } } } } return this.saveProfiles(); } removeWalletByAddress( address: string, profileId: string = this.authProvider.loggedProfileId, ): Observable<boolean> { delete this.profiles[profileId].wallets[address]; return this.saveProfiles(); } ensureWalletDelegateProperties( wallet: Wallet, delegateOrUserName: string | Delegate, ): Observable<boolean> { if (!wallet) { return throwError("WALLET_EMPTY"); } const userName: string = !delegateOrUserName || typeof delegateOrUserName === "string" ? (delegateOrUserName as string) : delegateOrUserName.username; if (!userName) { return throwError("USERNAME_EMPTY"); } if (wallet.isDelegate && wallet.username === userName) { return EMPTY; } wallet.isDelegate = true; wallet.username = userName; return this.updateWallet(wallet, this.currentProfile.profileId, true); } getWalletByAddress( address: string, profileId: string = this.authProvider.loggedProfileId, ): Wallet { if (!address || lodash.isUndefined(profileId)) { return; } const profile = this.getProfileById(profileId); let wallet = new Wallet(); if (profile.wallets[address]) { wallet = wallet.deserialize(profile.wallets[address]); wallet.loadTransactions(wallet.transactions); return wallet; } return null; } // Save only if wallet exists in profile updateWallet( wallet: Wallet, profileId: string, notificate: boolean = false, ): Observable<any> { if (lodash.isUndefined(profileId)) { return throwError("EMPTY_PROFILE_ID"); } const profile = this.getProfileById(profileId); if (profile && profile.wallets[wallet.address]) { return this.saveWallet(wallet, profileId, notificate); } return EMPTY; } saveWallet( wallet: Wallet, profileId: string = this.authProvider.loggedProfileId, notificate: boolean = false, ) { if (lodash.isUndefined(profileId)) { return throwError("EMPTY_PROFILE_ID"); } const profile = this.getProfileById(profileId); wallet.lastUpdate = new Date().getTime(); profile.wallets[wallet.address] = wallet; this.profiles[profileId] = profile; if (notificate) { this.onUpdateWallet$.next(wallet); } return this.saveProfiles(); } public setWalletLabel( wallet: Wallet, label: string, ): Observable<never | any> { if (!wallet) { return throwError({ key: "VALIDATION.INVALID_WALLET", } as TranslatableObject); } if ( label && lodash.some( this.currentProfile.wallets, (w) => w.label && w.label.toLowerCase() === label.toLowerCase() && w.address !== wallet.address, ) ) { return throwError({ key: "VALIDATION.LABEL_EXISTS", parameters: { label }, } as TranslatableObject); } wallet.label = label; return this.updateWallet(wallet, this.currentProfile.profileId); } public getWalletLabel( walletOrAddress: Wallet | string, profileId?: string, ): string { let wallet: Wallet; if (typeof walletOrAddress === "string") { wallet = this.getWalletByAddress(walletOrAddress, profileId); } else { wallet = walletOrAddress; } if (!wallet) { return null; } return wallet.username || wallet.label; } setCurrentWallet(wallet: Wallet) { this.currentWallet = wallet; } clearCurrentWallet() { this.currentWallet = undefined; } loadProfiles() { return this.storageProvider.getObject(constants.STORAGE_PROFILES).pipe( map((profiles) => { // we have to create "real" contacts here, because the "address" property was not on the contact object // in the first versions of the app return lodash.mapValues(profiles, (profile, profileId) => ({ ...profile, profileId, contacts: lodash.transform( profile.contacts, UserDataServiceImpl.mapContact, {}, ), })); }), ); } loadNetworks(): Observable<Record<string, StoredNetwork>> { return new Observable((observer) => { // Return defaults networks from arkts this.storageProvider .getObject(constants.STORAGE_NETWORKS) .subscribe((networks) => { if (!networks || lodash.isEmpty(networks)) { const uniqueDefaults = {}; for (const network of this.defaultNetworks) { uniqueDefaults[this.generateUniqueId()] = network; } this.storageProvider.set( constants.STORAGE_NETWORKS, uniqueDefaults, ); observer.next(uniqueDefaults); } else { observer.next(networks); } observer.complete(); }); }); } getKeysByWallet(wallet: Wallet, password: string): WalletKeys { if (!wallet.cipherKey && !wallet.cipherSecondKey) { return; } const keys: WalletKeys = {}; if (wallet.cipherKey) { keys.key = this.forgeProvider.decrypt( wallet.cipherKey, password, wallet.address, wallet.iv, ); } if (wallet.cipherSecondKey) { keys.secondKey = this.forgeProvider.decrypt( wallet.cipherSecondKey, password, wallet.address, wallet.iv, ); } return keys; } private setCurrentNetwork(): void { if (!this.currentProfile) { return; } const network = new StoredNetwork(); Object.assign(network, this.networks[this.currentProfile.networkId]); this.onActivateNetwork$.next(network); this.currentNetwork = network; } private setCurrentProfile( profileId: string, broadcast: boolean = true, ): void { if (profileId && this.profiles[profileId]) { const profile = new Profile().deserialize(this.profiles[profileId]); this.currentProfile = profile; if (broadcast) { this.onSelectProfile$.next(profile); } } else { this.currentProfile = null; this.authProvider.logout(false); } } private loadAllData() { this.loadProfiles().subscribe((profiles) => (this.profiles = profiles)); this.loadNetworks().subscribe((networks) => (this.networks = networks)); } private onLogin() { return this.authProvider.onLogin$.subscribe((id) => { this.setCurrentProfile(id); this.setCurrentNetwork(); }); } private onClearStorage() { this.storageProvider.onClear$.pipe(debounceTime(100)).subscribe(() => { this.loadAllData(); this.setCurrentProfile(null); }); } private generateUniqueId(): string { return uuid(); } }
the_stack
// A '.tsx' file enables JSX support in the TypeScript compiler, // for more information see the following page on the TypeScript wiki: // https://github.com/Microsoft/TypeScript/wiki/JSX import * as React from 'react'; import * as Utility from '../../Utility'; import * as Actions from '../../Actions/UserCenter'; import { connect } from 'react-redux'; import { UserInfo } from '../../States/AppState'; import { refreshCurrentUserInfo } from '../../AsyncActions/UserCenter'; interface Props { /** * 更新store中的信息 */ refreshUserInfo: ()=>void; /** * store中的用户信息 */ userInfo: UserInfo; } interface States { /** * 提示信息 */ info: string; /** * 用户当前的头像地址 */ avatarURL: string; /** * 本地图片选框是否显示 */ isShown: boolean; /** * 本地图片选框总高度 */ divheight: number; /** * 本地图片选框总宽度 */ divWidth: number; /** * 本地图片选框选择器宽度(与高度相同) */ selectorWidth: number; /** * 本地图片选框选择器上距上边框距离 */ selectorTop: number; /** * 本地图片选框选择器上距左边框距离 */ selectorLeft: number; /** * 渲染到的头像地址 */ avatarNow: string; /** * 是否在加载过程 */ isLoading: boolean; /** * 用户选择的本地图片宽度 */ naturalWidth: number; /** * 用户选择的本地图片高度 */ naturalHeight: number; /** * IMG对象 */ img: HTMLImageElement; /** * 选择器最大宽度(与高度相同) */ NUM_MAX: number; /** * 缩放倍数 */ scaling: number; /** * 是否在选用默认头像 */ choosingDefault: boolean; /** * 用户选择的本体图片类型(扩展名) */ fileType: string; } /** * 用户中心页 * 修改头像组件 */ class UserCenterConfigAvatar extends React.Component<Props, States> { /** * 对Canvas的引用 */ myCanvas: HTMLCanvasElement; /** * 对选择器的引用 */ selector: HTMLDivElement; /** * 对调整器的引用 */ resize: HTMLSpanElement; /** * 新头像用的Canvas画布 */ newAvatar: HTMLCanvasElement; /** * 覆盖在用户选择头像的灰色蒙版 */ cover: HTMLDivElement; /** * 当前正在拖拽的元素 */ dragging: HTMLElement; /** * 拖曳X偏移 */ diffX: number; /** * 拖曳Y偏移 */ diffY: number; constructor(props: Props) { super(props); const userInfo = Utility.getLocalStorage('userInfo'); this.state = { avatarURL: '', info: '', isShown: false, divheight: 0, divWidth: 0, selectorWidth: 160, selectorLeft: 0, selectorTop: 0, avatarNow: props.userInfo.portraitUrl, isLoading: false, naturalWidth: 0, naturalHeight: 0, img: null, NUM_MAX: 0, scaling: 1, choosingDefault: false, fileType: '' }; this.handleChange = this.handleChange.bind(this); this.handleIMGLoad = this.handleIMGLoad.bind(this); this.handleSelectorMove = this.handleSelectorMove.bind(this); this.handleResizeMove = this.handleResizeMove.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.handleCoverMouseMove = this.handleCoverMouseMove.bind(this); this.handleMouseUp = this.handleMouseUp.bind(this); this.setDefaultAvatar = this.setDefaultAvatar.bind(this); } //用户选择本地图像后触发 handleChange(e) { let file: File = e.target.files[0]; //判断文件类型 if (!file.type.match('image.*')) { this.setState({ info: '请选择图片文件', isShown: false, divheight: 0 }); return false; } //记录文件类型 this.setState({ fileType: file.type }); //读取文件并准备显示在网页中 let render = new FileReader(); render.readAsDataURL(file); render.addEventListener('load', (e) => { this.setState({ isShown: true, avatarURL: (e as any).target.result }); }); } //图片读取完毕触发的函数 handleIMGLoad(width, height, img) { //处理过小的图片 if (width < 160 || height < 160) { this.setState({ info: '图片至少为 160*160', isShown: false, divheight: 0 }); return; } //获取Canvas2D对象 let ctx = this.myCanvas.getContext('2d'); let scaling = this.state.scaling; //处理宽度大于1000的图片,记录缩放倍数 while (width / scaling > 800) { scaling = scaling * 1.1; } //处理Canvas宽高,注意不同与css,这里宽高是HTML属性 this.myCanvas.width = width / scaling; this.myCanvas.height = height / scaling; //绘制图片 ctx.drawImage(img, 0, 0, width, height, 0, 0, width / scaling, height / scaling); this.setState({ divheight: height / scaling + 50, divWidth: width / scaling + 50, isShown: true, info: '请选择要显示的区域', selectorLeft: width / scaling / 4, selectorTop: height / scaling / 4, selectorWidth: Math.min(height / scaling, width / scaling) / 2, naturalWidth: width / scaling, naturalHeight: height / scaling, img: img, NUM_MAX: Math.min(500, width / scaling, height / scaling), scaling: scaling }); } //鼠标松开时清除拖曳对象 handleMouseUp() { this.dragging = null; } //用原生的事件绑定,react的事件绑定会丢失一些信息 componentDidMount() { this.selector.addEventListener('mousedown', this.handleSelectorMove); this.selector.addEventListener('mousemove', this.handleSelectorMove); this.selector.addEventListener('mouseup', this.handleSelectorMove); this.resize.addEventListener('mousedown', this.handleResizeMove); this.resize.addEventListener('mousemove', this.handleResizeMove); this.resize.addEventListener('mouseup', this.handleResizeMove); this.cover.addEventListener('mousemove', this.handleCoverMouseMove); this.cover.addEventListener('mouseup', this.handleCoverMouseMove); window.addEventListener('mouseup', this.handleMouseUp); } //组件卸载时解除事件绑定 componentWillUnmount() { this.selector.removeEventListener('mousedown', this.handleSelectorMove); this.selector.removeEventListener('mousemove', this.handleSelectorMove); this.selector.removeEventListener('mouseup', this.handleSelectorMove); this.resize.removeEventListener('mousedown', this.handleResizeMove); this.resize.removeEventListener('mousemove', this.handleResizeMove); this.resize.removeEventListener('mouseup', this.handleResizeMove); this.cover.removeEventListener('mousemove', this.handleCoverMouseMove); this.cover.removeEventListener('mouseup', this.handleCoverMouseMove); window.removeEventListener('mouseup', this.handleMouseUp); } //处理选择器的拖曳 handleSelectorMove(event) { //如果当前正在拖曳调整器,则将事件传递给相应的函数处理 if (this.dragging !== undefined && this.dragging !== null && this.dragging.id === 'resize') { this.handleCoverMouseMove(event); } else { switch (event.type) { //按下鼠标时记录当前位置 case 'mousedown': this.diffX = event.clientX - event.target.offsetLeft; this.diffY = event.clientY - event.target.offsetTop; this.dragging = event.target; break; //鼠标移动时不断调整选择器位置 case 'mousemove': if (this.dragging !== null) { let y = event.clientY - this.diffY, x = event.clientX - this.diffX; this.setState((prevState) => { if (y < 0) { y = 0; } if (x < 0) { x = 0; } if (y > prevState.naturalHeight - this.state.selectorWidth) { y = prevState.naturalHeight - this.state.selectorWidth; } if (x > prevState.naturalWidth - this.state.selectorWidth) { x = prevState.naturalWidth - this.state.selectorWidth; } return { selectorTop: y, selectorLeft: x } }); } break; //鼠标松开时清空记录 case 'mouseup': this.dragging = null; break; } } } //处理选择器的拖曳,大部分同上 handleResizeMove(event) { switch (event.type) { case 'mousedown': this.diffX = event.clientX - event.target.offsetLeft; this.dragging = event.target; break; case 'mousemove': if (this.dragging !== null) { this.diffY = event.clientX - event.target.offsetLeft; this.setState((prevState) => { let num = prevState.selectorWidth + this.diffY - this.diffX; let max = Math.min(prevState.NUM_MAX, prevState.naturalWidth - prevState.selectorLeft, prevState.naturalHeight - prevState.selectorTop); if (!isNaN(num)) { if (num < 100) { num = 100 } if (num > max) { num = max } } return { selectorWidth: isNaN(num) ? prevState.selectorWidth : num }; }); } break; case 'mouseup': this.dragging = null; break; } } //处理鼠标移动过快时脱离拖曳元素,大部分同上 handleCoverMouseMove(e) { switch (e.type) { case 'mouseup': this.dragging = null; break; case 'mousemove': if (this.dragging !== undefined && this.dragging !== null && this.dragging.id === 'resize') { this.diffY = e.clientX - this.dragging.offsetLeft; this.setState((prevState) => { let num = prevState.selectorWidth + this.diffY - this.diffX; if (!isNaN(num)) { let max = Math.min(prevState.NUM_MAX, prevState.naturalWidth - prevState.selectorLeft, prevState.naturalHeight - prevState.selectorTop); if (num < 100) { num = 100 } if (num > max) { num = max } } return { selectorWidth: isNaN(num) ? prevState.selectorWidth : num }; }); } else if (this.dragging !== undefined && this.dragging !== null && this.dragging.id === 'selector') { let y = e.clientY - this.diffY, x = e.clientX - this.diffX; this.setState((prevState) => { if (y < 0) { y = 0; } if (x < 0) { x = 0; } if (y > prevState.naturalHeight - this.state.selectorWidth) { y = prevState.naturalHeight - this.state.selectorWidth; } if (x > prevState.naturalWidth - this.state.selectorWidth) { x = prevState.naturalWidth - this.state.selectorWidth; } return { selectorTop: y, selectorLeft: x } }); } break; } } //处理本地图片的剪切 handleSubmit() { //用新画布绘制头像 let canvas = this.newAvatar; let ctx = canvas.getContext('2d'); const x = this.state.selectorLeft, y = this.state.selectorTop, width = this.state.selectorWidth; canvas.width = width; canvas.height = width; ctx.drawImage(this.state.img, x * this.state.scaling, y * this.state.scaling, width * this.state.scaling, width * this.state.scaling, 0, 0, width, width); //Canvas内容转为文件,toBlob第二个参数为文件类型,第三个参数为压缩率(仅对jpeg有效) canvas.toBlob(async (result) => { let file: any = new Blob([result], { type: this.state.fileType }); file.lastModifiedDate = Date.now(); file.name = '头像.' + this.state.fileType.slice(this.state.fileType.indexOf('/') + 1, this.state.fileType.length); try{ //上传头像文件到API const url = `/file/portrait`; let myHeaders = new Headers(); myHeaders.append('Authorization', await Utility.getToken()); let formdata = new FormData(); formdata.append('files', file, file.name); formdata.append('contentType', "multipart/form-data"); let res = await Utility.cc98Fetch(url, { method: 'POST', headers: myHeaders, body: formdata }); let data: string[] = await res.json(); if (res.status === 200 && data.length !== 0) { //根据返回的图片地址修改个人信息 this.changeAvatar(data[0]); } }catch(e){ this.setState({ info: '修改失败', isLoading: false, isShown: false, divheight: 0, choosingDefault: false, avatarURL: '' }); } }, this.state.fileType, 0.75); } //选择默认头像 async setDefaultAvatar(e: React.MouseEvent<HTMLImageElement>) { var ele = e.target as HTMLImageElement; await this.changeAvatar(ele.src); } //根据传入的头像地址修改头像地址 async changeAvatar(avatarUrl: string) { try { this.setState({ isLoading: true }); const token = await Utility.getToken(); const url = '/me/portrait'; let myHeaders = new Headers(); myHeaders.append('Content-Type', 'application/json'); myHeaders.append('Authorization', token); let res = await Utility.cc98Fetch(url, { method: 'PUT', headers: myHeaders, body: JSON.stringify(avatarUrl) }); if (res.status === 200) { this.setState({ info: '修改成功', avatarNow: avatarUrl, isLoading: false, isShown: false, divheight: 0, choosingDefault: false, avatarURL: '' }); this.props.refreshUserInfo(); } else { throw new Error(); } } catch (e) { this.setState({ info: '修改失败', isLoading: false, isShown: false, divheight: 0, choosingDefault: false, avatarURL: '' }); } } render() { const style = { display: 'none' }; const userInfo = Utility.getLocalStorage('userInfo'); return ( <div> <h2>修改头像</h2> <div className="user-center-config-avatar"> <img src={this.state.avatarNow}></img> <div> <button id="chooseDefaultAvatar" type="button" onClick={() => this.setState({ choosingDefault: true, info: '暂时只有六枚' })}>选择论坛头像</button> <div> <input onChange={e => { this.handleChange(e); e.target.value = ""; }} id="uploadAvatar" type="file" accept="image/*" style={style} /> <label htmlFor="uploadAvatar" onClick={() => this.setState({ choosingDefault: false })}><p>选择本地图片</p></label> <p style={{ color: 'red', margin: '0' }}>{this.state.info}</p> <button type="button" className="config-submit-button" style={this.state.isShown ? {} : style} onClick={this.handleSubmit} disabled={this.state.isLoading}>提交</button> </div> </div> <div className="user-center-config-avatar-preview" style={this.state.isShown ? { opacity: 1, marginTop: '2rem' } : { zIndex: -1 }}> <div style={{ position: 'absolute', width: '824px', overflow: 'hidden', paddingBottom: '50px' }}> <canvas id="newAvatar" style={style} ref={(a) => { this.newAvatar = a; }}></canvas> <canvas ref={(canvas) => { this.myCanvas = canvas }} style={this.state.isShown ? { position: 'relative' } : { display: 'none' }} /> <div id="cover" ref={(div) => { this.cover = div; }} style={{ width: `${this.state.divWidth}px`, height: `${this.state.divheight}px`, top: 0 }}></div> <div className="imgdata" style={this.state.isShown ? { width: `${this.state.selectorWidth}px`, height: `${this.state.selectorWidth}px`, borderRadius: `${this.state.selectorWidth / 2}px`, top: `${this.state.selectorTop}px`, left: `${this.state.selectorLeft}px` } : style}> <img src={this.state.avatarURL} style={{ position: 'relative', top: `-${this.state.selectorTop}px`, left: `-${this.state.selectorLeft}px`, width: `${this.state.naturalWidth}px`, height: `${this.state.naturalHeight}px` }} /> </div> <div id="selector" ref={(div) => { this.selector = div; }} style={this.state.isShown ? { width: `${this.state.selectorWidth}px`, height: `${this.state.selectorWidth}px`, borderRadius: `${this.state.selectorWidth / 2}px`, top: `${this.state.selectorTop}px`, left: `${this.state.selectorLeft}px` } : style}></div> <span id="resize" ref={(span) => { this.resize = span; }} style={{ top: `${this.state.selectorWidth + this.state.selectorTop}px`, left: `${this.state.selectorWidth + this.state.selectorLeft}px` }}></span> </div> <img onLoad={(e) => { this.handleIMGLoad((e as any).target.naturalWidth, (e as any).target.naturalHeight, (e as any).target); }} style={style} src={this.state.avatarURL} /> </div> <div style={{ width: '100%', height: `${this.state.divheight}px`, transitionDuration: '.5s' }}></div> <div style={this.state.choosingDefault ? { display: 'flex', flexDirection: 'row', width: '100%', justifyContent: 'center', flexWrap: 'wrap' } : { display: 'none' }}> {[ 'default_avatar_boy.png', 'default_avatar_girl.png', 'default_avatar_boy2.jpg', 'default_avatar_girl2.jpg', 'default_avatar_boy3.jpg', 'default_avatar_girl3.jpg' ].map(item => <img key={item} style={{ margin: '3rem 5rem', cursor: 'pointer', height: '10rem', width: '10rem' }} onClick={this.setDefaultAvatar} src={`//www.cc98.org/static/images/${item}`} />)} </div> </div> </div> ); } } function mapState(state) { return { userInfo: state.userInfo.currentUserInfo }; } function mapDispatch(dispatch) { return { refreshUserInfo: () => { dispatch(refreshCurrentUserInfo()); } }; } export default connect(mapState, mapDispatch)(UserCenterConfigAvatar);
the_stack
import { NS_BOSH, NS_CLIENT, NS_COMPONENT, NS_JINGLE_FILE_TRANSFER_5, NS_JINGLE_RTP_INFO_1, NS_SERVER } from './Namespaces'; export const VERSION = '__STANZAJS_VERSION__'; // ==================================================================== // Frequently Used Values // ==================================================================== const NotAuthorized = 'not-authorized'; // ==================================================================== // Named Enum Constants // ==================================================================== export const StreamType = { Bosh: NS_BOSH, Client: NS_CLIENT, Component: NS_COMPONENT, Server: NS_SERVER } as const; export type StreamType = typeof StreamType[keyof typeof StreamType]; export const SASLFailureCondition = { AccountDisabled: 'account-disabled', CredentialsExpired: 'credentials-expired', EncryptionRequired: 'encryption-required', IncorrectEncoding: 'incorrect-encoding', InvalidAuthzid: 'invalid-authzid', InvalidMechanism: 'invalid-mechanism', MalformedRequest: 'malformed-request', MechanismTooWeak: 'mechanism-too-weak', NotAuthorized, TemporaryAuthFailure: 'temporary-auth-failure' } as const; export type SASLFailureCondition = typeof SASLFailureCondition[keyof typeof SASLFailureCondition]; export const StreamErrorCondition = { BadFormat: 'bad-format', BadNamespacePrefix: 'bad-namespace-prefix', Conflict: 'conflict', ConnectionTimeout: 'connection-timeout', HostGone: 'host-gone', HostUnknown: 'host-unknown', ImproperAddressing: 'improper-addressing', InternalServerError: 'internal-server-error', InvalidFrom: 'invalid-from', InvalidId: 'invalid-id', InvalidNamespace: 'invalid-namespace', InvalidXML: 'invalid-xml', NotAuthorized, NotWellFormed: 'not-well-formed', PolicyViolation: 'policy-violation', RemoteConnectionFailed: 'remote-connection-failed', Reset: 'reset', ResourceConstraint: 'resource-constraint', RestrictedXML: 'restricted-xml', SeeOtherHost: 'see-other-host', SystemShutdown: 'system-shutdown', UndefinedCondition: 'undefined-condition', UnsupportedEncoding: 'unsupported-encoding', UnsupportedStanzaType: 'unsupported-stanza-type', UnsupportedVersion: 'unsupported-version' } as const; export type StreamErrorCondition = typeof StreamErrorCondition[keyof typeof StreamErrorCondition]; export const StanzaErrorCondition = { BadRequest: 'bad-request', Conflict: 'conflict', FeatureNotImplemented: 'feature-not-implemented', Forbidden: 'forbidden', Gone: 'gone', InternalServerError: 'internal-server-error', ItemNotFound: 'item-not-found', JIDMalformed: 'jid-malformed', NotAcceptable: 'not-acceptable', NotAllowed: 'not-allowed', NotAuthorized, PolicyViolation: 'policy-violation', RecipientUnavailable: 'recipient-unavailable', Redirect: 'redirect', RegistrationRequired: 'registration-required', RemoteServerNotFound: 'remote-server-not-found', RemoteServerTimeout: 'remote-server-timeout', ResourceConstraint: 'resource-constraint', ServiceUnavailable: 'service-unavailable', SubscriptionRequired: 'subscription-required', UndefinedCondition: 'undefined-condition', UnexpectedRequest: 'unexpected-request' } as const; export type StanzaErrorCondition = typeof StanzaErrorCondition[keyof typeof StanzaErrorCondition]; export const MessageType = { Chat: 'chat', Error: 'error', GroupChat: 'groupchat', Headline: 'headline', Normal: 'normal' } as const; export type MessageType = typeof MessageType[keyof typeof MessageType]; export const PresenceType = { Available: undefined, Error: 'error', Probe: 'probe', Subscribe: 'subscribe', Subscribed: 'subscribed', Unavailable: 'unavailable', Unsubscribe: 'unsubscribe', Unsubscribed: 'unsubscribed' } as const; export type PresenceType = typeof PresenceType[keyof typeof PresenceType]; export const IQType = { Error: 'error', Get: 'get', Result: 'result', Set: 'set' } as const; export type IQType = typeof IQType[keyof typeof IQType]; export const PresenceShow = { Away: 'away', Chat: 'chat', DoNotDisturb: 'dnd', ExtendedAway: 'xa' } as const; export type PresenceShow = typeof PresenceShow[keyof typeof PresenceShow]; export const RosterSubscription = { Both: 'both', From: 'from', None: 'none', ReceivePresenceOnly: 'to', Remove: 'remove', SendAndReceivePresence: 'both', SendPresenceOnly: 'from', To: 'to' } as const; export type RosterSubscription = typeof RosterSubscription[keyof typeof RosterSubscription]; export const DataFormType = { Cancel: 'cancel', Form: 'form', Result: 'result', Submit: 'submit' } as const; export type DataFormType = typeof DataFormType[keyof typeof DataFormType]; export const DataFormFieldType = { Boolean: 'boolean', Fixed: 'fixed', Hidden: 'hidden', JID: 'jid-single', JIDMultiple: 'jid-multi', List: 'list-single', ListMultiple: 'list-multi', Password: 'text-private', Text: 'text-single', TextMultiple: 'text-multi', TextPrivate: 'text-private' } as const; export type DataFormFieldType = typeof DataFormFieldType[keyof typeof DataFormFieldType]; export const MUCAffiliation = { Admin: 'admin', Banned: 'outcast', Member: 'member', None: 'none', Outcast: 'outcast', Owner: 'owner' } as const; export type MUCAffiliation = typeof MUCAffiliation[keyof typeof MUCAffiliation]; export const MUCRole = { Moderator: 'moderator', None: 'none', Participant: 'participant', Visitor: 'visitor' } as const; export type MUCRole = typeof MUCRole[keyof typeof MUCRole]; export const MUCStatusCode = { AffiliationChanged: '101', AffiliationLost: '321', Banned: '301', Error: '333', Kicked: '307', LoggingDisabled: '171', LoggingEnabled: '170', MembershipLost: '322', NickChanged: '303', NickChangedByService: '210', NonAnonymous: '172', NonAnonymousRoom: '100', NonPrivacyConfigurationChange: '104', RoomCreated: '201', SelfPresence: '110', SemiAnonymous: '173', Shutdown: '332', UnavailableMembersListed: '102', UnavailableMembersNotListed: '103' } as const; export type MUCStatusCode = typeof MUCStatusCode[keyof typeof MUCStatusCode]; export const PubsubErrorCondition = { ClosedNode: 'closed-node', ConfigurationRequired: 'configuration-required', InvalidJID: 'invalid-jid', InvalidOptions: 'invalid-options', InvalidPayload: 'invalid-payload', InvalidSubscriptionId: 'invalid-subid', ItemForbidden: 'item-forbidden', ItemRequired: 'item-required', JIDRequired: 'jid-required', MaxItemsExceeded: 'max-items-exceeded', MaxNodesExceeded: 'max-nodes-exceeded', NodeIdRequired: 'nodeid-required', NotInRosterGroup: 'not-in-roster-group', NotSubscribed: 'not-subscribed', PayloadRequired: 'payload-required', PayloadTooBig: 'payload-too-big', PendingSubscription: 'pending-subscription', PresenceSubscriptionRequired: 'presence-subscription-required', SubscriptionIdRequired: 'subid-required', TooManySubscriptions: 'too-many-subscriptions', Unsupported: 'unsupported', UnsupportedAccessModel: 'unsupported-access-model' } as const; export type PubsubErrorCondition = typeof PubsubErrorCondition[keyof typeof PubsubErrorCondition]; export const ChatState = { Active: 'active', Composing: 'composing', Gone: 'gone', Inactive: 'inactive', Paused: 'paused' } as const; export type ChatState = typeof ChatState[keyof typeof ChatState]; export const JingleSessionRole = { Initiator: 'initiator', Responder: 'responder' } as const; export type JingleSessionRole = typeof JingleSessionRole[keyof typeof JingleSessionRole]; export const JingleApplicationDirection = { Inactive: 'inactive', Receive: 'recvonly', Send: 'sendonly', SendReceive: 'sendrecv' } as const; export type JingleApplicationDirection = typeof JingleApplicationDirection[keyof typeof JingleApplicationDirection]; export const JingleContentSenders = { Both: 'both', Initiator: 'initiator', None: 'none', Responder: 'responder' } as const; export type JingleContentSenders = typeof JingleContentSenders[keyof typeof JingleContentSenders]; export const JingleAction = { ContentAccept: 'content-accept', ContentAdd: 'content-add', ContentModify: 'content-modify', ContentReject: 'content-reject', ContentRemove: 'content-remove', DescriptionInfo: 'description-info', SecurityInfo: 'security-info', SessionAccept: 'session-accept', SessionInfo: 'session-info', SessionInitiate: 'session-initiate', SessionTerminate: 'session-terminate', TransportAccept: 'transport-accept', TransportInfo: 'transport-info', TransportReject: 'transport-reject', TransportReplace: 'transport-replace' } as const; export type JingleAction = typeof JingleAction[keyof typeof JingleAction]; export const JingleErrorCondition = { OutOfOrder: 'out-of-order', TieBreak: 'tie-break', UnknownContent: 'unknown-content', UnknownSession: 'unknown-session', UnsupportedInfo: 'unsupported-info' } as const; export type JingleErrorCondition = typeof JingleErrorCondition[keyof typeof JingleErrorCondition]; export const JingleReasonCondition = { AlternativeSession: 'alternative-session', Busy: 'busy', Cancel: 'cancel', ConnectivityError: 'connectivity-error', Decline: 'decline', Expired: 'expired', FailedApplication: 'failed-application', FailedTransport: 'failed-transport', GeneralError: 'general-error', Gone: 'gone', IncompatibleParameters: 'incompatible-parameters', MediaError: 'media-error', SecurityError: 'security-error', Success: 'success', Timeout: 'timeout', UnsupportedApplications: 'unsupported-applications', UnsupportedTransports: 'unsupported-transports' } as const; export type JingleReasonCondition = typeof JingleReasonCondition[keyof typeof JingleReasonCondition]; // ==================================================================== // Standalone Constants // ==================================================================== export const USER_MOODS = [ 'afraid', 'amazed', 'amorous', 'angry', 'annoyed', 'anxious', 'aroused', 'ashamed', 'bored', 'brave', 'calm', 'cautious', 'cold', 'confident', 'confused', 'contemplative', 'contented', 'cranky', 'crazy', 'creative', 'curious', 'dejected', 'depressed', 'disappointed', 'disgusted', 'dismayed', 'distracted', 'embarrassed', 'envious', 'excited', 'flirtatious', 'frustrated', 'grateful', 'grieving', 'grumpy', 'guilty', 'happy', 'hopeful', 'hot', 'humbled', 'humiliated', 'hungry', 'hurt', 'impressed', 'in_awe', 'in_love', 'indignant', 'interested', 'intoxicated', 'invincible', 'jealous', 'lonely', 'lost', 'lucky', 'mean', 'moody', 'nervous', 'neutral', 'offended', 'outraged', 'playful', 'proud', 'relaxed', 'relieved', 'remorseful', 'restless', 'sad', 'sarcastic', 'satisfied', 'serious', 'shocked', 'shy', 'sick', 'sleepy', 'spontaneous', 'stressed', 'strong', 'surprised', 'thankful', 'thirsty', 'tired', 'undefined', 'weak', 'worried' ]; export const USER_ACTIVITY_GENERAL = [ 'doing_chores', 'drinking', 'eating', 'exercising', 'grooming', 'having_appointment', 'inactive', 'relaxing', 'talking', 'traveling', 'undefined', 'working' ]; export const USER_ACTIVITY_SPECIFIC = [ 'at_the_spa', 'brushing_teeth', 'buying_groceries', 'cleaning', 'coding', 'commuting', 'cooking', 'cycling', 'cycling', 'dancing', 'day_off', 'doing_maintenance', 'doing_the_dishes', 'doing_the_laundry', 'driving', 'fishing', 'gaming', 'gardening', 'getting_a_haircut', 'going_out', 'hanging_out', 'having_a_beer', 'having_a_snack', 'having_breakfast', 'having_coffee', 'having_dinner', 'having_lunch', 'having_tea', 'hiding', 'hiking', 'in_a_car', 'in_a_meeting', 'in_real_life', 'jogging', 'on_a_bus', 'on_a_plane', 'on_a_train', 'on_a_trip', 'on_the_phone', 'on_vacation', 'on_video_phone', 'other', 'partying', 'playing_sports', 'praying', 'reading', 'rehearsing', 'running', 'running_an_errand', 'scheduled_holiday', 'shaving', 'shopping', 'skiing', 'sleeping', 'smoking', 'socializing', 'studying', 'sunbathing', 'swimming', 'taking_a_bath', 'taking_a_shower', 'thinking', 'walking', 'walking_the_dog', 'watching_a_movie', 'watching_tv', 'working_out', 'writing' ]; export const JINGLE_INFO = (namespace: string, name: string): string => `{${namespace}}${name}`; export const JINGLE_INFO_MUTE = JINGLE_INFO(NS_JINGLE_RTP_INFO_1, 'mute'); export const JINGLE_INFO_UNMUTE = JINGLE_INFO(NS_JINGLE_RTP_INFO_1, 'unmute'); export const JINGLE_INFO_HOLD = JINGLE_INFO(NS_JINGLE_RTP_INFO_1, 'hold'); export const JINGLE_INFO_UNHOLD = JINGLE_INFO(NS_JINGLE_RTP_INFO_1, 'unhold'); export const JINGLE_INFO_ACTIVE = JINGLE_INFO(NS_JINGLE_RTP_INFO_1, 'active'); export const JINGLE_INFO_RINGING = JINGLE_INFO(NS_JINGLE_RTP_INFO_1, 'ringing'); export const JINGLE_INFO_CHECKSUM_5 = JINGLE_INFO(NS_JINGLE_FILE_TRANSFER_5, 'checksum'); export const JINGLE_INFO_RECEIVED_5 = JINGLE_INFO(NS_JINGLE_FILE_TRANSFER_5, 'received'); // ==================================================================== // Helper Functions // ==================================================================== export function sendersToDirection( role: JingleSessionRole, senders: JingleContentSenders = JingleContentSenders.Both ): JingleApplicationDirection { const isInitiator = role === JingleSessionRole.Initiator; switch (senders) { case JingleContentSenders.Initiator: return isInitiator ? JingleApplicationDirection.Send : JingleApplicationDirection.Receive; case JingleContentSenders.Responder: return isInitiator ? JingleApplicationDirection.Receive : JingleApplicationDirection.Send; case JingleContentSenders.Both: return JingleApplicationDirection.SendReceive; } return JingleApplicationDirection.Inactive; } export function directionToSenders( role: JingleSessionRole, direction: JingleApplicationDirection = JingleApplicationDirection.SendReceive ): JingleContentSenders { const isInitiator = role === JingleSessionRole.Initiator; switch (direction) { case JingleApplicationDirection.Send: return isInitiator ? JingleContentSenders.Initiator : JingleContentSenders.Responder; case JingleApplicationDirection.Receive: return isInitiator ? JingleContentSenders.Responder : JingleContentSenders.Initiator; case JingleApplicationDirection.SendReceive: return JingleContentSenders.Both; } return JingleContentSenders.None; }
the_stack
import { CollectionToken, GroupToken, ParameterToken, SeparatorToken, StringToken, TableToken, Token, createQueryState, } from './tokens'; import { SelectFn, Selectable } from './SelectFn'; import { AnyColumn, Column } from './column'; import { DbConfig } from './config'; import { AnyExpression, Expression } from './expression'; import { FromItem } from './with'; import { Query } from './query'; import { QueryExecutorFn } from './types'; import { ResultSet } from './result-set'; import { Star } from './sql-functions'; import { AnyTable, Table } from './TableType'; import { TableDefinition } from './table'; export { SelectFn }; type JoinType = 'left-join' | 'left-side-of-right-join' | 'full-join'; type ToJoinType<OldType, NewType extends JoinType> = Extract< OldType, 'left-side-of-right-join' > extends never ? NewType : OldType; // It's important to note that to make sure we infer the table name, we should pass object instead // of any as the second argument to the table. type GetTableName<T extends AnyTable> = T extends Table<any, infer A, object> ? A : never; type AddLeftJoin<Columns, JoinTable> = { [K in keyof Columns]: Columns[K] extends Column< infer Config, infer Name, infer TableName, infer DataType, infer IsNotNull, infer HasDefault, infer JoinType > ? Extract<GetTableName<JoinTable>, TableName> extends never ? Column<Config, Name, TableName, DataType, IsNotNull, HasDefault, JoinType> : Column< Config, Name, TableName, DataType, IsNotNull, HasDefault, ToJoinType<JoinType, 'left-join'> > : never; }; type AddRightJoin<Columns, JoinTable> = { [K in keyof Columns]: Columns[K] extends Column< infer Config, infer Name, infer TableName, infer DataType, infer IsNotNull, infer HasDefault, infer JoinType > ? Extract<GetTableName<JoinTable>, TableName> extends never ? Column< Config, Name, TableName, DataType, IsNotNull, HasDefault, ToJoinType<JoinType, 'left-side-of-right-join'> > : Columns[K] : never; }; type AddJoinType<Columns, NewJoinType extends JoinType> = { [K in keyof Columns]: Columns[K] extends Column< infer Config, infer Name, infer TableName, infer DataType, infer IsNotNull, infer HasDefault, infer OldJoinType > ? Column< Config, Name, TableName, DataType, IsNotNull, HasDefault, ToJoinType<OldJoinType, NewJoinType> > : never; }; type Join< Query extends SelectQuery<any, any, boolean>, JoinTable extends AnyTable | FromItem<any, any>, > = Query extends SelectQuery<infer Config, infer ExistingColumns, infer IncludesStar> ? IncludesStar extends true ? SelectQuery< Config, ExistingColumns & Omit<GetColumns<JoinTable>, keyof ExistingColumns>, true > : SelectQuery<Config, ExistingColumns, false> : never; type GetColumns<From extends AnyTable | FromItem<any, any>> = From extends Table< any, any, infer Columns > ? Columns : From extends FromItem<any, infer Q> ? Q extends Query<infer Returning> ? Returning : never : never; type LeftJoin< Query extends SelectQuery<any, any>, JoinTable extends AnyTable | FromItem<any, any>, > = Query extends SelectQuery<infer Config, infer ExistingColumns, infer IncludesStar> ? IncludesStar extends true ? SelectQuery<Config, ExistingColumns & AddJoinType<GetColumns<JoinTable>, 'left-join'>> : SelectQuery<Config, AddLeftJoin<ExistingColumns, JoinTable>> : never; type RightJoin< Query extends SelectQuery<any, any>, JoinTable extends AnyTable | FromItem<any, any>, > = Query extends SelectQuery<infer Config, infer ExistingColumns, infer IncludesStar> ? IncludesStar extends true ? SelectQuery< Config, AddJoinType<ExistingColumns, 'left-side-of-right-join'> & GetColumns<JoinTable> > : SelectQuery<Config, AddRightJoin<ExistingColumns, JoinTable>> : never; type FullJoin< Query extends SelectQuery<any, any>, JoinTable extends AnyTable | FromItem<any, any>, > = Query extends SelectQuery<infer Config, infer ExistingColumns, infer IncludesStar> ? IncludesStar extends true ? SelectQuery<Config, AddJoinType<ExistingColumns & GetColumns<JoinTable>, 'full-join'>> : SelectQuery<Config, AddJoinType<ExistingColumns, 'full-join'>> : never; // https://www.postgresql.org/docs/12/sql-select.html export class SelectQuery< Config extends DbConfig, Columns extends { [column: string]: any }, IncludesStar = false, > extends Query<Columns> { private _selectQueryBrand: any; /** @internal */ getReturningKeys() { return this.returningKeys; } constructor( private readonly queryExecutor: QueryExecutorFn, private readonly returningKeys: string[], private readonly includesStar: boolean, private readonly tokens: Token[], ) { super(); } async exec() { const queryState = createQueryState(this.tokens); return this.queryExecutor(queryState.text.join(` `), queryState.parameters); } then<Result1, Result2 = never>( onFulfilled?: | (( value: ResultSet<Config, SelectQuery<Config, Columns>, false>[], ) => Result1 | PromiseLike<Result1>) | undefined | null, onRejected?: ((reason: any) => Result2 | PromiseLike<Result2>) | undefined | null, ): Promise<Result1 | Result2> { const queryState = createQueryState(this.tokens); return this.queryExecutor(queryState.text.join(` `), queryState.parameters) .then((result) => (onFulfilled ? onFulfilled(result.rows as any) : result)) .catch(onRejected) as any; } private newSelectQuery(tokens: Token[], table?: AnyTable): SelectQuery<Config, Columns> { const returningKeys = this.includesStar && table ? [ ...this.returningKeys, ...Object.keys(table).filter( (name) => ![`as`, `getName`, `getOriginalName`].includes(name), ), ] : this.returningKeys; return new SelectQuery(this.queryExecutor, returningKeys, this.includesStar, tokens); } // [ FROM from_item [, ...] ] from<T extends AnyTable>( fromItem: T, ): T extends TableDefinition<any> ? never : Join<SelectQuery<Config, Columns, IncludesStar>, T> { const table = fromItem as AnyTable; return this.newSelectQuery( [...this.tokens, new StringToken(`FROM`), new TableToken(table)], table, ) as any; } join<T extends AnyTable>(table: T): Join<SelectQuery<Config, Columns, IncludesStar>, T> { return this.newSelectQuery( [...this.tokens, new StringToken(`JOIN`), new TableToken(table)], table, ) as any; } innerJoin<JoinTable extends AnyTable>( table: JoinTable, ): Join<SelectQuery<Config, Columns, IncludesStar>, JoinTable> { return this.newSelectQuery( [...this.tokens, new StringToken(`INNER JOIN`), new TableToken(table)], table, ) as any; } leftOuterJoin<JoinTable extends AnyTable>( table: JoinTable, ): LeftJoin<SelectQuery<Config, Columns, IncludesStar>, JoinTable> { return this.newSelectQuery( [...this.tokens, new StringToken(`LEFT OUTER JOIN`), new TableToken(table)], table, ) as any; } leftJoin<JoinTable extends AnyTable>( table: JoinTable, ): LeftJoin<SelectQuery<Config, Columns, IncludesStar>, JoinTable> { return this.newSelectQuery( [...this.tokens, new StringToken(`LEFT JOIN`), new TableToken(table)], table, ) as any; } rightOuterJoin<JoinTable extends AnyTable>( table: JoinTable, ): RightJoin<SelectQuery<Config, Columns, IncludesStar>, JoinTable> { return this.newSelectQuery( [...this.tokens, new StringToken(`RIGHT OUTER JOIN`), new TableToken(table)], table, ) as any; } rightJoin<JoinTable extends AnyTable>( table: JoinTable, ): RightJoin<SelectQuery<Config, Columns, IncludesStar>, JoinTable> { return this.newSelectQuery( [...this.tokens, new StringToken(`RIGHT JOIN`), new TableToken(table)], table, ) as any; } fullOuterJoin<JoinTable extends AnyTable>( table: JoinTable, ): FullJoin<SelectQuery<Config, Columns, IncludesStar>, JoinTable> { return this.newSelectQuery( [...this.tokens, new StringToken(`FULL OUTER JOIN`), new TableToken(table)], table, ) as any; } fullJoin<JoinTable extends AnyTable>( table: JoinTable, ): FullJoin<SelectQuery<Config, Columns, IncludesStar>, JoinTable> { return this.newSelectQuery( [...this.tokens, new StringToken(`FULL JOIN`), new TableToken(table)], table, ) as any; } // This doesn't go with an ON or USING afterwards crossJoin<JoinTable extends AnyTable>( table: AnyTable, ): Join<SelectQuery<Config, Columns, IncludesStar>, JoinTable> { return this.newSelectQuery( [...this.tokens, new StringToken(`CROSS JOIN`), new TableToken(table)], table, ) as any; } forUpdate(): SelectQuery<Config, Columns> { return this.newSelectQuery([...this.tokens, new StringToken(`FOR UPDATE`)]); } forNoKeyUpdate(): SelectQuery<Config, Columns> { return this.newSelectQuery([...this.tokens, new StringToken(`FOR NO KEY UPDATE`)]); } forShare(): SelectQuery<Config, Columns> { return this.newSelectQuery([...this.tokens, new StringToken(`FOR SHARE`)]); } forKeyShare(): SelectQuery<Config, Columns> { return this.newSelectQuery([...this.tokens, new StringToken(`FOR KEY SHARE`)]); } /** @internal */ toTokens() { return this.tokens; } on( joinCondition: Expression<Config, boolean, boolean, string>, ): SelectQuery<Config, Columns, IncludesStar> { return this.newSelectQuery([ ...this.tokens, new StringToken(`ON`), new GroupToken(joinCondition.toTokens()), ]) as any; } using(...columns: AnyColumn[]): SelectQuery<Config, Columns> { return this.newSelectQuery([ ...this.tokens, new StringToken(`USING`), new GroupToken([ new SeparatorToken( ',', columns.map((column) => new CollectionToken(column.toTokens())), ), ]), ]); } // [ WHERE condition ] where(condition: Expression<Config, boolean, boolean, string>): SelectQuery<Config, Columns> { return this.newSelectQuery([...this.tokens, new StringToken(`WHERE`), ...condition.toTokens()]); } // [ GROUP BY grouping_element [, ...] ] // ( ) // expression // ( expression [, ...] ) // ROLLUP ( { expression | ( expression [, ...] ) } [, ...] ) // CUBE ( { expression | ( expression [, ...] ) } [, ...] ) // GROUPING SETS ( grouping_element [, ...] ) groupBy(...expressions: AnyExpression[]): SelectQuery<Config, Columns> { return this.newSelectQuery([ ...this.tokens, new StringToken(`GROUP BY`), new SeparatorToken( ',', expressions.map((expression) => new CollectionToken(expression.toTokens())), ), ]); } // [ HAVING condition [, ...] ] having( ...conditions: Expression<Config, boolean, boolean, string>[] ): SelectQuery<Config, Columns> { return this.newSelectQuery([ ...this.tokens, new StringToken(`HAVING`), new SeparatorToken( `,`, conditions.map((condition) => new CollectionToken(condition.toTokens())), ), ]); } // [ WINDOW window_name AS ( window_definition ) [, ...] ] window(): SelectQuery<Config, Columns> { return undefined as any; } // [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] select ] // [ ORDER BY expression [ ASC | DESC | USING operator ] [ NULLS { FIRST | LAST } ] [, ...] ] orderBy(...expressions: AnyExpression[]): SelectQuery<Config, Columns> { return this.newSelectQuery([ ...this.tokens, new StringToken(`ORDER BY`), new SeparatorToken( ',', expressions.map((expression) => new CollectionToken(expression.toTokens())), ), ]); } // [ LIMIT { count | ALL } ] limit(limit: number | 'ALL'): SelectQuery<Config, Columns> { if (limit === `ALL`) { return this.newSelectQuery([...this.tokens, new StringToken(`LIMIT ALL`)]); } else { return this.newSelectQuery([ ...this.tokens, new StringToken(`LIMIT`), new ParameterToken(limit), ]); } } // [ OFFSET start [ ROW | ROWS ] ] offset(start: number): SelectQuery<Config, Columns> { return this.newSelectQuery([ ...this.tokens, new StringToken(`OFFSET`), new ParameterToken(start), ]); } fetch(count: number): SelectQuery<Config, Columns> { return this.newSelectQuery([ ...this.tokens, new StringToken(`FETCH FIRST`), new ParameterToken(count), new StringToken(`ROWS ONLY`), ]); } of(table: AnyTable): SelectQuery<Config, Columns> { return this.newSelectQuery([ ...this.tokens, new StringToken(`OF`), new StringToken(table.getName()), ]); } nowait(): SelectQuery<Config, Columns> { return this.newSelectQuery([...this.tokens, new StringToken(`NOWAIT`)]); } skipLocked(): SelectQuery<Config, Columns> { return this.newSelectQuery([...this.tokens, new StringToken(`SKIP LOCKED`)]); } union(query: Query<any>): SelectQuery<Config, Columns, IncludesStar> { return this.newSelectQuery([...this.tokens, new StringToken(`UNION`), ...query.toTokens()]); } unionAll(query: Query<any>): SelectQuery<Config, Columns, IncludesStar> { return this.newSelectQuery([...this.tokens, new StringToken(`UNION ALL`), ...query.toTokens()]); } } export const makeSelect = <Config extends DbConfig>( queryExecutor: QueryExecutorFn, initialTokens?: Token[], ): SelectFn<Config> => <T extends Selectable>(...columns: T[]) => { const includesStar = !!columns.find((column) => column instanceof Star); const returningKeys = columns .filter((column) => !(column instanceof Star)) .map((column) => { if (column instanceof Query) { return column.getReturningKeys()[0]; } if (!column) { throw new Error(`Column '${column}' not found in columns '${columns}'`); } return (column as any).getName(); }); return new SelectQuery(queryExecutor, returningKeys, includesStar, [ ...(initialTokens || []), new StringToken(`SELECT`), new SeparatorToken( `,`, columns.map((column) => { const tokens = column.toTokens(true); if (column instanceof Query) { return new GroupToken(tokens); } return new CollectionToken(tokens); }), ), ]) as any; };
the_stack
import { TABS_TITLE_KEY } from '@/constant'; import _ from 'lodash'; import { COMPONENT_TYPE_VALUE, COMPONENT_CONFIG_NAME, FILE_TYPE, CONFIG_ITEM_TYPE, } from '@/constant'; import type { IModifyComp, IScheduleComponentComp, IComponentProps } from './interface'; const DEFAULT_PARAMS = [ 'storeType', 'principal', 'versionName', 'kerberosFileName', 'uploadFileName', 'isMetadata', 'isDefault', ]; // 是否为yarn、hdfs、Kubernetes组件 export function isNeedTemp(typeCode: number): boolean { const temp: number[] = [COMPONENT_TYPE_VALUE.YARN, COMPONENT_TYPE_VALUE.HDFS]; return temp.indexOf(typeCode) > -1; } export function isYarn(typeCode: number): boolean { return COMPONENT_TYPE_VALUE.YARN === typeCode; } export function isFLink(typeCode: number): boolean { return COMPONENT_TYPE_VALUE.FLINK === typeCode; } export function isHaveGroup(typeCode: number): boolean { const tmp: number[] = [COMPONENT_TYPE_VALUE.FLINK, COMPONENT_TYPE_VALUE.SPARK]; return tmp.indexOf(typeCode) > -1; } export function notCustomParam(typeCode: number): boolean { const tmp: number[] = [COMPONENT_TYPE_VALUE.SFTP]; return tmp.indexOf(typeCode) > -1; } export function isOtherVersion(code: number): boolean { const tmp: number[] = [ COMPONENT_TYPE_VALUE.FLINK, COMPONENT_TYPE_VALUE.SPARK, COMPONENT_TYPE_VALUE.SPARK_THRIFT, COMPONENT_TYPE_VALUE.HIVE_SERVER, ]; return tmp.indexOf(code) > -1; } export function isSameVersion(code: number): boolean { const tmp: number[] = [COMPONENT_TYPE_VALUE.HDFS, COMPONENT_TYPE_VALUE.YARN]; return tmp.indexOf(code) > -1; } export function isMultiVersion(code: number): boolean { const tmp: number[] = [ COMPONENT_TYPE_VALUE.FLINK, COMPONENT_TYPE_VALUE.SPARK, COMPONENT_TYPE_VALUE.SPARK_THRIFT, ]; return tmp.indexOf(code) > -1; } export function needZipFile(type: number): boolean { const tmp: number[] = [FILE_TYPE.KERNEROS, FILE_TYPE.CONFIGS]; return tmp.indexOf(type) > -1; } export function showDataCheckBox(code: number): boolean { const tmp: number[] = [COMPONENT_TYPE_VALUE.HIVE_SERVER, COMPONENT_TYPE_VALUE.SPARK_THRIFT]; return tmp.indexOf(code) > -1; } export function getActionType(mode: string): string { switch (mode) { case 'view': return '查看集群'; case 'new': return '新增集群'; case 'edit': return '编辑集群'; default: return ''; } } export function isDataCheckBoxs(comps: any[]): boolean { return comps.filter((comp) => showDataCheckBox(comp.componentTypeCode)).length === 2; } export function isSourceTab(activeKey: number): boolean { return activeKey === TABS_TITLE_KEY.SOURCE; } export function initialScheduling(): IScheduleComponentComp[][] { const arr: IScheduleComponentComp[][] = []; Object.values(TABS_TITLE_KEY).forEach((tabKey: string | number) => { if (typeof tabKey === 'number') { arr[tabKey] = []; } }); return arr; } export function giveMeAKey(): string { // eslint-disable-next-line no-bitwise return `${new Date().getTime()}${~~(Math.random() * 100000)}`; } export function isViewMode(mode: string): boolean { return mode === 'view'; } export function isFileParam(key: string): boolean { return ['kerberosFileName', 'uploadFileName'].indexOf(key) > -1; } export function isMetaData(key: string): boolean { return ['isMetadata'].indexOf(key) > -1; } export function isDefaultVersion(key: string): boolean { return ['isDefault'].indexOf(key) > -1; } export function isDeployMode(key: string): boolean { return key === 'deploymode'; } export function isRadioLinkage(type: string): boolean { return type === CONFIG_ITEM_TYPE.RADIO_LINKAGE; } export function isGroupType(type: string): boolean { return type === CONFIG_ITEM_TYPE.GROUP; } export function isCustomType(type: string): boolean { return type === CONFIG_ITEM_TYPE.CUSTOM_CONTROL; } // 模版中存在id则为自定义参数 export function getCustomerParams(temps: any[]): any[] { return temps.filter((temp) => isCustomType(temp.type)); } export function getCompsId(currentComps: IScheduleComponentComp[], id: number | string): number[] { const ids: number[] = []; currentComps.forEach((comp) => { (comp?.multiVersion ?? []).forEach((vcomp) => { if (vcomp?.id === id) ids.push(vcomp.id); }); }); return ids; } export function getValueByJson(value: any): any { return value ? JSON.parse(value) : null; } export function getOptions(version: any[]): any[] { const opt: any[] = []; version.forEach((ver: any, index: number) => { opt[index] = { label: ver.key, value: ver.key }; if (ver?.values && ver?.values?.length > 0) { opt[index] = { ...opt[index], children: getOptions(ver.values), }; } }); return opt; } export function getCompsName(comps: Set<IModifyComp>): string[] { return Array.from(comps).map((comp: IModifyComp) => { if (isMultiVersion(comp.typeCode)) { return `${COMPONENT_CONFIG_NAME[comp.typeCode]} ${comp.versionName}`; } return COMPONENT_CONFIG_NAME[comp.typeCode]; }); } export function getInitialValue(version: any[], commVersion: string): any[] { const parentNode: Record<string, any> = {}; function setParentNode(nodes: any[], parent?: any) { if (!nodes) return; return nodes.forEach((data) => { const node = { value: data.key, parent }; parentNode[data.key] = node; setParentNode(data.values, node); }); } function getParentNode(value: string) { let node: any[] = []; const currentNode = parentNode[value]; node.push(currentNode.value); if (currentNode.parent) { node = [...getParentNode(currentNode.parent.value), ...node]; } return node; } setParentNode(version); return getParentNode(commVersion); } // 是否 yarn 和 hdfs 组件都存在 export function isSchedulings(initialCompData: any[]): boolean { let scheduling = 0; initialCompData.forEach((comps) => { if (comps.findIndex((comp: any) => isSameVersion(comp.componentTypeCode)) > -1) { scheduling += 1; } }); return scheduling === 2; } /** * @param param * 处理单条自定义参数的key\value值 * 处理数据结构为%1532398855125918-key, %1532398855125918-value * 返回数据结构[{key: key, value: value, id: id}] */ function handleSingleParam(params: any) { const tempParamObj: Record<string, { key: string; value: string }> = {}; const customParamConfig: any[] = []; if (!params) return {}; Object.entries(params).forEach(([keys, values]) => { if (values && _.isString(values) && _.isString(keys)) { const p = keys.split('%')[1].split('-'); tempParamObj[p[0]] = { ...tempParamObj[p[0]], [p[1]]: values, }; } }); Object.keys(tempParamObj).forEach((key) => { customParamConfig.push({ key: tempParamObj[key].key, value: tempParamObj[key].value, id: key, type: CONFIG_ITEM_TYPE.CUSTOM_CONTROL, }); }); return customParamConfig; } /** * @param param 自定义参数对象 * @param turnp 转化为{key:value}型数据,仅支持不含group类型组组件 * 先组内处理自定义参数再处理普通类型的自定义参数 * 返回数据结构 * [{ * group: { * key: key, * value: value * } * }] */ export function handleCustomParam(params: any, turnp?: boolean): any { let customParam: any = []; if (!params) return {}; Object.entries(params).forEach(([key, value]) => { if (value && !_.isString(value)) { customParam = [...customParam, { [key]: handleSingleParam(value) }]; } }); if (turnp) { const config: Record<string, any> = {}; customParam.concat(handleSingleParam(params)).forEach((item: any) => { config[item.key] = item.value; }); return config; } return customParam.concat(handleSingleParam(params)); } /** * @param temp 初始模版值 * 处理初始模版值返回只包含自定义参数的键值 * 返回结构如下 * { * %1532398855125918-key: key, * %1532398855125918-value: value, * group: { * %1532398855125918-key: key, * %1532398855125918-value: value, * } * } */ export function getParamsByTemp(temp: any[]): any { const batchParams: any = {}; (isDeployMode(temp[0]?.key) ? temp[0].values : temp).forEach((item: any) => { if (item.type === CONFIG_ITEM_TYPE.GROUP) { const params: Record<string, any> = {}; item.values.forEach((groupItem: any) => { if (groupItem.id) { params[`%${groupItem.id}-key`] = groupItem?.key ?? ''; params[`%${groupItem.id}-value`] = groupItem?.value ?? ''; } }); batchParams[item.key] = params; } if (isCustomType(item.type)) { batchParams[`%${item.id}-key`] = item?.key ?? ''; batchParams[`%${item.id}-value`] = item?.value ?? ''; } }); return batchParams; } // 后端需要value值加单引号处理 function handleSingQuoteKeys(val: string, key: string) { const singQuoteKeys = ['c.NotebookApp.ip', 'c.NotebookApp.token', 'c.NotebookApp.default_url']; let newVal = val; singQuoteKeys.forEach((singlekey) => { if (singlekey === key && val.indexOf("'") === -1) { newVal = `'${val}'`; } }); return newVal; } /** * @param * comp 表单组件值 * initialCompData 初始表单组件值 * componentTemplate用于表单回显值需要包含表单对应的value和并自定义参数 */ export function handleComponentTemplate(comp: any, initialCompData: any): any { /** 外层数据先删除一层自定义参数 */ const newComponentTemplate = JSON.parse(initialCompData.componentTemplate).filter( (v: any) => v.type !== CONFIG_ITEM_TYPE.CUSTOM_CONTROL, ); const componentConfig = handleComponentConfig(comp); const customParamConfig = handleCustomParam(comp.customParam); let isGroup = false; // componentTemplate 存入 componentConfig 对应值 Object.entries(componentConfig).forEach(([key, values]) => { if (!_.isString(values) && !_.isArray(values)) { Object.entries(values as any).forEach(([groupKey, value]) => { (isDeployMode(newComponentTemplate[0].key) ? newComponentTemplate[0].values : newComponentTemplate ).forEach((temps: any) => { if (temps.key === key) { // eslint-disable-next-line no-param-reassign temps.values = temps.values.filter( (temp: any) => temp.type !== CONFIG_ITEM_TYPE.CUSTOM_CONTROL, ); temps.values.forEach((temp: any) => { if (temp.key === groupKey) { // eslint-disable-next-line no-param-reassign temp.value = value; } }); } }); }); } else { newComponentTemplate.forEach((temps: any) => { if (temps.key === key) { // eslint-disable-next-line no-param-reassign temps.value = values; } else if (isRadioLinkage(temps.type)) { temps.values.forEach((temp: any) => { // eslint-disable-next-line no-param-reassign if (temp.values[0].key === key) temp.values[0].value = values; }); } }); } }); if (Object.values(customParamConfig).length === 0) { return newComponentTemplate; } // 和并自定义参数 customParamConfig.forEach((config: any) => { if (!config?.type) { isGroup = true; Object.entries(config).forEach(([key, value]) => { (isDeployMode(newComponentTemplate[0].key) ? newComponentTemplate[0].values : newComponentTemplate ).forEach((temp: any) => { if (temp.key === key && temp.type === CONFIG_ITEM_TYPE.GROUP) { // eslint-disable-next-line no-param-reassign temp.values = temp.values.concat(value); } }); }); } }); if (!isGroup) return newComponentTemplate.concat(customParamConfig); return newComponentTemplate; } /** * @param comp * @param turnp 格式 => 为tue时对应componentConfig格式为{%-key:value} * 返回componentConfig */ export function handleComponentConfig(comp: any, turnp?: boolean): any { // 处理componentConfig const componentConfig: Record<string, any> = {}; function wrapperKey(key: string): string { if (turnp) return key.split('.').join('%'); return key.split('%').join('.'); } Object.entries(comp?.componentConfig ?? {}).forEach(([key, values]) => { componentConfig[wrapperKey(key)] = values; if (!_.isString(values) && !_.isArray(values)) { const groupConfig: Record<string, any> = {}; Object.entries(values as any).forEach(([groupKey, value]) => { const wrapper = wrapperKey(groupKey); groupConfig[wrapper] = turnp ? value : handleSingQuoteKeys(value as string, wrapper); }); componentConfig[key] = groupConfig; } }); return componentConfig; } /** * @param comp * @param typeCode * 返回包含自定义参数的componentConfig * typeCode识别是否有组类别 */ export function handleComponentConfigAndCustom(comp: any, typeCode: number): any { // 处理componentConfig let componentConfig = handleComponentConfig(comp); const isFlinkStandalone = componentConfig?.clusterMode === 'standalone'; // flink 组件含有 standalone 类型,没有 group 包裹 // 自定义参数和componentConfig和并 const customParamConfig = handleCustomParam(comp.customParam); if (isHaveGroup(typeCode) && !isFlinkStandalone && customParamConfig.length) { // eslint-disable-next-line no-restricted-syntax for (const config of customParamConfig) { // eslint-disable-next-line for (const key in config) { // eslint-disable-next-line no-restricted-syntax for (const groupConfig of config[key]) { componentConfig[key] = { ...componentConfig[key], [groupConfig.key]: groupConfig.value, }; } } } } if ((!isHaveGroup(typeCode) || isFlinkStandalone) && Object.values(customParamConfig).length) { // eslint-disable-next-line no-restricted-syntax for (const item of customParamConfig) { componentConfig = { ...componentConfig, [item.key]: item.value, }; } } return componentConfig; } export function getSingleTestStatus( params: { typeCode: number; versionName?: string }, value: any, testStatus: any, ): any[] { const typeCode = params.typeCode ?? ''; const versionName = params.versionName ?? ''; const currentStatus = testStatus[String(typeCode)] ?? {}; let multiVersion = currentStatus?.multiVersion ?? []; if (multiVersion.length) { let sign = false; multiVersion = multiVersion.map((version: any) => { if (version?.componentVersion === versionName) { sign = true; return value; } return version; }); if (!sign && value) multiVersion.push(value); } if (!multiVersion.length && value) multiVersion.push(value); return multiVersion; } export function includesCurrentComp( modifyComps: any[], params: { typeCode: number; versionName?: string }, ): boolean { const { typeCode, versionName } = params; for (let i = 0; i < modifyComps.length; i += 1) { const comp = modifyComps[i] || {}; if (comp.typeCode === typeCode && !comp.versionName) return true; if (comp.typeCode === typeCode && comp.versionName === versionName) return true; } return false; } export function getCurrentComp( initialCompDataArr: any[], params: { typeCode: number; versionName?: string }, ): any { const { typeCode, versionName } = params; let currentComp = {}; // eslint-disable-next-line no-restricted-syntax for (const comp of initialCompDataArr) { // eslint-disable-next-line no-restricted-syntax for (const vcomp of comp?.multiVersion ?? []) { if (vcomp?.componentTypeCode === typeCode) { if (!versionName && vcomp) currentComp = vcomp; if (vcomp?.versionName === versionName) currentComp = vcomp; } } } return currentComp; } export function getCurrent1Comp( initialCompDataArr: IScheduleComponentComp[][], params: { typeCode: number; versionName?: string }, ): IComponentProps | Record<string, unknown> { const { typeCode, versionName } = params; let currentComp: IComponentProps | Record<string, unknown> = {}; // eslint-disable-next-line no-restricted-syntax for (const compArr of initialCompDataArr) { // eslint-disable-next-line no-restricted-syntax for (const comp of compArr) { // eslint-disable-next-line no-restricted-syntax for (const vcomp of comp?.multiVersion ?? []) { if (vcomp?.componentTypeCode === typeCode) { if (!versionName && vcomp) currentComp = vcomp; if (vcomp?.versionName === versionName) currentComp = vcomp; } } } } return currentComp; } /** * @param comp 已渲染组件表单值 * @param initialComp 组件初始值 * * 通过比对表单值和初始值对比是否变更 * 返回含有组件code数组 * */ function handleCurrentComp(comp: any, initialComp: any, typeCode: number): boolean { /** * 基本参数对比 * 文件对比,只比较文件名称 */ for (let index = 0; index < DEFAULT_PARAMS.length; index += 1) { const param = DEFAULT_PARAMS[index]; let compValue = comp[param]; if (isFileParam(param)) { compValue = comp[param]?.name ?? comp[param]; } if (isMetaData(param)) { if (comp[param] === true) compValue = 1; if (comp[param] === false) compValue = 0; } if ( (compValue || compValue === 0) && !_.isEqual(compValue, initialComp[param]?.name ?? initialComp[param]) ) { return true; } } /** * 除 hdfs、yarn、kerberos组件 * 对比之前先处理一遍表单的数据和自定义参数, 获取含有自定义参数的componentConfig */ if (!isNeedTemp(Number(typeCode))) { const compConfig = handleComponentConfigAndCustom(comp, Number(typeCode)); if (!Object.values(compConfig).length) return false; if ( !_.isEqual( compConfig, initialComp?.componentConfig ? JSON.parse(initialComp.componentConfig) : {}, ) ) { return true; } } else { /** 比对 hdfs、yarn 自定义参数 */ const compTemp = comp.customParam ? handleSingleParam(comp.customParam) : []; const initialTemp = getCustomerParams(getValueByJson(initialComp?.componentTemplate) ?? []); if (!_.isEqual(compTemp, initialTemp)) { return true; } } return false; } /** * @param comps 已渲染各组件表单值 * @param initialCompData 各组件初始值 * @param versionMap 组件的typeCode与对应的versionName数组映射 * * 通过比对表单值和初始值对比是否变更 * 返回含有组件code数组 * */ export function getModifyComp( comps: Record<string, any>, initialCompData: IScheduleComponentComp[][], versionMap?: Record<number, string[]>, ) { const modifyComps = new Set<IModifyComp>(); Object.entries(comps).forEach(([typeCode, comp]) => { const typeCodeNum = Number(typeCode); if (isMultiVersion(typeCodeNum)) { const versionNames = versionMap?.[typeCodeNum]; if (!versionNames) return; versionNames.forEach((versionName) => { if (!versionName) return; const versionArr: string[] = versionName.split('.'); const currentComp = versionArr.reduce((pre, cur) => pre?.[cur], comp) || {}; const initialComp = getCurrent1Comp(initialCompData, { typeCode: typeCodeNum, versionName, }); if (handleCurrentComp(currentComp, initialComp, typeCodeNum)) { modifyComps.add({ typeCode: typeCodeNum, versionName, }); } }); } else { const initialComp = getCurrent1Comp(initialCompData, { typeCode: typeCodeNum, }); if (handleCurrentComp(comp, initialComp, typeCodeNum)) { modifyComps.add({ typeCode: typeCodeNum }); } } }); return modifyComps; }
the_stack
import {Test, O, A, T, U, M, F, S} from '../sources' import {Key} from '../sources/Any/Key' import {OptionalDeep} from '../sources/Object/Optional' const {checks, check} = Test // /////////////////////////////////////////////////////////////////////////////////////// // OBJECT //////////////////////////////////////////////////////////////////////////////// type O = { a: string, b: number; c: {a: 'a'} & {b: 'b'}; d?: 'string0'; readonly e?: 'string1'; readonly f: 0; g: O; h?: 1; j: 'a' | undefined; k: {a: {b: string}}; x: () => 1; }; type O1 = { a: string | number; b: object; c: {a: 'a'} & {b: 'b'}; d?: never; readonly e?: 'string1'; readonly f: 0; g: {}; h: never; i: {a: string}; j: 'a' | undefined; k: {a: {b: string, c: 0}}; l: [1, 2, 3]; }; // --------------------------------------------------------------------------------------- // ASSIGN type O_ASSIGN = {readonly a: 1, c: 2}; type Os_ASSIGN = [{a: 2, readonly b: 1}, {a: 3, c?: 1}]; type ASSIGN_O_Os = {readonly a: 3, readonly b: 1, c: 1 | 2}; checks([ check<O.Assign<O_ASSIGN, Os_ASSIGN>, ASSIGN_O_Os, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // ATLEAST type O_ATLEAST = { a?: 1; b?: 2; c?: 3; d: 4; } | { e: 5; f: 6; } | { g?: 7; h?: 8; }; type ATLEAST_O_ABF = { a: 1; b: 2; c: 3; d: 4; } | { a: 1; b?: 2; c?: 3; d?: 4; } | { a?: 1; b: 2; c?: 3; d?: 4; } | { e: 5; f: 6; } | { e?: 5; f: 6; } | { g?: 7; h?: 8; }; checks([ check<O.AtLeast<O_ATLEAST, 'a' | 'b' | 'f'>, ATLEAST_O_ABF, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // COMPULSORY type COMPULSORY_O = { a: string, b: number; c: {a: 'a'} & {b: 'b'}; d: 'string0'; readonly e: 'string1'; readonly f: 0; g: O; // recursion h: 1; j: 'a'; k: {a: {b: string}}; x: () => 1; }; checks([ check<O.Compulsory<O>, COMPULSORY_O, Test.Pass>(), ]) function COMPULSORY_GENERIC<O extends {n?: number}>(o: O) { const v0 = o as O.Compulsory<O, Key, 'flat'> const v1 = o as O.Compulsory<O, Key, 'deep'> const p0: number = v0.n const p1: number = v1.n } // --------------------------------------------------------------------------------------- // COMPULSORYKEYS type COMPULSORYKEYS_O = 'a' | 'b' | 'c' | 'f' | 'g' | 'k' | 'x'; checks([ check<O.CompulsoryKeys<O>, COMPULSORYKEYS_O, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // DIFF type DIFF_O_O1_DEFAULT = { i: {a: string}; l: [1, 2, 3]; x: () => 1; }; type DIFF_O_O1_EQUALS = { a: string; b: number; d?: 'string0'; g: O; h?: 1; i: {a: string}; k: {a: {b: string}}; l: [1, 2, 3]; x: () => 1; }; checks([ check<O.Diff<O, O1, 'default'>, DIFF_O_O1_DEFAULT, Test.Pass>(), check<O.Diff<O, O1, 'equals'>, DIFF_O_O1_EQUALS, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- type DIFF_O1_O_DEFAULT = { i: {a: string}; l: [1, 2, 3]; x: () => 1; }; type DIFF_O1_O_EQUALS = { a: string | number; b: object; d?: never; g: {}; h: never; i: {a: string}; k: {a: {b: string, c: 0}}; l: [1, 2, 3]; x: () => 1; }; checks([ check<O.Diff<O1, O, 'default'>, DIFF_O1_O_DEFAULT, Test.Pass>(), check<O.Diff<O1, O, 'equals'>, DIFF_O1_O_EQUALS, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // EITHER type O_EITHER = { a: string; b?: number; readonly c?: object; } | { a: 'a', b: 'b'; }; type EITHER_O_AB_TRUE = { a: string; b?: undefined; readonly c?: object; } | { a?: undefined; b?: number; readonly c?: object; } | { a: 'a'; b?: undefined; } | { b: 'b'; a?: undefined; }; type EITHER_O_AB_FALSE = { a: string; readonly c?: object; } | { b?: number; readonly c?: object; } | { a: 'a'; } | { b: 'b'; }; checks([ check<O.Either<O_EITHER, 'a' | 'b'>, EITHER_O_AB_TRUE, Test.Pass>(), check<O.Either<O_EITHER, 'a' | 'b', 0>, EITHER_O_AB_FALSE, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // EXCLUDE type EXCLUDE_O_O1_DEFAULT = { x: () => 1; }; type EXCLUDE_O_O1_EQUALS = { a: string; b: number; d?: 'string0'; g: O; h?: 1; k: {a: {b: string}}; x: () => 1; }; checks([ check<O.Exclude<O, O1, 'default'>, EXCLUDE_O_O1_DEFAULT, Test.Pass>(), check<O.Exclude<O, O1, 'equals'>, EXCLUDE_O_O1_EQUALS, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- type EXCLUDE_O1_O_DEFAULT = { i: {a: string}; l: [1, 2, 3]; }; type EXCLUDE_O1_O_EQUALS = { a: string | number; b: object; d?: never; g: {}; h: never; i: {a: string}; k: {a: {b: string, c: 0}}; l: [1, 2, 3]; }; checks([ check<O.Exclude<O1, O, 'default'>, EXCLUDE_O1_O_DEFAULT, Test.Pass>(), check<O.Exclude<O1, O, 'equals'>, EXCLUDE_O1_O_EQUALS, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // EXCLUDEKEYS type EXCLUDEKEYS_O_DEFAULT = 'x'; type EXCLUDEKEYS_O_EQUALS = 'a' | 'b' | 'd' | 'g' | 'h' | 'k' | 'x'; checks([ check<O.ExcludeKeys<O, O1, 'default'>, EXCLUDEKEYS_O_DEFAULT, Test.Pass>(), check<O.ExcludeKeys<O, O1, 'equals'>, EXCLUDEKEYS_O_EQUALS, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- type EXCLUDEKEYS_O1_DEFAULT = 'i' | 'l'; type EXCLUDEKEYS_O1_EQUALS = 'a' | 'b' | 'd' | 'g' | 'h' | 'i' | 'k' | 'l'; checks([ check<O.ExcludeKeys<O1, O, 'default'>, EXCLUDEKEYS_O1_DEFAULT, Test.Pass>(), check<O.ExcludeKeys<O1, O, 'equals'>, EXCLUDEKEYS_O1_EQUALS, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // FILTER type FILTER_O_DEFAULT = { b: number; c: {a: 'a'} & {b: 'b'}; d?: 'string0'; readonly e?: 'string1'; readonly f: 0; g: O; h?: 1; j: 'a' | undefined; k: {a: {b: string}}; x: () => 1; }; type FILTER_O_EQUALS = { b: number; c: {a: 'a'} & {b: 'b'}; d?: 'string0'; readonly e?: 'string1'; readonly f: 0; g: O; h?: 1; j: 'a' | undefined; k: {a: {b: string}}; x: () => 1; }; checks([ check<O.Filter<O, string, 'extends->'>, FILTER_O_DEFAULT, Test.Pass>(), check<O.Filter<O, string, 'equals'>, FILTER_O_EQUALS, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // FILTERKEYS type FILTERKEYS_O_DEFAULT = 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'j' | 'k' | 'x'; type FILTERKEYS_O_EQUALS = 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'j' | 'k' | 'x'; checks([ check<O.FilterKeys<O, string, 'extends->'>, FILTERKEYS_O_DEFAULT, Test.Pass>(), check<O.FilterKeys<O, string, 'equals'>, FILTERKEYS_O_EQUALS, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // HAS checks([ check<O.Has<O, 'X', string | number, 'extends->'>, 0, Test.Pass>(), check<O.Has<O, 'c', string, 'extends->'>, 0, Test.Pass>(), check<O.Has<O, 'c', {a: 'a'} & {b: 'b'}, 'equals'>, 1, Test.Pass>(), check<O.Has<O, 'd', string | undefined, 'extends->'>, 1, Test.Pass>(), check<O.Has<O, 'd', 'string0' | undefined, 'equals'>, 1, Test.Pass>(), check<O.Has<O, 'd', string, 'extends->'>, 0 | 1, Test.Pass>(), check<O.Has<O, 'd', 'string0', 'equals'>, 0, Test.Pass>(), check<O.Has<O, 'd', undefined, 'extends->'>, 0 | 1, Test.Pass>(), check<O.Has<O, 'd', 'string0', 'equals'>, 0, Test.Pass>(), check<O.Has<O1, 'a', string, 'extends->'>, 0 | 1, Test.Pass>(), check<O.Has<O, 'f', 0 | undefined | 'a', 'extends->'>, 1, Test.Pass>(), check<O.Has<O, 'f', 0 | undefined | 'a', 'equals'>, 0, Test.Pass>(), check<O.Has<O, 'a' | 'd', string, 'extends->'>, 0 | 1, Test.Pass>(), check<O.Has<O, 'a' | 'd', string | undefined, 'extends->'>, 1, Test.Pass>(), check<O.Has<O, 'xx' | 'd', string | undefined, 'extends->'>, 1, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // HASPATH checks([ check<O.HasPath<O, ['g', 'g', 'g'], object, 'extends->'>, 1, Test.Pass>(), check<O.HasPath<O, ['g', 'g', 'g'], O, 'equals'>, 1, Test.Pass>(), check<O.HasPath<O, ['g', 'g', 'g', 'a'], string, 'extends->'>, 1, Test.Pass>(), check<O.HasPath<O, ['g', 'x', 'g'], object, 'extends->'>, 0, Test.Pass>(), check<O.HasPath<O, [], any, 'extends->'>, 1, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // INCLUDES checks([ check<O.Includes<O, 'xxxx', 'extends->'>, 0, Test.Pass>(), check<O.Includes<O, 'xxxx', 'equals'>, 0, Test.Pass>(), check<O.Includes<O, string, 'extends->'>, 1, Test.Pass>(), check<O.Includes<O, string, 'equals'>, 1, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // INTERSECT type INTERSECT_O_O1_DEFAULT = O.Omit<O, 'x'>; type INTERSECT_O_O1_EQUALS = { c: {a: 'a'} & {b: 'b'}; readonly e?: 'string1'; readonly f: 0; j: 'a' | undefined; }; checks([ check<O.Intersect<O, O1, 'default'>, INTERSECT_O_O1_DEFAULT, Test.Pass>(), check<O.Intersect<O, O1, 'equals'>, INTERSECT_O_O1_EQUALS, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // INTERSECTKEYS type INTERSECTKEYS_O_DEFAULT = U.Exclude<keyof O, 'x'>; type INTERSECTKEYS_O_EQUALS = 'c' | 'e' | 'f' | 'j'; checks([ check<O.IntersectKeys<O, O1, 'default'>, INTERSECTKEYS_O_DEFAULT, Test.Pass>(), check<O.IntersectKeys<O, O1, 'equals'>, INTERSECTKEYS_O_EQUALS, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // INVERT const INVERT_SYM = Symbol('') const INVERT_SYM2 = Symbol('') type O_INVERT_T1 = { A: 'Av'; B: typeof INVERT_SYM; C: 42; }; type O_INVERT_T2 = O_INVERT_T1 | { Af: 'Avf'; Bf: typeof INVERT_SYM2; Cf: 43; }; type T1_INVERT_O = { Av: 'A'; [INVERT_SYM]: 'B'; 42: 'C'; }; type T2_INVERT_O = { Av: 'A'; [INVERT_SYM]: 'B'; 42: 'C'; } | { Avf: 'Af'; [INVERT_SYM2]: 'Bf'; 43: 'Cf'; }; interface O_INVERT_I1 { A: 'Av'; B: typeof INVERT_SYM; C: 42; } interface O_INVERT_I2 { Af: 'Avf'; Bf: typeof INVERT_SYM2; Cf: 43; } interface I1_INVERT_O { Av: 'A'; [INVERT_SYM]: 'B'; 42: 'C'; } interface I2_INVERT_O { Avf: 'Af'; [INVERT_SYM2]: 'Bf'; 43: 'Cf'; } checks([ check<O.Invert<O_INVERT_T1>, T1_INVERT_O, Test.Pass>(), check<O.Invert<O_INVERT_T2>, T2_INVERT_O, Test.Pass>(), check<O.Invert<O_INVERT_I1>, T1_INVERT_O, Test.Pass>(), check<O.Invert<O_INVERT_I1>, I1_INVERT_O, Test.Pass>(), check<O.Invert<O_INVERT_I1 | O_INVERT_I2>, T2_INVERT_O, Test.Pass>(), check<O.Invert<O_INVERT_I1 | O_INVERT_I2>, I1_INVERT_O | I2_INVERT_O, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // LISTOF type O_LISTOF_INDEX = { '0': 1; '2': 3; '3': never; '5': 5; '6': 6; }; type O_LISTOF_NUMBER = { [K in number]: 42 }; type O_LISTOF_STRING = { [K in string]: 42 }; type O_LISTOF_SYMBOL = { [K in symbol]: 42 }; type LISTOF_INDEX_O = [1, 3, never, 5, 6]; type LISTOF_NUMBER_O = 42[]; type LISTOF_STRING_O = 42[]; type LISTOF_SYMBOL_O = unknown[]; checks([ check<O.ListOf<O_LISTOF_INDEX>, LISTOF_INDEX_O, Test.Pass>(), check<O.ListOf<O_LISTOF_NUMBER>, LISTOF_NUMBER_O, Test.Pass>(), check<O.ListOf<O_LISTOF_STRING>, LISTOF_STRING_O, Test.Pass>(), check<O.ListOf<O_LISTOF_SYMBOL>, LISTOF_SYMBOL_O, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // MERGE type O_MERGE = { a?: string; c: { a?: string; b?: number; } | Date; d: 'hello' | undefined; e: number | {a: 1}; f?: { a: string; b?: number; }, g?: { a?: string; b?: number; }; h: { a: number; b: number; } | undefined; i: { a: string; } | undefined; j: { a: { b?: {}; }; }, k?: {[k: string]: string}; l: [{a: 'a'}]; n: 42; }; type O1_MERGE = { a: object | undefined; b: number; c: { a: object; b?: object; c: object; }; d: 'goodbye'; e: string | {b: 2}; f?: { a: object; b?: object; c: object; }; h: { a: string; }; i: { a: number; } | undefined; j?: { a: { b?: { c: 1; }; }; }; k: {} | Date; l: [{b: 'b'}, 2, 3]; m: []; }; type MERGE_O_O1_LODASH = { a: string | object | undefined; b: number; c: { a?: string; b?: number; } | Date; d: 'hello' | 'goodbye'; e: number | {a: 1}; f?: { a: string; b?: number; } | { a: object; b?: object; c: object; }, g?: { a?: string; b?: number; }; h: { a: number; b: number; } | { a: string; }; i: { a: string; } | { a: number; } | undefined; j: { a: { b?: {}; }; }, k: {} | {[k: string]: string} | Date; l: [{a: 'a'}]; m: []; n: 42; }; type MERGE_O_O1_DEEP_LODASH = { a: string | object | undefined; b: number; c: { a: string | object; b?: number | object; c: object; } | Date; d: 'hello' | 'goodbye'; e: number | {a: 1} | {a: 1, b: 2}; f?: { a: string; b?: number | undefined; } | { a: object; b?: object | undefined; c: object; } | { a: string; b?: number | object | undefined; c: object; } | undefined; g?: { a?: string; b?: number; }; h: { a: number; b: number; } | { a: string; }; i: { a: string; } | { a: number; } | undefined; j: { a: { b?: {} | { c: 1; }; }; } | { a: { b?: {}; }; }, k: {} | {[k: string]: string} | {[x: string]: string | undefined} | Date; l: [{a: 'a', b: 'b'}, 2, 3]; m: []; n: 42; }; checks([ check<O.Merge<[1], [2, 3], 'flat'>, [1, 3], Test.Pass>(), check<O.Merge<[1], [2, 3], 'deep'>, [1, 3], Test.Pass>(), check<O.Merge<O_MERGE, O1_MERGE, 'flat', M.BuiltIn, undefined>, MERGE_O_O1_LODASH, Test.Pass>(), check<O.Merge<O_MERGE, O1_MERGE, 'deep', M.BuiltIn, undefined>, MERGE_O_O1_DEEP_LODASH, Test.Pass>(), ]) function MERGE_GENERIC<O extends {n?: number}>(o: O) { const v0 = o as O.Merge<O, {n: string}, 'flat'> const v1 = o as O.Merge<O, {n: string}, 'deep'> const p0: string | number = v0.n const p1: string | number = v1.n } // --------------------------------------------------------------------------------------- // MERGEALL checks([ check<O.MergeAll<{}, [O_MERGE, O1_MERGE], 'flat', M.BuiltIn, undefined>, MERGE_O_O1_LODASH, Test.Pass>(), check<O.MergeAll<{}, [O_MERGE, O1_MERGE], 'deep', M.BuiltIn, undefined>, MERGE_O_O1_DEEP_LODASH, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // MODIFY checks([ check<O.Modify<{a?: string}, {a: A.x, b: 9}>, {a: string, b: 9}, Test.Pass>(), check<O.Modify<{}, {a: A.x, b: 9}>, {a: never, b: 9}, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // NONNULLABLE type NONNULLABLE_O_FLAT = { a: string; b: number; c: {a: 'a'} & {b: 'b'}; d?: 'string0'; readonly e?: 'string1'; readonly f: 0; g: O; h?: 1; j: 'a'; k: {a: {b: string}}; x: () => 1; }; type NONNULLABLE_O_J_FLAT = { a: string; b: number; c: {a: 'a'} & {b: 'b'}; d?: 'string0'; readonly e?: 'string1'; readonly f: 0; g: O; h?: 1; j: 'a'; k: {a: {b: string}}; x: () => 1; }; checks([ check<O.NonNullable<O, keyof O, 'flat'>, NONNULLABLE_O_FLAT, Test.Pass>(), check<O.NonNullable<O, 'j', 'flat'>, NONNULLABLE_O_J_FLAT, Test.Pass>(), check<O.Path<O.NonNullable<O, 'g', 'deep'>, ['g', 'g']>, O.NonNullable<O, keyof O, 'deep'>, Test.Pass>(), ]) function NONNULLABLE_GENERIC<O extends {n: number[] | undefined}>(o: O) { const v0 = o as O.NonNullable<O, Key, 'flat'> const v1 = o as O.NonNullable<O, Key, 'deep'> const p0: number[] = v0.n const p1: number[] = v1.n } // --------------------------------------------------------------------------------------- // NONNULLABLEKEYS checks([ check<O.NonNullableKeys<O>, 'a' | 'b' | 'c' | 'f' | 'g' | 'k' | 'x', Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // NULLABLE type NULLABLE_O_FLAT = { a: string | undefined | null; b: number | undefined | null; c: {a: 'a'} & {b: 'b'} | undefined | null; d?: 'string0' | null; readonly e?: 'string1' | null; readonly f: 0 | undefined | null; g: O | undefined | null; h?: 1 | null; j: 'a' | undefined | null; k: {a: {b: string}} | undefined | null; x: (() => 1) | undefined | null; }; type NULLABLE_O_A_FLAT = { a: string | undefined | null; b: number; c: {a: 'a'} & {b: 'b'}; d?: 'string0'; readonly e?: 'string1'; readonly f: 0; g: O; h?: 1; j: 'a' | undefined; k: {a: {b: string}}; x: () => 1; }; checks([ check<O.Nullable<O, keyof O, 'flat'>, NULLABLE_O_FLAT, Test.Pass>(), check<O.Nullable<O, 'a', 'flat'>, NULLABLE_O_A_FLAT, Test.Pass>(), check<O.Path<O.Nullable<O, 'g', 'deep'>, ['g', 'g']>, O.Nullable<O, keyof O, 'deep'> | undefined | null, Test.Pass>(), ]) function NULLABLE_GENERIC<O extends {n: number[]}>(o: O) { const v0 = o as O.Nullable<O, Key, 'flat'> const v1 = o as O.Nullable<O, Key, 'deep'> const p0: number[] | undefined | null = v0.n const p1: (number | undefined | null)[] | null | undefined = v1.n } // --------------------------------------------------------------------------------------- // NULLABLEKEYS checks([ check<O.NullableKeys<O>, 'd' | 'e' | 'h' | 'j', Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // OBJECT // Cannot be tested // --------------------------------------------------------------------------------------- // OMIT type OMIT_O_DEH = { a: string; b: number; c: {a: 'a'} & {b: 'b'}; readonly f: 0; g: O; j: 'a' | undefined; k: {a: {b: string}}; x: () => 1; }; checks([ check<O.Omit<O, 'd' | 'e' | 'h'>, OMIT_O_DEH, Test.Pass>(), check<O.Omit<O, keyof O>, {}, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // OPTIONAL type OPTIONAL_O_FLAT = { a?: string, b?: number; c?: {a: 'a'} & {b: 'b'}; d?: 'string0'; readonly e?: 'string1'; readonly f?: 0; g?: O; h?: 1; j?: 'a'; k?: {a: {b: string}}; x?: () => 1; }; type OPTIONAL_O_A_FLAT = { a?: string; b: number; c: {a: 'a'} & {b: 'b'}; d?: 'string0'; readonly e?: 'string1'; readonly f: 0; g: O; h?: 1; j: 'a' | undefined; k: {a: {b: string}}; x: () => 1; }; checks([ check<O.Optional<O, keyof O, 'flat'>, OPTIONAL_O_FLAT, Test.Pass>(), check<O.Optional<O, 'a', 'flat'>, OPTIONAL_O_A_FLAT, Test.Pass>(), check<O.Path<O.Optional<O, 'g', 'deep'>, ['g', 'g']>, O.Optional<O, keyof O, 'deep'> | undefined, Test.Pass>(), ]) function OPTIONAL_GENERIC<O extends {values: number[]}>(o: O) { let v0 = o as O.Optional<O, Key, 'flat'> let v1 = o as O.Optional<O, Key, 'deep'> const p0: number[] | undefined = v0.values const p1: OptionalDeep<O['values']> | undefined = v1.values v0 = {} v1 = {} } // --------------------------------------------------------------------------------------- // PARTIAL type PARTIAL_O_FLAT = { a?: string, b?: number; c?: {a: 'a'} & {b: 'b'}; d?: 'string0'; readonly e?: 'string1'; readonly f?: 0; g?: O; h?: 1; j?: 'a'; k?: {a: {b: string}}; x?: () => 1; }; checks([ check<O.Partial<O, 'flat'>, PARTIAL_O_FLAT, Test.Pass>(), check<O.Path<O.Partial<O, 'deep'>, ['g', 'g']>, O.Partial<O, 'deep'> | undefined, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // OPTIONALKEYS checks([ check<O.OptionalKeys<O>, 'd' | 'e' | 'h', Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // OVERWRITE checks([ check<O.Overwrite<{a: string}, {a: number, b: any}>, {a: number}, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // PATCH type PATCH_O_O1 = { a: string; b: number; c: {a: 'a'} & {b: 'b'}; d?: 'string0'; readonly e?: 'string1'; readonly f: 0; g: O; h?: 1; i: {a: string}; j: 'a' | undefined; k: {a: {b: string}}; l: [1, 2, 3]; x: () => 1; }; type PATCH_O1_O = { a: string | number; b: object; c: {a: 'a'} & {b: 'b'}; d?: never; readonly e?: 'string1'; readonly f: 0; g: {}; h: never; i: {a: string}; j: 'a' | undefined; k: {a: {b: string, c: 0}}; l: [1, 2, 3]; x: () => 1; }; type PATCH_O_O1_DEEP = { a: string; b: number; c: {a: 'a', b: 'b'}; d?: 'string0'; readonly e?: 'string1'; readonly f: 0; g: O; h?: 1; i: {a: string}; j: 'a' | undefined; k: {a: {b: string, c: 0}}; l: [1, 2, 3]; x: () => 1; }; checks([ check<O.Patch<O, O1>, PATCH_O_O1, Test.Pass>(), check<O.Patch<O1, O>, PATCH_O1_O, Test.Pass>(), check<O.Patch<O, O1, 'deep'>, PATCH_O_O1_DEEP, Test.Pass>(), ]) function PATCH_GENERIC<O extends {n: number}>(o: O) { const v0 = o as O.Patch<O, {a: string}, 'flat'> const v1 = o as O.Patch<O, {a: string}, 'deep'> const p0n: number = v0.n const p1n: number = v1.n const p0a: string = v0.a const p1a: string = v1.a } // --------------------------------------------------------------------------------------- // PATCHALL checks([ check<O.PatchAll<{}, [O, O1]>, PATCH_O_O1, Test.Pass>(), check<O.PatchAll<{}, [O, O1], 'deep'>, PATCH_O_O1_DEEP, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // PATH checks([ check<O.Path<O, ['g', 'g', 'g']>, O['g'], Test.Pass>(), check<O.Path<O, ['g', 'g', 'g', 'a']>, string, Test.Pass>(), check<O.Path<O, ['g', 'x', 'g']>, undefined, Test.Pass>(), // check<O.Path<O, []>, undefined, Test.Pass>(), check<O.Path<O, ['d']>, 'string0' | undefined, Test.Pass>(), ]) type O_PATH_U = { b: { c: { d: 'bcd'; }; b: 'bb'; }; c: 1; } | { a: { b: boolean | { c: 'abc'; }; }; c: 2; }; checks([ check<O.Path<O_PATH_U, ['c']>, 1 | 2, Test.Pass>(), check<O.Path<O_PATH_U, ['b', 'c', 'x']>, undefined, Test.Pass>(), check<O.Path<O_PATH_U, ['b', 'c', 'd']>, 'bcd' | undefined, Test.Pass>(), check<O.Path<O_PATH_U, ['a', 'b', 'c']>, 'abc' | undefined, Test.Pass>(), check<O.Path<O_PATH_U, ['a' | 'b', 'b']>, boolean | 'bb' | {c: 'abc'} | undefined, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // PATHS type O_PATHS = { a: { a: boolean; }; b: { a: { a: {}; }; b: {}; }; } | { c: boolean }; checks([ check<O.Paths<{'prop': {a: 1}[]}>, T.NonNullable<['prop'?, number?, 'a'?]>, Test.Pass>(), check<O.Paths<O_PATHS>, T.NonNullable<['a'?, 'a'?] | ['b'?, 'a'?, 'a'?] | ['b'?, 'b'?] | ['c'?]>, Test.Pass>(), check<O.Paths<O[]>, O.Paths<O[]>, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // PICK type PICK_O_DEF = { d?: 'string0'; readonly e?: 'string1'; readonly f: 0; }; checks([ check<O.Pick<O, 'd' | 'e' | 'f'>, PICK_O_DEF, Test.Pass>(), check<O.Pick<O, keyof O>, O, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // READONLY type READONLY_O_FLAT = { readonly a: string, readonly b: number; readonly c: {a: 'a'} & {b: 'b'}; readonly d?: 'string0'; readonly e?: 'string1'; readonly f: 0; readonly g: O; readonly h?: 1; readonly j: 'a' | undefined; readonly k: {a: {b: string}}; readonly x: () => 1; }; type READONLY_O_A_FLAT = { readonly a: string, b: number; c: {a: 'a'} & {b: 'b'}; d?: 'string0'; readonly e?: 'string1'; readonly f: 0; g: O; h?: 1; j: 'a' | undefined; k: {a: {b: string}}; x: () => 1; }; checks([ check<O.Readonly<O, keyof O, 'flat'>, READONLY_O_FLAT, Test.Pass>(), check<O.Readonly<O, 'a', 'flat'>, READONLY_O_A_FLAT, Test.Pass>(), check<O.Path<O.Readonly<O, 'g', 'deep'>, ['g', 'g']>, O.Readonly<O, keyof O, 'deep'>, Test.Pass>(), ]) function READONLY_GENERIC<O extends {n?: number[]}>(o: O) { const v0 = o as O.Readonly<O, Key, 'flat'> const v1 = o as O.Readonly<O, Key, 'deep'> const p0: number[] | undefined = v0.n const p1: readonly number[] | undefined = v1.n // @ts-expect-error v0.n = 1 // @ts-expect-error v1.n = 1 } // --------------------------------------------------------------------------------------- // READONLYKEYS checks([ check<O.ReadonlyKeys<O>, 'e' | 'f', Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // RECORD type RECORD_AB_A_OPTR = { readonly a?: string; readonly b?: string; }; type RECORD_AB_A_OPTW = { a?: string; b?: string; }; type RECORD_AB_A_REQR = { readonly a: string; readonly b: string; }; type RECORD_AB_A_REQW = { a: string; b: string; }; checks([ check<O.Record<'a' | 'b', string, ['?', 'R']>, RECORD_AB_A_OPTR, Test.Pass>(), check<O.Record<'a' | 'b', string, ['?', 'W']>, RECORD_AB_A_OPTW, Test.Pass>(), check<O.Record<'a' | 'b', string, ['!', 'R']>, RECORD_AB_A_REQR, Test.Pass>(), check<O.Record<'a' | 'b', string, ['!', 'W']>, RECORD_AB_A_REQW, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // REPLACE type REPLACE_STRING_NUMBER = { a: number; b: number; c: {a: 'a'} & {b: 'b'}; d?: 'string0'; readonly e?: 'string1'; readonly f: 0; g: O; h?: 1; j: 'a' | undefined; k: { a: { b: string; }; }; x: () => 1; }; checks([ check<O.Replace<O, string, number>, REPLACE_STRING_NUMBER, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // REQUIRED type REQUIRED_O_FLAT = { a: string, b: number; c: {a: 'a'} & {b: 'b'}; d: 'string0'; readonly e: 'string1'; readonly f: 0; g: O; h: 1; j: 'a' | undefined; k: {a: {b: string}}; x: () => 1; }; type REQUIRED_O_D_FLAT = { a: string, b: number; c: {a: 'a'} & {b: 'b'}; d: 'string0'; readonly e?: 'string1'; readonly f: 0; g: O; h?: 1; j: 'a' | undefined; k: {a: {b: string}}; x: () => 1; }; checks([ check<O.Required<O, keyof O, 'flat'>, REQUIRED_O_FLAT, Test.Pass>(), check<O.Required<O, 'd', 'flat'>, REQUIRED_O_D_FLAT, Test.Pass>(), check<O.Path<O.Required<O, 'g', 'deep'>, ['g', 'g']>, O.Required<O, keyof O, 'deep'>, Test.Pass>(), ]) function REQUIRED_GENERIC<O extends {n?: number[]}>(o: O) { const v0 = o as O.Required<O, Key, 'flat'> const v1 = o as O.Required<O, Key, 'deep'> const p0: number[] = v0.n const p1: number[] = v1.n } // --------------------------------------------------------------------------------------- // REQUIREDKEYS checks([ check<O.RequiredKeys<O>, 'a' | 'b' | 'c' | 'f' | 'g' | 'j' | 'k' | 'x', Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // SELECT type SELECT_O_DEFAULT = { a: string; d?: 'string0'; readonly e?: 'string1'; j: 'a' | undefined; }; type SELECT_O_EQUALS = { a: string, }; checks([ check<O.Select<O, string, 'extends->'>, SELECT_O_DEFAULT, Test.Pass>(), check<O.Select<O, string, 'equals'>, SELECT_O_EQUALS, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // SELECTKEYS type SELECTKEYS_O_DEFAULT = 'a' | 'd' | 'e' | 'j'; type SELECTKEYS_O_EQUALS = 'a'; checks([ check<O.SelectKeys<O, string, 'extends->'>, SELECTKEYS_O_DEFAULT, Test.Pass>(), check<O.SelectKeys<O, string, 'equals'>, SELECTKEYS_O_EQUALS, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // UNDEFINABLE type UNDEFINABLE_O_FLAT = { a: string | undefined; b: number | undefined; c: {a: 'a'} & {b: 'b'} | undefined; d?: 'string0'; readonly e?: 'string1'; readonly f: 0 | undefined; g: O | undefined; h?: 1; j: 'a' | undefined; k: {a: {b: string}} | undefined; x: (() => 1) | undefined; }; type UNDEFINABLE_O_A_FLAT = { a: string | undefined; b: number; c: {a: 'a'} & {b: 'b'}; d?: 'string0'; readonly e?: 'string1'; readonly f: 0; g: O; h?: 1; j: 'a' | undefined; k: {a: {b: string}}; x: () => 1; }; checks([ check<O.Undefinable<O, keyof O, 'flat'>, UNDEFINABLE_O_FLAT, Test.Pass>(), check<O.Undefinable<O, 'a', 'flat'>, UNDEFINABLE_O_A_FLAT, Test.Pass>(), check<O.Path<O.Undefinable<O, 'g', 'deep'>, ['g', 'g']>, O.Undefinable<O, keyof O, 'deep'> | undefined, Test.Pass>(), ]) function UNDEFINABLE_GENERIC<O extends {n: number}>(o: O) { const v0 = o as O.Required<O, Key, 'flat'> const v1 = o as O.Required<O, Key, 'deep'> const p0: number | undefined = v0.n const p1: number | undefined = v1.n } // --------------------------------------------------------------------------------------- // UNDEFINABLEKEYS checks([ check<O.UndefinableKeys<O>, 'd' | 'e' | 'h' | 'j', Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // UNIONIZE type O_UNIONIZE = { a: 'a'; b: 'b'; c: never; d?: 1; }; type O1_UNIONIZE = { a: 'b'; b?: 'x'; c: 42; d: {}; }; type UNIONIZE_O_O1 = { a: 'a' | 'b'; b: 'b' | 'x' | undefined; c: 42; d?: {} | 1; }; checks([ check<O.Unionize<O_UNIONIZE, O1_UNIONIZE>, UNIONIZE_O_O1, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // UNIONOF type O_UNIONOF = { a: 'a'; b: 'b'; c: never; d: 1; }; type UNIONOF_O = 'a' | 'b' | 1; checks([ check<O.UnionOf<O_UNIONOF>, UNIONOF_O, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // UPDATE type O_UPDATE = { a?: 'a'; }; type UPDATE_O = { a?: 'xxxx'; }; type UPDATE_O_X = { a?: 'a'; }; type UPDATE_O_STRING_42 = { [x: string]: 42; // @ts-ignore a?: 42 | undefined; }; checks([ check<O.Update<O_UPDATE, 'a' | 'b', 'xxxx'>, UPDATE_O, Test.Pass>(), check<O.Update<O_UPDATE, 'a' | 'b', A.x>, UPDATE_O_X, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // WRITABLE type WRITABLE_O_FLAT = { a: string, b: number; c: {a: 'a'} & {b: 'b'}; d?: 'string0'; e?: 'string1'; f: 0; g: O; h?: 1; j: 'a' | undefined; k: {a: {b: string}}; x: () => 1; }; type WRITABLE_O_E_FLAT = { a: string, b: number; c: {a: 'a'} & {b: 'b'}; d?: 'string0'; e?: 'string1'; readonly f: 0; g: O; h?: 1; j: 'a' | undefined; k: {a: {b: string}}; x: () => 1; }; checks([ check<O.Writable<O, keyof O, 'flat'>, WRITABLE_O_FLAT, Test.Pass>(), check<O.Writable<O, 'e', 'flat'>, WRITABLE_O_E_FLAT, Test.Pass>(), check<O.Path<O.Writable<O, 'g', 'deep'>, ['g', 'g']>, O.Writable<O, keyof O, 'deep'>, Test.Pass>(), ]) function WRITABLE_GENERIC<O extends {readonly n: number}>(o: O) { const v0 = o as O.Writable<O, Key, 'flat'> const v1 = o as O.Writable<O, Key, 'deep'> const p0: number = v0.n const p1: number = v1.n v0.n = 1 v1.n = 1 } // --------------------------------------------------------------------------------------- // WRITABLEKEYS checks([ check<O.WritableKeys<O>, 'a' | 'b' | 'c' | 'd' | 'g' | 'h' | 'j' | 'k' | 'x', Test.Pass>(), ]) // /////////////////////////////////////////////////////////////////////////////////////// // OBJECT.P ////////////////////////////////////////////////////////////////////////////// type OP = {// A binary tree a: { a: string; b: { a: 'aba'; b: 'abb'; }; }; b?: { a: { a: 'baa'; b: 'bab'; }; b: { a: 'bba'; b: 'bbb'; }; }; c?: string; }; type OP_UNIONS = { a: { a: string; b: { a: 'aba'; b: 'abb'; }; } | 'a'; b?: { a: { a: 'baa'; b: 'bab'; }; b: { a: 'bba'; b: 'bbb'; }; } | 'b'; c?: string; }; type OP_ARRAYS = { a: { a: string; b: { a: 'aba'; b: 'abb'; }[]; }[][]; b?: { a: { a: 'baa'; b: 'bab'; }[]; b: { a: 'bba'; b: 'bbb'; }[]; }[]; c?: string; }; type OP_ARRAYS_UNIONS = { a: { a: string; b: { a: 'aba'; b: 'abb'; }[]; }[][] | 'a'[]; b?: { a: { a: 'baa'; b: 'bab'; }[]; b: { a: 'bba'; b: 'bbb'; }[]; }[] | 'b'[][]; c?: string; }; // --------------------------------------------------------------------------------------- // P.MERGE type O_PMERGE = { a: { a: string; b: { a: 'aba'; b: 'abb'; x: string; }; }; b?: { a: { a: 'baa'; b: 'bab'; }; b: { a: 'bba'; b: 'bbb'; x: string; }; }; c?: string; }; type O_PMERGE_UNIONS = { a: { a: string; b: { a: 'aba'; b: 'abb'; x: string; }; } | 'a'; b?: { a: { a: 'baa'; b: 'bab'; }; b: { a: 'bba'; b: 'bbb'; x: string; }; } | 'b'; c?: string; }; checks([ check<O.P.Merge<OP, ['a' | 'b', 'b'], {x: string}>, O_PMERGE, Test.Pass>(), check<O.P.Merge<OP_UNIONS, ['a' | 'b', 'b'], {x: string}>, O_PMERGE_UNIONS, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // P.OMIT type O_POMIT = { a: { b: { a: 'aba'; b: 'abb'; }; }; b?: { b: { a: 'bba'; b: 'bbb'; }; }; c?: string; }; type O_POMIT_UNIONS = { a: { b: { a: 'aba'; b: 'abb'; }; } | 'a'; b?: { b: { a: 'bba'; b: 'bbb'; }; } | 'b'; c?: string; }; checks([ check<O.P.Omit<OP, ['a' | 'b', 'a']>, O_POMIT, Test.Pass>(), check<O.P.Omit<OP_UNIONS, ['a' | 'b', 'a']>, O_POMIT_UNIONS, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // P.PICK type O_PPICK = { a: { a: string; }; b?: { a: { a: 'baa'; b: 'bab'; }; }; }; type O_PPICK_UNIONS = { a: { a: string; } | 'a'; b?: { a: { a: 'baa'; b: 'bab'; }; } | 'b'; }; type O_PPICK_AUTOPATH = { a: { a: string; b: { a: 'aba'; b: 'abb'; }; }; } | { a: { a: string; }; } | { b?: { a: { b: 'bab'; }; } | undefined; } const o_ppick_autopath = pick({} as OP, ['a', 'a.a', 'b.a.b']) declare function pick<T extends Record<string, any>, K extends string>( obj: T, keys: F.AutoPath<T, K>[] ): A.Compute<O.P.Pick<T, S.Split<K, '.'>>> checks([ check<O.P.Pick<OP, ['a' | 'b', 'a']>, O_PPICK, Test.Pass>(), check<O.P.Pick<OP_UNIONS, ['a' | 'b', 'a']>, O_PPICK_UNIONS, Test.Pass>(), check<typeof o_ppick_autopath, O_PPICK_AUTOPATH, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // P.READONLY type O_PREADONLY = { a: { readonly a: string; b: { a: 'aba'; b: 'abb'; }; }; b?: { readonly a: { a: 'baa'; b: 'bab'; }; b: { a: 'bba'; b: 'bbb'; }; }; c?: string; }; type O_PREADONLY_UNIONS = { a: { readonly a: string; b: { a: 'aba'; b: 'abb'; }; } | 'a'; b?: { readonly a: { a: 'baa'; b: 'bab'; }; b: { a: 'bba'; b: 'bbb'; }; } | 'b'; c?: string; }; checks([ check<O.P.Readonly<OP, ['a' | 'b', 'a']>, O_PREADONLY, Test.Pass>(), check<O.P.Readonly<OP_UNIONS, ['a' | 'b', 'a']>, O_PREADONLY_UNIONS, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // P.UPDATE type O_PUPDATE = { a: { a: 'x'; b: { a: 'aba'; b: 'abb'; }; }; b?: { a: 'x'; b: { a: 'bba'; b: 'bbb'; }; }; c?: string; }; type O_PUPDATE_UNIONS = { a: 'a' | { a: 'x'; b: { a: 'aba'; b: 'abb'; }; }, b?: 'b' | { a: 'x'; b: { a: 'bba'; b: 'bbb'; }; }, c?: string; }; type O_PUPDATE_VPATH = { a: 'a' | { a: string; b: { a: 'aba'; b: 'abb'; }; }; b?: 'b' | { a: { a: 'baa'; b: 'bab'; }; b: { a: 'bba'; b: 'bbb'; }; }; c?: string; }; checks([ check<O.P.Update<OP, ['a' | 'b', 'a'], 'x'>, O_PUPDATE, Test.Pass>(), check<O.P.Update<OP_UNIONS, ['a' | 'b', 'a'], 'x'>, O_PUPDATE_UNIONS, Test.Pass>(), check<O.P.Update<OP_UNIONS, ['a' | 'b' | 'c', 'a', 'a', 'a'], 'x'>, O_PUPDATE_VPATH, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // P.RECORD type RECORD_ABCD_STRING_OPTR = { readonly a?: { readonly b?: { readonly d?: string; }; readonly c?: { readonly d?: string; }; }; }; type RECORD_ABCD_STRING_OPTW = { a?: { b?: { d?: string; }; c?: { d?: string; }; }; }; type RECORD_ABCD_STRING_REQR = { readonly a: { readonly b: { readonly d: string; }; readonly c: { readonly d: string; }; }; }; type RECORD_ABCD_STRING_REQW = { a: { b: { d: string; }; c: { d: string; }; }; }; checks([ check<O.P.Record<['a', 'b' | 'c', 'd'], string, ['?', 'R']>, RECORD_ABCD_STRING_OPTR, Test.Pass>(), check<O.P.Record<['a', 'b' | 'c', 'd'], string, ['?', 'W']>, RECORD_ABCD_STRING_OPTW, Test.Pass>(), check<O.P.Record<['a', 'b' | 'c', 'd'], string, ['!', 'R']>, RECORD_ABCD_STRING_REQR, Test.Pass>(), check<O.P.Record<['a', 'b' | 'c', 'd'], string, ['!', 'W']>, RECORD_ABCD_STRING_REQW, Test.Pass>(), ])
the_stack
module TDev.RT { //? A picture //@ stem("pic") icon("fa-file-image-o") walltap enumerable export class Picture extends RTValue { // keep track of the original url, until the context is modified in any fashion // since the URL might contain access tokens, it should never be leaked to the user private _url: string; private _cors: boolean; private canvas : HTMLCanvasElement; private ctx : CanvasRenderingContext2D; private _date : DateTime = undefined; private _location: Location_ = undefined; // might be cached private _isResource: boolean = false; private _isReadOnly: boolean = false; private imageData : ImageData = null; private imageDataHasChanges = false; private fitToColumn = false; private initFn:(p:Picture)=>Promise; private initPromise:Promise; constructor() { super() } public clearUrl() { this._url = undefined; } public getReadonlyUrlSync() { if (this._isReadOnly && this._url && !this.canvas && !/^data:/.test(this._url)) return this._url; return undefined; } public getUrlAsync(): Promise { var url = this.getReadonlyUrlSync(); if (url) return Promise.as(url); return this.getDataUriAsync(); } public getDataUriAsync(quality: number = 0.95, maxWidth : number = -1): Promise { return this.initAsync() .then(() => { this.commitImageData(); return this.getDataUri(quality, maxWidth); }); } public getImageElement(): HTMLImageElement { if (this._isReadOnly && this._url && !this.canvas) { Util.log("img: direct display " + this._url.slice(0, 100)); var img = <HTMLImageElement>createElement("img"); img.src = this._url; img.alt = this._url; return img; } return undefined; } public getDataUri(quality: number = 0.9, maxWidth: number = -1, forceJpeg = false): string { this.commitImageData(); var c = this.getCanvas(); // dealing with empty image if (c.width == 0 || c.height == 0) { // create a 1x1 image to avoid a bogus data uri c = <HTMLCanvasElement>document.createElement('canvas'); c.width = 1; c.height = 1; } if (maxWidth > 0 && c.width > maxWidth) { var temp = <HTMLCanvasElement>document.createElement('canvas'); temp.width = maxWidth; temp.height = maxWidth / c.width * c.height; var tempCtx = temp.getContext("2d"); tempCtx.drawImage(c, 0, 0, c.width, c.height, 0, 0, temp.width, temp.height); c = temp; } if (quality >= 1 && !forceJpeg) return c.toDataURL('image/png'); else return c.toDataURL('image/jpeg', quality); } static mk(w:number, h:number) : Picture { var p = new Picture(); p.initFn = () => { p._init(w, h); return Promise.as(); }; return p; } static mkSync(w:number, h:number) : Picture { var p = new Picture(); p.initPromise = Promise.as(); p._init(w, h); return p; } private imgLoadAsync(url : string, cors : boolean, dataUrl : string = null): Promise { var rt = Runtime.theRuntime; var auth = (!dataUrl && cors && !Cloud.isArtUrl(url)) ? Cloud.authenticateAsync(lf("image proxying")) : Promise.as(true); return auth.then((authenticated) => { // ask wab to expand urls Util.log('picture load: 0'); if (dataUrl) { Util.log('picture load: dataurl, skipping wab request'); return undefined; } else return Media.pictureDataUriAsync(url); }).then(d => { // update data url as needed if (!dataUrl && d) { Util.log('picture: updated dataurl'); dataUrl = d; } return new Promise((onSuccess: (v: any) => any, onError: (v: any) => any, onProgress: (v: any) => any) => { Util.log('picture: loading'); var img = <HTMLImageElement> document.createElement("img"); img.onload = () => { Util.log('picture: loaded ' + img.width + 'x' + img.height); this._init(img.width, img.height); this._url = url; this._cors = cors; this.ctx.drawImage(img, 0, 0); img = null; dataUrl = null; href = null; onSuccess(this); }; img.onerror = () => { Util.log('picture: failed to load'); this._init(480, 480); this._url = url; this._cors = cors; this.ctx.save(); this.ctx.fillStyle = "lightgray"; this.ctx.fillRect(0, 0, 480, 480); this.ctx.fillStyle = "white"; this.ctx.textAlign = "center"; this.ctx.textBaseline = "top"; this.ctx.font = "240px sans-serif"; this.ctx.fillText(':(', 240, 60); this.ctx.font = "42px sans-serif"; this.ctx.fillText('picture failed to load', 240, 360); this.ctx.restore(); img = null; dataUrl = null; href = null; onSuccess(this); }; //(<any>img).crossOrigin = 'anonymous'; // attempt to thwart cross origin pixel security http://blog.chromium.org/2011/07/using-cross-domain-images-in-webgl-and.html var href = dataUrl ? dataUrl : cors ? Web.proxy(Cloud.toCdnUrl(url)) : url; img.src = href; img.alt = url; }) }); } private delayLoadSync(f: (p: Picture) => Promise): Picture { this.initFn = f; return this; } private delayLoad(f: (p: Picture) => Promise): Promise { this.delayLoadSync(f); return Promise.as(this); } static delayed(f:(p:Picture)=>Promise):Promise { return new Picture().delayLoad(f); } static fromImage(img: HTMLImageElement): Picture { var p = Picture.mkSync(img.width, img.height); p.ctx.save(); p.ctx.drawImage(img, 0, 0, img.width, img.height); p.ctx.restore(); return p; } static fromCanvas(canvas : HTMLCanvasElement) : Picture { var p = Picture.mkSync(canvas.width, canvas.height); p.ctx.save(); p.ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height); p.ctx.restore(); return p; } static fromDataUrl(dataUrl:string, originalUrl : string = null, isResource = false) : Promise { if (!dataUrl) return Promise.as(null); Util.log('picture: loading from dataurl'); Util.check(/^data:image\/(jpeg|png|svg\+xml);base64,/i.test(dataUrl)); var img = new Picture(); img._isResource = isResource; img._isReadOnly = isResource; return img.delayLoad((p) => p.imgLoadAsync(originalUrl, false, dataUrl)); } static fromUrlSync(url: string, isReadOnly = false, cors = true): Picture { var img = new Picture(); img._url = url; img._isResource = false; img._isReadOnly = isReadOnly; return img.delayLoadSync(p => p.loadAsync(url, cors)); } static fromUrl(url: string, isReadOnly = false, cors = true): Promise { return Promise.as(Picture.fromUrlSync(url, isReadOnly, cors)); } // specialized in various platforms static patchLocalArtUrl(url : string) : string { return url; } static fromArtUrl(url:string) : Promise { // make sure to avoid loading a data url if (/^data:image\/(jpeg|png|svg\+xml);base64,/i.test(url)) return Picture.fromDataUrl(url, undefined, true); var cors = true; // update local art as needed if (/^\.\/art\//.test(url)) { url = Picture.patchLocalArtUrl(url); cors = false; // no CORS needed } return ArtCache.getArtAsync(url, "image/*") .then(() => { Util.log('picture: fromArtUrl delayed'); var img = new Picture(); img._url = url; img._isResource = true; img._isReadOnly = true; return img.delayLoad((p) => p.loadAsync(url, cors)); }) } private loadAsync(url: string, cors : boolean) { // do not test for CORS with data urls if (/^data:image\/(jpeg|png|svg\+xml);base64,/i.test(url)) return this.imgLoadAsync(url, false, url); // caching? if (this._isResource || Cloud.isArtUrl(url)) return ArtCache.getArtAsync(url, "image/*") .then(dataUrl => this.imgLoadAsync(url, cors, dataUrl)); // default load return this.imgLoadAsync(url, cors); } static fromSVGIcon(name:string, sz:number) { var p = Picture.mkSync(sz, sz); p.ctx.save(); var scale = sz/480; p.ctx.fillStyle = "white"; p.ctx.scale(scale, scale); SVG.drawSVG(p.ctx, name); p.ctx.restore(); p.fitToColumn = false; return p; } private _init(w:number, h:number) { w = Math.round(w); h = Math.round(h); this.slowlyloadingelement = undefined; this.canvas = <HTMLCanvasElement>document.createElement("canvas"); this.canvas.width = w; this.canvas.height = h; this.ctx = this.canvas.getContext("2d"); } private commitImageData() { if (this.imageDataHasChanges) { this.imageDataHasChanges = false; this.ctx.putImageData(this.imageData, 0, 0); } } private changed(invalidateData = true) { if (this._isReadOnly) TDev.Util.userError(lf("This picture cannot be modified. Use 'clone' to get a copy of the picture that can be modified.\n\n var pic := \u273fmy art->clone")); if (invalidateData) { this.commitImageData(); this.imageData = null; } this.versioncounter++; this._url = undefined; // image modified, forget about url } public getImageData() : ImageData { Util.assert(!!this.ctx); if (!this.imageData) this.imageData = this.ctx.getImageData(0, 0, this.widthSync(), this.heightSync()); return this.imageData; } public hasCanvas() { return !!this.canvas; } public widthSync():number { return this.canvas.width; } public heightSync():number { return this.canvas.height; } public getCanvas() : HTMLCanvasElement { Util.assert(!!this.canvas); return this.canvas; } //? Gets the number of pixels //@ readsMutable returns(number) //@ picAsync public count(r:ResumeCtx) { this.loadFirst(r, () => { return this.canvas.width * this.canvas.height; }); } //? Gets the date time where the picture was taken; if any. //@ readsMutable returns(DateTime) //@ picAsync public date(r:ResumeCtx) { this.loadFirst(r, () => { return this._date; }); } //? Gets the height in pixels //@ readsMutable returns(number) //@ picAsync public height(r:ResumeCtx) { this.loadFirst(r, () => { return this.canvas.height; }); } //? Checks if the picture is the same instance as the other picture. This action does not check that pixels are the same between two different pictures. public equals(other_picture: Picture) : boolean { return this == other_picture; } //? Indicates if the picture width is greater than its height //@ readsMutable returns(boolean) //@ picAsync public is_panorama(r:ResumeCtx) { this.loadFirst(r, () => { return this.canvas.width > this.canvas.height; }); } //? Gets the location where the picture was taken; if any. //@ flow(SourceGeoLocation) returns(Location_) //@ readsMutable //@ picAsync public location(r:ResumeCtx) { this.loadFirst(r, () => { return this._location; }); } //? Gets the width in pixels //@ readsMutable returns(number) //@ picAsync public width(r:ResumeCtx) { this.loadFirst(r, () => { return this.canvas.width; }); } //? Refreshes the picture on the wall //@ readsMutable public update_on_wall() : void { if (this.imageData) this.ctx.putImageData(this.imageData, 0, 0); //commitImageData(); } //? Gets the pixel color at the given linear index //@ readsMutable returns(Color) //@ picAsync public at(index:number, r:ResumeCtx) { this.loadFirst(r, () => { if (isNaN(index)) return Colors.transparent(); index = Math.round(index); index *= 4; var id = this.getImageData(); if (index < 0 || index >= id.data.length) return Colors.transparent(); return Color.fromArgb(id.data[index+3], id.data[index], id.data[index+1], id.data[index+2]); }); } public initAsync() : Promise { if (this.initPromise) return this.initPromise; var f = this.initFn; if (f) { this.initFn = null; this.initPromise = f(this); this.initPromise.done(() => { this.initPromise = null; }) if (this.initPromise) return this.initPromise; } return Promise.as(); } public loadFirst(r:ResumeCtx, f:()=>any):void { Util.assert(!!r); // fail early if no resume ctx if (!this.initPromise && !this.initFn) { //Util.log('picture: sync load'); if (!f) r.resume(); else r.resumeVal(f()); } else { //Util.log('picture: async load'); this.initAsync().done(() => { if (!f) r.resume(); else r.resumeVal(f()); }) } } private atPosition(r:ResumeCtx, left:number, top:number, angle:number, opacity:number, f:() => void):void { this.loadFirst(r, () => { this.changed(); this.ctx.save(); this.ctx.translate(left, top); this.ctx.rotate(angle / 180 * Math.PI); this.ctx.globalAlpha = Math_.normalize(opacity); f(); this.ctx.restore(); }) } //? Writes another picture at a given location. The opacity ranges from 0 (transparent) to 1 (opaque). //@ writesMutable [other].readsMutable //@ [opacity].defl(1) //@ picAsync public blend(other: Picture, left: number, top: number, angle: number, opacity: number, r:ResumeCtx): void { opacity = Math_.normalize(opacity); this.atPosition(r, left, top, angle, opacity, () => { other.initAsync().done(() => this.ctx.drawImage(other.getCanvas(), 0, 0)) }); } //? Returns a copy of the image //@ readsMutable [result].writesMutable returns(Picture) //@ picAsync public clone(r:ResumeCtx) { this.loadFirst(r, () => { this.commitImageData(); var p = Picture.mkSync(this.widthSync(), this.heightSync()); p.ctx.drawImage(this.canvas, 0, 0); p._url = this._url; p._cors = this._cors; p._date = this._date; p._location = this._location; return p; }); } //? Fills a rectangle with a given color //@ writesMutable //@ [width].defl(100) [height].defl(100) [angle].defl(0) [color].deflExpr('colors->accent') //@ picAsync public fill_rect(left:number, top:number, width:number, height:number, angle:number, color:Color, r:ResumeCtx) : void { this.atPosition(r, left, top, angle, color.A(), () => { this.ctx.fillStyle = color.toHtml(); this.ctx.fillRect(0, 0, width, height); }); } //? Gets the pixel color //@ readsMutable returns(Color) //@ picAsync public pixel(left: number, top: number, r:ResumeCtx) { this.initAsync().done(() => { left = Math.round(left); top = Math.round(top); this.at(left + top * this.widthSync(), r); }); } public getViewCanvasClone(): HTMLCanvasElement { this.commitImageData(); // Create a deep copy of the canvas to allow multiple pictures at once var rc = <HTMLCanvasElement>document.createElement("canvas"); rc.width = this.widthSync(); rc.height = this.heightSync(); var rx = rc.getContext("2d"); rx.drawImage(this.canvas, 0, 0); return rc; } public getViewCanvas(): HTMLCanvasElement { this.commitImageData(); if (this.canvas.parentElement || LayoutMgr.RenderExecutionMode()) { // Create a deep copy of the canvas to allow multiple pictures at once var rc = <HTMLCanvasElement>document.createElement("canvas"); rc.width = this.widthSync(); rc.height = this.heightSync(); var rx = rc.getContext("2d"); rx.drawImage(this.canvas, 0, 0); this.canvas = rc; this.ctx = rx; this.slowlyloadingelement = undefined; } this.fitToColumn = !LayoutMgr.RenderExecutionMode(); if (this.fitToColumn && this.heightSync() > 0 && this.widthSync() > 0) { var r = this.heightSync() / this.widthSync(); var colwidth = SizeMgr.getColumnWidth(); if (this.widthSync() > colwidth) { this.canvas.style.width = colwidth + "px"; this.canvas.style.height = (colwidth * r) + "px"; } } return this.canvas; } private slowlyloadingelement: HTMLElement; public getViewCore(s: IStackFrame, b: BoxBase): HTMLElement { var r = div("viewPicture"); var img = this.getImageElement(); if (img) { img.setAttribute('class', 'wall-picture'); this.slowlyloadingelement = img; return img; } else { this.slowlyloadingelement = undefined; this.initAsync().done(() => { this.commitImageData(); r.setChildren(this.getViewCanvas()); b.RefreshOnScreen(); }); } return r; } public updateViewCore(s: IStackFrame, b: BoxBase) { if (LayoutMgr.RenderExecutionMode() && this.slowlyloadingelement) { this.slowlyloadingelement.onload = () => { //Util.log("onload"); if (this.slowlyloadingelement.offsetParent) { // element is already in DOM... remove and reinsert element so it does resize var c = this.getViewCore(s, b); c.onload = () => { b.RefreshOnScreen(); } c.onerror = () => { b.SwapImageContent(Picture.errorPic()); } b.SwapImageContent(c); } else { b.RefreshOnScreen(); } } this.slowlyloadingelement.onerror = () => { // Util.log("onerror") b.SwapImageContent(Picture.errorPic()); } } } static errorPic(): HTMLElement { // Util.log("onerror") var frowny = div(null, ":("); var msg = div(null, lf("picture failed to load")); var rect = div(null, frowny, document.createElement("br"), msg); rect.style.background = "lightgray"; rect.style.fontFamily = "sans-serif"; rect.style.color = "white"; frowny.style.fontSize = "240px"; msg.style.marginBottom = "1em"; msg.style.marginLeft = "1em"; msg.style.fontSize = "42px"; rect.style.height = "480px"; rect.style.width = "480px"; return rect; } //? Resizes the picture to the given size in pixels //@ writesMutable //@ [width].defl(100) [height].defl(-1) //@ picAsync public resize(width:number, height:number, r:ResumeCtx) : void { this.loadFirst(r, () => { this.changed(); width = Math.round(width); height = Math.round(height); if (width < 1) width = Math.floor(this.widthSync() / this.heightSync() * height); if (height < 1) height = Math.floor(this.heightSync() / this.widthSync() * width); if (width == this.widthSync() && height == this.heightSync()) return; var ow = this.widthSync(); var oh = this.heightSync(); // clone canvas var temp = <HTMLCanvasElement>document.createElement('canvas'); temp.width = ow; temp.height = oh; var tempCtx = temp.getContext("2d"); tempCtx.drawImage(this.canvas, 0, 0, ow, oh); // resize and draw this.canvas.width = width; this.canvas.height = height; this.ctx.save(); this.ctx.drawImage(temp, 0, 0, ow, oh, 0, 0, width, height); this.ctx.restore(); }); } //? Saves the picture and returns the file name if successful. //@ flow(SinkMedia) returns(string) //@ readsMutable ignoreReturnValue //@ async public save_to_library(r:ResumeCtx) // : string { HTML.showProgressNotification(lf("saving picture")); this.loadFirst(r, () => { var defaultName = Picture.niceFilename() + ".png"; if ((<any>window).navigator.msSaveOrOpenBlob) { try { var result = (<any>window).navigator.msSaveOrOpenBlob(this.canvas.msToBlob(), defaultName); return defaultName; } catch(e) { HTML.showProgressNotification(lf("saving picture failed...")); return ""; } } else { var url = this.canvas.toDataURL('image/png'); HTML.browserDownload(url, Util.toFileName(defaultName, 'pic')); } return defaultName; }); } //? Clears the picture to a given color //@ writesMutable //@ [color].deflExpr('colors->transparent') //@ picAsync public clear(color:Color, r:ResumeCtx) : void { this.loadFirst(r, () => { this.changed(); this.ctx.save(); this.ctx.clearRect(0, 0, this.widthSync(), this.heightSync()); this.ctx.fillStyle = color.toHtml(); this.ctx.fillRect(0, 0, this.widthSync(), this.heightSync()); this.ctx.restore(); }); } //? Clears a rectangle on a the picture to a given color //@ writesMutable //@ [color].deflExpr('colors->transparent') [width].defl(10) [height].defl(10) //@ picAsync public clear_rect(color: Color, left: number, top: number, width: number, height: number, r: ResumeCtx): void { if (isNaN(left) || isNaN(top) || isNaN(width) || isNaN(height) || width <= 0 || height <= 0) { r.resume(); } else { this.loadFirst(r, () => { this.changed(); this.ctx.save(); this.ctx.clearRect(left, top, width, height); this.ctx.fillStyle = color.toHtml(); this.ctx.fillRect(left, top, width, height); this.ctx.restore(); }); } } public eraseWhiteBackgroundAsync() : Promise { return this.initAsync() .then(() => { this.changed(); this.ctx.save(); var data = this.ctx.getImageData(0, 0, this.widthSync(), this.heightSync()); var p = data.data; var threshold = 25; for (var i = 0; i < p.length; i+=4) { var dr = 255 - p[i]; var dg = 255 - p[i+1]; var db = 255 - p[i+2]; if (dr < threshold && dg < threshold && db < threshold) { p[i + 3] = Math.floor((dr + dg + db) / (3 * threshold) * 255); } } this.ctx.putImageData(data, 0, 0); this.ctx.restore(); }); } //? Recolors the picture with the background and foreground color, based on a color threshold between 0.0 and 1.0 //@ writesMutable //@ [background].deflExpr('colors->accent') [foreground].deflExpr('colors->background') [threshold].defl(0.65) //@ picAsync public colorize(background:Color, foreground:Color, threshold:number, r:ResumeCtx) : void { this.loadFirst(r, () => { this.changed(); this.ctx.save(); var data = this.ctx.getImageData(0, 0, this.widthSync(), this.heightSync()); var p = data.data; var ba = background.a; var br = background.r; var bg = background.g; var bb = background.b; var fa = foreground.a; var fr = foreground.r; var fg = foreground.g; var fb = foreground.b; var threshold255 = 255 * Math_.normalize(threshold) * 3; for (var i = 0; i < p.length; i+=4) { var k = (p[i] + p[i+1] + p[i+2]); var isb = k < threshold255; // apply tint p[i] = isb ? br : fr; p[i + 1] = isb ? bg : fg; p[i + 2] = isb ? bb : fb; p[i + 3] = isb ? ba : fa; } this.ctx.putImageData(data, 0, 0); this.ctx.restore(); }); } //? Inverts the colors in the picture //@ writesMutable //@ picAsync public negative(r : ResumeCtx) : void { this.loadFirst(r, () => { this.changed(); this.ctx.save(); var data = this.ctx.getImageData(0, 0, this.widthSync(), this.heightSync()); var p = data.data; for (var i = 0; i < p.length; i+=4) { p[i] = 255 - p[i]; p[i+1] = 255 - p[i+1]; p[i+2] = 255 - p[i+2]; } this.ctx.putImageData(data, 0, 0); this.ctx.restore(); }); } //? Makes picture monochromatic (black and white) //@ writesMutable //@ picAsync public desaturate(r:ResumeCtx) : void { this.loadFirst(r, () => { this.changed(); this.ctx.save(); var data = this.ctx.getImageData(0, 0, this.widthSync(), this.heightSync()); var p = data.data; for (var i = 0; i < p.length; i+=4) { var k = (p[i] + p[i+1] + p[i+2])/3; // apply tint p[i] = k; p[i+1] = k; p[i+2] = k; } this.ctx.putImageData(data, 0, 0); this.ctx.restore(); }); } //? Inverts the red, blue and green channels //@ writesMutable //@ picAsync public invert(r:ResumeCtx) : void { this.loadFirst(r, () => { this.changed(); this.ctx.save(); var data = this.ctx.getImageData(0, 0, this.widthSync(), this.heightSync()); var p = data.data; for (var i = 0; i < p.length; i+=4) { p[i] = 255-p[i]; p[i+1] = 255-p[i+1]; p[i+2] = 255-p[i+2]; } this.ctx.putImageData(data, 0, 0); this.ctx.restore(); }); } //? Converts every pixel to gray and tints it with the given color. //@ writesMutable //@ [color].deflExpr('colors->sepia') //@ picAsync public tint(color:Color, r:ResumeCtx) : void { this.loadFirst(r, () => { var tint = color; this.changed(); var ta = tint.A(); var tr = tint.R(); var tg = tint.G(); var tb = tint.B(); this.ctx.save(); var data = this.ctx.getImageData(0, 0, this.widthSync(), this.heightSync()); var p = data.data; // see Digital video and HDTV: algorithms and interfaces for (var i = 0; i < p.length; i+=4) { var a = p[i+3]; var r = p[i]; var g = p[i+1]; var b = p[i+2];; // convert to gray with constant factors according to luminance contribution // of each color channel, 0.2126 - 0.7152 - 0.0722 var gray = (r * 0.2126 + g * 0.7152 + b * 0.0722); // apply tint a = a * ta; r = gray * tr; g = gray * tg; b = gray * tb; p[i+3] = a; p[i] = r; p[i+1] = g; p[i+2] = b; } this.ctx.putImageData(data, 0, 0); this.ctx.restore(); }); } //? Changes the brightness of the picture. factor in [-1, 1]. //@ writesMutable //@ [factor].defl(0.05) //@ picAsync public brightness(factor:number, r:ResumeCtx) : void { this.loadFirst(r, () => { this.changed(); // see Digital video and HDTV: algorithms and interfaces // brightness is a translation of pixels var f = factor < -1.0 ? -1.0 : factor > 1.0 ? 1.0 : factor; var fi = f * 255; this.ctx.save(); var data = this.ctx.getImageData(0, 0, this.widthSync(), this.heightSync()); var p = data.data; for (var i = 0; i < p.length; i+=4) { var r = p[i]; var g = p[i+1]; var b = p[i+2];; var ri = r + fi; var gi = g + fi; var bi = b + fi; r = ri > 255 ? 255 : (ri < 0 ? 0 : ri); g = gi > 255 ? 255 : (gi < 0 ? 0 : gi); b = bi > 255 ? 255 : (bi < 0 ? 0 : bi); p[i] = r; p[i+1] = g; p[i+2] = b; } this.ctx.putImageData(data, 0, 0); this.ctx.restore(); }); } //? Changes the contrast of the picture. factor in [-1, 1]. //@ writesMutable //@ [factor].defl(0.05) //@ picAsync public contrast(factor:number, r:ResumeCtx) : void { this.loadFirst(r, () => { this.changed(); // see Digital video and HDTV: algorithms and interfaces // contrast is a scaling of pixels var f = factor < -1.0 ? -1.0 : factor > 1.0 ? 1.0 : factor; var cfi = 1 + f; this.ctx.save(); var data = this.ctx.getImageData(0, 0, this.widthSync(), this.heightSync()); var p = data.data; for (var i = 0; i < p.length; i+=4) { var r = p[i]; var g = p[i+1]; var b = p[i+2];; var ri = r - 128; var gi = g - 128; var bi = b - 128; ri = ri * cfi; gi = gi * cfi; bi = bi * cfi; ri = ri + 128; gi = gi + 128; bi = bi + 128; r = ri > 255 ? 255 : (ri < 0 ? 0 : ri); g = gi > 255 ? 255 : (gi < 0 ? 0 : gi); b = bi > 255 ? 255 : (bi < 0 ? 0 : bi); p[i] = r; p[i+1] = g; p[i+2] = b; } this.ctx.putImageData(data, 0, 0); this.ctx.restore(); }); } //? Crops a sub-image //@ writesMutable //@ picAsync public crop(left:number, top:number, width:number, height:number, r:ResumeCtx) : void { this.loadFirst(r, () => { var ileft = Math.round(left); var itop = Math.round(top); var iwidth = Math.round(width); var iheight = Math.round(height); if (this.widthSync() == 0 || this.heightSync() == 0) return; // nothing to crop // make sure parameters are in bounds if (ileft < 0) ileft = 0; else if (ileft >= this.widthSync()) ileft = this.widthSync() - 1; if (itop < 0) itop = 0; else if (itop >= this.heightSync()) itop = this.heightSync() - 1; if (ileft + iwidth > this.widthSync()) iwidth = this.widthSync() - ileft; if (itop + iheight > this.heightSync()) iheight = this.heightSync() - itop; this.cropInternal(ileft, itop, iwidth, iheight); }); } private cropInternal(left:number, top:number, cwidth:number, cheight:number) : void { Util.assertCode(left >= 0 && left < this.widthSync()); Util.assertCode(top >= 0 && top < this.heightSync()); Util.assertCode(cwidth >= 0 && left + cwidth <= this.widthSync()); Util.assertCode(cheight >= 0 && top + cheight <= this.heightSync()); this.changed(); var imageData: ImageData = undefined; if (cwidth > 0 && cheight > 0) imageData = this.ctx.getImageData(left, top, cwidth, cheight); this.canvas.width = cwidth; this.canvas.height = cheight; this.ctx = this.canvas.getContext("2d"); if (imageData) this.ctx.putImageData(imageData, 0, 0); } //? Draws an elliptic border with a given color //@ writesMutable //@ [width].defl(100) [height].defl(100) [angle].defl(0) [c].deflExpr('colors->accent') [thickness].defl(3) //@ picAsync public draw_ellipse(left:number, top:number, width:number, height:number, angle:number, c:Color, thickness:number, r:ResumeCtx) : void { if (isNaN(thickness) || thickness < 0) thickness = 2.0; this.atPosition(r, left+width/2, top+height/2, angle, c.A(), () => { this.ctx.scale(width/height, 1); this.ctx.strokeStyle = c.toHtml(); this.ctx.lineWidth = thickness; this.ctx.beginPath(); this.ctx.arc(0,0,height/2, 0, 2*Math.PI); this.ctx.stroke(); }); } //? Draws a line between two points //@ writesMutable //@ [color].deflExpr('colors->accent') [thickness].defl(3) //@ picAsync public draw_line(x1:number, y1:number, x2:number, y2:number, color:Color, thickness:number, r:ResumeCtx) : void { if (isNaN(thickness) || thickness < 0) thickness = 2.0; this.atPosition(r, 0, 0, 0, color.A(), () => { this.ctx.beginPath(); this.ctx.strokeStyle = color.toHtml(); this.ctx.lineWidth = thickness; this.ctx.moveTo(x1, y1) this.ctx.lineTo(x2, y2); this.ctx.stroke(); }); } //? Draws a rectangle border with a given color //@ writesMutable //@ [width].defl(100) [height].defl(100) [angle].defl(0) [color].deflExpr('colors->accent') [thickness].defl(3) //@ picAsync public draw_rect(left:number, top:number, width:number, height:number, angle:number, color:Color, thickness:number, r:ResumeCtx) : void { if (isNaN(thickness) || thickness < 0) thickness = 2.0; this.atPosition(r, left, top, angle, color.A(), () => { this.ctx.strokeStyle = color.toHtml(); this.ctx.lineWidth = thickness; this.ctx.strokeRect(0, 0, width, height); }); } //? Draws some text border with a given color and font size //@ writesMutable //@ [font_size].defl(16) [angle].defl(0) [color].deflExpr('colors->foreground') //@ picAsync public draw_text(left:number, top:number, text:string, font_size:number, angle:number, color:Color, r:ResumeCtx) : void { this.atPosition(r, left, top, angle, color.A(), () => { this.ctx.fillStyle = color.toHtml(); this.ctx.font = font_size + "px sans-serif"; this.ctx.textBaseline = "top"; this.ctx.fillText(text, 0, 0); }); } //? Fills a ellipse with a given color //@ writesMutable //@ [width].defl(100) [height].defl(100) [angle].defl(0) [color].deflExpr('colors->random') //@ picAsync public fill_ellipse(left:number, top:number, width:number, height:number, angle:number, color:Color, r:ResumeCtx) : void { this.atPosition(r, left+width/2, top+height/2, angle, color.A(), () => { this.ctx.scale(width/height, 1); this.ctx.strokeStyle = color.toHtml(); this.ctx.fillStyle = color.toHtml(); this.ctx.beginPath(); this.ctx.arc(0,0,height/2, 0, 2*Math.PI); this.ctx.fill(); }); } //? Draws a path with a given color. //@ writesMutable //@ [angle].defl(0) [color].deflExpr('colors->random') //@ picAsync public draw_path(left : number, top : number, angle : number, color:Color, thickness : number, data : string, r : ResumeCtx) : void { this.atPosition(r, left, top, angle, color.A(), () => { var parts = data.split(' '); this.ctx.strokeStyle = color.toHtml(); this.ctx.lineWidth = thickness; this.ctx.beginPath(); Picture.parsePathData(this.ctx, data); this.ctx.stroke(); }); } //? Fills a path with a given color. //@ writesMutable //@ [angle].defl(0) [color].deflExpr('colors->random') //@ picAsync public fill_path(left : number, top : number, angle : number, color:Color, data : string, r : ResumeCtx) : void { this.atPosition(r, left, top, angle, color.A(), () => { this.ctx.strokeStyle = color.toHtml(); this.ctx.fillStyle = color.toHtml(); this.ctx.beginPath(); Picture.parsePathData(this.ctx, data); this.ctx.fill(); }); } static parseSvg(xml : string, width : number, height : number) : HTMLCanvasElement { try { var svg = XmlObject.mk(xml); if (!svg || svg.name() != "svg") return null; var svgWidth = parseFloat(svg.attr("width")); var svgHeight = parseFloat(svg.attr("height")); if (height < 0) height = width / svgWidth * svgHeight; else if (width < 0) width = height / svgHeight * svgWidth; var canvas = <HTMLCanvasElement>document.createElement("canvas"); canvas.width = width; canvas.height = height; var ctx = canvas.getContext("2d"); ctx.scale(width / svgWidth, height / svgHeight); var g = svg.child("g"); if (!g) return null; var transform = g.attr("transform"); var m = /matrix\(([^)]+)\)/.exec(transform); if (m) { var v = m[1].split(/[, ]/).map(p => parseFloat(p)); ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]); } var paths = g.children(''); ctx.fillStyle = 'none'; ctx.strokeStyle = 'none'; for(var i = 0; i < paths.count(); ++i) { var path = paths.at(i); ctx.save(); switch(path.name()) { case 'path': ctx.beginPath(); if(!Picture.parsePathData(ctx, path.attr('d'))) return null; Picture.parsePathStyle(ctx, path); break; case 'polygon': ctx.beginPath(); if(!Picture.parsePolygonData(ctx, path.attr('points'))) return null; ctx.closePath(); Picture.parseFillStyle(ctx, path); Picture.parseStrokeStyle(ctx, path); break; case 'line': ctx.moveTo(parseFloat(path.attr('x1')), parseFloat(path.attr('y1'))); ctx.lineTo(parseFloat(path.attr('x2')), parseFloat(path.attr('y2'))); Picture.parseStrokeStyle(ctx,path); break; case 'rect': ctx.rect(parseFloat(path.attr('x')), parseFloat(path.attr('y')), parseFloat(path.attr('width')), parseFloat(path.attr('height'))) Picture.parseFillStyle(ctx, path); Picture.parseStrokeStyle(ctx, path); break; default: Util.log('svg rendering: unsupported command ' + path.name()); return null; } ctx.restore(); } return canvas; } catch(e) { return null; } } static parsePolygonData(ctx : CanvasRenderingContext2D , data : string) { if (!data) return false; var points = data.split(' ').map(p => p.split(',').map(x => parseFloat(x))); for(var i = 0; i < points.length; ++i) { var p = points[i]; if (i == 0) ctx.moveTo(p[0], p[1]); else ctx.lineTo(p[0], p[1]); } return true; } static parseFillStyle(ctx : CanvasRenderingContext2D, x : XmlObject) { var fill = x.attr('fill'); if (fill) ctx.fillStyle = x.attr('fill'); if (!fill || fill != 'none') { ctx.closePath(); ctx.fill(); } } static parseStrokeStyle(ctx : CanvasRenderingContext2D, x : XmlObject) { var stroke = x.attr('stroke'); if (stroke && stroke != 'none') { ctx.strokeStyle = stroke; if (x.attr('stroke-width')) ctx.lineWidth = parseFloat(x.attr('stroke-width')); if (x.attr('stroke-linejoin')) ctx.lineJoin = x.attr('stroke-linejoin'); ctx.stroke(); } } static parsePathStyle(ctx : CanvasRenderingContext2D , x : XmlObject) { if (!x.attr('fill') && !x.attr('style')) { ctx.strokeStyle = '#000000'; ctx.closePath(); ctx.fill(); return; } Picture.parseFillStyle(ctx, x); Picture.parseStrokeStyle(ctx, x); var data = x.attr('style'); if (data) { var m = /fill:([^;]+);/i.exec(data); if (m && !/none/.test(m[1])) { ctx.fillStyle = m[1]; ctx.closePath(); ctx.fill(); } m = /stroke:([^;]+);/i.exec(data); if (m && !/none/.test(m[1])) { ctx.strokeStyle = m[1]; m = /stroke-width:([^;]+);/.exec(data); if (m) ctx.lineWidth = parseFloat(m[1]); ctx.stroke(); } } } static applyStyle(ctx : CanvasRenderingContext2D) { if (ctx.fillStyle && ctx.fillStyle != 'none') ctx.fill(); } static parsePathData(ctx : CanvasRenderingContext2D , data : string) { if (!data) return false; var parts = data .replace(/-/gm, ' -') .replace(/[a-zA-Z]/gm, ' $& ') .replace(/,/gm, ' ') .split(/\s+/) .filter(p => !!p); var x = 0; var y = 0; var rx = 0; var ry = 0; var i = 0; var cpx = 0; // last control point var cpy = 0; var lastCommand = ''; while(i < parts.length) { var command = parts[i++]; switch(command) { case 'Z': case 'z': ctx.closePath(); break; case 'm': rx = x; ry = y; ctx.moveTo(rx = rx + parseFloat(parts[i++]), ry = ry + parseFloat(parts[i++])); while(i+1 < parts.length && !isNaN(parseFloat(parts[i]))) ctx.lineTo(rx = rx + parseFloat(parts[i++]), ry = ry + parseFloat(parts[i++])); x = rx; y = ry; break; case 'M': ctx.moveTo(x = parseFloat(parts[i++]), y = parseFloat(parts[i++])); while(i+1 < parts.length && !isNaN(parseFloat(parts[i]))) ctx.lineTo(x = parseFloat(parts[i++]), y = parseFloat(parts[i++])); break; case 'l': rx = x; ry = y; do { ctx.lineTo(rx = rx + parseFloat(parts[i++]), ry = ry + parseFloat(parts[i++])); } while(i+1 < parts.length && !isNaN(parseFloat(parts[i]))); x = rx; y = ry; break; case 'L': do { ctx.lineTo(x = parseFloat(parts[i++]), y = parseFloat(parts[i++])); } while(i+1 < parts.length && !isNaN(parseFloat(parts[i]))); break; case 'c': rx = x; ry = y; do { var x1 = rx + parseFloat(parts[i++]); var y1 = ry + parseFloat(parts[i++]); var x2 = rx + parseFloat(parts[i++]); var y2 = ry + parseFloat(parts[i++]); ctx.bezierCurveTo( x1, y1, x2, y2, rx = rx + parseFloat(parts[i++]), ry = ry + parseFloat(parts[i++])); } while(i+5 < parts.length && !isNaN(parseFloat(parts[i]))); cpx = x2; cpy = y2; x = rx; y = ry; break; case 'C': do { ctx.bezierCurveTo( parseFloat(parts[i++]), parseFloat(parts[i++]), cpx = parseFloat(parts[i++]), cpy = parseFloat(parts[i++]), x = parseFloat(parts[i++]), y = parseFloat(parts[i++])); } while(i+5 < parts.length && !isNaN(parseFloat(parts[i]))); break; case 'S': if (!/^[CcSs]$/.test(lastCommand)) { cpx = x; cpy = y; } do { var x2 = parseFloat(parts[i++]); var y2 = parseFloat(parts[i++]); var x1 = 2*x-cpx; var y1 = 2*y-cpy; ctx.bezierCurveTo(x1,y1, cpx = x2, cpy = y2, x = parseFloat(parts[i++]), y = parseFloat(parts[i++])); } while(i+3 < parts.length && !isNaN(parseFloat(parts[i]))); break; case 's': rx = x; ry = y; if (!/^[CcSs]$/.test(lastCommand)) { cpx = rx; cpy = ry; } do { var x2 = rx + parseFloat(parts[i++]); var y2 = ry + parseFloat(parts[i++]); var x1 = 2*rx-cpx; var y1 = 2*ry-cpy; ctx.bezierCurveTo( x1, y1, cpx = x2, cpy = y2, rx = rx + parseFloat(parts[i++]), ry = ry + parseFloat(parts[i++])); } while(i+3 < parts.length && !isNaN(parseFloat(parts[i]))); x = rx; y = ry; break; case 'H': rx = parseFloat(parts[i++]); ctx.lineTo(rx, y); x = rx; break; case 'h': rx = x + parseFloat(parts[i++]); ctx.lineTo(rx, y); x = rx; break; case 'V': ry = parseFloat(parts[i++]); ctx.lineTo(x, ry); y = ry; break; case 'v': ry = y + parseFloat(parts[i++]); ctx.lineTo(x, ry); y = ry; break; default: Util.log('svg rendering: unknown path command ' + command); return false; } lastCommand = command; } return true; } //? Sets the pixel color at a given pixel //@ writesMutable //@ [color].deflExpr('colors->accent') //@ picAsync public set_pixel(left:number, top:number, color:Color, r:ResumeCtx) : void { this.loadFirst(r, () => { left = Math.round(left); top = Math.round(top); if (left < 0 || top < 0 || left >= this.widthSync() || top >= this.heightSync()) return; this.changed(false); this.imageDataHasChanges = true; /* var c = color.toHtml(); if (color.A() != 1) this.ctx.clearRect(left, top, 1, 1); this.ctx.fillStyle = c; this.ctx.strokeStyle = c; this.ctx.fillRect(left, top, 1, 1); */ this.getImageData(); var d = this.imageData.data; var idx = (left + top * this.widthSync()) * 4; d[idx+0] = color.r; d[idx+1] = color.g; d[idx+2] = color.b; d[idx+3] = color.a; /* // this one is slower if (!this._onePixelData) { this._onePixelData = this.ctx.createImageData(1,1); // only do this once per page } var d = this._onePixelData.data; d[0] = color.R(); d[1] = color.G(); d[2] = color.B(); d[3] = color.A(); this.ctx.putImageData( this._onePixelData, left, top ); */ }); } //? Copy all pixels from the picture //@ allocates returns(Buffer) //@ writesMutable //@ picAsync public to_buffer(r:ResumeCtx) { this.loadFirst(r, () => { this.changed(); var d = this.getImageData(); this.imageData = null; return Buffer.fromImageData(d); }) } //? Copy pixels from `buffer` to the picture //@ writesMutable //@ picAsync public write_buffer(buffer:Buffer, r:ResumeCtx) { this.loadFirst(r, () => { this.changed(); var d = buffer.imageData; if (!d) { d = this.ctx.createImageData(this.widthSync(), this.heightSync()) var sz = d.width * d.height * 4; var dst = d.data var src = buffer.buffer for (var i = 0; i < sz; ++i) dst[i] = src[i] } this.ctx.putImageData(d, 0, 0); }) } //? Shares this message ('' to pick from a list) //@ flow(SinkSharing) //@ readsMutable uiAsync public share(where: string, message: string, r:ResumeCtx): void { HTML.showProgressNotification(lf("sharing picture...")); this.initAsync() .then(() => ShareManager.sharePictureAsync(this, where, message)) .done(() => r.resume()); } //? Flips the picture horizontally //@ writesMutable //@ picAsync public flip_horizontal(r:ResumeCtx): void { this.loadFirst(r,() => { this.commitImageData(); this.changed(); var temp = <HTMLCanvasElement>document.createElement("canvas"); temp.width = this.canvas.width; temp.height = this.canvas.height; var tempCtx = temp.getContext("2d"); tempCtx.drawImage(this.canvas, 0, 0); this.ctx.save(); this.ctx.translate(temp.width, 0); this.ctx.scale(-1, 1); this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); this.ctx.drawImage(temp, 0, 0); this.ctx.restore(); }); } //? Flips the picture vertically //@ writesMutable //@ picAsync public flip_vertical(r:ResumeCtx): void { this.loadFirst(r, () => { this.commitImageData(); this.changed(); var temp = <HTMLCanvasElement>document.createElement("canvas"); temp.width = this.canvas.width; temp.height = this.canvas.height; var tempCtx = temp.getContext("2d"); tempCtx.drawImage(this.canvas, 0, 0); this.ctx.save(); this.ctx.translate(0, this.canvas.height); this.ctx.scale(1, -1); this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); this.ctx.drawImage(temp, 0, 0); this.ctx.restore(); }); } //? Encodes the image into a data uri using the desired quality (1 best, 0 worst). If the quality value is 1, the image is encoded as PNG, otherwise JPEG. //@ async readsMutable returns(string) [quality].defl(0.85) //@ picAsync public to_data_uri(quality: number, r: ResumeCtx): void { this.loadFirst(r, () => { var uri = this.getDataUri(Math_.normalize(quality)); r.resumeVal(uri); }); } //? Writes an Scalable Vector Graphics (SVG) document at a given location. By default, this action uses the viewport size provided in the SVG document when width or height are negative. //@ writesMutable //@ [width].defl(-1) [height].defl(-1) //@ picAsync //@ import("npm", "xmldom", "0.1.*") public blend_svg(markup: string, left: number, top: number, width: number, height: number, angle: number, r: ResumeCtx): void { // try canvas rendering in IE if (Browser.browser == BrowserSoftware.ie10 || Browser.browser == BrowserSoftware.ie11) { var cvs = Picture.parseSvg(markup, width, height); if (cvs) { this.atPosition(r, left, top, angle, 1, () => { this.ctx.drawImage(cvs, 0, 0, cvs.width, cvs.height); }); return; } } // browser svg rendering var svg = "data:image/svg+xml;base64," + Web.base64_encode(markup); var img = <HTMLImageElement>document.createElement("img"); // workaround IE11 issue var svgWidth = markup.match(/width="(\d+)"/); if (svgWidth) img.width = parseInt(svgWidth[1]); var svgHeight = markup.match(/height="(\d+)"/); if (svgHeight) img.height = parseInt(svgHeight[1]); var unhappy = () => { this.ctx.fillStyle = "lightgray"; this.ctx.fillRect(0, 0, 100, 100); this.ctx.fillStyle = "white"; this.ctx.textAlign = "center"; this.ctx.textBaseline = "top"; this.ctx.font = "80px sans-serif"; this.ctx.fillText(':(', 50, 0); }; var svgLoadFailed = () => { this.atPosition(r, left, top, angle, 1, () => { unhappy(); }); } img.onload = () => { this.atPosition(r, left, top, angle, 1, () => { // image might be empty if (!img.width || !img.height) { Time.log('blend_svg error: empty svg'); unhappy(); } else { // rescale as needed var w = width > 0 ? width : img.width; var h = height > 0 ? height : img.height; if (width < 0 && height > 0) w = height / img.height * img.width; else if (height < 0 && width > 0) h = width / img.width * img.height; // draw svg try { this.ctx.drawImage(img, 0, 0, w, h); } catch(ex) { try { // observed in IE11: sometimes, first call fails. this.ctx.drawImage(img, 0, 0, w, h); } catch(ex2) { unhappy(); } } } }); }; img.onerror = () => { Time.log('blend_svg error: svg load failed'); svgLoadFailed(); }; img.src = svg; } //? Displays the image to the wall; you need to call 'update on wall' later if you want changes to be reflected. //@ readsMutable //@ embedsLink("Wall", "Picture") public post_to_wall(s: IStackFrame): void { super.post_to_wall(s) } static niceFilename() : string { var now = Time.now(); return now.year() + "-" + now.month() + "-" + now.day() + "-" + now.hour() + "-" + now.minute() + "-" + now.second() + "-" + now.millisecond(); } //? Shows an art picture in the docs. //@ docsOnly public docs_render(height:number, caption:string) { } //? Get the web address of an art resource; invalid if not available. public readonly_url():string { return this.getReadonlyUrlSync() } } }
the_stack
import { Injectable, Optional, Inject, LoggerService as NestLoggerService, } from '@nestjs/common'; import { clc, yellow } from '@nestjs/common/utils/cli-colors.util'; import { DEFAULT_ERROR_LOG_NAME, DEFAULT_MAX_SIZE, DEFAULT_WEB_LOG_NAME, LOGGER_MODULE_OPTIONS, PROJECT_LOG_DIR_NAME, } from './logger.constants'; import { LoggerModuleOptions, WinstonLogLevel } from './logger.interface'; import { getAppRootPath } from './utils/app-root-path.util'; import { createLogger, Logger as WinstonLogger, format } from 'winston'; import { join } from 'path'; import * as WinstonDailyRotateFile from 'winston-daily-rotate-file'; import { isDev } from 'src/config/env'; import { isPlainObject } from 'lodash'; /** * 默认输出的日志等级 */ const DEFAULT_LOG_CONSOLE_LEVELS: WinstonLogLevel = isDev() ? 'info' : 'error'; const DEFAULT_LOG_WINSTON_LEVELS: WinstonLogLevel = 'info'; /** * 日志输出等级,基于Nest配置扩展,与winston配合,由于log等级与winston定义冲突,需要转为info * https://github.com/nestjs/nest/blob/master/packages/common/services/utils/is-log-level-enabled.util.ts */ const LOG_LEVEL_VALUES: Record<WinstonLogLevel, number> = { debug: 4, verbose: 3, info: 2, warn: 1, error: 0, }; @Injectable() export class LoggerService implements NestLoggerService { private static lastTimestampAt?: number; /** * 日志文件存放文件夹路径 */ private logDir: string; /** * winston实例 */ private winstonLogger: WinstonLogger; constructor(); constructor(context: string, options: LoggerModuleOptions); constructor( @Optional() protected context?: string, @Optional() @Inject(LOGGER_MODULE_OPTIONS) protected options: LoggerModuleOptions = {}, ) { // 默认配置 this.options.timestamp === undefined && (this.options.timestamp = true); // 文件输出等级 !this.options.level && (this.options.level = DEFAULT_LOG_WINSTON_LEVELS); // 控制台输出等级 !this.options.consoleLevel && (this.options.consoleLevel = DEFAULT_LOG_CONSOLE_LEVELS); // 输出的文件大小 !this.options.maxFileSize && (this.options.maxFileSize = DEFAULT_MAX_SIZE); // 默认输出文件名 !this.options.appLogName && (this.options.appLogName = DEFAULT_WEB_LOG_NAME); !this.options.errorLogName && (this.options.errorLogName = DEFAULT_ERROR_LOG_NAME); // 初始化 winston this.initWinston(); } /** * 初始化winston */ private initWinston() { // 配置日志输出目录 if (this.options.dir) { this.logDir = this.options.dir; } else { // 如果不指定,则使用 使用 当前项目目录 + logs 路径进行保存 this.logDir = join(getAppRootPath(), PROJECT_LOG_DIR_NAME); } const transportOptions: WinstonDailyRotateFile.DailyRotateFileTransportOptions = { dirname: this.logDir, maxSize: this.options.maxFileSize, maxFiles: this.options.maxFiles, }; // 多路日志 const webTransport = new WinstonDailyRotateFile( Object.assign(transportOptions, { filename: this.options.appLogName }), ); // 所有error级别都记录在该文件下 const errorTransport = new WinstonDailyRotateFile( Object.assign(transportOptions, { filename: this.options.errorLogName, level: 'error', }), ); // 初始化winston this.winstonLogger = createLogger({ level: this.options.level, format: format.json({ space: 0, }), levels: LOG_LEVEL_VALUES, transports: [webTransport, errorTransport], }); } /** * 获取日志存放路径 */ protected getLogDir(): string { return this.logDir; } /** * 获取winston实例 */ protected getWinstonLogger(): WinstonLogger { return this.winstonLogger; } /** * Write a 'info' level log, if the configured level allows for it. * Prints to `stdout` with newline. */ log(message: any, context?: string): void; log(message: any, ...optionalParams: [...any, string?]): void; log(message: any, ...optionalParams: any[]) { const consoleEnable = this.isConsoleLevelEnabled('info'); const winstonEnable = this.isWinstonLevelEnabled('info'); if (!consoleEnable && !winstonEnable) { return; } const { messages, context } = this.getContextAndMessagesToPrint([ message, ...optionalParams, ]); if (consoleEnable) { this.printMessages(messages, context, 'info'); } this.recordMessages(messages, context, 'info'); } /** * Write an 'error' level log, if the configured level allows for it. * Prints to `stderr` with newline. */ error(message: any, context?: string): void; error(message: any, stack?: string, context?: string): void; error(message: any, ...optionalParams: [...any, string?, string?]): void; error(message: any, ...optionalParams: any[]) { const consoleEnable = this.isConsoleLevelEnabled('error'); const winstonEnable = this.isWinstonLevelEnabled('error'); if (!consoleEnable && !winstonEnable) { return; } const { messages, context, stack } = this.getContextAndStackAndMessagesToPrint([message, ...optionalParams]); if (consoleEnable) { this.printMessages(messages, context, 'error', 'stderr'); this.printStackTrace(stack); } this.recordMessages(messages, context, 'error', stack); } /** * Write a 'warn' level log, if the configured level allows for it. * Prints to `stdout` with newline. */ warn(message: any, context?: string): void; warn(message: any, ...optionalParams: [...any, string?]): void; warn(message: any, ...optionalParams: any[]) { const consoleEnable = this.isConsoleLevelEnabled('warn'); const winstonEnable = this.isWinstonLevelEnabled('warn'); if (!consoleEnable && !winstonEnable) { return; } const { messages, context } = this.getContextAndMessagesToPrint([ message, ...optionalParams, ]); if (consoleEnable) { this.printMessages(messages, context, 'warn'); } this.recordMessages(messages, context, 'warn'); } /** * Write a 'debug' level log, if the configured level allows for it. * Prints to `stdout` with newline. */ debug(message: any, context?: string): void; debug(message: any, ...optionalParams: [...any, string?]): void; debug(message: any, ...optionalParams: any[]) { const consoleEnable = this.isConsoleLevelEnabled('debug'); const winstonEnable = this.isWinstonLevelEnabled('debug'); if (!consoleEnable && !winstonEnable) { return; } const { messages, context } = this.getContextAndMessagesToPrint([ message, ...optionalParams, ]); if (consoleEnable) { this.printMessages(messages, context, 'debug'); } this.recordMessages(messages, context, 'debug'); } /** * Write a 'verbose' level log, if the configured level allows for it. * Prints to `stdout` with newline. */ verbose(message: any, context?: string): void; verbose(message: any, ...optionalParams: [...any, string?]): void; verbose(message: any, ...optionalParams: any[]) { const consoleEnable = this.isConsoleLevelEnabled('verbose'); const winstonEnable = this.isWinstonLevelEnabled('verbose'); if (!consoleEnable && !winstonEnable) { return; } const { messages, context } = this.getContextAndMessagesToPrint([ message, ...optionalParams, ]); if (consoleEnable) { this.printMessages(messages, context, 'verbose'); } this.recordMessages(messages, context, 'verbose'); } protected isConsoleLevelEnabled(level: WinstonLogLevel): boolean { // 默认禁止生产模式控制台日志输出 if (!isDev() && !this.options.disableConsoleAtProd) { return false; } if (this.options.consoleLevel === 'none') { return false; } return LOG_LEVEL_VALUES[level] <= LOG_LEVEL_VALUES[level]; } protected isWinstonLevelEnabled(level: WinstonLogLevel): boolean { // 默认禁止生产模式控制台日志输出 if (this.options.level === 'none') { return false; } return LOG_LEVEL_VALUES[level] <= LOG_LEVEL_VALUES[level]; } // code from -> https://github.com/nestjs/nest/blob/master/packages/common/services/console-logger.service.ts protected getTimestamp(): string { const localeStringOptions = { year: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', day: '2-digit', month: '2-digit', }; return new Date(Date.now()).toLocaleString( undefined, localeStringOptions as Intl.DateTimeFormatOptions, ); } protected recordMessages( messages: unknown[], context = '', logLevel: WinstonLogLevel = 'info', stack?: string, ) { messages.forEach((message) => { const output = isPlainObject(message) ? JSON.stringify( message, (_, value) => typeof value === 'bigint' ? value.toString() : value, 0, ) : (message as string); this.winstonLogger.log(logLevel, output, { context, stack, pid: process.pid, timestamp: this.getTimestamp(), }); }); } protected printMessages( messages: unknown[], context = '', logLevel: WinstonLogLevel = 'info', writeStreamType?: 'stdout' | 'stderr', ) { const color = this.getColorByLogLevel(logLevel); messages.forEach((message) => { const output = isPlainObject(message) ? `${color('Object:')}\n${JSON.stringify( message, (_, value) => typeof value === 'bigint' ? value.toString() : value, 2, )}\n` : color(message as string); const pidMessage = color(`[Nest] ${process.pid} - `); const contextMessage = context ? yellow(`[${context}] `) : ''; const timestampDiff = this.updateAndGetTimestampDiff(); const formattedLogLevel = color(logLevel.toUpperCase().padStart(7, ' ')); const computedMessage = `${pidMessage}${this.getTimestamp()} ${formattedLogLevel} ${contextMessage}${output}${timestampDiff}\n`; process[writeStreamType ?? 'stdout'].write(computedMessage); }); } protected printStackTrace(stack: string) { if (!stack) { return; } process.stderr.write(`${stack}\n`); } private updateAndGetTimestampDiff(): string { const includeTimestamp = LoggerService.lastTimestampAt && this.options?.timestamp; const result = includeTimestamp ? yellow(` +${Date.now() - LoggerService.lastTimestampAt}ms`) : ''; LoggerService.lastTimestampAt = Date.now(); return result; } private getContextAndMessagesToPrint(args: unknown[]) { if (args?.length <= 1) { return { messages: args, context: this.context }; } const lastElement = args[args.length - 1]; const isContext = typeof lastElement === 'string'; if (!isContext) { return { messages: args, context: this.context }; } return { context: lastElement as string, messages: args.slice(0, args.length - 1), }; } private getContextAndStackAndMessagesToPrint(args: unknown[]) { const { messages, context } = this.getContextAndMessagesToPrint(args); if (messages?.length <= 1) { return { messages, context }; } const lastElement = messages[messages.length - 1]; const isStack = typeof lastElement === 'string'; if (!isStack) { return { messages, context }; } return { stack: lastElement as string, messages: messages.slice(0, messages.length - 1), context, }; } private getColorByLogLevel(level: WinstonLogLevel): (text: string) => string { switch (level) { case 'debug': return clc.magentaBright; case 'warn': return clc.yellow; case 'error': return clc.red; case 'verbose': return clc.cyanBright; default: return clc.green; } } }
the_stack
import { Assert, AITestClass } from "@microsoft/ai-test-framework"; import { IConfiguration, ITelemetryPlugin, ITelemetryItem, IPlugin, CoreUtils, IAppInsightsCore, normalizeJsName, random32, mwcRandom32, mwcRandomSeed } from "../../../src/applicationinsights-core-js" import { AppInsightsCore } from "../../../src/JavaScriptSDK/AppInsightsCore"; import { IChannelControls } from "../../../src/JavaScriptSDK.Interfaces/IChannelControls"; import { _InternalMessageId, LoggingSeverity } from "../../../src/JavaScriptSDK.Enums/LoggingEnums"; import { _InternalLogMessage, DiagnosticLogger } from "../../../src/JavaScriptSDK/DiagnosticLogger"; const AIInternalMessagePrefix = "AITR_"; const MaxInt32 = 0xFFFFFFFF; export class ApplicationInsightsCoreTests extends AITestClass { public testInitialize() { super.testInitialize(); } public testCleanup() { super.testCleanup(); } public registerTests() { this.testCase({ name: "ApplicationInsightsCore: Initialization validates input", test: () => { const samplingPlugin = new TestSamplingPlugin(); const appInsightsCore = new AppInsightsCore(); try { appInsightsCore.initialize(null, [samplingPlugin]); } catch (error) { Assert.ok(true, "Validates configuration"); } const config2: IConfiguration = { endpointUrl: "https://dc.services.visualstudio.com/v2/track", instrumentationKey: "40ed4f60-2a2f-4f94-a617-22b20a520864", extensionConfig: {} }; try { appInsightsCore.initialize(config2, null); } catch (error) { Assert.ok(true, "Validates extensions are provided"); } const config: IConfiguration = { endpointUrl: "https://dc.services.visualstudio.com/v2/track", instrumentationKey: "", extensionConfig: {} }; try { appInsightsCore.initialize(config, [samplingPlugin]); } catch (error) { Assert.ok(true, "Validates instrumentationKey"); } const channelPlugin1 = new ChannelPlugin(); channelPlugin1.priority = 1001; const config3 = { extensions: [channelPlugin1], endpointUrl: "https://dc.services.visualstudio.com/v2/track", instrumentationKey: "", extensionConfig: {} }; try { appInsightsCore.initialize(config3, [samplingPlugin]); } catch (error) { Assert.ok(true, "Validates channels cannot be passed in through extensions"); } const channelPlugin2 = new ChannelPlugin(); channelPlugin2.priority = 200; const config4 = { channels: [[channelPlugin2]], endpointUrl: "https://dc.services.visualstudio.com/v2/track", instrumentationKey: "", extensionConfig: {} }; let thrown = false; try { appInsightsCore.initialize(config4, [samplingPlugin]); } catch (error) { thrown = true; } Assert.ok(thrown, "Validates channels passed in through config, priority cannot be less Channel controller priority"); } }); this.testCase({ name: "ApplicationInsightsCore: Initialization initializes setNextPlugin", test: () => { const samplingPlugin = new TestSamplingPlugin(); samplingPlugin.priority = 20; const channelPlugin = new ChannelPlugin(); channelPlugin.priority = 1001; // Assert prior to initialize Assert.ok(!samplingPlugin.nexttPlugin, "Not setup prior to pipeline initialization"); const appInsightsCore = new AppInsightsCore(); appInsightsCore.initialize( { instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41" }, [samplingPlugin, channelPlugin]); Assert.ok(!!samplingPlugin.nexttPlugin, "setup prior to pipeline initialization"); } }); this.testCase({ name: "ApplicationInsightsCore: Plugins can be added with same priority", test: () => { const samplingPlugin = new TestSamplingPlugin(); samplingPlugin.priority = 20; const samplingPlugin1 = new TestSamplingPlugin(); samplingPlugin1.priority = 20; const channelPlugin = new ChannelPlugin(); channelPlugin.priority = 1001; const appInsightsCore = new AppInsightsCore(); try { appInsightsCore.initialize( { instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41" }, [samplingPlugin, samplingPlugin1, channelPlugin]); Assert.ok("No error on duplicate priority"); } catch (error) { Assert.ok(false); // duplicate priority does not throw error } } }); this.testCase({ name: "ApplicationInsightsCore: flush clears channel buffer", test: () => { const channelPlugin = new ChannelPlugin(); const appInsightsCore = new AppInsightsCore(); appInsightsCore.initialize( { instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41" }, [channelPlugin]); Assert.ok(!channelPlugin.isUnloadInvoked, "Unload not called on initialize"); appInsightsCore.getTransmissionControls().forEach(queues => { queues.forEach((q: IChannelControls & ChannelPlugin) => { if (q.onunloadFlush) { q.onunloadFlush() } }); }); Assert.ok(channelPlugin.isUnloadInvoked, "Unload triggered for channel"); } }); this.testCase({ name: "config.channel adds additional queue to existing channels", test: () => { const channelPlugin = new ChannelPlugin(); channelPlugin.priority = 1030; const channelPlugin1 = new ChannelPlugin(); channelPlugin1.priority = 1030; const appInsightsCore = new AppInsightsCore(); appInsightsCore.initialize( { instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41", channels: [[channelPlugin1]] }, [channelPlugin]); const channelQueues = appInsightsCore.getTransmissionControls(); Assert.equal(2, channelQueues.length, "Total number of channel queues"); Assert.equal(1, channelQueues[0].length, "Number of channels in queue 1"); Assert.equal(1, channelQueues[1].length, "Number of channels in queue 2"); } }); this.testCase({ name: 'ApplicationInsightsCore: track adds required default fields if missing', useFakeTimers: true, test: () => { const expectedIKey: string = "09465199-12AA-4124-817F-544738CC7C41"; const expectedTimestamp = new Date().toISOString(); const expectedBaseType = "EventData"; const channelPlugin = new ChannelPlugin(); const appInsightsCore = new AppInsightsCore(); appInsightsCore.initialize({ instrumentationKey: expectedIKey }, [channelPlugin]); // Act const bareItem: ITelemetryItem = { name: 'test item' }; appInsightsCore.track(bareItem); this.clock.tick(1); // Test Assert.equal(expectedIKey, bareItem.iKey, "Instrumentation key is added"); Assert.deepEqual(expectedTimestamp, bareItem.time, "Timestamp is added"); } }); this.testCase({ name: 'ApplicationInsightsCore: track does not replace non-empty iKey', useFakeTimers: true, test: () => { const configIkey: string = "configIkey"; const eventIkey: string = "eventIkey"; const channelPlugin = new ChannelPlugin(); const appInsightsCore = new AppInsightsCore(); appInsightsCore.initialize({ instrumentationKey:configIkey}, [channelPlugin]); // Act const bareItem: ITelemetryItem = { name: 'test item', iKey: eventIkey }; appInsightsCore.track(bareItem); this.clock.tick(1); // Test Assert.equal(eventIkey, bareItem.iKey, "Instrumentation key is replaced"); } }); this.testCase({ name: "DiagnosticLogger: Critical logging history is saved", test: () => { // Setup const channelPlugin = new ChannelPlugin(); const appInsightsCore = new AppInsightsCore(); appInsightsCore.initialize({ instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41", loggingLevelTelemetry: 999 }, [channelPlugin]); const messageId: _InternalMessageId = _InternalMessageId.CannotAccessCookie; // can be any id const logInternalSpy = this.sandbox.spy(appInsightsCore.logger, 'logInternalMessage'); // Test precondition Assert.ok(logInternalSpy.notCalled, 'PRE: No internal logging performed yet'); Assert.equal(0, appInsightsCore.logger.queue.length, 'PRE: No logging recorded'); // Act appInsightsCore.logger.throwInternal(LoggingSeverity.CRITICAL, messageId, "Test Error"); // Test postcondition Assert.ok(logInternalSpy.calledOnce, 'POST: Logging success'); Assert.equal(messageId, logInternalSpy.args[0][1].messageId, "Correct message logged"); Assert.ok(logInternalSpy.args[0][1].message.indexOf('Test Error') !== -1, "Correct message logged"); Assert.equal(1, appInsightsCore.logger.queue.length, "POST: Correct messageId logged"); Assert.ok(appInsightsCore.logger.queue[0].message.indexOf('Test Error') !== -1, "Correct message logged"); Assert.equal(messageId, appInsightsCore.logger.queue[0].messageId, "Correct message logged"); } }); this.testCase({ name: 'DiagnosticLogger: Logger can be created with default constructor', test: () => { // setup const channelPlugin = new ChannelPlugin(); const appInsightsCore = new AppInsightsCore(); appInsightsCore.logger = new DiagnosticLogger(); const messageId: _InternalMessageId = _InternalMessageId.CannotAccessCookie; // can be any id const logInternalSpy = this.sandbox.spy(appInsightsCore.logger, 'logInternalMessage'); // Verify precondition Assert.ok(logInternalSpy.notCalled, 'PRE: No internal logging performed yet'); Assert.equal(0, appInsightsCore.logger.queue.length, 'PRE: No internal logging performed yet'); // Act appInsightsCore.logger.throwInternal(LoggingSeverity.CRITICAL, messageId, "Some message"); // Test postcondition Assert.ok(logInternalSpy.calledOnce, 'POST: Logging success'); Assert.equal(messageId, logInternalSpy.args[0][1].messageId, "Correct message logged"); Assert.equal(messageId, appInsightsCore.logger.queue[0].messageId, "POST: Correct messageId logged"); // Logging same error doesn't duplicate Assert.equal(1, appInsightsCore.logger.queue.length, "Pre: Only 1 logged message"); appInsightsCore.logger.throwInternal(LoggingSeverity.CRITICAL, messageId, "Some message"); Assert.equal(1, appInsightsCore.logger.queue.length, "Pre: Still only 1 logged message"); } }); // TODO: test no reinitialization this.testCase({ name: "Initialize: core cannot be reinitialized", test: () => { // Setup const channelPlugin = new ChannelPlugin(); const appInsightsCore = new AppInsightsCore(); const initFunction = () => appInsightsCore.initialize({ instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41" }, [channelPlugin]); // Assert precondition Assert.ok(!appInsightsCore.isInitialized(), "PRE: core constructed but not initialized"); // Init initFunction(); // Assert initialized Assert.ok(appInsightsCore.isInitialized(), "core is initialized"); Assert.throws(initFunction, Error, "Core cannot be reinitialized"); } }); // TODO: test pollInternalLogs this.testCase({ name: "DiagnosticLogger: Logs can be polled", useFakeTimers: true, test: () => { // Setup const channelPlugin = new ChannelPlugin(); const appInsightsCore = new AppInsightsCore(); appInsightsCore.initialize( { instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41", diagnosticLogInterval: 1 }, [channelPlugin]); const trackTraceSpy = this.sandbox.stub(appInsightsCore, "track"); Assert.equal(0, appInsightsCore.logger.queue.length, "Queue is empty"); // Setup queue const queue: _InternalLogMessage[] = appInsightsCore.logger.queue; queue.push(new _InternalLogMessage(1, "Hello1")); queue.push(new _InternalLogMessage(2, "Hello2")); const poller = appInsightsCore.pollInternalLogs(); // Assert precondition Assert.equal(2, appInsightsCore.logger.queue.length, "Queue contains 2 items"); // Act this.clock.tick(1); // Assert postcondition Assert.equal(0, appInsightsCore.logger.queue.length, "Queue is empty"); const data1 = trackTraceSpy.args[0][0]; Assert.ok(data1.baseData.message.indexOf("Hello1") !== -1); const data2 = trackTraceSpy.args[1][0]; Assert.ok(data2.baseData.message.indexOf("Hello2") !== -1); // Cleanup clearInterval(poller); } }); // TODO: test stopPollingInternalLogs this.testCase({ name: "DiagnosticLogger: stop Polling InternalLogs", useFakeTimers: true, test: () => { // Setup const channelPlugin = new ChannelPlugin(); const appInsightsCore = new AppInsightsCore(); appInsightsCore.initialize( { instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41", diagnosticLogInterval: 1 }, [channelPlugin]); Assert.equal(0, appInsightsCore.logger.queue.length, "Queue is empty"); // Setup queue const queue: _InternalLogMessage[] = appInsightsCore.logger.queue; queue.push(new _InternalLogMessage(1, "Hello1")); queue.push(new _InternalLogMessage(2, "Hello2")); appInsightsCore.pollInternalLogs(); // Assert precondition Assert.equal(2, appInsightsCore.logger.queue.length, "Queue contains 2 items"); // Act appInsightsCore.stopPollingInternalLogs(); this.clock.tick(1); // Assert postcondition Assert.equal(2, appInsightsCore.logger.queue.length, "Queue is not empty"); } }); // TODO: test stopPollingInternalLogs and check max size of the queue. this.testCase({ name: "DiagnosticLogger: stop Polling InternalLogs", useFakeTimers: true, test: () => { // Setup const channelPlugin = new ChannelPlugin(); const appInsightsCore = new AppInsightsCore(); appInsightsCore.initialize( { instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41", diagnosticLogInterval: 1 }, [channelPlugin]); appInsightsCore.pollInternalLogs(); // Assert precondition Assert.equal(0, appInsightsCore.logger.queue.length, "Queue contains 0 items"); // Act appInsightsCore.stopPollingInternalLogs(); let count = 1002; while(count > 0) { appInsightsCore.logger.throwInternal(LoggingSeverity.CRITICAL, count, "Test Error"); --count; } // this.clock.tick(1000); // Assert postcondition Assert.equal(26, appInsightsCore.logger.queue.length, "Queue is not empty"); } }); // TODO: test logger crosscontamination this.testCase({ name: "DiagnosticLogger: Logs in separate cores do not interfere", test: () => { // Setup const channelPlugin = new ChannelPlugin(); const appInsightsCore = new AppInsightsCore(); appInsightsCore.initialize( { instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41", loggingLevelTelemetry: 999 }, [channelPlugin] ); const dummyCore = new AppInsightsCore(); dummyCore.initialize( { instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41", loggingLevelTelemetry: 999 }, [channelPlugin] ); const aiSpy = this.sandbox.spy(appInsightsCore.logger, 'logInternalMessage'); const dummySpy = this.sandbox.spy(dummyCore.logger, 'logInternalMessage'); const messageId: _InternalMessageId = _InternalMessageId.CannotAccessCookie; // can be any id // Test precondition Assert.equal(0, appInsightsCore.logger.queue.length, 'PRE: No internal logging performed yet'); Assert.ok(aiSpy.notCalled, "PRE: messageId not yet logged"); Assert.equal(0, dummyCore.logger.queue.length, 'PRE: No dummy logging'); Assert.ok(dummySpy.notCalled, "PRE: No dummy messageId logged"); // Act appInsightsCore.logger.throwInternal(LoggingSeverity.CRITICAL, messageId, "Test Error"); // Test postcondition Assert.equal(1, appInsightsCore.logger.queue.length, 'POST: Logging success'); Assert.ok(aiSpy.called, "POST: Correct messageId logged"); Assert.equal(0, dummyCore.logger.queue.length, 'POST: No dummy logging'); Assert.ok(dummySpy.notCalled, "POST: No dummy messageId logged"); } }); this.testCase({ name: "ApplicationInsightsCore: Plugins can be provided through configuration", test: () => { const samplingPlugin = new TestSamplingPlugin(); samplingPlugin.priority = 20; const channelPlugin = new ChannelPlugin(); channelPlugin.priority = 1001; const appInsightsCore = new AppInsightsCore(); try { appInsightsCore.initialize( { instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41", extensions: [samplingPlugin] }, [channelPlugin]); } catch (error) { Assert.ok(false, "No error expected"); } let found = false; (appInsightsCore as any)._extensions.forEach(ext => { if (ext.identifier === samplingPlugin.identifier) { found = true; } }); Assert.ok(found, "Plugin pased in through config is part of pipeline"); } }); this.testCase({ name: "ApplicationInsightsCore: Non telemetry specific plugins are initialized and not part of telemetry processing pipeline", test: () => { const samplingPlugin = new TestSamplingPlugin(); samplingPlugin.priority = 20; const testPlugin = new TestPlugin(); const channelPlugin = new ChannelPlugin(); channelPlugin.priority = 1001; const appInsightsCore = new AppInsightsCore(); try { appInsightsCore.initialize( { instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41" }, [testPlugin, samplingPlugin, channelPlugin]); } catch (error) { Assert.ok(false, "Exception not expected"); } Assert.ok(typeof ((appInsightsCore as any)._extensions[0].processTelemetry) !== 'function', "Extensions can be provided through overall configuration"); } }); this.testCase({ name: "Channels can be passed in through configuration", test: () => { const channelPlugin1 = new ChannelPlugin(); channelPlugin1.priority = 1001; const channelPlugin2 = new ChannelPlugin(); channelPlugin2.priority = 1002; const channelPlugin3 = new ChannelPlugin(); channelPlugin3.priority = 1001; const appInsightsCore = new AppInsightsCore(); appInsightsCore.initialize( { instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41", channels: [[channelPlugin1, channelPlugin2], [channelPlugin3]] }, []); Assert.ok(channelPlugin1._nextPlugin === channelPlugin2); Assert.ok(CoreUtils.isNullOrUndefined(channelPlugin3._nextPlugin)); const channelControls = appInsightsCore.getTransmissionControls(); Assert.ok(channelControls.length === 2); Assert.ok(channelControls[0].length === 2); Assert.ok(channelControls[1].length === 1); Assert.ok(channelControls[0][0] === channelPlugin1); Assert.ok(channelControls[1][0] === channelPlugin3); Assert.ok(channelPlugin2._nextPlugin === undefined); Assert.ok(channelPlugin3._nextPlugin === undefined); } }); this.testCase({ name: 'ApplicationInsightsCore: user can add two channels in single queue', test: () => { const channelPlugin1 = new ChannelPlugin(); channelPlugin1.priority = 1001; const channelPlugin2 = new ChannelPlugin(); channelPlugin2.priority = 1002; const channelPlugin3 = new ChannelPlugin(); channelPlugin3.priority = 1003; const appInsightsCore = new AppInsightsCore(); appInsightsCore.initialize( { instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41" }, [channelPlugin1, channelPlugin2, channelPlugin3]); Assert.ok(channelPlugin1._nextPlugin === channelPlugin2); Assert.ok(channelPlugin2._nextPlugin === channelPlugin3); Assert.ok(CoreUtils.isNullOrUndefined(channelPlugin3._nextPlugin)); const channelControls = appInsightsCore.getTransmissionControls(); Assert.ok(channelControls.length === 1); Assert.ok(channelControls[0].length === 3); Assert.ok(channelControls[0][0] === channelPlugin1); Assert.ok(channelControls[0][1] === channelPlugin2); Assert.ok(channelControls[0][2] === channelPlugin3); } }); this.testCase({ name: 'ApplicationInsightsCore: Validates root level properties in telemetry item', test: () => { const expectedIKey: string = "09465199-12AA-4124-817F-544738CC7C41"; const channelPlugin = new ChannelPlugin(); channelPlugin.priority = 1001; const samplingPlugin = new TestSamplingPlugin(true); const appInsightsCore = new AppInsightsCore(); appInsightsCore.initialize({ instrumentationKey: expectedIKey }, [samplingPlugin, channelPlugin]); // Act const bareItem: ITelemetryItem = { name: 'test item', ext: { "user": { "id": "test" } }, tags: [{ "device.id": "AABA40BC-EB0D-44A7-96F5-ED2103E47AE9" }], data: { "custom data": { "data1": "value1" } }, baseType: "PageviewData", baseData: { name: "Test Page" } }; appInsightsCore.track(bareItem); } }); this.testCase({ name: "Channels work even if no extensions are present", test: () => { const channelPlugin = new ChannelPlugin(); channelPlugin.priority = 1030; const appInsightsCore = new AppInsightsCore(); const channelSpy = this.sandbox.stub(channelPlugin, "processTelemetry"); appInsightsCore.initialize( { instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41", channels: [[channelPlugin]] }, []); const event: ITelemetryItem = { name: 'test' }; appInsightsCore.track(event); const evt = channelSpy.args[0][0]; Assert.ok(evt.name === "test"); } }); this.testCase({ name: "ApplicationInsightsCore: Track queue event when not all extensions are initialized", test: () => { const trackPlugin = new TrackPlugin(); const channelPlugin = new ChannelPlugin(); channelPlugin.priority = 1001; const appInsightsCore = new AppInsightsCore(); const channelSpy = this.sandbox.stub(channelPlugin, "processTelemetry"); appInsightsCore.initialize( { instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41" }, [trackPlugin, channelPlugin]); Assert.ok(channelSpy.calledOnce, "Channel process incorrect number of times"); Assert.ok(channelSpy.args[0][0].name == "TestEvent1", "Incorrect event"); Assert.ok(appInsightsCore.eventCnt() == 0, "Event queue wrong number of events"); } }); this.testCase({ name: "ApplicationInsightsCore: Validate JS name normalization", test: () => { Assert.equal("Hello", normalizeJsName("Hello")); Assert.equal("Hello_World", normalizeJsName("Hello.World")); Assert.equal("_Hello_World", normalizeJsName("@Hello.World")); Assert.equal("_Hello_World", normalizeJsName("#Hello.World")); Assert.equal("_Hello_World", normalizeJsName(".Hello#World")); Assert.equal("_Hello_World_", normalizeJsName(".Hello(World)")); Assert.equal("_Hello_World_", normalizeJsName(".Hello&World%")); Assert.equal("_Hello_World_", normalizeJsName("!Hello=World+")); Assert.equal("_Hello_World_", normalizeJsName("~Hello[World]")); Assert.equal("_Hello_World_", normalizeJsName(":Hello{World}")); Assert.equal("_Hello_World_", normalizeJsName("\'Hello\'World;")); Assert.equal("_Hello_World_", normalizeJsName("\"Hello\\World\"")); Assert.equal("_Hello_World_", normalizeJsName("|Hello<World>")); Assert.equal("_Hello_World_", normalizeJsName("?Hello,World-")); } }); this.testCase({ name: 'newId tests length', test: () => { _checkNewId(5, CoreUtils.newId(5), "Test the previous length"); _checkNewId(10, CoreUtils.newId(10), "Test the double the previous length"); _checkNewId(22, CoreUtils.newId(), "Test new default length"); _checkNewId(99, CoreUtils.newId(99), "Test 99 character == 74.25 bytes"); _checkNewId(200, CoreUtils.newId(200), "Test 200 character == 150 bytes"); // Check the id is not zero filled ("A") based on the an int32 === 5 base64 bytes (plus 2 bits) let newId = CoreUtils.newId(); Assert.notEqual("AAAAAAAAAAAAAAAA", newId.substring(0, 16), "Make sure that [" + newId + "] value is not zero filled (generally -- it is randomly possible)") Assert.notEqual("AAAAAAAAAAAAAAAA", newId.substring(5), "Make sure that [" + newId + "] value is not zero filled (generally -- it is randomly possible)") } }); this.testCase({ name: 'newId check randomness', timeout: 15000, test: () => { let map = {}; // Check that mwcRandom is bing called (relies on the mwc implementation from the default seed) mwcRandomSeed(1); Assert.notEqual(722346555, random32(), "Make sure that the mwcRandom was not being called - step 1"); Assert.notEqual(3284929732, random32(), "Make sure that the mwcRandom was not being called - step2"); // cause auto seeding again mwcRandomSeed(); for (let lp = 0; lp < 10000; lp ++) { let newId = CoreUtils.newId(); if (map[newId]) { Assert.ok(false, "[" + newId + "] was duplicated...") } map[newId] = true; } mwcRandomSeed(1); Assert.notEqual(722346555, random32(), "Make sure that the mwcRandom was not being called"); } }); this.testCase({ name: 'newId check randomness -- emulating IE', timeout: 15000, test: () => { let map = {}; // Enumlate IE this.setUserAgent("Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)"); this.setCrypto(null); // Check that mwcRandom is bing called (relies on the mwc implementation from the default seed) mwcRandomSeed(1); Assert.equal(722346555, random32(), "Make sure that the mwcRandom was being called - step 1"); Assert.equal(3284929732, random32(), "Make sure that the mwcRandom was being called - step2"); // cause auto seeding again mwcRandomSeed(); Assert.notEqual(722346555, random32(), "Make sure that the mwcRandom was being called - step 3"); for (let lp = 0; lp < 10000; lp ++) { let newId = CoreUtils.newId(); if (map[newId]) { Assert.ok(false, "[" + newId + "] was duplicated...") } map[newId] = true; } // Reset the seed and re-check the expected result mwcRandomSeed(1); Assert.equal(722346555, random32(), "Make sure that the mwcRandom was not being called - step 4"); } }); this.testCase({ name: 'Test CoreUtils.randomValue() randomness and distribution', timeout: 15000, test: () => { let numBuckets = 100; let buckets: number[] = _createBuckets(100); let runs = 1000000; for (let lp = 0; lp < runs; lp++) { const bucket = CoreUtils.randomValue(numBuckets-1); buckets[bucket] ++; } let min = 10; let max = -1; let mode = 0; for (let lp = 0; lp < numBuckets; lp++) { buckets[lp] /= runs; mode += buckets[lp]; min = Math.min(min, buckets[lp]); max = Math.max(max, buckets[lp]); if (buckets[lp] === 0) { Assert.ok(false, 'Bucket: ' + lp + ' is empty!'); } } Assert.equal(undefined, buckets[numBuckets], 'Make sure that we only allocated the correct number of buckets'); const totalVariance = mode / numBuckets; let perfectDist = 1 / numBuckets; let testDist = perfectDist * 1.5; Assert.ok(min > 0 && min <= testDist, min + ': Make sure that we have a good minimum distribution, perfect distribution is (1/bucketCount) = ' + perfectDist); Assert.ok(max > 0 && max <= testDist, max + ': Make sure that we have a good maximum distribution, perfect distribution is (1/bucketCount) = ' + perfectDist); Assert.ok(totalVariance > 0 && totalVariance <= testDist, totalVariance + ': Check the average distribution perfect distribution is (1/bucketCount) = ' + perfectDist); } }); this.testCase({ name: 'Test CoreUtils.random32() randomness and distribution', timeout: 15000, test: () => { let numBuckets = 100; let buckets: number[] = _createBuckets(100); let runs = 1000000; for (let lp = 0; lp < runs; lp++) { // Need to use floor otherwise the bucket is defined as a float as the index const bucket = Math.floor((CoreUtils.random32() / MaxInt32) * numBuckets); buckets[bucket] ++; } let min = 10; let max = -1; let mode = 0; for (let lp = 0; lp < numBuckets; lp++) { buckets[lp] /= runs; mode += buckets[lp]; min = Math.min(min, buckets[lp]); max = Math.max(max, buckets[lp]); if (buckets[lp] === 0) { Assert.ok(false, 'Bucket: ' + lp + ' is empty!'); } } Assert.equal(undefined, buckets[numBuckets], 'Make sure that we only allocated the correct number of buckets'); const totalVariance = mode / numBuckets; let perfectDist = 1 / numBuckets; let testDist = perfectDist * 1.5; Assert.ok(min > 0 && min <= testDist, min + ': Make sure that we have a good minimum distribution, perfect distribution is (1/bucketCount) = ' + perfectDist); Assert.ok(max > 0 && max <= testDist, max + ': Make sure that we have a good maximum distribution, perfect distribution is (1/bucketCount) = ' + perfectDist); Assert.ok(totalVariance > 0 && totalVariance <= testDist, totalVariance + ': Check the average distribution perfect distribution is (1/bucketCount) = ' + perfectDist); } }); this.testCase({ name: 'Test CoreUtils.mwcRandom32() randomness and distribution', timeout: 15000, test: () => { let numBuckets = 100; let buckets: number[] = _createBuckets(100); let runs = 1000000; for (let lp = 0; lp < runs; lp++) { // Need to use floor otherwise the bucket is defined as a float as the index const bucket = Math.floor((CoreUtils.mwcRandom32() / MaxInt32) * numBuckets); buckets[bucket] ++; } let min = 10; let max = -1; let mode = 0; for (let lp = 0; lp < numBuckets; lp++) { buckets[lp] /= runs; mode += buckets[lp]; min = Math.min(min, buckets[lp]); max = Math.max(max, buckets[lp]); if (buckets[lp] === 0) { Assert.ok(false, 'Bucket: ' + lp + ' is empty!'); } } Assert.equal(undefined, buckets[numBuckets], 'Make sure that we only allocated the correct number of buckets'); const totalVariance = mode / numBuckets; let perfectDist = 1 / numBuckets; let testDist = perfectDist * 1.5; Assert.ok(min > 0 && min <= testDist, min + ': Make sure that we have a good minimum distribution, perfect distribution is (1/bucketCount) = ' + perfectDist); Assert.ok(max > 0 && max <= testDist, max + ': Make sure that we have a good maximum distribution, perfect distribution is (1/bucketCount) = ' + perfectDist); Assert.ok(totalVariance > 0 && totalVariance <= testDist, totalVariance + ': Check the average distribution perfect distribution is (1/bucketCount) = ' + perfectDist); } }); function _createBuckets(num: number) { // Using helper function as TypeScript 2.5.3 is complaining about new Array<number>(100).fill(0); let buckets: number[] = []; for (let lp = 0; lp < num; lp++) { buckets[lp] = 0; } return buckets; } function _checkNewId(idLen: number, newId: string, message: string) { Assert.equal(idLen, newId.length, "[" + newId + "] - " + message); } } } class TestSamplingPlugin implements ITelemetryPlugin { public processTelemetry: (env: ITelemetryItem) => void; public initialize: (config: IConfiguration) => void; public identifier: string = "AzureSamplingPlugin"; public setNextPlugin: (next: ITelemetryPlugin) => void; public priority: number = 5; public version = "1.0.31-Beta"; public nexttPlugin: ITelemetryPlugin; private samplingPercentage; private _validateItem = false; constructor(validateItem: boolean = false) { this.processTelemetry = this._processTelemetry.bind(this); this.initialize = this._start.bind(this); this.setNextPlugin = this._setNextPlugin.bind(this); this._validateItem = validateItem; } private _processTelemetry(env: ITelemetryItem) { if (!env) { throw Error("Invalid telemetry object"); } if (this._validateItem) { Assert.ok(env.baseData); Assert.ok(env.baseType); Assert.ok(env.data); Assert.ok(env.ext); Assert.ok(env.tags); } } private _start(config: IConfiguration) { if (!config) { throw Error("required configuration missing"); } const pluginConfig = config.extensions ? config.extensions[this.identifier] : null; this.samplingPercentage = pluginConfig ? pluginConfig.samplingPercentage : 100; } private _setNextPlugin(next: ITelemetryPlugin): void { this.nexttPlugin = next; } } class ChannelPlugin implements IChannelControls { public _nextPlugin: ITelemetryPlugin; public isFlushInvoked = false; public isUnloadInvoked = false; public isTearDownInvoked = false; public isResumeInvoked = false; public isPauseInvoked = false; public version: string = "1.0.33-Beta"; public processTelemetry; public identifier = "Sender"; public priority: number = 1001; constructor() { this.processTelemetry = this._processTelemetry.bind(this); } public pause(): void { this.isPauseInvoked = true; } public resume(): void { this.isResumeInvoked = true; } public teardown(): void { this.isTearDownInvoked = true; } flush(async?: boolean, callBack?: () => void): void { this.isFlushInvoked = true; if (callBack) { callBack(); } } onunloadFlush(async?: boolean) { this.isUnloadInvoked = true; } setNextPlugin(next: ITelemetryPlugin) { this._nextPlugin = next; } public initialize = (config: IConfiguration) => { } public _processTelemetry(env: ITelemetryItem) { } } class TestPlugin implements IPlugin { public identifier: string = "TestPlugin"; public version: string = "1.0.31-Beta"; private _config: IConfiguration; public initialize(config: IConfiguration) { this._config = config; // do custom one time initialization } } class TrackPlugin implements IPlugin { public identifier: string = "TrackPlugin"; public version: string = "1.0.31-Beta"; public priority = 2; public _nextPlugin: ITelemetryPlugin; public isInitialized: any; private _config: IConfiguration; public initialize(config: IConfiguration, core: IAppInsightsCore, extensions: IPlugin[]) { this._config = config; core.track({ name: 'TestEvent1' }); } public setNextPlugin(next: ITelemetryPlugin) { this._nextPlugin = next; } public processTelemetry(evt: ITelemetryItem) { this._nextPlugin.processTelemetry(evt); } }
the_stack
import express, { Request, Response, NextFunction } from 'express'; import * as error from '../../../../error'; import { Tournament, Player } from '../../../../../Tournament'; import path from 'path'; import matchAPI, { pickMatch } from '../match'; import { pick } from '../../../../../utils'; import { requireAuth, requireAdmin } from '../auth'; import { handleBotUpload, UploadData } from '../../../../handleBotUpload'; import { TournamentPlayerDoesNotExistError } from '../../../../../DimensionError'; import { removeDirectorySync } from '../../../../../utils/System'; import { spawnSync } from 'child_process'; import { TournamentType } from '../../../../../Tournament/TournamentTypes'; const router = express.Router(); /** * Get tournament by tournamentID in request. Requires dimension to be stored. */ const getTournament = (req: Request, res: Response, next: NextFunction) => { const tournament = req.data.dimension.tournaments.get( req.params.tournamentID ); if (!tournament) { return next( new error.BadRequest( `No tournament found with name or id of '${req.params.tournamentID}' in dimension ${req.data.dimension.id} - '${req.data.dimension.name}'` ) ); } req.data.tournament = tournament; next(); }; router.use('/:tournamentID', getTournament); /** * Picks out relevant fields for a tournament */ export const pickTournament = ( t: Tournament ): Pick<Tournament, 'configs' | 'id' | 'log' | 'name' | 'status'> => { return pick(t, 'configs', 'id', 'log', 'name', 'status'); }; /** * GET * Gets tournament details */ router.get('/:tournamentID', (req, res) => { const picked = pickTournament(req.data.tournament); res.json({ error: null, tournament: picked }); }); // attach the match API router.use('/:tournamentID/match', matchAPI); /** * GET * Returns all matches in the dimension */ router.get('/:tournamentID/match', (req: Request, res: Response) => { const matchData = {}; req.data.tournament.matches.forEach((match, key) => { matchData[key] = pickMatch(match); }); res.json({ error: null, matches: matchData }); }); /** * GET * * Get the current match queue */ router.get('/:tournamentID/match-queue', (req, res) => { res.json({ error: null, matchQueue: req.data.tournament.matchQueue }); }); /** * POST * * Set configs by specifying in a configs field of the body. This does a deep merge that overwrites only the fields * specified. Note that functions in the fields are always constant, and can never change. */ router.post( '/:tournamentID/configs', requireAdmin, async (req: Request, res: Response, next: NextFunction) => { if (!req.body.configs) return next(new error.BadRequest('Missing configs')); try { // ladder types have asynchronous config setting when using DB if (req.data.tournament.configs.type === TournamentType.LADDER) { const tournament = <Tournament.Ladder>req.data.tournament; await tournament.setConfigs(req.body.configs); res.json({ error: null }); } else { req.data.tournament.setConfigs(req.body.configs); } } catch (err) { return next(err); } } ); /** * POST * * Run a tournament if it is initialized or resume it if it was stopped */ router.post( '/:tournamentID/run', requireAdmin, (req: Request, res: Response, next: NextFunction) => { if (req.data.tournament.status === Tournament.Status.INITIALIZED) { req.data.tournament .run({}, true) .then(() => { res.json({ error: null, msg: 'Running Tournament' }); }) .catch(next); } else if (req.data.tournament.status === Tournament.Status.STOPPED) { req.data.tournament .resume(true) .then(() => { res.json({ error: null, msg: 'Running Tournament' }); }) .catch(next); } else if (req.data.tournament.status === Tournament.Status.RUNNING) { return next(new error.BadRequest('Tournament is already running')); } else { return next( new error.BadRequest( `Tournament cannot be run. Status is ${req.data.tournament.status}` ) ); } } ); /** * POST * Stops a tournament if it isn't stopped */ router.post( '/:tournamentID/stop', requireAdmin, (req: Request, res: Response, next: NextFunction) => { if (req.data.tournament.status !== Tournament.Status.RUNNING) { return next( new error.BadRequest(`Can't stop a tournament that isn't running`) ); } // stop the tournament req.data.tournament .stop(true) .then(() => { res.json({ error: null, msg: 'Stopped Tournament' }); }) .catch(next); } ); /** * GET * Gets ranks for the tournament */ router.get( '/:tournamentID/ranks', async (req: Request, res: Response, next: NextFunction) => { try { let ranks = []; const offset = parseInt(req.query.offset ? req.query.offset : 0); const limit = parseInt(req.query.limit ? req.query.limit : -1); if (req.data.tournament.configs.type === TournamentType.LADDER) { ranks = await req.data.tournament.getRankings(offset, limit); } else { ranks = await req.data.tournament.getRankings(); } res.json({ error: null, ranks: ranks }); } catch { return next(new error.InternalServerError("Couldn't retrieve rankings")); } } ); /** * DELETE * * Deletes a match */ router.delete( '/:tournamentID/match/:matchID', requireAdmin, (req, res, next) => { return req.data.tournament .removeMatch(req.params.matchID) .then(() => { res.json({ error: null }); }) .catch((err) => { return next(new error.InternalServerError(err)); }); // TODO: There should be a better way to abstract this so we don't need to store something related to the match API // in the dimensions API. // I also don't want to store a removeMatch function in the match itself as that doesn't make sense. } ); /** * DELETE * * Removes a player with specified playerID */ router.delete( '/:tournamentID/players/:playerID', requireAuth, (req, res, next) => { if ( !req.data.dimension.databasePlugin.isAdmin(req.data.user) && req.params.playerID !== req.data.user.playerID ) { return next( new error.Unauthorized(`Insufficient permissions to delete this player`) ); } return req.data.tournament .removePlayer(req.params.playerID) .then(() => { res.json({ error: null }); }) .catch((err) => { if (err instanceof TournamentPlayerDoesNotExistError) { return next( new error.BadRequest( `Player with ID ${req.params.playerID} does not exist` ) ); } else { return next( new error.InternalServerError( `Something went wrong: ${err.message}` ) ); } }); } ); /** * GET * * Retrieves player stat of the ongoing tournament */ router.get('/:tournamentID/players/:playerID', async (req, res) => { const tournament = req.data.tournament; const { playerStat } = await tournament.getPlayerStat(req.params.playerID); if (playerStat) { res.json({ error: null, player: playerStat }); } else { res.json({ error: null, player: null }); } }); /** * GET * * Retrieves past player matches. Requires a backing database */ router.get('/:tournamentID/players/:playerID/match', async (req, res, next) => { if (!req.query.offset || !req.query.limit || !req.query.order) return next(new error.BadRequest('Missing params')); const db = req.data.dimension.databasePlugin; if (req.data.dimension.hasDatabase()) { try { const matchData = await db.getPlayerMatches( req.params.playerID, req.params.tournamentID, parseInt(req.query.offset), parseInt(req.query.limit), parseInt(req.query.order) ); res.json({ error: null, matches: matchData }); } catch (err) { return next(err); } } else { return next( new error.NotImplemented( 'Requires a database plugin in order to retrieve past matches' ) ); } }); /** * GET * * Returns a url to download the bot if a storage service is provided, otherwise directly returns the bot file */ router.get( '/:tournamentID/players/:playerID/bot', requireAuth, async (req, res, next) => { if ( !req.data.dimension.databasePlugin.isAdmin(req.data.user) && req.params.playerID !== req.data.user.playerID ) { return next( new error.Unauthorized( `Insufficient permissions to retrieve this player` ) ); } const tournament = req.data.tournament; req.data.dimension.databasePlugin .getUser(req.params.playerID) .then((user) => { const player: Player = user.statistics[tournament.getKeyName()].player; if (req.data.dimension.hasStorage()) { const key = player.botkey; req.data.dimension.storagePlugin.getDownloadURL(key).then((url) => { res.json({ error: null, url: url }); }); } else { // send a zipped up version of their bot directly if no storage service is used res.sendFile(player.zipFile); } }) .catch(next); } ); /** * POST * * Reset rankings */ router.post( '/:tournamentID/reset', requireAdmin, async (req: Request, res: Response, next: NextFunction) => { if (req.data.tournament.configs.type !== TournamentType.LADDER) { return next( new error.BadRequest( `Can't reset a tournament that is not of the ladder type` ) ); } const tournament = <Tournament.Ladder>req.data.tournament; tournament .resetRankings() .then(() => { res.json({ error: null, message: 'ranks reset' }); }) .catch(next); } ); /** * POST Route * Takes in form data of names: string[], files: File[], playerIDs: string[] * file must be a zip * id is a tournament ID string specified only if you want to upload a new bot to replace an existing one * */ router.post( '/:tournamentID/upload/', requireAuth, async (req: Request, res: Response, next: NextFunction) => { let data: Array<UploadData>; if (req.data.dimension.getStation().configs.disableUploads) { return next(new error.BadRequest('Uploads are disabled')); } try { data = await handleBotUpload(req, req.data.user); } catch (err) { return next(err); } if (data.length > 1) return next( new error.BadRequest('Can only upload one tournament bot at a time') ); const bot = data[0]; let id = bot.playerID; // if user is admin, get the actual user the upload is for let user = req.data.user; if (req.data.dimension.hasDatabase()) { if (req.data.dimension.databasePlugin.isAdmin(req.data.user)) { user = await req.data.dimension.databasePlugin.getUser(id); if (!user) return next(new error.BadRequest('Invalid player ID')); } } const zipLoc = path.join(path.dirname(bot.file), 'bot.zip'); // upload bot if storage is used let botkey: string; if (req.data.dimension.hasStorage()) { const storage = req.data.dimension.storagePlugin; botkey = await storage.uploadTournamentFile( bot.originalFile, user, req.data.tournament ); // as we use storage, we can delete the extracted content safely removeDirectorySync(path.dirname(bot.file)); } else { // store the zip file spawnSync('cp', [bot.originalFile, zipLoc]); } // if no id given, we will generate an ID to use. Generated here using the below function to avoid duplicate ids if (!id) { id = req.data.tournament.generateNextTournamentIDString(); } if (bot.name || bot.botdir || botkey) { req.data.tournament.addplayer( { file: bot.file, name: bot.name, zipFile: zipLoc, botdir: bot.botdir, botkey: botkey, }, id ); } else { req.data.tournament.addplayer(bot.file, id); } res.json({ error: null, message: 'Successfully uploaded bot' }); } ); /** * POST * * Upload a bot for a single player by corresponding key. This route does not verify the botkey, nor pathtofile */ router.post( '/:tournamentID/upload-by-key', requireAuth, async (req: Request, res: Response, next: NextFunction) => { if (!req.data.dimension.hasStorage()) return next( new error.NotImplemented('Server does not have storage setup') ); if (!req.body.playerID) return next(new error.BadRequest('Missing player ID')); if (!req.body.botkey) return next(new error.BadRequest('Missing botkey')); if (!req.body.botname) return next(new error.BadRequest('Missing botname')); if (!req.body.pathtofile) return next(new error.BadRequest('Missing pathtofile')); let user = req.data.user; if (req.data.dimension.hasDatabase()) { if (req.data.dimension.databasePlugin.isAdmin(req.data.user)) { user = await req.data.dimension.databasePlugin.getUser( req.body.playerID ); if (!user) return next(new error.BadRequest('Invalid player ID')); } } try { await req.data.tournament.addplayer( { file: req.body.pathtofile, name: req.body.botname, // the nulls are ok as these aren't used if storage is used zipFile: null, botdir: null, botkey: req.body.botkey, }, req.body.playerID ); } catch (err) { return next(new error.InternalServerError(err)); } res.json({ error: null, message: 'Succesfully uploaded bot', }); } ); /** * POST * * Create queued matches */ router.post( '/:tournamentID/match-queue/', requireAdmin, async (req: Request, res: Response, next: NextFunction) => { if (!req.body.matchQueue) return next(new error.BadRequest('Missing matchQueue field')); if (!req.body.matchQueue.length) return next(new error.BadRequest('Must provide an array')); if (req.data.tournament.type === Tournament.Type.LADDER) { const t = <Tournament.Ladder>req.data.tournament; t.scheduleMatches(...req.body.matchQueue); res.json({ error: null, message: `Queued ${req.body.matchQueue.length} matches`, }); } } ); export default router;
the_stack
export type RangeMapper = ( fromByte: number, toByte: number ) => { url: string; fromByte: number; toByte: number }; export type RequestLimiter = (bytes: number) => void; export type LazyFileConfig = { /** function to map a read request to an url with read request */ rangeMapper: RangeMapper; /** must be known beforehand if there's multiple server chunks (i.e. rangeMapper returns different urls) */ fileLength?: number; /** chunk size for random access requests (should be same as sqlite page size) */ requestChunkSize: number; /** number of virtual read heads. default: 3 */ maxReadHeads?: number; /** max read speed for sequential access. default: 5 MiB */ maxReadSpeed?: number; /** if true, log all read pages into the `readPages` field for debugging */ logPageReads?: boolean; /** if defined, this is called once per request and passed the number of bytes about to be requested **/ requestLimiter?: RequestLimiter; }; export type PageReadLog = { pageno: number; // if page was already loaded wasCached: boolean; // how many pages were prefetched prefetch: number; }; type ReadHead = { startChunk: number; speed: number }; export class LazyUint8Array { private serverChecked = false; private readonly chunks: Uint8Array[] = []; // Loaded chunks. Index is the chunk number totalFetchedBytes = 0; totalRequests = 0; readPages: PageReadLog[] = []; private _length?: number; // LRU list of read heds, max length = maxReadHeads. first is most recently used private readonly readHeads: ReadHead[] = []; private readonly _chunkSize: number; private readonly rangeMapper: RangeMapper; private readonly maxSpeed: number; private readonly maxReadHeads: number; private readonly logPageReads: boolean; private readonly requestLimiter: RequestLimiter; constructor(config: LazyFileConfig) { this._chunkSize = config.requestChunkSize; this.maxSpeed = Math.round( (config.maxReadSpeed || 5 * 1024 * 1024) / this._chunkSize ); // max 5MiB at once this.maxReadHeads = config.maxReadHeads ?? 3; this.rangeMapper = config.rangeMapper; this.logPageReads = config.logPageReads ?? false; if (config.fileLength) { this._length = config.fileLength; } this.requestLimiter = config.requestLimiter == null ? ((ignored) => {}) : config.requestLimiter; } /** * efficiently copy the range [start, start + length) from the http file into the * output buffer at position [outOffset, outOffest + length) * reads from cache or synchronously fetches via HTTP if needed */ copyInto( buffer: Uint8Array, outOffset: number, length: number, start: number ): number { if (start >= this.length) return 0; length = Math.min(this.length - start, length); const end = start + length; let i = 0; while (i < length) { // {idx: 24, chunkOffset: 24, chunkNum: 0, wantedSize: 16} const idx = start + i; const chunkOffset = idx % this.chunkSize; const chunkNum = (idx / this.chunkSize) | 0; const wantedSize = Math.min(this.chunkSize, end - idx); let inChunk = this.getChunk(chunkNum); if (chunkOffset !== 0 || wantedSize !== this.chunkSize) { inChunk = inChunk.subarray(chunkOffset, chunkOffset + wantedSize); } buffer.set(inChunk, outOffset + i); i += inChunk.length; } return length; } private lastGet = -1; /* find the best matching existing read head to get the given chunk or create a new one */ private moveReadHead(wantedChunkNum: number): ReadHead { for (const [i, head] of this.readHeads.entries()) { const fetchStartChunkNum = head.startChunk + head.speed; const newSpeed = Math.min(this.maxSpeed, head.speed * 2); const wantedIsInNextFetchOfHead = wantedChunkNum >= fetchStartChunkNum && wantedChunkNum < fetchStartChunkNum + newSpeed; if (wantedIsInNextFetchOfHead) { head.speed = newSpeed; head.startChunk = fetchStartChunkNum; if (i !== 0) { // move head to front this.readHeads.splice(i, 1); this.readHeads.unshift(head); } return head; } } const newHead: ReadHead = { startChunk: wantedChunkNum, speed: 1, }; this.readHeads.unshift(newHead); while (this.readHeads.length > this.maxReadHeads) this.readHeads.pop(); return newHead; } /** get the given chunk from cache or fetch it from remote */ private getChunk(wantedChunkNum: number): Uint8Array { let wasCached = true; if (typeof this.chunks[wantedChunkNum] === "undefined") { wasCached = false; // double the fetching chunk size if the wanted chunk would be within the next fetch request const head = this.moveReadHead(wantedChunkNum); const chunksToFetch = head.speed; const startByte = head.startChunk * this.chunkSize; let endByte = (head.startChunk + chunksToFetch) * this.chunkSize - 1; // including this byte endByte = Math.min(endByte, this.length - 1); // if datalength-1 is selected, this is the last block const buf = this.doXHR(startByte, endByte); for (let i = 0; i < chunksToFetch; i++) { const curChunk = head.startChunk + i; if (i * this.chunkSize >= buf.byteLength) break; // past end of file const curSize = (i + 1) * this.chunkSize > buf.byteLength ? buf.byteLength - i * this.chunkSize : this.chunkSize; // console.log("constructing chunk", buf.byteLength, i * this.chunkSize, curSize); this.chunks[curChunk] = new Uint8Array( buf, i * this.chunkSize, curSize ); } } if (typeof this.chunks[wantedChunkNum] === "undefined") throw new Error("doXHR failed (bug)!"); const boring = !this.logPageReads || this.lastGet == wantedChunkNum; if (!boring) { this.lastGet = wantedChunkNum; this.readPages.push({ pageno: wantedChunkNum, wasCached, prefetch: wasCached ? 0 : this.readHeads[0].speed - 1, }); } return this.chunks[wantedChunkNum]; } /** verify the server supports range requests and find out file length */ private checkServer() { var xhr = new XMLHttpRequest(); const url = this.rangeMapper(0, 0).url; // can't set Accept-Encoding header :( https://stackoverflow.com/questions/41701849/cannot-modify-accept-encoding-with-fetch xhr.open("HEAD", url, false); // // maybe this will help it not use compression? // xhr.setRequestHeader("Range", "bytes=" + 0 + "-" + 1e12); xhr.send(null); if (!((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status); var datalength: number | null = Number( xhr.getResponseHeader("Content-length") ); var hasByteServing = xhr.getResponseHeader("Accept-Ranges") === "bytes"; const encoding = xhr.getResponseHeader("Content-Encoding"); var usesCompression = encoding && encoding !== "identity"; if (!hasByteServing) { const msg = "Warning: The server did not respond with Accept-Ranges=bytes. It either does not support byte serving or does not advertise it (`Accept-Ranges: bytes` header missing), or your database is hosted on CORS and the server doesn't mark the accept-ranges header as exposed. This may lead to incorrect results."; console.warn( msg, "(seen response headers:", xhr.getAllResponseHeaders(), ")" ); // throw Error(msg); } if (usesCompression) { console.warn( `Warning: The server responded with ${encoding} encoding to a HEAD request. Ignoring since it may not do so for Range HTTP requests, but this will lead to incorrect results otherwise since the ranges will be based on the compressed data instead of the uncompressed data.` ); } if (usesCompression) { // can't use the given data length if there's compression datalength = null; } if (!this._length) { if (!datalength) { console.error("response headers", xhr.getAllResponseHeaders()); throw Error("Length of the file not known. It must either be supplied in the config or given by the HTTP server."); } this._length = datalength; } this.serverChecked = true; } get length() { if (!this.serverChecked) { this.checkServer(); } return this._length!; } get chunkSize() { if (!this.serverChecked) { this.checkServer(); } return this._chunkSize!; } private doXHR(absoluteFrom: number, absoluteTo: number) { console.log( `[xhr of size ${(absoluteTo + 1 - absoluteFrom) / 1024} KiB @ ${ absoluteFrom / 1024 } KiB]` ); this.requestLimiter(absoluteTo - absoluteFrom); this.totalFetchedBytes += absoluteTo - absoluteFrom; this.totalRequests++; if (absoluteFrom > absoluteTo) throw new Error( "invalid range (" + absoluteFrom + ", " + absoluteTo + ") or no bytes requested!" ); if (absoluteTo > this.length - 1) throw new Error( "only " + this.length + " bytes available! programmer error!" ); const { fromByte: from, toByte: to, url, } = this.rangeMapper(absoluteFrom, absoluteTo); // TODO: Use mozResponseArrayBuffer, responseStream, etc. if available. var xhr = new XMLHttpRequest(); xhr.open("GET", url, false); if (this.length !== this.chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to); // Some hints to the browser that we want binary data. xhr.responseType = "arraybuffer"; if (xhr.overrideMimeType) { xhr.overrideMimeType("text/plain; charset=x-user-defined"); } xhr.send(null); if (!((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status); if (xhr.response !== undefined) { return xhr.response as ArrayBuffer; } else { throw Error("xhr did not return uint8array"); } } } /** create the actual file object for the emscripten file system */ export function createLazyFile( FS: any, parent: string, name: string, canRead: boolean, canWrite: boolean, lazyFileConfig: LazyFileConfig ) { var lazyArray = new LazyUint8Array(lazyFileConfig); var properties = { isDevice: false, contents: lazyArray }; var node = FS.createFile(parent, name, properties, canRead, canWrite); node.contents = lazyArray; // Add a function that defers querying the file size until it is asked the first time. Object.defineProperties(node, { usedBytes: { get: /** @this {FSNode} */ function () { return this.contents.length; }, }, }); // override each stream op with one that tries to force load the lazy file first var stream_ops: any = {}; var keys = Object.keys(node.stream_ops); keys.forEach(function (key) { var fn = node.stream_ops[key]; stream_ops[key] = function forceLoadLazyFile() { FS.forceLoadFile(node); return fn.apply(null, arguments); }; }); // use a custom read function stream_ops.read = function stream_ops_read( stream: { node: { contents: LazyUint8Array } }, buffer: Uint8Array, offset: number, length: number, position: number ) { FS.forceLoadFile(node); const contents = stream.node.contents; return contents.copyInto(buffer, offset, length, position); }; node.stream_ops = stream_ops; return node; }
the_stack
import type { Axis } from "../xy/axes/Axis"; import type { RadarChart } from "./RadarChart"; import type { Grid } from "../xy/axes/Grid"; import type { IPoint } from "../../core/util/IPoint"; import type { Graphics } from "../../core/render/Graphics"; import { Slice } from "../../core/render/Slice"; import type { AxisTick } from "../xy/axes/AxisTick"; import type { AxisBullet } from "../xy/axes/AxisBullet"; import type { Tooltip } from "../../core/render/Tooltip"; import { AxisRenderer, IAxisRendererSettings, IAxisRendererPrivate } from "../xy/axes/AxisRenderer"; import { AxisLabelRadial } from "../xy/axes/AxisLabelRadial"; import { Percent, p100 } from "../../core/util/Percent"; import { ListTemplate } from "../../core/util/List"; import { Template } from "../../core/util/Template"; import { arc } from "d3-shape"; import * as $utils from "../../core/util/Utils"; import * as $math from "../../core/util/Math"; export interface IAxisRendererCircularSettings extends IAxisRendererSettings { /** * Outer radius of the axis. * * If set in percent, it will be relative to chart's own `radius`. * * @see {@link https://www.amcharts.com/docs/v5/charts/radar-chart/radar-axes/#Axis_radii_and_angles} for more info */ radius?: number | Percent; /** * Inner radius of the axis. * * If set in percent, it will be relative to chart's own `innerRadius`. * * If value is negative, inner radius will be calculated from the outer edge. * * @see {@link https://www.amcharts.com/docs/v5/charts/radar-chart/radar-axes/#Axis_radii_and_angles} for more info */ innerRadius?: number | Percent; /** * Series start angle. * * If not set, will use chart's `startAngle.` * * @see {@link https://www.amcharts.com/docs/v5/charts/radar-chart/radar-axes/#Axis_radii_and_angles} for more info */ startAngle?: number; /** * Series end angle. * * If not set, will use chart's `endAngle.` * * @see {@link https://www.amcharts.com/docs/v5/charts/radar-chart/radar-axes/#Axis_radii_and_angles} for more info */ endAngle?: number; /** * @todo am: needs description */ axisAngle?: number; } export interface IAxisRendererCircularPrivate extends IAxisRendererPrivate { radius?: number; innerRadius?: number; startAngle?: number; endAngle?: number; } /** * Renderer for circular axes. */ export class AxisRendererCircular extends AxisRenderer { /** * Chart this renderer is for. */ declare public chart: RadarChart | undefined; /** * A list of labels in the axis. * * `labels.template` can be used to configure labels. * * @default new ListTemplate<AxisLabelRadial> */ public readonly labels: ListTemplate<AxisLabelRadial> = new ListTemplate( Template.new({}), () => AxisLabelRadial._new(this._root, { themeTags: $utils.mergeTags(this.labels.template.get("themeTags", []), this.get("themeTags", [])) }, [this.labels.template]) ); /** * A list of fills in the axis. * * `axisFills.template` can be used to configure axis fills. * * @default new ListTemplate<Slice> */ public readonly axisFills: ListTemplate<Slice> = new ListTemplate( Template.new({}), () => Slice._new(this._root, { themeTags: $utils.mergeTags(this.axisFills.template.get("themeTags", ["fill"]), this.get("themeTags", [])) }, [this.axisFills.template]) ); public static className: string = "AxisRendererCircular"; public static classNames: Array<string> = AxisRenderer.classNames.concat([AxisRendererCircular.className]); declare public _settings: IAxisRendererCircularSettings; declare public _privateSettings: IAxisRendererCircularPrivate; protected _fillGenerator = arc(); public _afterNew() { this._settings.themeTags = $utils.mergeTags(this._settings.themeTags, ["renderer", "circular"]); super._afterNew(); this.setPrivateRaw("letter", "X"); this.setRaw("position", "absolute"); } public _changed() { super._changed(); if (this.isDirty("radius") || this.isDirty("innerRadius") || this.isDirty("startAngle") || this.isDirty("endAngle")) { this.updateLayout(); } } /** * @ignore */ public updateLayout() { const chart = this.chart; if (chart) { const radius = chart.getPrivate("radius", 0); let r = $utils.relativeToValue(this.get("radius", p100), radius); if (r < 0) { r = radius + r; } this.setPrivate("radius", r); let ir = $utils.relativeToValue(this.get("innerRadius", chart.getPrivate("innerRadius", 0)), radius) * chart.getPrivate("irModifyer", 1); if (ir < 0) { ir = r + ir; } this.setPrivate("innerRadius", ir); let startAngle = this.get("startAngle", chart.get("startAngle", -90)); let endAngle = this.get("endAngle", chart.get("endAngle", 270)); this.setPrivate("startAngle", startAngle); this.setPrivate("endAngle", endAngle); this.set("draw", (display) => { const p0 = this.positionToPoint(0); display.moveTo(p0.x, p0.y); if (startAngle > endAngle) { [startAngle, endAngle] = [endAngle, startAngle]; } display.arc(0, 0, r, startAngle * $math.RADIANS, endAngle * $math.RADIANS); }); this.axis.markDirtySize(); } } /** * @ignore */ public updateGrid(grid?: Grid, position?: number, endPosition?: number) { if (grid) { if (position == null) { position = 0; } let location = grid.get("location", 0.5); if (endPosition != null && endPosition != position) { position = position + (endPosition - position) * location; } let radius = this.getPrivate("radius", 0); let innerRadius = this.getPrivate("innerRadius", 0); let angle = this.positionToAngle(position); this.toggleVisibility(grid, position, 0, 1); if (radius != null) { grid.set("draw", (display) => { display.moveTo(innerRadius * $math.cos(angle), innerRadius * $math.sin(angle)); display.lineTo(radius * $math.cos(angle), radius * $math.sin(angle)); }) } } } /** * Converts relative position to angle. * * @param position Position * @return Angle */ public positionToAngle(position: number): number { const axis: Axis<AxisRenderer> = this.axis; const startAngle = this.getPrivate("startAngle", 0); const endAngle = this.getPrivate("endAngle", 360); const start = axis.get("start", 0); const end = axis.get("end", 1); let arc = (endAngle - startAngle) / (end - start); let angle: number; if (this.get("inversed")) { angle = startAngle + (end - position) * arc; } else { angle = startAngle + (position - start) * arc; } return angle; } // do not delete protected _handleOpposite() { } /** * Converts relative position to an X/Y coordinate. * * @param position Position * @return Point */ public positionToPoint(position: number): IPoint { const radius = this.getPrivate("radius", 0); const angle = this.positionToAngle(position); return { x: radius * $math.cos(angle), y: radius * $math.sin(angle) }; } /** * @ignore */ public updateLabel(label?: AxisLabelRadial, position?: number, endPosition?: number, count?: number) { if (label) { if (position == null) { position = 0; } let location = 0.5; if (count != null && count > 1) { location = label.get("multiLocation", location); } else { location = label.get("location", location); } if (endPosition != null && endPosition != position) { position = position + (endPosition - position) * location; } const radius = this.getPrivate("radius", 0); const innerRadius = this.getPrivate("innerRadius", 0); const angle = this.positionToAngle(position); label.setPrivate("radius", radius); label.setPrivate("innerRadius", innerRadius); label.set("labelAngle", angle); this.toggleVisibility(label, position, label.get("minPosition", 0), label.get("maxPosition", 1)); } } /** * @ignore */ public fillDrawMethod(fill: Graphics, startAngle?: number, endAngle?: number) { fill.set("draw", (display) => { if (startAngle == null) { startAngle = this.getPrivate("startAngle", 0); } if (endAngle == null) { endAngle = this.getPrivate("endAngle", 0); } const y0 = this.getPrivate("innerRadius", 0); const y1 = this.getPrivate("radius", 0); this._fillGenerator.context(display as any); this._fillGenerator({ innerRadius: y0, outerRadius: y1, startAngle: (startAngle + 90) * $math.RADIANS, endAngle: (endAngle + 90) * $math.RADIANS }); }) } /** * @ignore */ public updateTick(tick?: AxisTick, position?: number, endPosition?: number, count?: number) { if (tick) { if (position == null) { position = 0; } let location = 0.5; if (count != null && count > 1) { location = tick.get("multiLocation", location); } else { location = tick.get("location", location); } if (endPosition != null && endPosition != position) { position = position + (endPosition - position) * location; } let length = tick.get("length", 0); const inside = tick.get("inside"); if (inside) { length *= -1 } let radius = this.getPrivate("radius", 0); let angle = this.positionToAngle(position); this.toggleVisibility(tick, position, tick.get("minPosition", 0), tick.get("maxPosition", 1)); if (radius != null) { tick.set("draw", (display) => { display.moveTo(radius * $math.cos(angle), radius * $math.sin(angle)); radius += length; display.lineTo(radius * $math.cos(angle), radius * $math.sin(angle)); }) } } } /** * @ignore */ public updateBullet(bullet?: AxisBullet, position?: number, endPosition?: number) { if (bullet) { const sprite = bullet.get("sprite"); if (sprite) { if (position == null) { position = 0; } let location = bullet.get("location", 0.5); if (endPosition != null && endPosition != position) { position = position + (endPosition - position) * location; } let radius = this.getPrivate("radius", 0); let angle = this.positionToAngle(position); this.toggleVisibility(sprite, position, 0, 1); sprite.setAll({ rotation: angle, x: radius * $math.cos(angle), y: radius * $math.sin(angle) }); } } } /** * @ignore */ public updateFill(fill?: Slice, position?: number, endPosition?: number) { if (fill) { if (position == null) { position = 0; } if (endPosition == null) { endPosition = 1; } let startAngle = this.fitAngle(this.positionToAngle(position)); let endAngle = this.fitAngle(this.positionToAngle(endPosition)); fill.setAll({ startAngle: startAngle, arc: endAngle - startAngle }); fill._setSoft("innerRadius", this.getPrivate("innerRadius")); fill._setSoft("radius", this.getPrivate("radius")); } } /** * @ignore */ public fitAngle(angle: number): number { const startAngle = this.getPrivate("startAngle", 0); const endAngle = this.getPrivate("endAngle", 0); const minAngle = Math.min(startAngle, endAngle); const maxAngle = Math.max(startAngle, endAngle); if (angle < minAngle) { angle = minAngle; } if (angle > maxAngle) { angle = maxAngle; } return angle; } /** * Returns axis length in pixels. * * @return Length */ public axisLength(): number { return Math.abs(this.getPrivate("radius", 0) * Math.PI * 2 * (this.getPrivate("endAngle", 360) - this.getPrivate("startAngle", 0)) / 360); } /** * @ignore */ public positionTooltip(tooltip: Tooltip, position: number) { let radius = this.getPrivate("radius", 0); const angle = this.positionToAngle(position); //return tooltip.set("pointTo", this.axis._display.toGlobal({ x: radius * $math.cos(angle), y: radius * $math.sin(angle) })); this._positionTooltip(tooltip, { x: radius * $math.cos(angle), y: radius * $math.sin(angle) }); } /** * @ignore */ public updateTooltipBounds(_tooltip: Tooltip) { } }
the_stack
namespace DexFormat { export class MultiDexFileReader { private static CLASSES_FILENAME:RegExp = /classes\d*\.dex/; public multidex:boolean; private dexFiles:DexFileReader[] = []; constructor(inputFileStream:ArrayBuffer) { var zip = new JSZip(inputFileStream); var files = zip.file(MultiDexFileReader.CLASSES_FILENAME); if (files.length == 0) { throw new Error("APK does not contain .dex file(s)."); } this.multidex = files.length > 1; for (var i = 0; i < files.length; i++) { var file = files[i]; var dexFileReader = new DexFileReader(file); this.dexFiles.push(dexFileReader); } } public getMethodRefs():MethodDef[] { var res = []; for (var i = 0; i < this.dexFiles.length; i++) { var dexFile = this.dexFiles[i]; res = res.concat(dexFile.getMethodRefs()); } return res; } public isMultidex():boolean { return this.multidex; } } export class DexFileReader { //Constants private static DEX_FILE_MAGIC:number[] = [0x64, 0x65, 0x78, 0x0a, 0x30, 0x33, 0x36, 0x00]; private static DEX_FILE_MAGIC_API_13:number[] = [0x64, 0x65, 0x78, 0x0a, 0x30, 0x33, 0x35, 0x00]; private header:DexHeader; private strings:string[] = []; private types:TypeDef[] = []; private protos:ProtoDef[] = []; private fields:FieldDef[] = []; private methods:MethodDef[] = []; private classes:ClassDef[] = []; constructor(file:JSZipObject) { var dv = new jDataView(file.asArrayBuffer()); if (!DexFileReader.isValidDexFile(dv.getBytes(8))) { throw new Error("APK not compatible."); } this.header = new DexHeader(dv); this.loadStrings(dv); this.loadTypes(dv); this.loadProtos(dv); this.loadFields(dv); this.loadMethods(dv); this.loadClasses(dv); this.markInternalClasses(); } public static getClassNameOnly(typeName:string):string { var dotted = DexFileReader.descriptorToDot(typeName); var start = dotted.lastIndexOf("."); if (start < 0) { return dotted; } else { return dotted.substring(start+1); } } public static getPackageNameOnly(typeName:string):string { var dotted = DexFileReader.descriptorToDot(typeName); var end = dotted.lastIndexOf("."); if (end < 0) { return ""; } else { return dotted.substring(0, end); } } public static descriptorToDot(descr:string):string { var targetLen = descr.length; var offset = 0; var arrayDepth = 0; /* strip leading [s; will be added to end */ while (targetLen > 1 && descr.charAt(offset) == '[') { offset++; targetLen--; } arrayDepth = offset; if (targetLen == 1) { descr = DexFileReader.getPrimitiveType(descr.charAt(offset)); offset = 0; targetLen = descr.length; } else { /* account for leading 'L' and trailing ';' */ if (targetLen >= 2 && descr.charAt(offset) == 'L' && descr.charAt(offset+targetLen-1) == ';') { targetLen -= 2; /* two fewer chars to copy */ offset++; /* skip the 'L' */ } } var buf = []; /* copy class name over */ var i; for (i = 0; i < targetLen; i++) { var ch = descr.charAt(offset + i); buf[i] = (ch == '/') ? '.' : ch; } /* add the appopriate number of brackets for arrays */ while (arrayDepth-- > 0) { buf[i++] = '['; buf[i++] = ']'; } return buf.join(""); } private static isValidDexFile(bytes:number[]):boolean { for (var i = 0; i < bytes.length; i++) { if (!(bytes[i] === DexFileReader.DEX_FILE_MAGIC[i] || bytes[i] === DexFileReader.DEX_FILE_MAGIC_API_13[i])) { return false; } } return true; } private markInternalClasses():void { for (var i = this.classes.length - 1; i >= 0; i--) { this.classes[i].getClassType().setInternal(true); } for (var i = 0; i < this.types.length; i++) { var className = this.types[i].getDescriptor(); if (className.length == 1) { // primitive class this.types[i].setInternal(true); } else if (className.charAt(0) == '[') { this.types[i].setInternal(true); } } } private loadStrings(dv:jDataView):void { var curStrings:string[] = []; var offsets:number[] = []; dv.seek(this.header.stringIdsOff); for (var i = 0; i < this.header.stringIdsSize; i++) { offsets[i] = dv.getInt32(); } dv.seek(offsets[0]); for (var i = 0; i < this.header.stringIdsSize; i++) { dv.seek(offsets[i]); curStrings[i] = dv.readStringUtf(); } this.strings = this.strings.concat(curStrings); } private loadTypes(dv:jDataView):void { var curTypes:TypeDef[] = []; dv.seek(this.header.typeIdsOff); for (var i = 0; i < this.header.typeIdsSize; i++) { var descriptorIdx = dv.getInt32(); curTypes[i] = new TypeDef(this, descriptorIdx); } this.types = this.types.concat(curTypes); } private loadProtos(dv:jDataView):void { var curProtos:ProtoDef[] = []; dv.seek(this.header.protoIdsOff); for (var i = 0; i < this.header.protoIdsSize; i++) { var shortyIdx = dv.getInt32(); var returnTypeIdx = dv.getInt32(); var parametersOff = dv.getInt32(); curProtos[i] = new ProtoDef(this, shortyIdx, returnTypeIdx, parametersOff); } /*for (var i = 0; i < this.header.protoIdsSize; i++) { var offset = curProtos[i].parametersOff; curProtos[i].types = []; if (offset != 0) { dv.seek(offset); var size = dv.getInt32(); for (var j = 0; j < size; j++) { curProtos[i].types[j] = dv.getInt16() & 0xffff; } } }*/ this.protos = this.protos.concat(curProtos) } private loadFields(dv:jDataView):void { var curFields:FieldDef[] = []; dv.seek(this.header.fieldIdsOff); for (var i = 0; i < this.header.fieldIdsSize; i++) { var classIdx = dv.getInt16() & 0xffff; var typeIdx = dv.getInt16() & 0xffff; var nameIdx = dv.getInt32(); curFields[i] = new FieldDef(this, classIdx, typeIdx, nameIdx); } this.fields = this.fields.concat(curFields); } private loadMethods(dv:jDataView):void { var curMethods:MethodDef[] = []; dv.seek(this.header.methodIdsOff); for (var i = 0; i < this.header.methodIdsSize; i++) { var classIdx = dv.getInt16() & 0xffff; var protoIdx = dv.getInt16() & 0xffff; var nameIdx = dv.getInt32(); curMethods[i] = new MethodDef(this, classIdx, protoIdx, nameIdx); } this.methods = this.methods.concat(curMethods); } private loadClasses(dv:jDataView):void { var curClasses:ClassDef[] = []; dv.seek(this.header.classDefsOff); for (var i = 0; i < this.header.classDefsSize; i++) { var classIdx = dv.getInt32(); var accessFlags = dv.getInt32(); var superclassIdx = dv.getInt32(); var interfacesOff = dv.getInt32(); var sourceFileIdx = dv.getInt32(); var annotationsOff = dv.getInt32(); var classDataOff = dv.getInt32(); var staticValuesOff = dv.getInt32(); curClasses[i] = new ClassDef(this, classIdx, accessFlags, superclassIdx, interfacesOff, sourceFileIdx, annotationsOff, classDataOff, staticValuesOff); } this.classes = this.classes.concat(curClasses); } private static getPrimitiveType(typeChar:string):string { switch (typeChar) { case 'B': return "byte"; case 'C': return "char"; case 'D': return "double"; case 'F': return "float"; case 'I': return "int"; case 'J': return "long"; case 'S': return "short"; case 'V': return "void"; case 'Z': return "boolean"; default: throw "Unexpected class char " + typeChar; return "UNKNOWN"; } } public getMethodRefs():MethodDef[] { return this.methods; } public getString(idx:number):string { return this.strings[idx]; } public getType(idx:number):TypeDef { return this.types[idx]; } public getProto(idx:number):ProtoDef { return this.protos[idx]; } public getClass(idx:number):ClassDef { for (var i = 0; i < this.classes.length; i++) { var searchIdx = this.classes[i].getClassIdx(); if (idx == searchIdx) { return this.classes[i]; } } return null; } } class DexHeader { private static ENDIAN_CONSTANT:number = 0x12345678; private static REVERSE_ENDIAN_CONSTANT:number = 0x78563412; public fileSize:number; public headerSize:number; public endianTag:number; public linkSize:number; public linkOff:number; public mapOff:number; public stringIdsSize:number; public stringIdsOff:number; public typeIdsSize:number; public typeIdsOff:number; public protoIdsSize:number; public protoIdsOff:number; public fieldIdsSize:number; public fieldIdsOff:number; public methodIdsSize:number; public methodIdsOff:number; public classDefsSize:number; public classDefsOff:number; public dataSize:number; public dataOff:number; constructor(dv:jDataView) { //Read endian tag first dv.seek(8 + 4 + 20 + 4 + 4); this.endianTag = dv.getInt32(); if (this.endianTag === DexHeader.ENDIAN_CONSTANT) { dv._littleEndian = false; } else if (this.endianTag === DexHeader.REVERSE_ENDIAN_CONSTANT) { dv._littleEndian = true; } else { throw new Error("APK read error (endianTag)!"); } dv.seek(8 + 4 + 20); this.fileSize = dv.getInt32(); this.headerSize = dv.getInt32(); this.endianTag = dv.getInt32(); this.linkSize = dv.getInt32(); this.linkOff = dv.getInt32(); this.mapOff = dv.getInt32(); this.stringIdsSize = dv.getInt32(); this.stringIdsOff = dv.getInt32(); this.typeIdsSize = dv.getInt32(); this.typeIdsOff = dv.getInt32(); this.protoIdsSize = dv.getInt32(); this.protoIdsOff = dv.getInt32(); this.fieldIdsSize = dv.getInt32(); this.fieldIdsOff = dv.getInt32(); this.methodIdsSize = dv.getInt32(); this.methodIdsOff = dv.getInt32(); this.classDefsSize = dv.getInt32(); this.classDefsOff = dv.getInt32(); this.dataSize = dv.getInt32(); this.dataOff = dv.getInt32(); } } jDataView.prototype.readStringUtf = function () { var len = this.readUnsignedLeb128(); return this.getString(len); }; jDataView.prototype.readUnsignedLeb128 = function () { var result = 0; do { var b = this.getUint8(); result = (result << 7) | (b & 0x7f); } while (b < 0); return result; }; }
the_stack
* @module Tools */ import { Id64String } from "@itwin/core-bentley"; import { PlanarClipMaskMode, PlanarClipMaskPriority, PlanarClipMaskSettings } from "@itwin/core-common"; import { BeButtonEvent, ContextRealityModelState, EventHandled, HitDetail, IModelApp, LocateFilterStatus, LocateResponse, PrimitiveTool, ScreenViewport, Tool, } from "@itwin/core-frontend"; /** Set Map Masking by selected models. * @beta */ export class SetMapHigherPriorityMasking extends Tool { public static override toolId = "SetMapHigherPriorityMask"; public static override get minArgs() { return 0; } public static override get maxArgs() { return 1; } public override async run(transparency?: number): Promise<boolean> { const vp = IModelApp.viewManager.selectedView; if (undefined === vp) return false; vp.changeBackgroundMapProps({ planarClipMask: { mode: PlanarClipMaskMode.Priority, priority: PlanarClipMaskPriority.BackgroundMap, transparency } }); vp.invalidateRenderPlan(); return true; } public override async parseAndRun(...args: string[]): Promise<boolean> { const transparency = parseFloat(args[0]); return this.run((transparency !== undefined && transparency < 1.0) ? transparency : undefined); } } /** Unmask Mask. * @beta */ export class UnmaskMapTool extends Tool { public static override toolId = "UnmaskMap"; public static override get minArgs() { return 0; } public static override get maxArgs() { return 0; } public override async run(): Promise<boolean> { const vp = IModelApp.viewManager.selectedView; if (undefined === vp) return false; vp.changeBackgroundMapProps({ planarClipMask: { mode: PlanarClipMaskMode.None } }); vp.invalidateRenderPlan(); return true; } } /** Base class for the reality model planar masking tools. * @beta */ export abstract class PlanarMaskBaseTool extends PrimitiveTool { protected readonly _acceptedModelIds = new Set<Id64String>(); protected readonly _acceptedSubCategoryIds = new Set<Id64String>(); protected readonly _acceptedElementIds = new Set<Id64String>(); protected _transparency?: number; protected _useSelection: boolean = false; protected _targetMaskModel?: Id64String | ContextRealityModelState; public override requireWriteableTarget(): boolean { return false; } public override async onPostInstall() { await super.onPostInstall(); this.setupAndPromptForNextAction(); } public override async onUnsuspend() { this.showPrompt(); } private setupAndPromptForNextAction(): void { this._useSelection = (undefined !== this.targetView && this.iModel.selectionSet.isActive); this.initLocateElements(!this._useSelection || (this.targetModelRequired() && !this._targetMaskModel)); IModelApp.locateManager.options.allowDecorations = true; // So we can select "contextual" reality models. this.showPrompt(); } protected targetModelRequired(): boolean { return true; } protected elementRequired(): boolean { return true; } protected allowSelection(): boolean { return true; } protected abstract showPrompt(): void; protected abstract createToolInstance(): PlanarMaskBaseTool; protected abstract applyMask(vp: ScreenViewport): void; private clearIds() { this._acceptedElementIds.clear(); this._acceptedModelIds.clear(); } public override async exitTool() { await super.exitTool(); this._transparency = undefined; } public async onRestartTool() { this.clearIds(); this._acceptedSubCategoryIds.clear(); const tool = this.createToolInstance(); if (!await tool.run()) await this.exitTool(); } public override async parseAndRun(...args: string[]): Promise<boolean> { const transparency = parseFloat(args[0]); this._transparency = (transparency !== undefined && transparency < 1.0) ? transparency : undefined; return this.run(); } public override async onCleanup() { if (0 !== this._acceptedElementIds.size) this.iModel.hilited.setHilite(this._acceptedElementIds, false); this.clearIds(); } public override async filterHit(hit: HitDetail, _out?: LocateResponse): Promise<LocateFilterStatus> { if (!hit.modelId) return LocateFilterStatus.Reject; if (undefined === this._targetMaskModel && this.targetModelRequired()) { if (undefined !== hit.viewport.displayStyle.contextRealityModelStates.find((x) => x.modelId === hit.modelId)) return LocateFilterStatus.Accept; const model = this.iModel.models.getLoaded(hit.modelId)?.asSpatialModel; return model?.isRealityModel ? LocateFilterStatus.Accept : LocateFilterStatus.Reject; } else return (hit.isElementHit && !hit.isModelHit && !this._acceptedElementIds.has(hit.sourceId)) ? LocateFilterStatus.Accept : LocateFilterStatus.Reject; } public override async onDataButtonDown(ev: BeButtonEvent): Promise<EventHandled> { const hit = await IModelApp.locateManager.doLocate(new LocateResponse(), true, ev.point, ev.viewport, ev.inputSource); const vp = IModelApp.viewManager.selectedView; if (undefined === vp) return EventHandled.No; if (undefined !== hit && undefined === this._targetMaskModel && this.targetModelRequired()) { if (hit.modelId) { this._targetMaskModel = hit.viewport.displayStyle.contextRealityModelStates.find((x) => x.modelId === hit.modelId) ?? hit.modelId; if (!this.elementRequired()) { this.applyMask(vp); await this.onRestartTool(); } } } else if (this._useSelection && this.iModel.selectionSet.isActive) { const elements = await this.iModel.elements.getProps(this.iModel.selectionSet.elements); for (const element of elements) { if (element.id && element.model) { this._acceptedElementIds.add(element.id); this._acceptedModelIds.add(element.model); } } this.applyMask(vp); await this.exitTool(); return EventHandled.No; } else if (undefined !== hit && hit.isElementHit) { const sourceId = hit.sourceId; if (!this._acceptedElementIds.has(sourceId)) { this._acceptedElementIds.add(sourceId); this._acceptedModelIds.add(hit.modelId!); if (hit.subCategoryId) this._acceptedSubCategoryIds.add(hit.subCategoryId); this.applyMask(vp); } } this.setupAndPromptForNextAction(); return EventHandled.No; } protected createSubCategoryMask() { return PlanarClipMaskSettings.createForElementsOrSubCategories(PlanarClipMaskMode.IncludeSubCategories, this._acceptedSubCategoryIds, this._acceptedModelIds, this._transparency); } protected createElementMask(option: "include" | "exclude") { const mode = "include" === option ? PlanarClipMaskMode.IncludeElements : PlanarClipMaskMode.ExcludeElements; return PlanarClipMaskSettings.createForElementsOrSubCategories(mode, this._acceptedElementIds, this._acceptedModelIds, this._transparency); } protected createModelMask() { return PlanarClipMaskSettings.createForModels(this._acceptedModelIds, this._transparency); } protected setRealityModelMask(vp: ScreenViewport, mask: PlanarClipMaskSettings): void { if (typeof this._targetMaskModel === "string") vp.displayStyle.settings.planarClipMasks.set(this._targetMaskModel, mask); else if (undefined !== this._targetMaskModel) this._targetMaskModel.planarClipMaskSettings = mask; } } /** Tool to mask background map by elements * @beta */ export class MaskBackgroundMapByElementTool extends PlanarMaskBaseTool { public static override toolId = "MaskBackgroundMapByElement"; public static override get minArgs() { return 0; } public static override get maxArgs() { return 1; } protected override targetModelRequired() { return false; } protected showPrompt(): void { IModelApp.notifications.outputPromptByKey(`FrontendDevTools:tools.MaskBackgroundMapByElement.Prompts.${this._useSelection ? "AcceptSelection" : "IdentifyMaskElement"}`); } protected createToolInstance(): PlanarMaskBaseTool { return new MaskBackgroundMapByElementTool(); } protected applyMask(vp: ScreenViewport): void { vp.changeBackgroundMapProps({ planarClipMask: this.createElementMask("include").toJSON() }); } } /** Tool to mask background map by excluded elements * @beta */ export class MaskBackgroundMapByExcludedElementTool extends PlanarMaskBaseTool { public static override toolId = "MaskBackgroundMapByExcludedElement"; public static override get minArgs() { return 0; } public static override get maxArgs() { return 1; } protected override targetModelRequired() { return false; } protected showPrompt(): void { IModelApp.notifications.outputPromptByKey(`FrontendDevTools:tools.MaskBackgroundMapByExcludedElement.Prompts.${this._useSelection ? "AcceptSelection" : "IdentifyMaskElement"}`); } protected createToolInstance(): PlanarMaskBaseTool { return new MaskBackgroundMapByExcludedElementTool(); } protected applyMask(vp: ScreenViewport): void { vp.changeBackgroundMapProps({ planarClipMask: this.createElementMask("exclude").toJSON() }); } } /** Tool to mask background map by SubCategories * @beta */ export class MaskBackgroundMapBySubCategoryTool extends PlanarMaskBaseTool { public static override toolId = "MaskBackgroundMapBySubCategory"; public static override get minArgs() { return 0; } public static override get maxArgs() { return 1; } protected override targetModelRequired() { return false; } protected override allowSelection(): boolean { return false; } // Need picking to get subcategory. protected showPrompt(): void { IModelApp.notifications.outputPromptByKey("FrontendDevTools:tools.MaskBackgroundMapBySubCategory.Prompts.IdentifyMaskSubCategory"); } protected createToolInstance(): PlanarMaskBaseTool { return new MaskBackgroundMapBySubCategoryTool(); } protected applyMask(vp: ScreenViewport): void { vp.changeBackgroundMapProps({ planarClipMask: this.createSubCategoryMask().toJSON() }); } } /** Tool to mask background map by geometric models * @beta */ export class MaskBackgroundMapByModelTool extends PlanarMaskBaseTool { public static override toolId = "MaskBackgroundMapByModel"; public static override get minArgs() { return 0; } public static override get maxArgs() { return 1; } protected override targetModelRequired() { return false; } protected showPrompt(): void { IModelApp.notifications.outputPromptByKey(`FrontendDevTools:tools.MaskBackgroundMapByModel.Prompts.${this._useSelection ? "AcceptSelection" : "IdentifyMaskModel"}`); } protected createToolInstance(): PlanarMaskBaseTool { return new MaskBackgroundMapByModelTool(); } protected applyMask(vp: ScreenViewport): void { vp.changeBackgroundMapProps({ planarClipMask: this.createModelMask().toJSON() }); } } /** Tool to mask reality model by elements * @beta */ export class MaskRealityModelByElementTool extends PlanarMaskBaseTool { public static override toolId = "MaskRealityModelByElement"; public static override get minArgs() { return 0; } public static override get maxArgs() { return 1; } protected override targetModelRequired() { return true; } protected showPrompt(): void { const key = `FrontendDevTools:tools.MaskRealityModelByElement.Prompts.${this._targetMaskModel === undefined ? "IdentifyRealityModel" : (this._useSelection ? "AcceptSelection" : "IdentifyMaskElement")}`; IModelApp.notifications.outputPromptByKey(key); } protected createToolInstance(): PlanarMaskBaseTool { return new MaskRealityModelByElementTool(); } protected applyMask(vp: ScreenViewport): void { this.setRealityModelMask(vp, this.createElementMask("include")); } } /** Tool to mask reality model by excluded elements * @beta */ export class MaskRealityModelByExcludedElementTool extends PlanarMaskBaseTool { public static override toolId = "MaskRealityModelByExcludedElement"; public static override get minArgs() { return 0; } public static override get maxArgs() { return 1; } protected override targetModelRequired() { return true; } protected showPrompt(): void { const key = `FrontendDevTools:tools.MaskRealityModelByExcludedElement.Prompts.${this._targetMaskModel === undefined ? "IdentifyRealityModel" : (this._useSelection ? "AcceptSelection" : "IdentifyMaskElement")}`; IModelApp.notifications.outputPromptByKey(key); } protected createToolInstance(): PlanarMaskBaseTool { return new MaskRealityModelByExcludedElementTool(); } protected applyMask(vp: ScreenViewport): void { this.setRealityModelMask(vp, this.createElementMask("exclude")); } } /** Tool to mask reality model by geometric models * @beta */ export class MaskRealityModelByModelTool extends PlanarMaskBaseTool { public static override toolId = "MaskRealityModelByModel"; public static override get minArgs() { return 0; } public static override get maxArgs() { return 1; } protected override targetModelRequired() { return true; } protected showPrompt(): void { const key = `FrontendDevTools:tools.MaskRealityModelByModel.Prompts.${this._targetMaskModel === undefined ? "IdentifyRealityModel" : (this._useSelection ? "AcceptSelection" : "IdentifyMaskModel")}`; IModelApp.notifications.outputPromptByKey(key); } protected createToolInstance(): PlanarMaskBaseTool { return new MaskRealityModelByModelTool(); } protected applyMask(vp: ScreenViewport): void { this.setRealityModelMask(vp, this.createModelMask()); } } /** Tool to mask reality model by SubCategories * @beta */ export class MaskRealityModelBySubCategoryTool extends PlanarMaskBaseTool { public static override toolId = "MaskRealityModelBySubCategory"; public static override get minArgs() { return 0; } public static override get maxArgs() { return 1; } protected override targetModelRequired() { return true; } protected override allowSelection(): boolean { return false; } // Need picking to get subcategory. protected showPrompt(): void { const key = `FrontendDevTools:tools.MaskRealityModelByModel.Prompts.${this._targetMaskModel === undefined ? "IdentifyRealityModel" : "IdentifyMaskSubCategory"}`; IModelApp.notifications.outputPromptByKey(key); } protected createToolInstance(): PlanarMaskBaseTool { return new MaskRealityModelBySubCategoryTool(); } protected applyMask(vp: ScreenViewport): void { this.setRealityModelMask(vp, this.createSubCategoryMask()); } } /** Tool to mask reality model by higher priority models. * @beta */ export class SetHigherPriorityRealityModelMasking extends PlanarMaskBaseTool { public static override toolId = "SetHigherPriorityRealityModelMasking"; public static override get minArgs() { return 0; } public static override get maxArgs() { return 2; } protected override targetModelRequired() { return true; } protected override elementRequired() { return false; } private _priority = 0; protected showPrompt(): void { IModelApp.notifications.outputPromptByKey("FrontendDevTools:tools.SetHigherPriorityRealityModelMasking.Prompts.IdentifyRealityModel"); } protected createToolInstance(): PlanarMaskBaseTool { return new SetHigherPriorityRealityModelMasking(); } protected applyMask(vp: ScreenViewport): void { const basePriority = this._targetMaskModel === vp.displayStyle.getOSMBuildingRealityModel() ? PlanarClipMaskPriority.GlobalRealityModel : PlanarClipMaskPriority.RealityModel; this.setRealityModelMask(vp, PlanarClipMaskSettings.createByPriority(basePriority + this._priority, this._transparency)!); } public override async parseAndRun(...args: string[]): Promise<boolean> { await super.parseAndRun(...args); const priority = parseInt(args[0], 10); this._priority = (priority === undefined || isNaN(priority)) ? 0 : priority; return this.run(); } } /** Remove masks from reality model. * @beta */ export class UnmaskRealityModelTool extends PlanarMaskBaseTool { public static override toolId = "UnmaskRealityModel"; protected override targetModelRequired() { return true; } protected showPrompt(): void { IModelApp.notifications.outputPromptByKey("FrontendDevTools:tools.UnmaskRealityModel.Prompts.IdentifyRealityModel"); } protected createToolInstance(): PlanarMaskBaseTool { return new UnmaskRealityModelTool(); } protected applyMask(vp: ScreenViewport): void { const settings = PlanarClipMaskSettings.createForElementsOrSubCategories(PlanarClipMaskMode.IncludeSubCategories, this._acceptedSubCategoryIds, this._acceptedModelIds); this.setRealityModelMask(vp, settings); } public override async onDataButtonDown(ev: BeButtonEvent): Promise<EventHandled> { const hit = await IModelApp.locateManager.doLocate(new LocateResponse(), true, ev.point, ev.viewport, ev.inputSource); if (hit?.modelId) { const model = hit.viewport.displayStyle.contextRealityModelStates.find((x) => x.modelId === hit.modelId); if (model) model.planarClipMaskSettings = undefined; else hit.viewport.displayStyle.settings.planarClipMasks.delete(hit.modelId); await this.onRestartTool(); } return EventHandled.No; } }
the_stack
import * as fs from 'fs'; import * as path from 'path'; import * as vm from 'vm'; import { compileJsiiForTest, HelperCompilationResult } from '../lib'; import { Compiler } from '../lib/compiler'; import { loadProjectInfo } from '../lib/project-info'; const DEPRECATED = '/** @deprecated Use something else */'; describe('Function generation', () => { test('generates the print function', () => { const result = compileJsiiForTest(``, undefined /* callback */, { addDeprecationWarnings: true, }); expect(jsFile(result, '.warnings.jsii')).toBe( `function print(name, deprecationMessage) { const deprecated = process.env.JSII_DEPRECATED; const deprecationMode = ["warn", "fail", "quiet"].includes(deprecated) ? deprecated : "warn"; const message = \`\${name} is deprecated.\\n \${deprecationMessage.trim()}\\n This API will be removed in the next major release.\`; switch (deprecationMode) { case "fail": throw new DeprecationError(message); case "warn": console.warn("[WARNING]", message); break; } } function getPropertyDescriptor(obj, prop) { const descriptor = Object.getOwnPropertyDescriptor(obj, prop); if (descriptor) { return descriptor; } const proto = Object.getPrototypeOf(obj); const prototypeDescriptor = proto && getPropertyDescriptor(proto, prop); if (prototypeDescriptor) { return prototypeDescriptor; } return {}; } const visitedObjects = new Set(); class DeprecationError extends Error { constructor(...args) { super(...args); Object.defineProperty(this, "name", { configurable: false, enumerable: true, value: "DeprecationError", writable: false, }); } } module.exports = { print, getPropertyDescriptor, DeprecationError }; `, ); }); test('generates a function for each type', () => { const result = compileJsiiForTest( ` export interface Foo {} export interface Bar {} export interface Baz {} `, undefined /* callback */, { addDeprecationWarnings: true }, ); expect(jsFile(result, '.warnings.jsii')).toMatch( `function testpkg_Foo(p) { } function testpkg_Bar(p) { } function testpkg_Baz(p) { }`, ); }); test('generates metadata', () => { const result = compileJsiiForTest( ` export interface Foo {} export interface Bar {} export interface Baz {} `, undefined /* callback */, { addDeprecationWarnings: true }, ); expect( result.assembly.metadata?.jsii?.compiledWithDeprecationWarnings, ).toBe(true); }); test('for each non-primitive property, generates a call', () => { const result = compileJsiiForTest( ` export interface Foo {} export interface Bar {} export interface Baz { readonly foo: Foo; readonly bar: Bar; readonly x: string; } `, undefined /* callback */, { addDeprecationWarnings: true }, ); expect(jsFile(result, '.warnings.jsii')).toMatch(`function testpkg_Baz(p) { if (p == null) return; visitedObjects.add(p); try { if (!visitedObjects.has(p.bar)) testpkg_Bar(p.bar); if (!visitedObjects.has(p.foo)) testpkg_Foo(p.foo); } finally { visitedObjects.delete(p); } }`); }); test('generates empty functions for interfaces', () => { const result = compileJsiiForTest( ` export interface IFoo { bar(): string; } `, undefined /* callback */, { addDeprecationWarnings: true }, ); expect(jsFile(result, '.warnings.jsii')).toMatch(`function testpkg_IFoo(p) { }`); }); test('generates empty functions for classes', () => { const result = compileJsiiForTest( ` export class Foo { bar() {return 0}; } `, undefined /* callback */, { addDeprecationWarnings: true }, ); expect(jsFile(result, '.warnings.jsii')).toMatch(`function testpkg_Foo(p) { }`); }); test('generates calls for recursive types', () => { const result = compileJsiiForTest( ` export interface Bar {readonly bar?: Bar} `, undefined /* callback */, { addDeprecationWarnings: true }, ); expect(jsFile(result, '.warnings.jsii')).toMatch( `function testpkg_Bar(p) { if (p == null) return; visitedObjects.add(p); try { if (!visitedObjects.has(p.bar)) testpkg_Bar(p.bar); } finally { visitedObjects.delete(p); } }`, ); }); test('generates exports for all the functions', () => { const result = compileJsiiForTest( ` export interface Foo {} export interface Bar {} export interface Baz {} `, undefined /* callback */, { addDeprecationWarnings: true }, ); expect(jsFile(result, '.warnings.jsii')).toMatch( `module.exports = { print, getPropertyDescriptor, DeprecationError, testpkg_Foo, testpkg_Bar, testpkg_Baz };`, ); }); test('generates functions for enums', () => { const result = compileJsiiForTest( ` export enum State { ON, ${DEPRECATED} OFF } `, undefined /* callback */, { addDeprecationWarnings: true }, ); expect(jsFile(result, '.warnings.jsii')) .toMatch(`function testpkg_State(p) { if (p == null) return; visitedObjects.add(p); try { const ns = require("./index.js"); if (Object.values(ns.State).filter(x => x === p).length > 1) return; if (p === ns.State.OFF) print("testpkg.State#OFF", "Use something else"); } finally { visitedObjects.delete(p); } } `); }); test('generates calls for deprecated inherited properties', () => { const result = compileJsiiForTest( ` export interface Baz { /** @deprecated message from Baz */ readonly x: string; } export interface Bar { /** @deprecated message from Bar */ readonly x: string; } export interface Foo extends Bar, Baz { } `, undefined /* callback */, { addDeprecationWarnings: true }, ); const warningsFileContent = jsFile(result, '.warnings.jsii'); // For each supertype, its corresponding function should be generated, as usual expect(warningsFileContent).toMatch(`function testpkg_Baz(p) { if (p == null) return; visitedObjects.add(p); try { if ("x" in p) print("testpkg.Baz#x", "message from Baz"); } finally { visitedObjects.delete(p); } }`); expect(warningsFileContent).toMatch(`function testpkg_Bar(p) { if (p == null) return; visitedObjects.add(p); try { if ("x" in p) print("testpkg.Bar#x", "message from Bar"); } finally { visitedObjects.delete(p); } }`); // But a call for one of the instances of the property should also be generated in the base function expect(warningsFileContent).toMatch(`function testpkg_Foo(p) { if (p == null) return; visitedObjects.add(p); try { if ("x" in p) print("testpkg.Baz#x", "message from Baz"); } finally { visitedObjects.delete(p); } }`); }); test('skips properties that are deprecated in one supertype but not the other', () => { const result = compileJsiiForTest( ` export interface Baz { readonly x: string; } export interface Bar { /** @deprecated message from Bar */ readonly x: string; } export interface Foo extends Bar, Baz { } `, undefined /* callback */, { addDeprecationWarnings: true }, ); const warningsFileContent = jsFile(result, '.warnings.jsii'); expect(warningsFileContent).toMatch(`function testpkg_Foo(p) { }`); }); test('generates calls for types with deprecated properties', () => { const result = compileJsiiForTest( ` export interface Bar { readonly x: string; } export interface Foo { readonly y: string; /** @deprecated kkkkkkkk */ readonly bar: Bar; } `, undefined /* callback */, { addDeprecationWarnings: true }, ); expect(jsFile(result, '.warnings.jsii')).toMatch(`function testpkg_Foo(p) { if (p == null) return; visitedObjects.add(p); try { if ("bar" in p) print("testpkg.Foo#bar", "kkkkkkkk"); if (!visitedObjects.has(p.bar)) testpkg_Bar(p.bar); } finally { visitedObjects.delete(p); } } `); }); test('generates calls for each property of a deprecated type', () => { const result = compileJsiiForTest( ` /** @deprecated use Bar instead */ export interface Foo { readonly bar: string; readonly baz: number; } `, undefined /* callback */, { addDeprecationWarnings: true }, ); expect(jsFile(result, '.warnings.jsii')).toMatch(`function testpkg_Foo(p) { if (p == null) return; visitedObjects.add(p); try { if ("bar" in p) print("testpkg.Foo#bar", "use Bar instead"); if ("baz" in p) print("testpkg.Foo#baz", "use Bar instead"); } finally { visitedObjects.delete(p); } } `); }); test('generates calls for types in other assemblies', () => { const calcBaseOfBaseRoot = resolveModuleDir( '@scope/jsii-calc-base-of-base', ); const calcBaseRoot = resolveModuleDir('@scope/jsii-calc-base'); const calcLibRoot = resolveModuleDir('@scope/jsii-calc-lib'); compile(calcBaseOfBaseRoot, false); compile(calcBaseRoot, true); compile(calcLibRoot, true); const warningsFile = loadWarningsFile(calcBaseRoot); // jsii-calc-base was compiled with warnings. So we expect to see handlers for its types in the warnings file expect(warningsFile).toMatch('_scope_jsii_calc_base'); // jsii-calc-base-of-base was not compiled with warnings. Its types shouldn't be in the warnings file expect(warningsFile).not.toMatch('_scope_jsii_calc_base_of_base'); // Recompiling without deprecation warning to leave the packages in a clean state compile(calcBaseRoot, false); compile(calcLibRoot, false); }, 120000); }); describe('Call injections', () => { test('does not add warnings by default', () => { const result = compileJsiiForTest( ` export class Foo { ${DEPRECATED} public bar(){} } `, ); expect(jsFile(result)).toMatch('bar() { }'); expect( result.assembly.metadata?.jsii?.compiledWithDeprecationWarnings, ).toBeFalsy(); }); test('generates a require statement', () => { const result = compileJsiiForTest( { 'index.ts': `export * from './some/folder/source'`, 'some/folder/source.ts': ` export class Foo { ${DEPRECATED} public bar(){} } `, }, undefined /* callback */, { addDeprecationWarnings: true }, ); const expectedPath = ['..', '..', '.warnings.jsii.js'].join('/'); const content = jsFile(result, 'some/folder/source'); expect(content).toContain( `const jsiiDeprecationWarnings = require("${expectedPath}")`, ); }, 60000); test('does not generate a require statement when no calls were injected', () => { const result = compileJsiiForTest( { 'index.ts': `export * from './some/folder/handler'`, 'some/folder/handler.ts': ` export function handler(event: any) { return event; } `, }, undefined /* callback */, { addDeprecationWarnings: true }, ); const expectedPath = ['..', '..', '.warnings.jsii.js'].join('/'); const content = jsFile(result, 'some/folder/handler'); expect(content).not.toContain( `const jsiiDeprecationWarnings = require("${expectedPath}")`, ); }, 60000); test('deprecated methods', () => { const result = compileJsiiForTest( ` export class Foo { ${DEPRECATED} public bar(){} } `, undefined /* callback */, { addDeprecationWarnings: true }, ); expect(jsFile(result)).toMatchInlineSnapshot(` "\\"use strict\\"; var _a; Object.defineProperty(exports, \\"__esModule\\", { value: true }); exports.Foo = void 0; const jsiiDeprecationWarnings = require(\\"./.warnings.jsii.js\\"); const JSII_RTTI_SYMBOL_1 = Symbol.for(\\"jsii.rtti\\"); class Foo { /** @deprecated Use something else */ bar() { try { jsiiDeprecationWarnings.print(\\"testpkg.Foo#bar\\", \\"Use something else\\"); } catch (error) { if (process.env.JSII_DEBUG !== \\"1\\" && error.name === \\"DeprecationError\\") { Error.captureStackTrace(error, this.bar); } throw error; } } } exports.Foo = Foo; _a = JSII_RTTI_SYMBOL_1; Foo[_a] = { fqn: \\"testpkg.Foo\\", version: \\"0.0.1\\" }; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJpbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7QUFDSSxNQUFhLEdBQUc7SUFDZCxxQ0FBcUM7SUFDOUIsR0FBRzs7Ozs7Ozs7T0FBSTs7QUFGaEIsa0JBR0MiLCJzb3VyY2VzQ29udGVudCI6WyJcbiAgICBleHBvcnQgY2xhc3MgRm9vIHtcbiAgICAgIC8qKiBAZGVwcmVjYXRlZCBVc2Ugc29tZXRoaW5nIGVsc2UgKi9cbiAgICAgIHB1YmxpYyBiYXIoKXt9XG4gICAgfVxuICAiXX0=" `); }); test('methods with parameters', () => { const result = compileJsiiForTest( ` export interface A {readonly x: number;} export class Foo { public bar(a: A, b: number){return a.x + b;} }`, undefined /* callback */, { addDeprecationWarnings: true }, ); expect(jsFile(result)).toMatchInlineSnapshot(` "\\"use strict\\"; var _a; Object.defineProperty(exports, \\"__esModule\\", { value: true }); exports.Foo = void 0; const jsiiDeprecationWarnings = require(\\"./.warnings.jsii.js\\"); const JSII_RTTI_SYMBOL_1 = Symbol.for(\\"jsii.rtti\\"); class Foo { bar(a, b) { try { jsiiDeprecationWarnings.testpkg_A(a); } catch (error) { if (process.env.JSII_DEBUG !== \\"1\\" && error.name === \\"DeprecationError\\") { Error.captureStackTrace(error, this.bar); } throw error; } return a.x + b; } } exports.Foo = Foo; _a = JSII_RTTI_SYMBOL_1; Foo[_a] = { fqn: \\"testpkg.Foo\\", version: \\"0.0.1\\" }; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJpbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7QUFFUyxNQUFhLEdBQUc7SUFDUixHQUFHLENBQUMsQ0FBSSxFQUFFLENBQVM7Ozs7Ozs7O01BQUUsT0FBTyxDQUFDLENBQUMsQ0FBQyxHQUFHLENBQUMsQ0FBQyxFQUFDOztBQUQ3QyxrQkFFQyIsInNvdXJjZXNDb250ZW50IjpbIlxuICAgICAgICBleHBvcnQgaW50ZXJmYWNlIEEge3JlYWRvbmx5IHg6IG51bWJlcjt9XG4gICAgICAgICBleHBvcnQgY2xhc3MgRm9vIHtcbiAgICAgICAgICBwdWJsaWMgYmFyKGE6IEEsIGI6IG51bWJlcil7cmV0dXJuIGEueCArIGI7fVxuICAgICAgICAgfSJdfQ==" `); }, 60000); test('deprecated getters', () => { const result = compileJsiiForTest( ` export class Foo { private _x = 0; ${DEPRECATED} public get x(){return this._x} } `, undefined /* callback */, { addDeprecationWarnings: true }, ); expect(jsFile(result)).toMatchInlineSnapshot(` "\\"use strict\\"; var _a; Object.defineProperty(exports, \\"__esModule\\", { value: true }); exports.Foo = void 0; const jsiiDeprecationWarnings = require(\\"./.warnings.jsii.js\\"); const JSII_RTTI_SYMBOL_1 = Symbol.for(\\"jsii.rtti\\"); class Foo { constructor() { this._x = 0; } /** @deprecated Use something else */ get x() { try { jsiiDeprecationWarnings.print(\\"testpkg.Foo#x\\", \\"Use something else\\"); } catch (error) { if (process.env.JSII_DEBUG !== \\"1\\" && error.name === \\"DeprecationError\\") { Error.captureStackTrace(error, jsiiDeprecationWarnings.getPropertyDescriptor(this, \\"x\\").get); } throw error; } return this._x; } } exports.Foo = Foo; _a = JSII_RTTI_SYMBOL_1; Foo[_a] = { fqn: \\"testpkg.Foo\\", version: \\"0.0.1\\" }; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJpbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7QUFDSSxNQUFhLEdBQUc7SUFBaEI7UUFDVSxPQUFFLEdBQUcsQ0FBQyxDQUFDO0tBR2hCO0lBRkMscUNBQXFDO0lBQ3JDLElBQVcsQ0FBQzs7Ozs7Ozs7TUFBRyxPQUFPLElBQUksQ0FBQyxFQUFFLENBQUEsRUFBQzs7QUFIaEMsa0JBSUMiLCJzb3VyY2VzQ29udGVudCI6WyJcbiAgICBleHBvcnQgY2xhc3MgRm9vIHtcbiAgICAgIHByaXZhdGUgX3ggPSAwO1xuICAgICAgLyoqIEBkZXByZWNhdGVkIFVzZSBzb21ldGhpbmcgZWxzZSAqL1xuICAgICAgcHVibGljIGdldCB4KCl7cmV0dXJuIHRoaXMuX3h9XG4gICAgfVxuICAiXX0=" `); }); test('deprecated setters', () => { const result = compileJsiiForTest( ` export class Foo { private _x = 0; public get x(){return this._x} ${DEPRECATED} public set x(_x: number) {this._x = _x;} } `, undefined /* callback */, { addDeprecationWarnings: true }, ); expect(jsFile(result)).toMatchInlineSnapshot(` "\\"use strict\\"; var _a; Object.defineProperty(exports, \\"__esModule\\", { value: true }); exports.Foo = void 0; const jsiiDeprecationWarnings = require(\\"./.warnings.jsii.js\\"); const JSII_RTTI_SYMBOL_1 = Symbol.for(\\"jsii.rtti\\"); class Foo { constructor() { this._x = 0; } get x() { try { jsiiDeprecationWarnings.print(\\"testpkg.Foo#x\\", \\"Use something else\\"); } catch (error) { if (process.env.JSII_DEBUG !== \\"1\\" && error.name === \\"DeprecationError\\") { Error.captureStackTrace(error, jsiiDeprecationWarnings.getPropertyDescriptor(this, \\"x\\").get); } throw error; } return this._x; } /** @deprecated Use something else */ set x(_x) { try { jsiiDeprecationWarnings.print(\\"testpkg.Foo#x\\", \\"Use something else\\"); } catch (error) { if (process.env.JSII_DEBUG !== \\"1\\" && error.name === \\"DeprecationError\\") { Error.captureStackTrace(error, jsiiDeprecationWarnings.getPropertyDescriptor(this, \\"x\\").set); } throw error; } this._x = _x; } } exports.Foo = Foo; _a = JSII_RTTI_SYMBOL_1; Foo[_a] = { fqn: \\"testpkg.Foo\\", version: \\"0.0.1\\" }; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJpbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7QUFDSSxNQUFhLEdBQUc7SUFBaEI7UUFDVSxPQUFFLEdBQUcsQ0FBQyxDQUFDO0tBS2hCO0lBSkMsSUFBVyxDQUFDOzs7Ozs7OztNQUFHLE9BQU8sSUFBSSxDQUFDLEVBQUUsQ0FBQSxFQUFDO0lBRTlCLHFDQUFxQztJQUNyQyxJQUFXLENBQUMsQ0FBQyxFQUFVOzs7Ozs7OztNQUFHLElBQUksQ0FBQyxFQUFFLEdBQUcsRUFBRSxDQUFDLEVBQUM7O0FBTDFDLGtCQU1DIiwic291cmNlc0NvbnRlbnQiOlsiXG4gICAgZXhwb3J0IGNsYXNzIEZvbyB7XG4gICAgICBwcml2YXRlIF94ID0gMDtcbiAgICAgIHB1YmxpYyBnZXQgeCgpe3JldHVybiB0aGlzLl94fVxuXG4gICAgICAvKiogQGRlcHJlY2F0ZWQgVXNlIHNvbWV0aGluZyBlbHNlICovXG4gICAgICBwdWJsaWMgc2V0IHgoX3g6IG51bWJlcikge3RoaXMuX3ggPSBfeDt9XG4gICAgfVxuICAiXX0=" `); }); test('creates a new instance of error when test', () => { const result = compileJsiiForTest( ` ${DEPRECATED} export class Foo { constructor(){} } `, undefined /* callback */, { addDeprecationWarnings: true }, ); expect(jsFile(result)).toMatchInlineSnapshot(` "\\"use strict\\"; var _a; Object.defineProperty(exports, \\"__esModule\\", { value: true }); exports.Foo = void 0; const jsiiDeprecationWarnings = require(\\"./.warnings.jsii.js\\"); const JSII_RTTI_SYMBOL_1 = Symbol.for(\\"jsii.rtti\\"); /** @deprecated Use something else */ class Foo { constructor() { try { jsiiDeprecationWarnings.print(\\"testpkg.Foo\\", \\"Use something else\\"); } catch (error) { if (process.env.JSII_DEBUG !== \\"1\\" && error.name === \\"DeprecationError\\") { Error.captureStackTrace(error, Foo); } throw error; } } } exports.Foo = Foo; _a = JSII_RTTI_SYMBOL_1; Foo[_a] = { fqn: \\"testpkg.Foo\\", version: \\"0.0.1\\" }; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJpbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7QUFDSSxxQ0FBcUM7QUFDckMsTUFBYSxHQUFHO0lBQ2Q7Ozs7OzJDQURXLEdBQUc7OztPQUNDOztBQURqQixrQkFFQyIsInNvdXJjZXNDb250ZW50IjpbIlxuICAgIC8qKiBAZGVwcmVjYXRlZCBVc2Ugc29tZXRoaW5nIGVsc2UgKi9cbiAgICBleHBvcnQgY2xhc3MgRm9vIHtcbiAgICAgIGNvbnN0cnVjdG9yKCl7fVxuICAgIH1cbiAgIl19" `); }); }); describe('thrown exceptions have the expected stack trace', () => { test('constructor', () => { const compilation = compileJsiiForTest( ` /** @deprecated for testing */ export class DeprecatedConstructor { public constructor() {} } function test() { new DeprecatedConstructor(); } test(); `, undefined, { addDeprecationWarnings: true }, ); const source = jsFile(compilation); const context = createVmContext(compilation); try { vm.runInContext(source, context, { filename: 'index.js' }); // The above line should have resulted in a DeprecationError being thrown expect(null).toBeInstanceOf(Error); } catch (error: any) { expect(error.stack.replace(process.cwd(), '<process.cwd>')) .toMatchInlineSnapshot(` "index.js:16 throw error; ^ DeprecationError: testpkg.DeprecatedConstructor is deprecated. for testing This API will be removed in the next major release. at test (index.js:23:5) at index.js:25:1" `); } }); test('getter', () => { const compilation = compileJsiiForTest( ` export class DeprecatedConstructor { /** @deprecated for testing */ public get property() { return 1337; } } function test() { const subject = new DeprecatedConstructor(); return subject.property; } test(); `, undefined, { addDeprecationWarnings: true }, ); const source = jsFile(compilation); const context = createVmContext(compilation); try { vm.runInContext(source, context, { filename: 'index.js' }); // The above line should have resulted in a DeprecationError being thrown expect(null).toBeInstanceOf(Error); } catch (error: any) { expect(error.stack.replace(process.cwd(), '<process.cwd>')) .toMatchInlineSnapshot(` "index.js:17 throw error; ^ DeprecationError: testpkg.DeprecatedConstructor#property is deprecated. for testing This API will be removed in the next major release. at test (index.js:27:20) at index.js:29:1" `); } }); test('setter', () => { const compilation = compileJsiiForTest( ` export class DeprecatedConstructor { private value = 1337; /** @deprecated for testing */ public get property(): number { return this.value; } public set property(value: number) { this.value = value; } } function test() { const subject = new DeprecatedConstructor(); subject.property = 42; } test(); `, undefined, { addDeprecationWarnings: true }, ); const source = jsFile(compilation); const context = createVmContext(compilation); try { vm.runInContext(source, context, { filename: 'index.js' }); // The above line should have resulted in a DeprecationError being thrown expect(null).toBeInstanceOf(Error); } catch (error: any) { expect(error.stack.replace(process.cwd(), '<process.cwd>')) .toMatchInlineSnapshot(` "index.js:32 throw error; ^ DeprecationError: testpkg.DeprecatedConstructor#property is deprecated. for testing This API will be removed in the next major release. at test (index.js:42:22) at index.js:44:1" `); } }); test('method', () => { const compilation = compileJsiiForTest( ` export class DeprecatedConstructor { /** @deprecated for testing */ public deprecated(): void { // Nothing to do } } function test() { const subject = new DeprecatedConstructor(); subject.deprecated(); } test(); `, undefined, { addDeprecationWarnings: true }, ); const source = jsFile(compilation); const context = createVmContext(compilation); try { vm.runInContext(source, context, { filename: 'index.js' }); // The above line should have resulted in a DeprecationError being thrown expect(null).toBeInstanceOf(Error); } catch (error: any) { expect(error.stack.replace(process.cwd(), '<process.cwd>')) .toMatchInlineSnapshot(` "index.js:17 throw error; ^ DeprecationError: testpkg.DeprecatedConstructor#deprecated is deprecated. for testing This API will be removed in the next major release. at test (index.js:26:13) at index.js:28:1" `); } }); }); function jsFile(result: HelperCompilationResult, baseName = 'index'): string { const file = Object.entries(result.files).find( ([name]) => name === `${baseName}.js`, ); if (!file) { throw new Error(`Could not find file with base name: ${baseName}`); } return file[1]; } function createVmContext(compilation: HelperCompilationResult) { const context = vm.createContext({ exports: {}, process: { env: { JSII_DEPRECATED: 'fail', }, }, // Bringing in a "fake" require(id) function that'll resolve relative paths // to files within the compilation output, and module names using the // regular require. When loading a file that was part of the compiler output, // this emulates the situation that would be if the file had been through a // bundler by turning all sequences of white spaces (new line included) into // single spaces. require: (id: string) => { if (!id.startsWith('./')) { // eslint-disable-next-line @typescript-eslint/no-require-imports return require(id); } const code = jsFile(compilation, path.basename(id, '.js')) // Pretend this has been webpack'd .replace(/\s+/gm, ' '); return vm.runInContext( `(function(module){ { ${code} } return module.exports; })({ exports: {} });`, context, { filename: id, lineOffset: -2, columnOffset: -4 }, ); }, }); // Limit error stack traces to 2 frames... We don't need more for the sake of this test. This is // important because past 2 levels, the stack frames will have entries that will be different on // different versions of node, and that'll break our unit tests... vm.runInContext('Error.stackTraceLimit = 2;', context); return context; } function resolveModuleDir(name: string) { return path.dirname(require.resolve(`${name}/package.json`)); } function compile(projectRoot: string, addDeprecationWarnings: boolean) { const { projectInfo } = loadProjectInfo(projectRoot); const compiler = new Compiler({ projectInfo, addDeprecationWarnings, }); compiler.emit(); } function loadWarningsFile(projectRoot: string) { return fs .readFileSync(path.join(projectRoot, '.warnings.jsii.js')) .toString(); }
the_stack
import * as Utils from "./common/utils"; import Renderer = require("./renderer"); import Ruler = require("./ruler"); export = Remarkable; declare class Remarkable { /** * Useful helper functions for custom rendering. */ static utils: typeof Utils; inline: { ruler: Ruler<Remarkable.InlineParsingRule> }; block: { ruler: Ruler<Remarkable.BlockParsingRule> }; core: { ruler: Ruler<Remarkable.CoreParsingRule> }; renderer: Renderer; /** * Markdown parser, done right. */ constructor(options?: Remarkable.Options); /** * Remarkable offers some "presets" as a convenience to quickly enable/disable * active syntax rules and options for common use cases. */ constructor(preset: "commonmark" | "full" | "remarkable", options?: Remarkable.Options); /** * `"# Remarkable rulezz!"` => `"<h1>Remarkable rulezz!</h1>"` */ render(markdown: string, env?: Remarkable.Env): string; /** * Define options. * * Note: To achieve the best possible performance, don't modify a Remarkable instance * on the fly. If you need multiple configurations, create multiple instances and * initialize each with a configuration that is ideal for that instance. */ set(options: Remarkable.Options): void; /** * Use a plugin. */ use(plugin: Remarkable.Plugin, options?: any): Remarkable; /** * Batch loader for components rules states, and options. */ configure(presets: Remarkable.Presets): void; /** * Parse the input `string` and return a tokens array. * Modifies `env` with definitions data. */ parse(str: string, env: Remarkable.Env): Remarkable.Token[]; /** * Parse the given content `string` as a single string. */ parseInline(str: string, env: Remarkable.Env): Remarkable.Token[]; /** * Render a single content `string`, without wrapping it * to paragraphs. */ renderInline(str: string, env?: Remarkable.Env): string; } declare namespace Remarkable { interface Env { [key: string]: any; } type GetBreak = Rule<ContentToken, "" | "\n">; interface Options { /** * Enable HTML tags in source. */ html?: boolean; /** * Use "/" to close single tags (<br />). */ xhtmlOut?: boolean; /** * Convert "\n" in paragraphs into <br>. */ breaks?: boolean; /** * CSS language prefix for fenced blocks. */ langPrefix?: string; /** * Autoconvert URL-like text to links. */ linkify?: boolean; /** * Set target to open link in */ linkTarget?: string; /** * Enable some language-neutral replacement + quotes beautification. */ typographer?: boolean; /** * Double + single quotes replacement pairs, when typographer enabled, * and smartquotes on. Set doubles to "«»" for Russian, "„“" for German. */ quotes?: string; /** * Highlighter function. Should return escaped HTML, or "" if the source * string is not changed. */ highlight?(str: string, lang: string): string; } type Plugin = (md: Remarkable, options?: any) => void; interface Presets { components: { [name: string]: { rules: Rules, }, }; options: Options; } interface StateBlock { src: string; /** Shortcuts to simplify nested calls */ parser: ParserBlock; options: Options; env: Env; tokens: BlockContentToken[]; bMarks: number[]; eMarks: number[]; tShift: number[]; /** required block content indent */ blkIndent: number; /** line index in src */ line: number; /** lines count */ lineMax: number; /** loose/tight mode for lists */ tight: boolean; /** If `list`, block parser stops on two newlines */ parentType: 'root' | 'list'; /** Indent of the current dd block, -1 if there isn't any */ ddIndent: number; level: number; result: string; isEmpty: (line: number) => boolean; skipEmptyLines: (from: number) => number; skipSpaces: (pos: number) => number; skipChars: (pos: number, code: number) => number; getLines: (begin: number, end: number, indent: number, keepLastLF: boolean) => string; } interface StateInline { src: string; env: Env; parser: ParserInline; tokens: ContentToken[]; pos: number; posMax: number; level: number; pending: string; pendingLevel: number; /** Set true when seek link label */ isInLabel: boolean; /** * Increment for each nesting link. * Used to prevent nesting in definitions. */ linkLevel: number; /** * Temporary storage for link url. */ linkContent: string; /** * Track unpaired `[` for link labels. */ labelUnmatchedScopes: number; push: (token: ContentToken) => void; pushPending: () => void; } /** * Return `true` if the parsing function has recognized the current position * in the input as one if its tokens. */ type CoreParsingRule = ( /** * Representation of the current input stream, and the results of * parsing it so far. */ state: StateInline, ) => boolean; /** * Return `true` if the parsing function has recognized the current position * in the input as one if its tokens. */ type InlineParsingRule = ( /** * Representation of the current input stream, and the results of * parsing it so far. */ state: StateInline, /** * If `true` we just do the recognition part, and don't bother to push a * token. */ silent: boolean ) => boolean; /** * Return `true` if the parsing function has recognized the current position * in the input as one if its tokens. */ type BlockParsingRule = ( /** * Representation of the current input stream, and the results of * parsing it so far. */ state: StateBlock, /** * The index of the current line. */ startLine: number, /** * The index of the last available line. */ endLine: number, /** * If `true` we just do the recognition part, and don't bother to push a * token. */ silent: boolean ) => boolean; type Rule<T extends TagToken = TagToken, R extends string = string> = ( /** * The list of tokens currently being processed. */ // tslint:disable-next-line:no-unnecessary-generics tokens: T[], /** * The index of the token currently being processed. */ idx: number, /** * The options given to remarkable. */ options?: Options, /** * The key-value store created by the parsing rules. */ env?: Env, /** * The possible instance of Remarkable. See `fence` renderer function. */ instance?: Remarkable, ) => R; /** * Renderer rules. */ interface Rules { [name: string]: Rule | { [name: string]: Rule<ContentToken> }; "blockquote_open": Rule<BlockquoteOpenToken>; "blockquote_close": Rule<BlockquoteCloseToken>; "code": Rule<CodeToken>; "fence": Rule<FenceToken>; "fence_custom": { [name: string]: Rule<FenceToken> }; "heading_open": Rule<HeadingOpenToken>; "heading_close": Rule<HeadingCloseToken>; "hr": Rule<HrToken>; "bullet_list_open": Rule<BulletListOpenToken>; "bullet_list_close": Rule<BulletListCloseToken>; "list_item_open": Rule<ListItemOpenToken>; "list_item_close": Rule<ListItemCloseToken>; "ordered_list_open": Rule<OrderedListOpenToken>; "ordered_list_close": Rule<OrderedListCloseToken>; "paragraph_open": Rule<ParagraphOpenToken>; "paragraph_close": Rule<ParagraphCloseToken>; "link_open": Rule<LinkOpenToken>; "link_close": Rule<LinkCloseToken>; "image": Rule<ImageToken>; "table_open": Rule<TableOpenToken>; "table_close": Rule<TableCloseToken>; "thead_open": Rule<THeadOpenToken>; "thead_close": Rule<THeadCloseToken>; "tbody_open": Rule<TBodyOpenToken>; "tbody_close": Rule<TBodyCloseToken>; "tr_open": Rule<TROpenToken>; "tr_close": Rule<TRCloseToken>; "th_open": Rule<THOpenToken>; "th_close": Rule<THCloseToken>; "td_open": Rule<TDOpenToken>; "td_close": Rule<TDCloseToken>; "strong_open": Rule<StrongOpenToken>; "strong_close": Rule<StrongCloseToken>; "em_open": Rule<EmOpenToken>; "em_close": Rule<EmCloseToken>; "del_open": Rule<DelOpenToken>; "del_close": Rule<DelCloseToken>; "ins_open": Rule<InsOpenToken>; "ins_close": Rule<InsCloseToken>; "mark_open": Rule<MarkOpenToken>; "mark_close": Rule<MarkCloseToken>; "sub": Rule<SubToken>; "sup": Rule<SupToken>; "hardbreak": Rule<HardbreakToken>; "softbreak": Rule<SoftbreakToken>; "text": Rule<TextToken>; "htmlblock": Rule<HtmlBlockToken>; "htmltag": Rule<HtmlTagToken>; "abbr_open": Rule<AbbrOpenToken>; "abbr_close": Rule<AbbrCloseToken>; "footnote_ref": Rule<FootnoteInlineToken>; "footnote_block_open": Rule<FootnoteBlockOpenToken>; "footnote_block_close": Rule<FootnoteBlockCloseToken>; "footnote_open": Rule<FootnoteOpenToken>; "footnote_close": Rule<FootnoteCloseToken>; "footnote_anchor": Rule<FootnoteAnchorToken>; "dl_open": Rule<DlOpenToken>; "dt_open": Rule<DtOpenToken>; "dd_open": Rule<DdOpenToken>; "dl_close": Rule<DlCloseToken>; "dt_close": Rule<DtCloseToken>; "dd_close": Rule<DdCloseToken>; /** * Check to see if `\n` is needed before the next token. */ getBreak: GetBreak; } interface TagToken { /** * The nesting level of the associated markdown structure in the source. */ level: number; /** * The type of the token. */ type: string; /** * Tokens generated by block parsing rules also include a `lines` * property which is a 2 elements array marking the first and last line of the * `src` used to generate the token. */ lines?: [number, number]; } interface BlockContentToken extends TagToken { /** * The content of the block. This might include inline mardown syntax * which may need further processing by the inline rules. */ content?: string; /** * This is initialized with an empty array (`[]`) and will be filled * with the inline parser tokens as the inline parsing rules are applied. */ children?: Token[]; } interface ContentToken extends TagToken { /** * A text token has a `content` property. This is passed to * the corresponding renderer to be converted for output. */ content?: any; /** * Is this a block element */ block?: boolean; } // --------------- // Specific Block Tokens // --------------- interface BlockquoteToken extends TagToken {} interface BlockquoteOpenToken extends BlockquoteToken { type: 'blockquote_open'; } interface BlockquoteCloseToken extends BlockquoteToken { type: 'blockquote_close'; } interface CodeToken extends BlockContentToken { /** * Code: `true` if block, `false` if inline. */ block: boolean; type: 'code'; } interface DlOpenToken extends TagToken { type: 'dl_open'; } interface DlCloseToken extends TagToken { type: 'dl_close'; } interface DtOpenToken extends TagToken { type: 'dt_open'; } interface DtCloseToken extends TagToken { type: 'dt_close'; } interface DdOpenToken extends TagToken { type: 'dd_open'; } interface DdCloseToken extends TagToken { type: 'dd_close'; } interface FenceToken extends ContentToken { content: string; block?: false; /** * Fenced block params. */ params: string; type: 'fence'; } interface FootnoteGenericToken extends TagToken { /** * Footnote id. */ id: number; /** * Footnote sub id. */ subId?: number; } interface FootnoteReferenceToken extends FootnoteGenericToken {} interface FootnoteReferenceOpenToken extends FootnoteReferenceToken { label: string; type: 'footnote_reference_open'; } interface FootnoteReferenceCloseToken extends FootnoteReferenceToken { type: 'footnote_reference_close'; } type HeadingValue = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; interface HeadingToken extends TagToken { hLevel: HeadingValue; } interface HeadingOpenToken extends HeadingToken { type: 'heading_open'; } interface HeadingCloseToken extends HeadingToken { type: 'heading_close'; } interface HrToken extends TagToken { type: 'hr'; } interface HtmlBlockToken extends ContentToken { content: string; block: false; type: 'htmlblock'; } interface LHeadingOpenToken extends HeadingOpenToken {} interface LHeadingCloseToken extends HeadingCloseToken {} interface OrderedListToken extends TagToken {} interface OrderedListOpenToken extends OrderedListToken { /** * Ordered list marker value. */ order: number; type: 'ordered_list_open'; } interface OrderedListCloseToken extends OrderedListToken { type: 'ordered_list_close'; } interface BulletListToken extends TagToken {} interface BulletListOpenToken extends BulletListToken { type: 'bullet_list_open'; } interface BulletListCloseToken extends BulletListToken { type: 'bullet_list_close'; } interface ListItemToken extends TagToken {} interface ListItemOpenToken extends ListItemToken { type: 'list_item_open'; } interface ListItemCloseToken extends ListItemToken { type: 'list_item_close'; } interface ParagraphToken extends TagToken { /** * Absence of empty line before current tag: `true` if absent, `false` * if present. List is tight if any list item is tight. */ tight: boolean; } interface ParagraphOpenToken extends ParagraphToken { type: 'paragraph_open'; } interface ParagraphCloseToken extends ParagraphToken { type: 'paragraph_close'; } interface TextToken extends TagToken { content?: string; type: 'text'; } interface StrongToken extends TagToken {} interface StrongOpenToken extends TagToken { type: 'strong_open'; } interface StrongCloseToken extends TagToken { type: 'strong_close'; } interface TableToken extends TagToken {} interface TableOpenToken extends TableToken { type: 'table_open'; } interface TableCloseToken extends TableToken { type: 'table_close'; } interface THeadToken extends TagToken {} interface THeadOpenToken extends THeadToken { type: 'thead_open'; } interface THeadCloseToken extends THeadToken { type: 'thead_close'; } interface TBodyToken extends TagToken {} interface TBodyOpenToken extends TBodyToken { type: 'tbody_open'; } interface TBodyCloseToken extends TBodyToken { type: 'tbody_close'; } interface TRToken extends TagToken {} interface TROpenToken extends TRToken { type: 'tr_open'; } interface TRCloseToken extends TRToken { type: 'tr_close'; } interface THToken extends TagToken {} interface THOpenToken extends THToken { type: 'th_open'; } interface THCloseToken extends THToken { type: 'th_close'; } interface TDToken extends TagToken {} interface TDOpenToken extends TDToken { type: 'td_open'; } interface TDCloseToken extends TDToken { type: 'td_close'; } // --------------- // Specific Block Tokens // --------------- interface LinkToken extends TagToken {} interface LinkOpenToken extends LinkToken { /** * Link url. */ href: string; /** * Link title. */ title?: string; type: 'link_open'; } interface LinkCloseToken extends LinkToken { type: 'link_close'; } interface DelToken extends TagToken {} interface DelOpenToken extends DelToken { type: 'del_open'; } interface DelCloseToken extends DelToken { type: 'del_open'; } interface EmToken extends TagToken {} interface EmOpenToken extends EmToken { type: 'em_open'; } interface EmCloseToken extends EmToken { type: 'em_close'; } interface HardbreakToken extends TagToken { type: 'hardbreak'; } interface SoftbreakToken extends TagToken { type: 'softbreak'; } interface FootnoteInlineToken extends FootnoteGenericToken { type: 'footnote_ref'; } interface HtmlTagToken extends ContentToken { content: string; type: 'htmltag'; } interface InsToken extends TagToken {} interface InsOpenToken extends InsToken { type: 'ins_open'; } interface InsCloseToken extends InsToken { type: 'ins_close'; } interface ImageToken extends ContentToken { /** * Image url. */ src: string; /** * Image alt. */ alt: string; /** * Image title. */ title: string; type: 'image'; } interface MarkToken extends TagToken {} interface MarkOpenToken extends MarkToken { type: 'mark_open'; } interface MarkCloseToken extends MarkToken { type: 'mark_close'; } interface SubToken extends ContentToken { content: string; type: 'sub'; } interface SupToken extends ContentToken { content: string; type: 'sup'; } // --------------- // Specific Core Tokens // --------------- interface AbbrToken extends TagToken {} interface AbbrOpenToken extends AbbrToken { /** * Abbreviation title. */ title: string; type: 'abbr_open'; } interface AbbrCloseToken extends AbbrToken { type: 'abbr_close'; } interface FootnoteToken extends FootnoteGenericToken {} interface FootnoteOpenToken extends FootnoteToken { type: 'footnote_open'; } interface FootnoteCloseToken extends FootnoteToken { type: 'footnote_close'; } interface FootnoteBlockToken extends TagToken {} interface FootnoteBlockOpenToken extends FootnoteBlockToken { type: 'footnote_block_open'; } interface FootnoteBlockCloseToken extends FootnoteBlockToken { type: 'footnote_block_close'; } interface FootnoteAnchorToken extends FootnoteGenericToken { type: 'footnote_anchor'; } type Token = | BlockContentToken | ContentToken | TagToken | BlockquoteToken | BlockquoteOpenToken | BlockquoteCloseToken | CodeToken | DlOpenToken | DlCloseToken | DtOpenToken | DtCloseToken | DdOpenToken | DdCloseToken | FenceToken | FootnoteGenericToken | FootnoteReferenceToken | FootnoteReferenceOpenToken | FootnoteReferenceCloseToken | HeadingToken | HeadingOpenToken | HeadingCloseToken | HrToken | HtmlBlockToken | LHeadingOpenToken | LHeadingCloseToken | OrderedListToken | OrderedListOpenToken | OrderedListCloseToken | BulletListToken | BulletListOpenToken | BulletListCloseToken | ListItemToken | ListItemOpenToken | ListItemCloseToken | ParagraphToken | ParagraphOpenToken | ParagraphCloseToken | TextToken | StrongToken | StrongOpenToken | StrongCloseToken | TableToken | TableOpenToken | TableCloseToken | THeadToken | THeadOpenToken | THeadCloseToken | TBodyToken | TBodyOpenToken | TBodyCloseToken | TRToken | TROpenToken | TRCloseToken | THToken | THOpenToken | THCloseToken | TDToken | TDOpenToken | TDCloseToken | LinkToken | LinkOpenToken | LinkCloseToken | DelToken | DelOpenToken | DelCloseToken | EmToken | EmOpenToken | EmCloseToken | HardbreakToken | SoftbreakToken | FootnoteInlineToken | HtmlTagToken | InsToken | InsOpenToken | InsCloseToken | ImageToken | MarkToken | MarkOpenToken | MarkCloseToken | SubToken | SupToken | AbbrToken | AbbrOpenToken | AbbrCloseToken | FootnoteToken | FootnoteOpenToken | FootnoteCloseToken | FootnoteBlockToken | FootnoteBlockOpenToken | FootnoteBlockCloseToken | FootnoteAnchorToken; } declare class ParserBlock { tokenize(state: Remarkable.StateBlock, startLine: number, endLine: number): void; parse(str: string, options: Remarkable.Options, env: Remarkable.Env, tokens: [Remarkable.Token]): void; } declare class ParserInline { skipToken(state: Remarkable.StateInline): void; tokenize(state: Remarkable.StateInline): void; parse(str: string, options: Remarkable.Options, env: Remarkable.Env, tokens: [Remarkable.Token]): void; validateLink(url: string): boolean; }
the_stack
import 'react-toastify/dist/ReactToastify.css' import { Map } from 'immutable' import { ToastContainer, toast } from 'react-toastify' import { connect } from 'react-redux' import { css } from 'glamor' import { getTranslate } from 'react-localize-redux' import { push } from 'connected-react-router' import { withStyles } from '@material-ui/core/styles' import AddIcon from '@material-ui/icons/Add' import Button from '@material-ui/core/Button' import Card from '@material-ui/core/Card' import CardContent from '@material-ui/core/CardContent' import CardHeader from '@material-ui/core/CardHeader' import CardMedia from '@material-ui/core/CardMedia' import Divider from '@material-ui/core/Divider' import Fab from '@material-ui/core/Fab' import Favorite from '@material-ui/icons/FavoriteBorder' import Grid from '@material-ui/core/Grid/Grid' import InputBase from '@material-ui/core/InputBase' import Paper from '@material-ui/core/Paper' import React, { Component } from 'react' import ReactImageFallback from 'react-image-fallback' import RemoveIcon from '@material-ui/icons/Remove' import StarRatingComponent from 'react-star-rating-component' import TextField from '@material-ui/core/TextField' import Typography from '@material-ui/core/Typography' import { Cart } from 'core/domain/cart' import * as addToCartActions from 'store/actions/addToCartActions' import { IProductDetailComponentProps } from './IProductDetailComponentProps' import { IProductDetailComponentState } from './IProductDetailComponentState' import uniqid from 'uniqid' const styles = (theme: any) => ({ root: { display: 'flex' }, demo: { height: 240 }, paper: { padding: theme.spacing(2), height: '100%', color: theme.palette.text.secondary, boxShadow: '0 0 0 0' }, control: { padding: theme.spacing(2) }, img: { margin: 20 }, postBody: { wordWrap: 'break-word', color: 'rgba(0, 0, 0, 0.87)', fontSize: '0.875rem', fontWeight: 400, fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif', lineHeight: '1.46429em', display: 'flex', padding: 5, paddignBottom: 5, flex: 1 }, button: { textTransform: 'capitalize', borderRadius: 30, padding: `${15}px ${35}px`, boxShadow: 'none' }, btnIncrement: { color: '#072a48', backgroundColor: 'white', border: 'solid', borderColor: '#072a48', width: '30px', cursor: 'pointer', borderWidth: '0.1ex' }, btnDelete: { color: 'white', backgroundColor: '#072a48', border: 'solid', borderColor: '#072a48', width: '30px', cursor: 'pointer', borderWidth: '0.1ex' }, paperbuttons: { backgroundColor: '#f7f7f7', borderTopLeftRadius: 0, borderTopRightRadius: 0, padding: theme.spacing(2), [theme.breakpoints.up(600 + theme.spacing(3) * 2)]: { padding: `${24}px ${48}px` } }, dialogShoppingButton: { backgroundColor: '#ffffff', color: '#f62f5e' }, bootstrapInput: { borderRadius: 10, position: 'relative', backgroundColor: theme.palette.common.white, border: '1px solid #ced4da', fontSize: 12, width: '20px', padding: '5px 6px', transition: theme.transitions.create(['border-color', 'box-shadow']) // Use the system font instead of the default Roboto font. }, borderbottom: { borderBottom: 'none' }, fab: { backgroundColor: 'white', boxShadow: 'none', color: '#f62f5e', textTransform: 'capitalize' }, quentityButton: { margin: '5px', width: '30px', height: '30px', minHeight: '30px', boxShadow: 'none', backgroundColor: '#efefef', color: '#2e2e2e' } }) /** * Create component class */ export class ProductDetailComponent extends Component< IProductDetailComponentProps, IProductDetailComponentState > { styles = {} /** * Component constructor * @param {object} props is an object properties of component */ constructor(props: IProductDetailComponentProps) { super(props) // Defaul state this.state = { emailInput: '', emailInputError: '', passwordInput: '', passwordInputError: '', confirmInputError: '', rating: 3, open: false, quantity: 1, show: true, max: 5, min: 0, cardId: '', sizeValue: '', colorValue: '' } // Binding functions to `this` // Binding function to `this` this.addToCart = this.addToCart.bind(this) this.handleForm = this.handleForm.bind(this) this.loadSizeAttributes = this.loadSizeAttributes.bind(this) this.loadColorAttributes = this.loadColorAttributes.bind(this) this.incrementItem = this.incrementItem.bind(this) this.decreaseItem = this.decreaseItem.bind(this) this.handleChange = this.handleChange.bind(this) this.handleSizeChange = this.handleSizeChange.bind(this) this.handleColorChange = this.handleColorChange.bind(this) } /** * Create a list of size Attributes * @return {DOM} posts */ loadSizeAttributes = () => { const { mergedProductsAttributes } = this.props let productSizeAttributes: any = [] mergedProductsAttributes.map((x, index) => { let newPost: any = x.get('attributeName') === 'Size' ? ( <Button color='secondary' key={x.get('attributeValueId')} id={x.get('attributeValue')} onClick={this.handleSizeChange} > {x.get('attributeValue')} </Button> ) : ( '' ) productSizeAttributes.push(newPost as never) }) return productSizeAttributes } handleSizeChange = (event: any) => { this.setState({ sizeValue: event.target.id }) } handleColorChange = (event: any) => { this.setState({ colorValue: event.target.id }) } /** * Create a list of size Attributes * @return {DOM} posts */ loadColorAttributes = () => { const { mergedProductsAttributes } = this.props let productColorAttributes: any = [] const styles = (x: any, selectedColor: any) => ({ backgroundColor: x, margin: '3px', width: '30px', height: '30px', display: 'inline-block', cursor: 'pointer', borderRadius: '50%', boxShadow: x === selectedColor ? '0px 0px 6px 1px rgba(0,0,0,1)' : '0px 0px 2px 1px rgba(0,0,0,1)' }) mergedProductsAttributes.map((x, index) => { let newPost: any = x.get('attributeName') === 'Color' ? ( // <Button color='secondary' key={x.get('attributeValueId')}> // {x.get('attributeValue')} // </Button> x.get('attributeValue') === 'White' ? ( <div key={x.get('attributeValue')} style={styles('#ffffff', '')} id={x.get('attributeValue')} onClick={this.handleColorChange} /> ) : x.get('attributeValue') === 'Black' ? ( <div key={x.get('attributeValue')} style={styles('#000000', '')} id={x.get('attributeValue')} onClick={this.handleColorChange} /> ) : x.get('attributeValue') === 'Red' ? ( <div key={x.get('attributeValue')} style={styles('#FF0000', '')} id={x.get('attributeValue')} onClick={this.handleColorChange} /> ) : x.get('attributeValue') === 'Orange' ? ( <div key={x.get('attributeValue')} style={styles('#FFA500', '')} id={x.get('attributeValue')} onClick={this.handleColorChange} /> ) : x.get('attributeValue') === 'Yellow' ? ( <div key={x.get('attributeValue')} style={styles('#FFFF00', '')} id={x.get('attributeValue')} onClick={this.handleColorChange} /> ) : x.get('attributeValue') === 'Green' ? ( <div key={x.get('attributeValue')} style={styles('#008000', '')} id={x.get('attributeValue')} onClick={this.handleColorChange} /> ) : x.get('attributeValue') === 'Blue' ? ( <div key={x.get('attributeValue')} style={styles('#0000FF', '')} id={x.get('attributeValue')} onClick={this.handleColorChange} /> ) : x.get('attributeValue') === 'Indigo' ? ( <div key={x.get('attributeValue')} style={styles('#4B0082', '')} id={x.get('attributeValue')} onClick={this.handleColorChange} /> ) : x.get('attributeValue') === 'Purple' ? ( <div key={x.get('attributeValue')} style={styles('#800080', '')} id={x.get('attributeValue')} onClick={this.handleColorChange} /> ) : ( '' ) ) : ( '' ) productColorAttributes.push(newPost as never) }) return productColorAttributes } /** * Handle data on input change * @param {event} evt is an event of inputs of element on change */ handleInputChange = (event: any) => { const target = event.target const value = target.type === 'checkbox' ? target.checked : target.value const name = target.name this.setState({ [name]: value }) switch (name) { case 'emailInput': this.setState({ emailInputError: '' }) break case 'passwordInput': this.setState({ confirmInputError: '', passwordInputError: '' }) break default: } } addToCart = () => { const { authed, goTo } = this.props if (!authed) { goTo!('/login') return } const { product, cart } = this.props let cartId if (cart && Object.keys(cart).length > 0) { cartId = Object.keys(cart)[0] } else { cartId = uniqid() } this.props.addToCart!(cartId, { productThumbnail: product.get('thumbnail'), productName: product.get('name'), productPrice: product.get('price'), productId: product.get('productId'), productColor: this.state.colorValue, productQuantity: this.state.quantity, productSize: this.state.sizeValue }) } /** * Handle Dialog close */ handleClose = () => { this.setState({ open: false }) } /** * Handle register form */ handleForm = () => { const { translate } = this.props let error = false if (this.state.emailInput === '') { this.setState({ emailInputError: translate!('login.emailRequiredError') }) error = true } if (this.state.passwordInput === '') { this.setState({ passwordInputError: translate!('login.passwordRequiredError') }) error = true } if (!error) { this.props.login!(this.state.emailInput, this.state.passwordInput) } } changeRating(newRating: any, name: any) { this.setState({ rating: newRating }) } onStarClick(nextValue: any, prevValue: any, name: any) { this.setState({ rating: nextValue }) } incrementItem = () => { this.setState(prevState => { if (prevState.quantity < 9) { return { quantity: prevState.quantity + 1 } } else { return null } }) } decreaseItem = () => { this.setState(prevState => { if (prevState.quantity > 0) { return { quantity: prevState.quantity - 1 } } else { return null } }) } handleChange = (event: any) => { this.setState({ quantity: event.target.value }) } componentWillMount() { this.setState({ cartId: '' }) } notify = () => { toast.success(this.props.translate!('common.featureImplementLater'), { position: toast.POSITION.TOP_CENTER, className: css({ background: '#ff3366' }) }) } /** * Reneder component DOM * @return {react element} return the DOM which rendered by component */ render() { let { product } = this.props const { classes, translate } = this.props const productSizeAttributes = this.loadSizeAttributes() const productColorAttributes = this.loadColorAttributes() return ( <React.Fragment> <Card key={`post-component-${'id'}`} style={{ margin: 5 }}> <CardContent className={classes.postBody} style={{ paddingBottom: 5 }} > <CardMedia className='productImage'> <ReactImageFallback src={`/images/${product.get('image')}`} fallbackImage={'/images/product_placeholder.png'} initialImage={`/images/product_loading.png`} alt='productImage' className={classes.img} /> </CardMedia> <div className='mainContent'> <StarRatingComponent name='rate1' starCount={5} value={4} onStarClick={this.onStarClick.bind(this)} /> <Typography style={{ lineHeight: 1.1 }} variant='h5'> {product.get('description')} </Typography> <Typography color='error'> {translate!('product.currency')} {product.get('price')} </Typography> <Typography variant='subtitle1' color='textSecondary'> Color </Typography> {productColorAttributes} {/* {availableColors.map(x => ( <div key={x} style={styles(x, '')} /> ))} */} <Typography variant='subtitle1' color='textSecondary'> Size </Typography> {productSizeAttributes} {/* {mergedProductsAttributes.map(x => ( x.get('attributeName') === 'Size' ? <Button color='secondary' key={x.get('attributeValueId')}> {x.get('attributeValue')} </Button> : '' ))} */} {/* {availableSizes.map(x => ( <Button color='secondary' key={x}> {x} </Button> ))} */} <Typography variant='subtitle1' color='textSecondary'> Quantity </Typography> <Fab color='secondary' className={classes.quentityButton} size='small' aria-label='Add' onClick={this.incrementItem} > <AddIcon /> </Fab> <InputBase id='bootstrap-input' value={this.state.quantity} onChange={this.handleChange} classes={{ input: classes.bootstrapInput }} /> <Fab color='secondary' aria-label='Add' className={classes.quentityButton} size='small' onClick={this.decreaseItem} > <RemoveIcon /> </Fab> <Typography style={{ margin: 10 }} /> <Paper className={classes.paper}> <React.Fragment> <Grid container spacing={2}> <Grid item container xs={6} sm={3} direction='row' justify='flex-start' alignItems='center' > <Button variant='contained' color='secondary' onClick={this.addToCart} className={classes.button} > {translate!('product.addToCart')} </Button> </Grid> <Grid item xs={6} sm={3} container direction='row' justify='flex-end' alignItems='center' onClick={this.notify} > <Favorite color='secondary' /> <Typography> {translate!('product.addToWishList')} </Typography> </Grid> </Grid> </React.Fragment> </Paper> </div> </CardContent> </Card> <Card key={`post-component-${'id'}`} style={{ margin: 5, backgroundColor: '#FaFaFa', padding: 10 }} > <CardHeader title={'Product Reviews'} /> <CardContent style={{ paddingBottom: 5 }}> <Grid container spacing={2}> <Grid item xs={6} sm={3}> <StarRatingComponent name='rate1' starCount={5} value={4} onStarClick={this.onStarClick.bind(this)} /> <Typography>Pablo Permins</Typography> <Typography color='textSecondary'>one hour ago</Typography> </Grid> <Grid item xs={12} sm={6}> <Typography> Got this through the post the other day and right from opening the packet. I knew this was quality, put it on and i was right </Typography> </Grid> </Grid> <Divider variant='middle' style={{ marginTop: 10, marginBottom: 10 }} /> <Typography variant='h5'>Add A Review</Typography> <Grid container spacing={2}> <Grid item xs={6} sm={3}> <Typography>Choose a Nick name</Typography> </Grid> <Grid item xs={12} sm={6}> <TextField InputLabelProps={{ className: classes.formLabel }} InputProps={{ classes: { root: classes.root, input: classes.inputSizeSmall } }} required id='nickname' name='nickName' label='Nick Name' fullWidth autoComplete='nickName' variant='outlined' /> </Grid> </Grid> <Grid container spacing={2}> <Grid item xs={6} sm={3}> <Typography>Your Review</Typography> </Grid> <Grid item xs={12} sm={6}> <TextField InputLabelProps={{ className: classes.formLabel }} InputProps={{ classes: { root: classes.root, input: classes.inputSizeSmall } }} required id='review' name='review' label='Review' fullWidth autoComplete='billing address-level2' variant='outlined' /> <Typography color='textSecondary'> You review must be at leat 50 characters </Typography> </Grid> </Grid> <Grid container spacing={2}> <Grid item xs={6} sm={3}> <Typography>Over All Rating</Typography> </Grid> <Grid item xs={12} sm={6}> <StarRatingComponent name='rate1' starCount={5} value={4} onStarClick={this.onStarClick.bind(this)} /> </Grid> </Grid> <Grid container spacing={2}> <Grid item xs={6} sm={3} /> <Grid item xs={12} sm={6}> <Button variant='contained' color='secondary' onClick={this.notify} className={classes.button} > {'Submit'} </Button> </Grid> </Grid> <ToastContainer autoClose={2000} /> </CardContent> </Card> </React.Fragment> ) } } /** * Map dispatch to props * @param {func} dispatch is the function to dispatch action to reducers * @param {object} ownProps is the props belong to component * @return {object} props of component */ const mapDispatchToProps = ( dispatch: any, ownProps: IProductDetailComponentProps ) => { return { goTo: (url: string) => dispatch(push(url)), addToCart: (cartId: string, cart: Cart) => { dispatch(addToCartActions.dbAddProductToCart(cartId, cart)) } } } /** * Map state to props * @param {object} state is the obeject from redux store * @param {object} ownProps is the props belong to component * @return {object} props of component */ const mapStateToProps = ( state: Map<string, any>, ownProps: IProductDetailComponentProps ) => { return { translate: getTranslate(state.get('locale')), authed: state.getIn(['authorize', 'authed'], false), avatarURL: state.getIn(['imageGallery', 'imageURLList']), imageRequests: state.getIn(['imageGallery', 'imageRequests']), cart: state.getIn(['addToCart', 'cartProducts']).toJS() } } // - Connect component to redux store export default connect( mapStateToProps, mapDispatchToProps )(withStyles(styles as any)(ProductDetailComponent as any) as any)
the_stack
// Note -- running these tests under cscript requires some ES5 polyfills const collectionToArray = <T>(col: { Item(key: any): T }): T[] => { const results: T[] = []; const enumerator = new Enumerator<T>(col); enumerator.moveFirst(); while (!enumerator.atEnd()) { results.push(enumerator.item()); enumerator.moveNext(); } return results; }; const fso = new ActiveXObject('Scripting.FileSystemObject'); // https://msdn.microsoft.com/en-us/library/ebkhfaaz(v=vs.84).aspx { /** Generates a string describing the drive type of a given Drive object. */ const driveTypeString = (drive: Scripting.Drive) => { switch (drive.DriveType) { case Scripting.DriveTypeConst.Removable: return 'Removeable'; case Scripting.DriveTypeConst.Fixed: return 'Fixecd'; case Scripting.DriveTypeConst.Remote: return 'Network'; case Scripting.DriveTypeConst.CDRom: return 'CD-ROM'; case Scripting.DriveTypeConst.RamDisk: return 'RAM Disk'; default: return 'Unknown'; } }; /** Generates a string describing the attributes of a file or folder. */ const attributesString = (f: Scripting.File | Scripting.Folder) => { const attr = f.Attributes; if (attr === 0) { return 'Normal'; } const attributeStrings: string[] = []; if (attr & Scripting.FileAttribute.Directory) { attributeStrings.push('Directory'); } if (attr & Scripting.FileAttribute.ReadOnly) { attributeStrings.push('Read-only'); } if (attr & Scripting.FileAttribute.Hidden) { attributeStrings.push('Hidden'); } if (attr & Scripting.FileAttribute.System) { attributeStrings.push('System'); } if (attr & Scripting.FileAttribute.Volume) { attributeStrings.push('Volume'); } if (attr & Scripting.FileAttribute.Archive) { attributeStrings.push('Archive'); } if (attr & Scripting.FileAttribute.Alias) { attributeStrings.push('Alias'); } if (attr & Scripting.FileAttribute.Compressed) { attributeStrings.push('Compressed'); } return attributeStrings.join(','); }; const drivesInfoReport = () => { const driveLine = (d: Scripting.Drive) => { let parts: Array<string | number> = [ d.DriveLetter, d.Path, driveTypeString(d), d.IsReady ? 'true' : 'false' ]; if (d.IsReady) { parts = parts.concat([ d.DriveType === Scripting.DriveTypeConst.Remote ? d.ShareName : d.VolumeName, d.FileSystem, d.TotalSize, d.FreeSpace, d.AvailableSpace, d.SerialNumber.toString(16) ]); } return parts.join(' '); }; const ret = ` Number of drives: ${fso.Drives.Count} Drive File Total Free Available Serial Letter Path Type Ready? Name System Space Space Space Number ${new Array(106).join('-')} ${collectionToArray(fso.Drives).map(driveLine).join('\n')}` .trim().replace(' ', '\t'); }; type fiileFolderKey = keyof Scripting.File & keyof Scripting.Folder; type keys = fiileFolderKey | 'Attribs' | 'Created' | 'Accessed' | 'Modified'; const detailBuilder = (f: Scripting.File | Scripting.Folder, x: fiileFolderKey | 'Attribs' | 'Created' | 'Accessed' | 'Modified') => { if (x === 'Attribs') { return attributesString(f); } const label = x; switch (x) { case 'Created': x = 'DateCreated'; break; case 'Accessed': x = 'DateLastAccessed'; break; case 'Modified': x = 'DateLastModified'; break; } return `${label}\t${f[x]}\n`; }; const fileDetailsString = (f: Scripting.File) => { const keys: keys[] = ['Path', 'Name', 'Type', 'Attribs', 'Created', 'Accessed', 'Modified', 'Size']; return keys.map(x => detailBuilder(f, x)).join(''); }; const folderDetailsString = (f: Scripting.Folder) => { const keys: keys[] = ['Path', 'Name', 'Attribs', 'Created', 'Accessed', 'Modified', 'Size']; return keys.map(x => detailBuilder(f, x)).join(''); }; const folderContentsString = (f: Scripting.Folder): string => { const files = collectionToArray(f.Files); const subfolders = collectionToArray(f.SubFolders); return ` Folder: ${f.Path} There ${files.length === 1 ? 'is 1 file' : `are ${files.length} files`} ${files.map(fileDetailsString).join('')} There ${subfolders.length === 1 ? 'is 1 subfolder' : `are ${subfolders.length} subfolders`} ${subfolders.map(folderDetailsString).join('')} ${subfolders.map(folderContentsString).join('')}` .trim().replace(' ', '\t'); }; const testDrive = 'C:\\'; const testPath = 'C:\\test'; const testfolderInfo = () => { if (!fso.DriveExists(testDrive) || !fso.FolderExists(testPath)) { return ''; } return folderContentsString(fso.GetFolder(testPath)); }; const deleteTestFolder = () => { // two ways to delete a file: const filepathToDelete = `${testPath}\\LoremIpsum\\Paragraph1.txt`; fso.DeleteFile(filepathToDelete); // fso.GetFile(filepathToDelete).Delete(); // two ways to delete a folder: fso.DeleteFolder(`${testPath}\\LoremIpsum`); fso.GetFolder(testPath).Delete(); }; const createLyrics = (folder: Scripting.Folder) => { let stream = folder.CreateTextFile('Paragraph1.txt'); stream.Write('Lorem Ipsum - Paragraph 1'); stream.WriteBlankLines(1); stream.WriteLine('Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas sem.'); stream.WriteLine('Donec ante. Nulla facilisi. Phasellus interdum nulla a nunc. Morbi laoreet nunc.'); stream.WriteBlankLines(2); stream.Close(); stream = folder.CreateTextFile('Paragraph2.txt'); stream.WriteLine('Lorem Ipsum - Paragraph 2'); stream.WriteBlankLines(1); stream.WriteLine('Nullam nulla quam, sollicitudin ut, lobortis ornare, tristique a, augue.'); stream.WriteLine('Vestibulum sem felis, fermentum eu, volutpat eu, vulputate eget, elit. '); stream.WriteBlankLines(2); stream.Close(); }; const getLyrics = () => { const folderPath = `${testPath}\\LoremIpsum`; let lyrics = ''; // One way to read from a file let stream = fso.OpenTextFile(fso.BuildPath(folderPath, 'Paragraph1.txt')); lyrics = stream.ReadAll() + '\n\n'; stream.Close(); // Another way to read from a file stream = fso.GetFile(fso.BuildPath(folderPath, 'Paragraph2.txt')).OpenAsTextStream(); while (!stream.AtEndOfStream) { lyrics += stream.ReadLine() + '\n'; } stream.Close(); return lyrics; }; const buildTestFolder = () => { // Bail out if the drive doesn't exists ... if (!fso.DriveExists(testDrive)) { return false; } // or the directory already exists if (fso.FolderExists(testPath)) { return false; } const testFolder = fso.CreateFolder(testPath); const stream = fso.CreateTextFile(fso.BuildPath(testPath, 'readme.txt')); stream.WriteLine('My sample text collection'); stream.Close(); const subfolder = testFolder.SubFolders.Add('LoremIpsum'); createLyrics(subfolder); return true; }; const echoLines = (linecount = 1) => new Array(linecount).forEach(() => WScript.Echo('')); if (!buildTestFolder()) { WScript.Echo('Test directory already exists or cannot be created. Cannot continue.'); } else { drivesInfoReport(); echoLines(2); WScript.Echo(testfolderInfo()); echoLines(2); WScript.Echo(getLyrics()); echoLines(2); deleteTestFolder(); } } // source --https://msdn.microsoft.com/en-us/library/ts2t8ybh(v=vs.84).aspx { const showFreeSpace = (drvPath: string) => { const d = fso.GetDrive(fso.GetDriveName(drvPath)); let s = `Drive ${drvPath} - `; s += d.VolumeName + '<br>'; s += `Free Space: ${d.FreeSpace / 1024} Kbytes`; return (s); }; } // source -- https://msdn.microsoft.com/en-us/library/kaf6yaft(v=vs.84).aspx { const getALine = (filespec: string) => { const file = fso.OpenTextFile(filespec, Scripting.IOMode.ForReading, false); let s = ''; while (!file.AtEndOfLine) { s += file.Read(1); } file.Close(); return (s); }; } // https://msdn.microsoft.com/en-us/library/ch28h2s7(v=vs.84).aspx { const showDriveInfo = (path: string) => { const bytesPerGB = 1024 * 1024 * 1024; const drv = fso.GetDrive(fso.GetDriveName(path)); const ret = drv.IsReady ? `${drv.Path} - ${drv.FreeSpace / bytesPerGB} GB free of ${drv.TotalSize / bytesPerGB} GB` : 'Not ready'; WScript.Echo(ret); }; const showFolderInfo = () => { const fldr = fso.GetFolder("c:\\"); let ret = ` Folder: ${fldr.Path} Drive: ${fldr.Drive} ${fldr.IsRootFolder ? 'Is root folder' : `Parent folder: ${fldr.ParentFolder}`} `.trim(); // Create and delete a folder. const newFolderName = 'C:\\TempFolder1'; fso.CreateFolder(newFolderName); ret += `Base Name of Added Folder: ${fso.GetBaseName(newFolderName)}`; fso.DeleteFolder(newFolderName); WScript.Echo(ret); }; } // https://msdn.microsoft.com/en-us/library/czxefwt8(v=vs.84).aspx { const readFiles = () => { const file = fso.CreateTextFile("c:\\testfile.txt", true); // Write a line. WScript.Echo('Writing file'); file.WriteLine("Hello World"); file.WriteBlankLines(1); file.Close(); // Read the contents of the file. WScript.Echo('Reading file'); const textStream = fso.OpenTextFile("c:\\testfile.txt", Scripting.IOMode.ForReading); WScript.Echo(`File contents = "${textStream.ReadLine()}"`); textStream.Close(); }; const manipulateFiles = () => { const file = fso.CreateTextFile("c:\\testfile.txt", true); WScript.Echo('Writing file'); // Write a line. file.Write("This is a test."); // Close the file to writing. file.Close(); WScript.Echo('Moving file to c:\\tmp'); // Get a handle to the file in root of C:\. let file2 = fso.GetFile("c:\\testfile.txt"); // Move the file to \tmp directory. file2.Move("c:\\tmp\\testfile.txt"); WScript.Echo('Copying file to c:\\temp <br>'); // Copy the file to \temp. file2.Copy('c:\\temp\\testfile.txt'); WScript.Echo('Deleting files <br>'); // Get handles to files' current location. file2 = fso.GetFile('c:\\tmp\\testfile.txt'); const file3 = fso.GetFile('c:\\temp\\testfile.txt'); // Delete the files. file2.Delete(); file3.Delete(); WScript.Echo('All done!'); }; }
the_stack
import { clamp } from "alcalzone-shared/math"; import { Accessory } from "./accessory"; import { conversions, deserializers, serializers } from "./conversions"; import { IPSODevice } from "./ipsoDevice"; import { deserializeWith, doNotSerialize, ipsoKey, IPSOOptions, required, serializeWith } from "./ipsoObject"; import { MAX_COLOR, predefinedColors, whiteSpectrumHex } from "./predefined-colors"; // see https://github.com/hreichert/smarthome/blob/master/extensions/binding/org.eclipse.smarthome.binding.tradfri/src/main/java/org/eclipse/smarthome/binding/modules/internal/TradfriColor.java // for some color conversion export type LightOperation = Partial<Pick<Light, "onOff" | "dimmer" | "whenPowerRestored" | "color" | "colorTemperature" | "colorX" | "colorY" | "hue" | "saturation" | "transitionTime" >>; export enum PowerRestoredAction { TurnOn = 2, RememberStatus = 4, } export class Light extends IPSODevice { constructor(options?: IPSOOptions, accessory?: Accessory) { super(options); // In order for the simplified API to work, the // accessory reference must be a proxy if (accessory != null && !accessory.isProxy) { accessory = accessory.createProxy(); } this._accessory = accessory; // get the model number to detect features if (accessory != null && accessory.deviceInfo != null && accessory.deviceInfo.modelNumber != null && accessory.deviceInfo.modelNumber.length > 0 ) { this._modelName = accessory.deviceInfo.modelNumber; } } @doNotSerialize private _modelName: string | undefined; @doNotSerialize private _accessory: Accessory | undefined; // All properties only exist after the light has been received from the gateway // so they are definitely assigned! @ipsoKey("5706") @doNotSerialize // this is done through hue/saturation public color: string = "f1e0b5"; // hex string // As of Gateway version v1.3.14, this is finally supported too // They both have to be given in the same payload or the other one is considered = 0 @ipsoKey("5707") @serializeWith(serializers.hue) @deserializeWith(deserializers.hue) @required((me: Light, ref?: Light) => ref != null && me.saturation !== ref.saturation) // force hue to be present if saturation is public hue!: number; // 0-360 @ipsoKey("5708") @serializeWith(serializers.saturation) @deserializeWith(deserializers.saturation) @required((me: Light, ref?: Light) => ref != null && me.hue !== ref.hue) // force saturation to be present if hue is public saturation!: number; // 0-100% @ipsoKey("5709") @doNotSerialize public colorX!: number; // int @ipsoKey("5710") @doNotSerialize public colorY!: number; // int // As of Gateway version v1.3.14, this is finally supported @ipsoKey("5711") @serializeWith(serializers.colorTemperature) @deserializeWith(deserializers.colorTemperature) public colorTemperature!: number; // This property was added in Gateway v1.3.14 // not sure what it does, as it is not in the IKEA app yet /** @internal */ @ipsoKey("5717") public UNKNOWN1: any; @ipsoKey("5712") @required() @serializeWith(serializers.transitionTime, { neverSkip: true }) @deserializeWith(deserializers.transitionTime, { neverSkip: true }) public transitionTime: number = 0.5; // <float> @ipsoKey("5805") public cumulativeActivePower!: number; // <float> @ipsoKey("5851") @serializeWith(serializers.brightness) @deserializeWith(deserializers.brightness) public dimmer!: number; // <int> [0..100] @ipsoKey("5850") public onOff!: boolean; @ipsoKey("5849") public whenPowerRestored!: PowerRestoredAction; @ipsoKey("5852") public onTime!: number; // <int> @ipsoKey("5820") public powerFactor!: number; // <float> @ipsoKey("5701") public unit!: string; /** * Returns true if the current lightbulb is dimmable */ public get isDimmable(): boolean { return true; // we know no lightbulbs that aren't dimmable } /** * Returns true if the current lightbulb is switchable */ public get isSwitchable(): boolean { return true; // we know no lightbulbs that aren't switchable } public clone(): this { const ret = super.clone(this._accessory); ret._modelName = this._modelName; return ret; } /** * Returns the supported color spectrum of the lightbulb */ private _spectrum: Spectrum | undefined; public get spectrum(): Spectrum { if (this._spectrum == null) { // determine the spectrum if (this.hue != null && this.saturation != null) { this._spectrum = "rgb"; } else if (this.colorTemperature != null) { this._spectrum = "white"; } else { this._spectrum = "none"; } } return this._spectrum; } /** * Creates a proxy which redirects the properties to the correct internal one */ public createProxy(): this { const raw = this._accessory instanceof Accessory ? this._accessory.options.skipValueSerializers : false ; switch (this.spectrum) { case "rgb": { const proxy = createRGBProxy(raw); return super.createProxy(proxy.get, proxy.set); } default: return this; } } // ================================= // Simplified API access /** * Ensures this instance is linked to a tradfri client and an accessory * @throws Throws an error if it isn't */ private ensureLink() { if (this.client == null) { throw new Error("Cannot use the simplified API on devices which aren't linked to a client instance."); } if (!(this._accessory instanceof Accessory)) { throw new Error("Cannot use the simplified API on lightbulbs which aren't linked to an Accessory instance."); } } /** Turn this lightbulb on */ public turnOn(): Promise<boolean> { this.ensureLink(); return this.client!.operateLight(this._accessory!, { onOff: true, }); } /** Turn this lightbulb off */ public turnOff(): Promise<boolean> { this.ensureLink(); return this.client!.operateLight(this._accessory!, { onOff: false, }); } /** Toggles this lightbulb on or off */ public toggle(value: boolean = !this.onOff): Promise<boolean> { this.ensureLink(); return this.client!.operateLight(this._accessory!, { onOff: value, }); } private operateLight(operation: LightOperation, transitionTime?: number): Promise<boolean> { this.ensureLink(); if (transitionTime != null) { transitionTime = Math.max(0, transitionTime); operation.transitionTime = transitionTime; } return this.client!.operateLight(this._accessory!, operation); } /** * Changes this lightbulb's brightness * @returns true if a request was sent, false otherwise */ public setBrightness(value: number, transitionTime?: number): Promise<boolean> { this.ensureLink(); value = clamp(value, 0, 100); return this.operateLight({ dimmer: value, }, transitionTime); } /** * Changes this lightbulb's color * @param value The target color as a 6-digit hex string * @returns true if a request was sent, false otherwise */ public setColor(value: string, transitionTime?: number): Promise<boolean> { this.ensureLink(); switch (this.spectrum) { case "rgb": { return this.operateLight({ color: value, }, transitionTime); } case "white": { // We make an exception for the predefined white spectrum colors if (!(value in whiteSpectrumHex)) { throw new Error( "White spectrum bulbs only support the following colors: " + Object.keys(whiteSpectrumHex).join(", "), ); } return this.operateLight({ colorTemperature: whiteSpectrumHex[value], }, transitionTime); } default: { throw new Error("setColor is only available for RGB lightbulbs"); } } } /** * Changes this lightbulb's color temperature * @param value The target color temperature in the range 0% (cold) to 100% (warm) * @returns true if a request was sent, false otherwise */ public setColorTemperature(value: number, transitionTime?: number): Promise<boolean> { this.ensureLink(); if (this.spectrum !== "white") throw new Error("setColorTemperature is only available for white spectrum lightbulbs"); value = clamp(value, 0, 100); return this.operateLight({ colorTemperature: value, }, transitionTime); } /** * Changes this lightbulb's color hue * @returns true if a request was sent, false otherwise */ public setHue(value: number, transitionTime?: number): Promise<boolean> { this.ensureLink(); if (this.spectrum !== "rgb") throw new Error("setHue is only available for RGB lightbulbs"); value = clamp(value, 0, 360); return this.operateLight({ hue: value, }, transitionTime); } /** * Changes this lightbulb's color saturation * @returns true if a request was sent, false otherwise */ public setSaturation(value: number, transitionTime?: number): Promise<boolean> { this.ensureLink(); if (this.spectrum !== "rgb") throw new Error("setSaturation is only available for RGB lightbulbs"); value = clamp(value, 0, 100); return this.operateLight({ saturation: value, }, transitionTime); } /** Turns this object into JSON while leaving out the potential circular reference */ public toJSON(): {} { return { onOff: this.onOff, whenPowerRestored: this.whenPowerRestored, dimmer: this.dimmer, color: this.color, colorTemperature: this.colorTemperature, colorX: this.colorX, colorY: this.colorY, hue: this.hue, isDimmable: this.isDimmable, isSwitchable: this.isSwitchable, spectrum: this.spectrum, saturation: this.saturation, transitionTime: this.transitionTime, }; } /** * Fixes property values that are known to be bugged */ public fixBuggedProperties(): this { super.fixBuggedProperties(); // For some reason the gateway reports lights with brightness 1 after turning off if (this.onOff === false && this.dimmer === MIN_BRIGHTNESS) this.dimmer = 0; return this; } } // remember the minimum possible non-zero brightness to fix the bugged properties; const MIN_BRIGHTNESS = deserializers.brightness(1); export type Spectrum = "none" | "white" | "rgb"; const rgbRegex = /^[0-9A-Fa-f]{6}$/; /** * Creates a proxy for an RGB lamp, * which converts RGB color to CIE xy */ function createRGBProxy(raw: boolean = false) { function get(me: Light, key: PropertyKey) { switch (key) { case "color": { if (typeof me.color === "string" && rgbRegex.test(me.color)) { // predefined color, return it return me.color; } else { // calculate it from hue/saturation const { r, g, b } = conversions.rgbFromHSV(me.hue, me.saturation / 100, 1); return conversions.rgbToString(r, g, b); } } default: return me[key as keyof Light]; } } function set(me: Light, key: PropertyKey, value: any) { switch (key) { case "color": { if (predefinedColors.has(value)) { // its a predefined color, use the predefined values const definition = predefinedColors.get(value)!; // we checked with `has` if (raw) { me.hue = definition.hue_raw; me.saturation = definition.saturation_raw; } else { me.hue = definition.hue; me.saturation = definition.saturation; } } else { // only accept HEX colors if (rgbRegex.test(value)) { // calculate the X/Y values const { r, g, b } = conversions.rgbFromString(value); const { h, s /* ignore v */ } = conversions.rgbToHSV(r, g, b); if (raw) { me.hue = Math.round(h / 360 * MAX_COLOR); me.saturation = Math.round(s * MAX_COLOR); } else { me.hue = h; me.saturation = s * 100; } } } break; } default: (me as any)[key] = value; } return true; } return { get, set }; }
the_stack
import * as TabWindow from '../src/ts/tabWindow'; import * as tabWindowUtils from '../src/ts/tabWindowUtils'; import difflet from 'difflet'; import * as rawTestData from '../test-data/testData'; import log from 'loglevel'; const testData = rawTestData as any; function dumpDiffs(objA, objB) { var s = difflet({ indent: 2, comment: true }).compare(objA, objB); console.log('diffs:'); console.log(s); } test('basic test', () => {}); test('makeFolderTabWindow', () => { const tabWindow = tabWindowUtils.makeFolderTabWindow( testData.d3BookmarkFolder ); const tabWindowJS = JSON.parse(JSON.stringify(tabWindow.toJS())); /* console.log("makeFolderTabWindow returned:") console.log(">>>>>>>") console.log(JSON.stringify(tabWindowJS,null,2)) console.log(">>>>>>>") console.log('diffs between tabWindowJS and expected:') dumpDiffs(tabWindowJS, testData.d3InitialExpectedTabWindow) */ expect(tabWindowJS).toEqual(testData.d3InitialExpectedTabWindow); expect(tabWindow.title).toBe('d3 docs'); }); test('chromeTabWindow', () => { const baseTabWindow = tabWindowUtils.makeChromeTabWindow( testData.chromeWindowSnap ); const tabWindowJS = JSON.parse(JSON.stringify(baseTabWindow.toJS())); /* console.log("makeChromeTabWindow returned: ") console.log(">>>>>") console.log(JSON.stringify(tabWindowJS,null,2)) console.log(">>>>>") */ const expectedTabWindow = { saved: false, savedTitle: '', savedFolderId: '', open: true, openWindowId: 442, windowType: 'normal', width: 1258, height: 957, tabItems: [ { saved: false, savedState: null, open: true, openState: { url: 'http://facebook.github.io/react/docs/component-api.html', openTabId: 443, active: false, openTabIndex: 0, favIconUrl: 'http://facebook.github.io/react/favicon.ico', title: 'Component API | React', audible: false, pinned: false, isSuspended: false, muted: false, }, }, { saved: false, savedState: null, open: true, openState: { url: 'http://facebook.github.io/react/docs/tutorial.html', openTabId: 445, active: false, openTabIndex: 1, favIconUrl: 'http://facebook.github.io/react/favicon.ico', title: 'Tutorial | React', audible: false, pinned: false, isSuspended: false, muted: false, }, }, { saved: false, savedState: null, open: true, openState: { url: 'http://stackoverflow.com/questions/21903604/is-there-any-proper-way-to-integrate-d3-js-graphics-into-facebook-react-applicat', openTabId: 447, active: false, openTabIndex: 2, favIconUrl: 'http://cdn.sstatic.net/stackoverflow/img/favicon.ico?v=4f32ecc8f43d', title: 'javascript - Is there any proper way to integrate d3.js graphics into Facebook React application? - Stack Overflow', audible: false, pinned: false, isSuspended: false, muted: false, }, }, { saved: false, savedState: null, open: true, openState: { url: 'http://facebook.github.io/flux/docs/overview.html#content', openTabId: 449, active: false, openTabIndex: 3, favIconUrl: '', title: 'Flux | Application Architecture for Building User Interfaces', audible: false, pinned: false, isSuspended: false, muted: false, }, }, { saved: false, savedState: null, open: true, openState: { url: 'http://fluxxor.com/', openTabId: 451, active: false, openTabIndex: 4, favIconUrl: 'http://fluxxor.com/favicon.ico', title: 'Fluxxor - Home', audible: false, pinned: false, isSuspended: false, muted: false, }, }, { saved: false, savedState: null, open: true, openState: { url: 'http://facebook.github.io/fixed-data-table/', openTabId: 453, active: false, openTabIndex: 5, favIconUrl: 'http://facebook.github.io/fixed-data-table/images/favicon-b4fca2450cb5aa407a2e106f42a92838.png', title: 'FixedDataTable', audible: false, pinned: false, isSuspended: false, muted: false, }, }, { saved: false, savedState: null, open: true, openState: { url: 'https://developer.chrome.com/extensions/declare_permissions', openTabId: 734, active: true, openTabIndex: 6, openerTabId: 449, favIconUrl: 'https://www.google.com/images/icons/product/chrome-32.png', title: 'Declare Permissions - Google Chrome', audible: false, pinned: false, isSuspended: false, muted: false, }, }, ], snapshot: false, chromeSessionId: null, expanded: null, }; // dumpDiffs(tabWindowJS, expectedTabWindow); expect(tabWindowJS).toEqual(expectedTabWindow); // Check that title matches active tab: const baseTitle = baseTabWindow.title; expect(baseTitle).toBe('Declare Permissions - Google Chrome'); // Now let's take state after closing the active tab that gave us our title: const updTabWindow = tabWindowUtils.updateWindow( baseTabWindow, testData.chromeWindowSnap2 ); const updTabWindowJS = JSON.parse(JSON.stringify(updTabWindow.toJS())); // console.log("Updated tab window: ") // console.log(JSON.stringify(updTabWindowJS,null,2)) const updTitle = updTabWindow.title; expect(updTitle).toBe('Fluxxor - Home'); }); /* * make sure we still get a deterministic title even when no tab active */ test('noActiveTabTitle', () => { const baseTabWindow = tabWindowUtils.makeChromeTabWindow( testData.chromeWindowSnap3 ); const tabWindowJS = JSON.parse(JSON.stringify(baseTabWindow.toJS())); const baseTitle = baseTabWindow.title; expect(baseTitle).toBe(testData.chromeWindowSnap3.tabs[0].title); }); test('missingSourceFieldsTests', () => { const bmFolder0 = { children: [ { dateAdded: 1395768341441, id: '432', index: 0, parentId: '431', // title deliberately omitted url: 'https://github.com/mbostock/d3/wiki/API-Reference', }, ], dateAdded: 1395768341427, dateGroupModified: 1430260300118, id: '431', index: 4, parentId: '377', title: 'd3 docs', }; const tabWindow = tabWindowUtils.makeFolderTabWindow( bmFolder0 as any, false ); const tabWindowJS = JSON.parse(JSON.stringify(tabWindow.toJS())); // console.log("makeFolderTabWindow returned:") // console.log(JSON.stringify(tabWindowJS,null,2)) const bmTabItem = tabWindow.tabItems.get(0); const bmTabTitle = bmTabItem.title; expect(bmTabTitle).toBe(bmFolder0.children[0].url); // window is still folder title: const windowTitle = tabWindow.title; // Let's use URL for title of untitled tabs: expect(windowTitle).toBe(bmFolder0.title); // TODO: Now omit folder title... const bmFolder1 = { children: [ { dateAdded: 1395768341441, id: '432', index: 0, parentId: '431', title: 'd3 API Reference', url: 'https://github.com/mbostock/d3/wiki/API-Reference', }, ], dateAdded: 1395768341427, dateGroupModified: 1430260300118, id: '431', index: 4, parentId: '377', // title deliberately omitted }; const tabWindow1 = tabWindowUtils.makeFolderTabWindow( bmFolder1 as any, false ); const tabWindow1JS = JSON.parse(JSON.stringify(tabWindow1.toJS())); const tabWindow1Title = tabWindow1.title; // revert to title of first tab: expect(tabWindow1Title).toBe(bmFolder1.children[0].title); const chromeWindowSnap4 = { alwaysOnTop: false, focused: false, height: 957, id: 442, incognito: false, left: 428, state: 'normal', tabs: [ { active: true, audible: false, favIconUrl: 'http://facebook.github.io/react/favicon.ico', height: 862, highlighted: false, id: 443, incognito: false, index: 0, muted: false, mutedCause: '', pinned: false, selected: false, status: 'complete', // title deliberately omitted url: 'http://facebook.github.io/react/docs/component-api.html', width: 1258, windowId: 442, }, ], }; const chromeTabWindow = tabWindowUtils.makeChromeTabWindow( chromeWindowSnap4 as any ); const chromeTabWindowJS = JSON.parse( JSON.stringify(chromeTabWindow.toJS()) ); const chromeTabWindowTitle = chromeTabWindow.title; expect(chromeTabWindow.title).toBe(chromeWindowSnap4.tabs[0].url); }); test('attachChromeWindow', () => { // Let's first create the tabWindow for our saved bookmark folder: const tabWindow = tabWindowUtils.makeFolderTabWindow( testData.d3BookmarkFolder ); const tabWindowJS = JSON.parse(JSON.stringify(tabWindow.toJS())); /* console.log('makeFolderTabWindow returned:'); console.log('>>>>>>>'); console.log(JSON.stringify(tabWindowJS, null, 2)); console.log('>>>>>>>'); console.log('diffs between tabWindowJS and expected:'); dumpDiffs(tabWindowJS, testData.d3InitialExpectedTabWindow); */ expect(tabWindowJS).toEqual(testData.d3InitialExpectedTabWindow); expect(tabWindow.title).toBe('d3 docs'); // Now let's do the attach: const updTabWindow = tabWindowUtils.updateWindow( tabWindow, testData.d3OpenedChromeWindow as any ); const updTabWindowJS = JSON.parse(JSON.stringify(updTabWindow.toJS())); /* console.log("updateTabWindow returned:") console.log(">>>>>>>") console.log(JSON.stringify(updTabWindowJS,null,2)) console.log(">>>>>>>") console.log("diffs between updTabWindow (actual) and expected:") dumpDiffs(updTabWindowJS, testData.d3AttachedExpectedTabWindow) */ expect(updTabWindowJS).toEqual(testData.d3AttachedExpectedTabWindow); const tabCount = updTabWindow.tabItems.count(); const openCount = updTabWindow.tabItems.count((t) => t.open); const savedCount = updTabWindow.tabItems.count((t) => t.saved); /* console.log( 'attachChromeWindow: ' + tabCount + ' total tabs, ' + openCount + ' open, ' + savedCount + ' saved' ); */ expect(tabCount).toBe(7); expect(openCount).toBe(6); expect(savedCount).toBe(6); // Now revert the window to saved state: const revTabWindow = tabWindowUtils.removeOpenWindowState( updTabWindow, false ); const revTabCount = revTabWindow.tabItems.count(); const revOpenCount = revTabWindow.tabItems.count((t) => t.open); const revSavedCount = revTabWindow.tabItems.count((t) => t.saved); /* console.log( 'attachChromeWindow after revert: ' + revTabCount + ' total tabs, ' + revOpenCount + ' open, ' + revSavedCount + ' saved' ); */ expect(revTabCount).toBe(6); expect(revOpenCount).toBe(0); expect(revSavedCount).toBe(6); }); const TEST_SAVE_TAB_ID = 445; test('saveTab', () => { log.setLevel(log.levels.DEBUG); const baseTabWindow = tabWindowUtils.makeChromeTabWindow( testData.chromeWindowSnap ); const tabWindowJS = JSON.parse(JSON.stringify(baseTabWindow.toJS())); /* console.log("makeChromeTabWindow returned: ") console.log(">>>>>") console.log(JSON.stringify(tabWindowJS,null,2)) console.log(">>>>>") */ const entry = baseTabWindow.findChromeTabId(TEST_SAVE_TAB_ID); expect(entry.length).toBe(2); const [tabIndex, baseTabItem] = entry; console.log('saveTab: base tab item: ', baseTabItem.toJS()); expect(baseTabItem.saved).toBe(false); expect(baseTabItem.savedState).toBe(null); const saveTabNode: chrome.bookmarks.BookmarkTreeNode = { dateAdded: 1405471223073, id: '999', index: 5, parentId: '777', title: 'React Tutorial', url: 'http://facebook.github.io/react/docs/tutorial.html', }; const savedTabWindow = tabWindowUtils.saveTab( baseTabWindow, baseTabItem, saveTabNode ); const savedTabWindowJS = JSON.parse(JSON.stringify(savedTabWindow.toJS())); /* console.log('savedTab returned: '); console.log('>>>>>'); console.log(JSON.stringify(savedTabWindowJS, null, 2)); console.log('>>>>>'); */ const savedEntry = savedTabWindow.findChromeTabId(TEST_SAVE_TAB_ID); expect(savedEntry.length).toBe(2); const [savedTabIndex, savedTabItem] = savedEntry; console.log('saveTab: savedTabItem:', savedTabItem.toJS()); expect(savedTabItem.saved).toBe(true); expect(savedTabItem.savedState.bookmarkId).toBe(saveTabNode.id); expect(savedTabItem.savedState.bookmarkIndex).toBe(saveTabNode.index); expect(savedTabItem.savedState.url).toBe(saveTabNode.url); });
the_stack
import { Glue42Core } from "@glue42/core"; import { Glue42Web } from "@glue42/web"; import { BridgeOperation, InternalLayoutsConfig, InternalPlatformConfig, LibController } from "../../common/types"; import { GlueController } from "../../controllers/glue"; import { SessionStorageController } from "../../controllers/session"; import logger from "../../shared/logger"; import { objEqual } from "../../shared/utils"; import { allLayoutsFullConfigDecoder, allLayoutsSummariesResultDecoder, getAllLayoutsConfigDecoder, layoutsImportConfigDecoder, layoutsOperationTypesDecoder, optionalSimpleLayoutResult, simpleLayoutConfigDecoder } from "./decoders"; import { IdbStore } from "./idbStore"; import { AllLayoutsFullConfig, AllLayoutsSummariesResult, GetAllLayoutsConfig, LayoutsImportConfig, LayoutsOperationTypes, OptionalSimpleLayoutResult, SimpleLayoutConfig } from "./types"; export class LayoutsController implements LibController { private started = false; private config!: InternalLayoutsConfig; private operations: { [key in LayoutsOperationTypes]: BridgeOperation } = { get: { name: "get", dataDecoder: simpleLayoutConfigDecoder, resultDecoder: optionalSimpleLayoutResult, execute: this.handleGetLayout.bind(this) }, getAll: { name: "getAll", dataDecoder: getAllLayoutsConfigDecoder, resultDecoder: allLayoutsSummariesResultDecoder, execute: this.handleGetAll.bind(this) }, export: { name: "export", dataDecoder: getAllLayoutsConfigDecoder, resultDecoder: allLayoutsFullConfigDecoder, execute: this.handleExport.bind(this) }, import: { name: "import", dataDecoder: layoutsImportConfigDecoder, execute: this.handleImport.bind(this) }, remove: { name: "remove", dataDecoder: simpleLayoutConfigDecoder, execute: this.handleRemove.bind(this) } } constructor( private readonly glueController: GlueController, private readonly idbStore: IdbStore, private readonly sessionStore: SessionStorageController ) { } private get logger(): Glue42Core.Logger.API | undefined { return logger.get("layouts.controller"); } public async start(config: InternalPlatformConfig): Promise<void> { this.config = config.layouts; this.logger?.trace(`initializing with mode: ${this.config.mode}`); if (this.config.local && this.config.local.length) { await this.mergeImport(this.config.local); } this.started = true; this.logger?.trace("initialization is completed"); } public async handleControl(args: any): Promise<any> { if (!this.started) { new Error("Cannot handle this windows control message, because the controller has not been started"); } const layoutsData = args.data; const commandId = args.commandId; const operationValidation = layoutsOperationTypesDecoder.run(args.operation); if (!operationValidation.ok) { throw new Error(`This layouts request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(operationValidation.error)}`); } const operationName: LayoutsOperationTypes = operationValidation.result; const incomingValidation = this.operations[operationName].dataDecoder?.run(layoutsData); if (incomingValidation && !incomingValidation.ok) { throw new Error(`Layouts request for ${operationName} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(incomingValidation.error)}`); } this.logger?.debug(`[${commandId}] ${operationName} command is valid with data: ${JSON.stringify(layoutsData)}`); const result = await this.operations[operationName].execute(layoutsData, commandId); const resultValidation = this.operations[operationName].resultDecoder?.run(result); if (resultValidation && !resultValidation.ok) { throw new Error(`Layouts request for ${operationName} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(resultValidation.error)}`); } this.logger?.trace(`[${commandId}] ${operationName} command was executed successfully`); return result; } public async handleGetAll(config: GetAllLayoutsConfig, commandId: string): Promise<AllLayoutsSummariesResult> { this.logger?.trace(`[${commandId}] handling get all layout summaries request for type: ${config.type}`); const allLayouts = await this.getAll(config.type); const summaries = allLayouts.map<Glue42Web.Layouts.LayoutSummary>((layout) => { return { name: layout.name, type: layout.type, context: layout.context, metadata: layout.metadata }; }); this.logger?.trace(`[${commandId}] all summaries have been compiled, responding to caller`); return { summaries }; } public async handleExport(config: GetAllLayoutsConfig, commandId: string): Promise<AllLayoutsFullConfig> { this.logger?.trace(`[${commandId}] handling get all layout full request for type: ${config.type}`); const layouts = await this.getAll(config.type); this.logger?.trace(`[${commandId}] full layouts collection have been compiled, responding to caller`); return { layouts }; } public async handleImport(config: LayoutsImportConfig, commandId: string): Promise<void> { this.logger?.trace(`[${commandId}] handling mass import request for layout names: ${config.layouts.map((l) => l.name).join(", ")}`); if (config.mode === "merge") { this.logger?.trace(`[${commandId}] importing the layouts in merge mode`); await this.mergeImport(config.layouts); } else { this.logger?.trace(`[${commandId}] importing the layouts in replace mode`); await this.replaceImport(config.layouts); } this.logger?.trace(`[${commandId}] mass import completed, responding to caller`); } public async handleRemove(config: SimpleLayoutConfig, commandId: string): Promise<void> { this.logger?.trace(`[${commandId}] handling remove request for ${JSON.stringify(config)}`); const layout = (await this.getAll(config.type)).find((l) => l.name === config.name && l.type === config.type); if (layout) { await this.delete(config.name, config.type); this.emitStreamData("layoutRemoved", layout); } const operationMessage = layout ? "has been removed" : "has not been removed, because it does not exist"; this.logger?.trace(`[${commandId}] ${config.name} of type ${config.type} ${operationMessage}`); } public async handleGetLayout(config: SimpleLayoutConfig, commandId: string): Promise<OptionalSimpleLayoutResult> { this.logger?.trace(`[${commandId}] handling get layout request for name: ${config.name} and type: ${config.type}`); const allLayouts = await this.getAll(config.type); const layout = allLayouts.find((l) => l.name === config.name); this.logger?.trace(`[${commandId}] request completed, responding to the caller`); return { layout }; } private emitStreamData(operation: "layoutChanged" | "layoutAdded" | "layoutRemoved", data: any): void { this.logger?.trace(`sending notification of event: ${operation} with data: ${JSON.stringify(data)}`); this.glueController.pushSystemMessage("layouts", operation, data); } public async mergeImport(layouts: Glue42Web.Layouts.Layout[]): Promise<void> { const currentLayouts = await this.getAll("Workspace"); const pendingEvents: Array<{ operation: "layoutChanged" | "layoutAdded" | "layoutRemoved"; layout: Glue42Web.Layouts.Layout }> = []; for (const layout of layouts) { const defCurrentIdx = currentLayouts.findIndex((app) => app.name === layout.name); if (defCurrentIdx > -1 && !objEqual(layout, currentLayouts[defCurrentIdx])) { this.logger?.trace(`change detected at layout ${layout.name}`); pendingEvents.push({ operation: "layoutChanged", layout }); currentLayouts[defCurrentIdx] = layout; continue; } if (defCurrentIdx < 0) { this.logger?.trace(`new layout: ${layout.name} detected, adding and announcing`); pendingEvents.push({ operation: "layoutAdded", layout }); currentLayouts.push(layout); } } await this.cleanSave(currentLayouts); pendingEvents.forEach((pending) => this.emitStreamData(pending.operation, pending.layout)); } public async replaceImport(layouts: Glue42Web.Layouts.Layout[]): Promise<void> { const currentLayouts = await this.getAll("Workspace"); const pendingEvents: Array<{ operation: "layoutChanged" | "layoutAdded" | "layoutRemoved"; layout: Glue42Web.Layouts.Layout }> = []; for (const layout of layouts) { const defCurrentIdx = currentLayouts.findIndex((app) => app.name === layout.name); if (defCurrentIdx < 0) { this.logger?.trace(`new layout: ${layout.name} detected, adding and announcing`); pendingEvents.push({ operation: "layoutAdded", layout }); continue; } if (!objEqual(layout, currentLayouts[defCurrentIdx])) { this.logger?.trace(`change detected at layout ${layout.name}`); pendingEvents.push({ operation: "layoutChanged", layout }); } currentLayouts.splice(defCurrentIdx, 1); } // everything that is left in the old snap here, means it is removed in the latest one currentLayouts.forEach((layout) => { this.logger?.trace(`layout ${layout.name} missing, removing and announcing`); pendingEvents.push({ operation: "layoutRemoved", layout }); }); await this.cleanSave(layouts); pendingEvents.forEach((pending) => this.emitStreamData(pending.operation, pending.layout)); } private async getAll(type: Glue42Web.Layouts.LayoutType): Promise<Glue42Web.Layouts.Layout[]> { let all: Glue42Web.Layouts.Layout[]; if (this.config.mode === "idb") { all = await this.idbStore.getAll(type); } else { all = this.sessionStore.getLayoutSnapshot().layouts; } return all; } private async cleanSave(layouts: Glue42Web.Layouts.Layout[]): Promise<void> { if (this.config.mode === "idb") { await this.idbStore.clear("Workspace"); for (const layout of layouts) { await this.idbStore.store(layout, layout.type); } return; } this.sessionStore.saveLayoutSnapshot({ layouts }); } private async delete(name: string, type: Glue42Web.Layouts.LayoutType): Promise<void> { if (this.config.mode === "idb") { await this.idbStore.delete(name, type); return; } const all = this.sessionStore.getLayoutSnapshot().layouts; const idxToRemove = all.findIndex((l) => l.name === name && l.type); if (idxToRemove > -1) { all.splice(idxToRemove, 1); } this.sessionStore.saveLayoutSnapshot({ layouts: all }); } }
the_stack
import { Component } from '../component'; import { CartesianOrientations, ColorClassNameTypes, Events, RenderTypes, Roles, } from '../../interfaces'; import { Tools } from '../../tools'; import * as Configuration from '../../configuration'; // D3 Imports import { select } from 'd3-selection'; export class Boxplot extends Component { type = 'boxplot'; renderType = RenderTypes.SVG; render(animate: boolean) { // Grab container SVG const svg = this.getComponentContainer({ withinChartClip: true }); const options = this.getOptions(); const { groupMapsTo } = options.data; const dataGroupNames = this.model.getDataGroupNames(); /* * Get graphable dimensions */ const mainXScale = this.services.cartesianScales.getMainXScale(); const mainYScale = this.services.cartesianScales.getMainYScale(); const [xScaleStart, xScaleEnd] = mainXScale.range(); const [yScaleEnd, yScaleStart] = mainYScale.range(); const width = xScaleEnd - xScaleStart; const height = yScaleEnd - yScaleStart; if (width === 0) { return; } // Get orientation of the chart const { cartesianScales } = this.services; const orientation = cartesianScales.getOrientation(); const isInVerticalOrientation = orientation === CartesianOrientations.VERTICAL; const [ getXValue, getYValue, ] = Tools.flipDomainAndRangeBasedOnOrientation( (d, i?) => this.services.cartesianScales.getDomainValue(d, i), (d, i?) => this.services.cartesianScales.getRangeValue(d, i), orientation ); const gridSize = Math.floor( (isInVerticalOrientation ? width : height) / dataGroupNames.length ); const boxWidth = Math.min(gridSize / 2, 16); const boxplotData = this.model.getBoxplotData(); /* * update or initialize all box groups */ const boxGroups = svg.selectAll('.box-group').data(boxplotData); boxGroups.exit().remove(); const boxGroupsEnter = boxGroups .enter() .append('g') .attr('class', 'box-group'); const allBoxGroups = boxGroups.merge(boxGroupsEnter); /* * draw the 2 range lines for each box */ // Start range line boxGroupsEnter .append('path') .merge(boxGroups.select('path.vertical-line.start')) .attr('class', () => this.model.getColorClassName({ classNameTypes: [ColorClassNameTypes.STROKE], originalClassName: 'vertical-line start', }) ) .attr('stroke-width', Configuration.boxplot.strokeWidth.default) .attr('fill', 'none') .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'boxplot-update-verticalstartline', animate, }) ) .attr('d', (d) => { const x0 = cartesianScales.getDomainValue(d[groupMapsTo]); const x1 = x0; const y0 = cartesianScales.getRangeValue(d.whiskers.min); const y1 = cartesianScales.getRangeValue(d.quartiles.q_25); return Tools.generateSVGPathString( { x0, x1, y0, y1 }, orientation ); }); // End range line boxGroupsEnter .append('path') .merge(boxGroups.select('path.vertical-line.end')) .attr('class', () => this.model.getColorClassName({ classNameTypes: [ColorClassNameTypes.STROKE], originalClassName: 'vertical-line end', }) ) .attr('stroke-width', Configuration.boxplot.strokeWidth.default) .attr('fill', 'none') .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'boxplot-update-verticalendline', animate, }) ) .attr('d', (d) => { const x0 = cartesianScales.getDomainValue(d[groupMapsTo]); const x1 = x0; const y0 = cartesianScales.getRangeValue(d.whiskers.max); const y1 = cartesianScales.getRangeValue(d.quartiles.q_75); return Tools.generateSVGPathString( { x0, x1, y0, y1 }, orientation ); }); /* * Draw out and update the boxes */ boxGroupsEnter .append('path') .merge(boxGroups.select('path.box')) .attr('class', () => this.model.getColorClassName({ classNameTypes: [ ColorClassNameTypes.FILL, ColorClassNameTypes.STROKE, ], originalClassName: 'box', }) ) .attr('fill-opacity', Configuration.boxplot.box.opacity.default) .attr('stroke-width', Configuration.boxplot.strokeWidth.default) .attr('role', Roles.GRAPHICS_SYMBOL) .attr('aria-roledescription', 'box') .attr('aria-label', (d) => d[groupMapsTo]) .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'boxplot-update-quartiles', animate, }) ) .attr('d', (d) => { const x0 = cartesianScales.getDomainValue(d[groupMapsTo]) - boxWidth / 2; const x1 = x0 + boxWidth; const y0 = cartesianScales.getRangeValue( Math[isInVerticalOrientation ? 'max' : 'min']( d.quartiles.q_75, d.quartiles.q_25 ) ); const y1 = y0 + Math.abs( cartesianScales.getRangeValue(d.quartiles.q_75) - cartesianScales.getRangeValue(d.quartiles.q_25) ); return Tools.generateSVGPathString( { x0, x1, y0, y1 }, orientation ); }); /* * Draw out and update highlight areas */ boxGroupsEnter .append('path') .merge(boxGroups.select('path.highlight-area')) .attr('class', 'highlight-area') .attr('opacity', 0) .attr('d', (d) => { const x0 = cartesianScales.getDomainValue(d[groupMapsTo]) - boxWidth / 2; const x1 = x0 + boxWidth; const y0 = cartesianScales.getRangeValue(d.whiskers.min); const y1 = cartesianScales.getRangeValue(d.whiskers.max); return Tools.generateSVGPathString( { x0, x1, y0, y1 }, orientation ); }); /* * Draw out and update the starting whisker */ boxGroupsEnter .append('path') .merge(boxGroups.select('path.whisker.start')) .attr('class', () => this.model.getColorClassName({ classNameTypes: [ColorClassNameTypes.STROKE], originalClassName: 'whisker start', }) ) .attr('stroke-width', Configuration.boxplot.strokeWidth.thicker) .attr('fill', 'none') .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'boxplot-update-startingwhisker', animate, }) ) .attr('d', (d) => { const x0 = cartesianScales.getDomainValue(d[groupMapsTo]) - boxWidth / 4; const x1 = x0 + boxWidth / 2; const y0 = cartesianScales.getRangeValue(d.whiskers.min); const y1 = cartesianScales.getRangeValue(d.whiskers.min); return Tools.generateSVGPathString( { x0, x1, y0, y1 }, orientation ); }); /* * Draw out and update the median line */ boxGroupsEnter .append('path') .merge(boxGroups.select('path.median')) .attr('fill', 'none') .attr('class', () => this.model.getColorClassName({ classNameTypes: [ColorClassNameTypes.STROKE], originalClassName: 'median', }) ) .attr('stroke-width', 2) .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'boxplot-update-median', animate, }) ) .attr('d', (d) => { const x0 = cartesianScales.getDomainValue(d[groupMapsTo]) - boxWidth / 2; const x1 = x0 + boxWidth; const y0 = cartesianScales.getRangeValue(d.quartiles.q_50); const y1 = y0; return Tools.generateSVGPathString( { x0, x1, y0, y1 }, orientation ); }); /* * Draw out and update the ending whisker */ boxGroupsEnter .append('path') .merge(boxGroups.select('path.whisker.end')) .attr('class', () => this.model.getColorClassName({ classNameTypes: [ColorClassNameTypes.STROKE], originalClassName: 'whisker end', }) ) .attr('stroke-width', Configuration.boxplot.strokeWidth.thicker) .attr('fill', 'none') .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'boxplot-update-endingwhisker', animate, }) ) .attr('d', (d) => { const x0 = cartesianScales.getDomainValue(d[groupMapsTo]) - boxWidth / 4; const x1 = x0 + boxWidth / 2; const y0 = cartesianScales.getRangeValue(d.whiskers.max); const y1 = cartesianScales.getRangeValue(d.whiskers.max); return Tools.generateSVGPathString( { x0, x1, y0, y1 }, orientation ); }); /* * Draw out and update the outlier circles */ const circles = allBoxGroups.selectAll('circle.outlier').data((d) => d.outliers.map((outlier) => { return { min: d.whiskers.min, max: d.whiskers.max, [groupMapsTo]: d[groupMapsTo], value: outlier, }; }) ); circles.exit().remove(); const circlesEnter = circles.enter().append('circle'); circles .merge(circlesEnter) .attr('r', Configuration.boxplot.circle.radius) .attr('class', () => this.model.getColorClassName({ classNameTypes: [ ColorClassNameTypes.FILL, ColorClassNameTypes.STROKE, ], originalClassName: 'outlier', }) ) .attr('fill-opacity', Configuration.boxplot.circle.opacity.default) .attr('cx', getXValue) .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'boxplot-update-circles', animate, }) ) .attr('cy', getYValue); this.addBoxEventListeners(); this.addCircleEventListeners(); } addBoxEventListeners() { const self = this; const options = this.getOptions(); const { groupMapsTo } = options.data; this.parent .selectAll('path.highlight-area') .on('mouseover', function (event, datum) { const hoveredElement = select(this); const parentElement = select(this.parentNode); parentElement .select('path.box') .classed('hovered', true) .attr( 'fill-opacity', Configuration.boxplot.box.opacity.hovered ); // Show tooltip for single datapoint self.services.events.dispatchEvent(Events.Tooltip.SHOW, { event, hoveredElement, items: [ { label: options.tooltip.groupLabel, value: datum[groupMapsTo], class: self.model.getColorClassName({ classNameTypes: [ColorClassNameTypes.TOOLTIP], }), }, { label: 'Minimum', value: datum.whiskers.min, }, { label: 'Q1', value: datum.quartiles.q_25, }, { label: 'Median', value: datum.quartiles.q_50, }, { label: 'Q3', value: datum.quartiles.q_75, }, { label: 'Maximum', value: datum.whiskers.max, }, { label: 'IQR', value: datum.quartiles.q_75 - datum.quartiles.q_25, }, ], }); // Dispatch mouse event self.services.events.dispatchEvent( Events.Boxplot.BOX_MOUSEOVER, { event, element: hoveredElement, datum, } ); }) .on('mousemove', function (event, datum) { const hoveredElement = select(this); // Dispatch mouse event self.services.events.dispatchEvent( Events.Boxplot.BOX_MOUSEMOVE, { event, element: hoveredElement, datum, } ); self.services.events.dispatchEvent(Events.Tooltip.MOVE, { event, }); }) .on('click', function (event, datum) { // Dispatch mouse event self.services.events.dispatchEvent(Events.Boxplot.BOX_CLICK, { event, element: select(this), datum, }); }) .on('mouseout', function (event, datum) { const hoveredElement = select(this); const parentElement = select(this.parentNode); parentElement .select('path.box') .classed('hovered', false) .attr( 'fill-opacity', Configuration.boxplot.box.opacity.default ); // Dispatch mouse event self.services.events.dispatchEvent( Events.Boxplot.BOX_MOUSEOUT, { event, element: hoveredElement, datum, } ); // Hide tooltip self.services.events.dispatchEvent(Events.Tooltip.HIDE, { hoveredElement, }); }); } addCircleEventListeners() { const self = this; const options = this.getOptions(); const { groupMapsTo } = options.data; const rangeIdentifier = this.services.cartesianScales.getRangeIdentifier(); this.parent .selectAll('circle') .on('mouseover', function (event, datum) { const hoveredElement = select(this); hoveredElement .classed('hovered', true) .attr( 'fill-opacity', Configuration.boxplot.circle.opacity.hovered ) .classed('unfilled', false); // Show tooltip for single datapoint self.services.events.dispatchEvent(Events.Tooltip.SHOW, { event, hoveredElement, items: [ { label: options.tooltip.groupLabel, value: datum[groupMapsTo], class: self.model.getColorClassName({ classNameTypes: [ColorClassNameTypes.TOOLTIP], }), }, { label: 'Outlier', value: datum[rangeIdentifier], }, ], }); // Dispatch mouse event self.services.events.dispatchEvent( Events.Boxplot.OUTLIER_MOUSEOVER, { event, element: hoveredElement, datum, } ); }) .on('mousemove', function (event, datum) { const hoveredElement = select(this); // Dispatch mouse event self.services.events.dispatchEvent( Events.Boxplot.OUTLIER_MOUSEMOVE, { event, element: hoveredElement, datum, } ); self.services.events.dispatchEvent(Events.Tooltip.MOVE, { event, }); }) .on('click', function (event, datum) { // Dispatch mouse event self.services.events.dispatchEvent( Events.Boxplot.OUTLIER_CLICK, { event, element: select(this), datum, } ); }) .on('mouseout', function (event, datum) { const hoveredElement = select(this); hoveredElement .classed('hovered', false) .attr( 'fill-opacity', Configuration.boxplot.circle.opacity.default ); // Dispatch mouse event self.services.events.dispatchEvent( Events.Boxplot.OUTLIER_MOUSEOUT, { event, element: hoveredElement, datum, } ); // Hide tooltip self.services.events.dispatchEvent(Events.Tooltip.HIDE, { hoveredElement, }); }); } }
the_stack
import * as angular from 'angular'; import * as _ from "underscore"; import {RestUrlConstants} from "./RestUrlConstants" export class RestUrlService { ROOT = RestUrlConstants.ROOT ADMIN_BASE_URL = RestUrlConstants.ADMIN_BASE_URL ADMIN_V2_BASE_URL = RestUrlConstants.ADMIN_V2_BASE_URL; SECURITY_BASE_URL = RestUrlConstants.SECURITY_BASE_URL TEMPLATES_BASE_URL = RestUrlConstants.TEMPLATES_BASE_URL FEEDS_BASE_URL = RestUrlConstants.FEEDS_BASE_URL SLA_BASE_URL = RestUrlConstants.SLA_BASE_URL CONTROLLER_SERVICES_BASE_URL = RestUrlConstants.CONTROLLER_SERVICES_BASE_URL SCHEMA_DISCOVERY_BASE_URL = RestUrlConstants.SCHEMA_DISCOVERY_BASE_URL GET_TEMPLATES_URL = RestUrlConstants.GET_TEMPLATES_URL GET_UNREGISTERED_TEMPLATES_URL = RestUrlConstants.GET_UNREGISTERED_TEMPLATES_URL HADOOP_AUTHORIZATATION_BASE_URL = RestUrlConstants.HADOOP_AUTHORIZATATION_BASE_URL UI_BASE_URL = RestUrlConstants.UI_BASE_URL DOMAIN_TYPES_BASE_URL = RestUrlConstants.DOMAIN_TYPES_BASE_URL UPLOAD_SAMPLE_TABLE_FILE = RestUrlConstants.UPLOAD_SAMPLE_TABLE_FILE UPLOAD_SPARK_SAMPLE_FILE = RestUrlConstants.UPLOAD_SPARK_SAMPLE_FILE LIST_FILE_PARSERS = RestUrlConstants.LIST_FILE_PARSERS LIST_SPARK_FILE_PARSERS = RestUrlConstants.LIST_SPARK_FILE_PARSERS VALIDATE_CRON_EXPRESSION_URL = RestUrlConstants.VALIDATE_CRON_EXPRESSION_URL PREVIEW_CRON_EXPRESSION_URL = RestUrlConstants.PREVIEW_CRON_EXPRESSION_URL GET_SYSTEM_NAME = RestUrlConstants.GET_SYSTEM_NAME ICONS_URL = RestUrlConstants.ICONS_URL ICON_COLORS_URL = RestUrlConstants.ICON_COLORS_URL CODE_MIRROR_TYPES_URL = RestUrlConstants.CODE_MIRROR_TYPES_URL CATEGORIES_URL = RestUrlConstants.CATEGORIES_URL SEARCH_URL = RestUrlConstants.SEARCH_URL HIVE_SERVICE_URL = RestUrlConstants.HIVE_SERVICE_URL SPARK_SHELL_SERVICE_URL = RestUrlConstants.SPARK_SHELL_SERVICE_URL ///TEMPLATE REGISTRATION REGISTER_TEMPLATE_URL = RestUrlConstants.REGISTER_TEMPLATE_URL; SAVE_TEMPLATE_ORDER_URL = RestUrlConstants.SAVE_TEMPLATE_ORDER_URL; GET_REGISTERED_TEMPLATES_URL = RestUrlConstants.GET_REGISTERED_TEMPLATES_URL GET_REGISTERED_TEMPLATE_PROPERTIES_URL = RestUrlConstants.GET_REGISTERED_TEMPLATE_PROPERTIES_URL; GET_REGISTERED_TEMPLATE_URL = RestUrlConstants.GET_REGISTERED_TEMPLATE_URL; REGISTERED_TEMPLATE_NIFI_INPUT_PORTS = RestUrlConstants.REGISTERED_TEMPLATE_NIFI_INPUT_PORTS; REGISTERED_TEMPLATE_NIFI_OUTPUT_PORTS = RestUrlConstants.REGISTERED_TEMPLATE_NIFI_OUTPUT_PORTS; REGISTERED_TEMPLATE_NIFI_ALL_PORTS = RestUrlConstants.REGISTERED_TEMPLATE_NIFI_ALL_PORTS; TEMPLATE_PROCESSOR_DATASOURCE_DEFINITIONS = RestUrlConstants.TEMPLATE_PROCESSOR_DATASOURCE_DEFINITIONS; TEMPLATE_FLOW_INFORMATION = RestUrlConstants.TEMPLATE_FLOW_INFORMATION; DISABLE_REGISTERED_TEMPLATE_URL = RestUrlConstants.DISABLE_REGISTERED_TEMPLATE_URL; ENABLE_REGISTERED_TEMPLATE_URL = RestUrlConstants.ENABLE_REGISTERED_TEMPLATE_URL; DELETE_REGISTERED_TEMPLATE_URL = RestUrlConstants.DELETE_REGISTERED_TEMPLATE_URL; REMOTE_PROCESS_GROUP_AWARE = RestUrlConstants.REMOTE_PROCESS_GROUP_AWARE ALL_REUSABLE_FEED_INPUT_PORTS = RestUrlConstants.ALL_REUSABLE_FEED_INPUT_PORTS ROOT_INPUT_PORTS = RestUrlConstants.ROOT_INPUT_PORTS CONFIGURATION_PROPERTIES_URL = RestUrlConstants.CONFIGURATION_PROPERTIES_URL METADATA_PROPERTY_NAMES_URL = RestUrlConstants.METADATA_PROPERTY_NAMES_URL GET_DATASOURCE_TYPES = RestUrlConstants.GET_DATASOURCE_TYPES //FEED URLS CREATE_FEED_FROM_TEMPLATE_URL = RestUrlConstants.CREATE_FEED_FROM_TEMPLATE_URL MERGE_FEED_WITH_TEMPLATE = RestUrlConstants.MERGE_FEED_WITH_TEMPLATE GET_FEEDS_URL = RestUrlConstants.GET_FEEDS_URL GET_FEED_NAMES_URL = RestUrlConstants.GET_FEED_NAMES_URL GET_POSSIBLE_FEED_PRECONDITIONS_URL = RestUrlConstants.GET_POSSIBLE_FEED_PRECONDITIONS_URL GET_POSSIBLE_SLA_METRIC_OPTIONS_URL = RestUrlConstants.GET_POSSIBLE_SLA_METRIC_OPTIONS_URL GET_POSSIBLE_SLA_ACTION_OPTIONS_URL = RestUrlConstants.GET_POSSIBLE_SLA_ACTION_OPTIONS_URL VALIDATE_SLA_ACTION_URL = RestUrlConstants.VALIDATE_SLA_ACTION_URL SAVE_FEED_SLA_URL = RestUrlConstants.SAVE_FEED_SLA_URL; SAVE_SLA_URL = RestUrlConstants.SAVE_SLA_URL DELETE_SLA_URL = RestUrlConstants.DELETE_SLA_URL GET_FEED_SLA_URL = RestUrlConstants.GET_FEED_SLA_URL GET_SLA_BY_ID_URL = RestUrlConstants.GET_SLA_BY_ID_URL GET_SLA_AS_EDIT_FORM = RestUrlConstants.GET_SLA_AS_EDIT_FORM GET_SLAS_URL = RestUrlConstants.GET_SLAS_URL GET_CONTROLLER_SERVICES_TYPES_URL = RestUrlConstants.GET_CONTROLLER_SERVICES_TYPES_URL GET_CONTROLLER_SERVICES_URL = RestUrlConstants.GET_CONTROLLER_SERVICES_URL GET_CONTROLLER_SERVICE_URL = RestUrlConstants.GET_CONTROLLER_SERVICE_URL CONTROLLER_SERVICES_PREVIEW_QUERY_URL = RestUrlConstants.CONTROLLER_SERVICES_PREVIEW_QUERY_URL FEED_VERSIONS_URL = RestUrlConstants.FEED_VERSIONS_URL FEED_VERSION_ID_URL = RestUrlConstants.FEED_VERSION_ID_URL FEED_VERSIONS_DIFF_URL = RestUrlConstants.FEED_VERSIONS_DIFF_URL FEED_PROFILE_STATS_URL = RestUrlConstants.FEED_PROFILE_STATS_URL FEED_PROFILE_SUMMARY_URL = RestUrlConstants.FEED_PROFILE_SUMMARY_URL FEED_PROFILE_VALID_RESULTS_URL = RestUrlConstants.FEED_PROFILE_VALID_RESULTS_URL FEED_PROFILE_INVALID_RESULTS_URL = RestUrlConstants.FEED_PROFILE_INVALID_RESULTS_URL ENABLE_FEED_URL = RestUrlConstants.ENABLE_FEED_URL DISABLE_FEED_URL = RestUrlConstants.DISABLE_FEED_URL START_FEED_URL = RestUrlConstants.START_FEED_URL UPLOAD_FILE_FEED_URL = RestUrlConstants.UPLOAD_FILE_FEED_URL FEED_DETAILS_BY_NAME_URL = RestUrlConstants.FEED_DETAILS_BY_NAME_URL CATEGORY_DETAILS_BY_SYSTEM_NAME_URL = RestUrlConstants.CATEGORY_DETAILS_BY_SYSTEM_NAME_URL CATEGORY_DETAILS_BY_ID_URL = RestUrlConstants.CATEGORY_DETAILS_BY_ID_URL /** * Gets the URL for retrieving the user fields for a new feed. * * @param {string} categoryId the category id * @returns {string} the URL */ GET_FEED_USER_FIELDS_URL = RestUrlConstants.GET_FEED_USER_FIELDS_URL /** * URL for retrieving the user fields for a new category. * @type {string} */ GET_CATEGORY_USER_FIELD_URL = RestUrlConstants.GET_CATEGORY_USER_FIELD_URL // Endpoint for administration of user fields ADMIN_USER_FIELDS = RestUrlConstants.ADMIN_USER_FIELDS //Field Policy Urls AVAILABLE_STANDARDIZATION_POLICIES = RestUrlConstants.AVAILABLE_STANDARDIZATION_POLICIES AVAILABLE_VALIDATION_POLICIES = RestUrlConstants.AVAILABLE_VALIDATION_POLICIES ADMIN_IMPORT_TEMPLATE_URL = RestUrlConstants.ADMIN_IMPORT_TEMPLATE_URL ADMIN_EXPORT_TEMPLATE_URL = RestUrlConstants.ADMIN_EXPORT_TEMPLATE_URL ADMIN_EXPORT_FEED_URL = RestUrlConstants.ADMIN_EXPORT_FEED_URL ADMIN_IMPORT_FEED_URL = RestUrlConstants.ADMIN_IMPORT_FEED_URL ADMIN_UPLOAD_STATUS_CHECK = RestUrlConstants.ADMIN_UPLOAD_STATUS_CHECK; // Hadoop Security Authorization HADOOP_SECURITY_GROUPS = RestUrlConstants.HADOOP_SECURITY_GROUPS // Security service URLs SECURITY_GROUPS_URL = RestUrlConstants.SECURITY_GROUPS_URL SECURITY_USERS_URL = RestUrlConstants.SECURITY_USERS_URL FEED_LINEAGE_URL = RestUrlConstants.FEED_LINEAGE_URL // Feed history data reindexing endpoint FEED_HISTORY_CONFIGURED = RestUrlConstants.FEED_HISTORY_CONFIGURED /** * Generates a URL for listing the controller services under the specified process group. * * @param {string} processGroupId the process group id * @returns {string} the URL for listing controller services */ LIST_SERVICES_URL = RestUrlConstants.LIST_SERVICES_URL /** * The endpoint for retrieving the list of available Hive partition functions. * * @type {string} */ PARTITION_FUNCTIONS_URL = RestUrlConstants.PARTITION_FUNCTIONS_URL /** * The endpoint for retrieving the NiFi status. * @type {string} */ NIFI_STATUS = RestUrlConstants.NIFI_STATUS /** * the endpoint for determining if NiFi is up or not * @type {string} */ IS_NIFI_RUNNING_URL = RestUrlConstants.IS_NIFI_RUNNING_URL /** * The endpoint for retrieving data sources. * @type {string} */ GET_DATASOURCES_URL = RestUrlConstants.GET_DATASOURCES_URL /** * The endpoint for querying a data source. */ QUERY_DATASOURCE_URL = RestUrlConstants.QUERY_DATASOURCE_URL /** * The endpoint for querying a data source. */ PREVIEW_DATASOURCE_URL = RestUrlConstants.PREVIEW_DATASOURCE_URL GET_NIFI_CONTROLLER_SERVICE_REFERENCES_URL = RestUrlConstants.GET_NIFI_CONTROLLER_SERVICE_REFERENCES_URL /** * Get/Post roles changes for a Feed entity * @param feedId the feed id * @returns {string} the url to get/post feed role changes */ FEED_ROLES_URL = RestUrlConstants.FEED_ROLES_URL /** * Get/Post roles changes for a Category entity * @param categoryId the category id * @returns {string} the url to get/post category role changes */ CATEGORY_ROLES_URL = RestUrlConstants.CATEGORY_ROLES_URL /** * Get/Post roles changes for a Category entity * @param categoryId the category id * @returns {string} the url to get/post category role changes */ CATEGORY_FEED_ROLES_URL = RestUrlConstants.CATEGORY_FEED_ROLES_URL /** * Get/Post roles changes for a Template entity * @param templateId the Template id * @returns {string} the url to get/post Template role changes */ TEMPLATE_ROLES_URL = RestUrlConstants.TEMPLATE_ROLES_URL /** * Endpoint for roles changes to a Datasource entity. * @param {string} datasourceId the datasource id * @returns {string} the url for datasource role changes */ DATASOURCE_ROLES_URL = RestUrlConstants.DATASOURCE_ROLES_URL CONNECTOR_ROLES_URL = RestUrlConstants.CONNECTOR_ROLES_URL /** * The URL for retrieving the list of template table option plugins. * @type {string} */ UI_TEMPLATE_TABLE_OPTIONS = RestUrlConstants.UI_TEMPLATE_TABLE_OPTIONS /** * The URL for retrieving the list of templates for custom rendering with nifi processors * @type {string} */ UI_PROCESSOR_TEMPLATES = RestUrlConstants.UI_PROCESSOR_TEMPLATES /** * return a list of the categorySystemName.feedSystemName * @type {string} */ OPS_MANAGER_FEED_NAMES = RestUrlConstants.OPS_MANAGER_FEED_NAMES /** * Formats a date as a string. */ FORMAT_DATE = RestUrlConstants.FORMAT_DATE /** * Parses a string as a date. */ PARSE_DATE = RestUrlConstants.PARSE_DATE }
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type MessagesTestsQueryVariables = { conversationID: string; }; export type MessagesTestsQueryResponse = { readonly me: { readonly conversation: { readonly " $fragmentRefs": FragmentRefs<"Messages_conversation">; } | null; } | null; }; export type MessagesTestsQuery = { readonly response: MessagesTestsQueryResponse; readonly variables: MessagesTestsQueryVariables; }; /* query MessagesTestsQuery( $conversationID: String! ) { me { conversation(id: $conversationID) { ...Messages_conversation id } id } } fragment ArtworkPreview_artwork on Artwork { slug internalID title artistNames date image { url aspectRatio } } fragment AttachmentPreview_attachment on Attachment { internalID } fragment FileDownload_attachment on Attachment { fileName downloadURL ...AttachmentPreview_attachment } fragment ImagePreview_attachment on Attachment { downloadURL ...AttachmentPreview_attachment } fragment Message_message on Message { __typename body createdAt internalID isFromUser isFirstMessage from { name email } attachments { id internalID contentType downloadURL fileName ...PDFPreview_attachment ...ImagePreview_attachment ...FileDownload_attachment } } fragment Messages_conversation on Conversation { id internalID from { name email id } to { name id } initialMessage lastMessageID orderConnection(first: 10, participantType: BUYER) { edges { node { __typename orderHistory { ...OrderUpdate_event __typename ... on CommerceOrderStateChangedEvent { createdAt state stateReason } ... on CommerceOfferSubmittedEvent { createdAt } } id } } } messagesConnection(first: 10, sort: DESC) { pageInfo { startCursor endCursor hasPreviousPage hasNextPage } edges { cursor node { __typename id internalID isFromUser isFirstMessage body createdAt attachments { id internalID contentType downloadURL fileName ...ImagePreview_attachment ...PDFPreview_attachment ...FileDownload_attachment } ...Message_message } } } items { item { __typename ... on Artwork { href ...ArtworkPreview_artwork } ... on Show { href ...ShowPreview_show } ... on Node { __isNode: __typename id } } } } fragment OrderUpdate_event on CommerceOrderEventUnion { __isCommerceOrderEventUnion: __typename __typename ... on CommerceOrderStateChangedEvent { createdAt stateReason state } ... on CommerceOfferSubmittedEvent { createdAt offer { amount fromParticipant definesTotal offerAmountChanged respondsTo { fromParticipant id } id } } } fragment PDFPreview_attachment on Attachment { fileName ...AttachmentPreview_attachment } fragment ShowPreview_show on Show { slug internalID name coverImage { url aspectRatio } fair { name id } partner { __typename ... on Partner { name } ... on Node { __isNode: __typename id } ... on ExternalPartner { id } } } */ const node: ConcreteRequest = (function(){ var v0 = [ { "defaultValue": null, "kind": "LocalArgument", "name": "conversationID" } ], v1 = [ { "kind": "Variable", "name": "id", "variableName": "conversationID" } ], v2 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v3 = { "alias": null, "args": null, "kind": "ScalarField", "name": "internalID", "storageKey": null }, v4 = { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }, v5 = { "alias": null, "args": null, "kind": "ScalarField", "name": "email", "storageKey": null }, v6 = [ (v4/*: any*/), (v2/*: any*/) ], v7 = { "kind": "Literal", "name": "first", "value": 10 }, v8 = { "alias": null, "args": null, "kind": "ScalarField", "name": "__typename", "storageKey": null }, v9 = { "alias": null, "args": null, "kind": "ScalarField", "name": "createdAt", "storageKey": null }, v10 = { "alias": null, "args": null, "kind": "ScalarField", "name": "fromParticipant", "storageKey": null }, v11 = [ (v7/*: any*/), { "kind": "Literal", "name": "sort", "value": "DESC" } ], v12 = { "alias": null, "args": null, "kind": "ScalarField", "name": "href", "storageKey": null }, v13 = { "alias": null, "args": null, "kind": "ScalarField", "name": "slug", "storageKey": null }, v14 = [ { "alias": null, "args": null, "kind": "ScalarField", "name": "url", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "aspectRatio", "storageKey": null } ], v15 = [ (v2/*: any*/) ], v16 = { "kind": "InlineFragment", "selections": (v15/*: any*/), "type": "Node", "abstractKey": "__isNode" }, v17 = { "enumValues": null, "nullable": false, "plural": false, "type": "String" }, v18 = { "enumValues": null, "nullable": false, "plural": false, "type": "ID" }, v19 = { "enumValues": null, "nullable": true, "plural": false, "type": "String" }, v20 = { "enumValues": null, "nullable": true, "plural": false, "type": "Image" }, v21 = { "enumValues": null, "nullable": false, "plural": false, "type": "Float" }, v22 = { "enumValues": null, "nullable": true, "plural": false, "type": "Boolean" }, v23 = { "enumValues": null, "nullable": false, "plural": false, "type": "Boolean" }, v24 = { "enumValues": [ "BUYER", "SELLER" ], "nullable": true, "plural": false, "type": "CommerceOrderParticipantEnum" }; return { "fragment": { "argumentDefinitions": (v0/*: any*/), "kind": "Fragment", "metadata": null, "name": "MessagesTestsQuery", "selections": [ { "alias": null, "args": null, "concreteType": "Me", "kind": "LinkedField", "name": "me", "plural": false, "selections": [ { "alias": null, "args": (v1/*: any*/), "concreteType": "Conversation", "kind": "LinkedField", "name": "conversation", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "Messages_conversation" } ], "storageKey": null } ], "storageKey": null } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": (v0/*: any*/), "kind": "Operation", "name": "MessagesTestsQuery", "selections": [ { "alias": null, "args": null, "concreteType": "Me", "kind": "LinkedField", "name": "me", "plural": false, "selections": [ { "alias": null, "args": (v1/*: any*/), "concreteType": "Conversation", "kind": "LinkedField", "name": "conversation", "plural": false, "selections": [ (v2/*: any*/), (v3/*: any*/), { "alias": null, "args": null, "concreteType": "ConversationInitiator", "kind": "LinkedField", "name": "from", "plural": false, "selections": [ (v4/*: any*/), (v5/*: any*/), (v2/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "ConversationResponder", "kind": "LinkedField", "name": "to", "plural": false, "selections": (v6/*: any*/), "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "initialMessage", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "lastMessageID", "storageKey": null }, { "alias": null, "args": [ (v7/*: any*/), { "kind": "Literal", "name": "participantType", "value": "BUYER" } ], "concreteType": "CommerceOrderConnectionWithTotalCount", "kind": "LinkedField", "name": "orderConnection", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceOrderEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": null, "kind": "LinkedField", "name": "node", "plural": false, "selections": [ (v8/*: any*/), { "alias": null, "args": null, "concreteType": null, "kind": "LinkedField", "name": "orderHistory", "plural": true, "selections": [ { "kind": "TypeDiscriminator", "abstractKey": "__isCommerceOrderEventUnion" }, (v8/*: any*/), { "kind": "InlineFragment", "selections": [ (v9/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "stateReason", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "state", "storageKey": null } ], "type": "CommerceOrderStateChangedEvent", "abstractKey": null }, { "kind": "InlineFragment", "selections": [ (v9/*: any*/), { "alias": null, "args": null, "concreteType": "CommerceOffer", "kind": "LinkedField", "name": "offer", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "amount", "storageKey": null }, (v10/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "definesTotal", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "offerAmountChanged", "storageKey": null }, { "alias": null, "args": null, "concreteType": "CommerceOffer", "kind": "LinkedField", "name": "respondsTo", "plural": false, "selections": [ (v10/*: any*/), (v2/*: any*/) ], "storageKey": null }, (v2/*: any*/) ], "storageKey": null } ], "type": "CommerceOfferSubmittedEvent", "abstractKey": null } ], "storageKey": null }, (v2/*: any*/) ], "storageKey": null } ], "storageKey": null } ], "storageKey": "orderConnection(first:10,participantType:\"BUYER\")" }, { "alias": null, "args": (v11/*: any*/), "concreteType": "MessageConnection", "kind": "LinkedField", "name": "messagesConnection", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "PageInfo", "kind": "LinkedField", "name": "pageInfo", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "startCursor", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "endCursor", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "hasPreviousPage", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "hasNextPage", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "MessageEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "cursor", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Message", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ (v8/*: any*/), (v2/*: any*/), (v3/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "isFromUser", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "isFirstMessage", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "body", "storageKey": null }, (v9/*: any*/), { "alias": null, "args": null, "concreteType": "Attachment", "kind": "LinkedField", "name": "attachments", "plural": true, "selections": [ (v2/*: any*/), (v3/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "contentType", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "downloadURL", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "fileName", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "MessageInitiator", "kind": "LinkedField", "name": "from", "plural": false, "selections": [ (v4/*: any*/), (v5/*: any*/) ], "storageKey": null } ], "storageKey": null } ], "storageKey": null } ], "storageKey": "messagesConnection(first:10,sort:\"DESC\")" }, { "alias": null, "args": (v11/*: any*/), "filters": [], "handle": "connection", "key": "Messages_messagesConnection", "kind": "LinkedHandle", "name": "messagesConnection" }, { "alias": null, "args": null, "concreteType": "ConversationItem", "kind": "LinkedField", "name": "items", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": null, "kind": "LinkedField", "name": "item", "plural": false, "selections": [ (v8/*: any*/), { "kind": "InlineFragment", "selections": [ (v12/*: any*/), (v13/*: any*/), (v3/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "title", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "artistNames", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "date", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "image", "plural": false, "selections": (v14/*: any*/), "storageKey": null } ], "type": "Artwork", "abstractKey": null }, { "kind": "InlineFragment", "selections": [ (v12/*: any*/), (v13/*: any*/), (v3/*: any*/), (v4/*: any*/), { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "coverImage", "plural": false, "selections": (v14/*: any*/), "storageKey": null }, { "alias": null, "args": null, "concreteType": "Fair", "kind": "LinkedField", "name": "fair", "plural": false, "selections": (v6/*: any*/), "storageKey": null }, { "alias": null, "args": null, "concreteType": null, "kind": "LinkedField", "name": "partner", "plural": false, "selections": [ (v8/*: any*/), { "kind": "InlineFragment", "selections": [ (v4/*: any*/) ], "type": "Partner", "abstractKey": null }, (v16/*: any*/), { "kind": "InlineFragment", "selections": (v15/*: any*/), "type": "ExternalPartner", "abstractKey": null } ], "storageKey": null } ], "type": "Show", "abstractKey": null }, (v16/*: any*/) ], "storageKey": null } ], "storageKey": null } ], "storageKey": null }, (v2/*: any*/) ], "storageKey": null } ] }, "params": { "id": "1e43b53d4068779d9f5c15d690cc8baa", "metadata": { "relayTestingSelectionTypeInfo": { "me": { "enumValues": null, "nullable": true, "plural": false, "type": "Me" }, "me.conversation": { "enumValues": null, "nullable": true, "plural": false, "type": "Conversation" }, "me.conversation.from": { "enumValues": null, "nullable": false, "plural": false, "type": "ConversationInitiator" }, "me.conversation.from.email": (v17/*: any*/), "me.conversation.from.id": (v18/*: any*/), "me.conversation.from.name": (v17/*: any*/), "me.conversation.id": (v18/*: any*/), "me.conversation.initialMessage": (v17/*: any*/), "me.conversation.internalID": { "enumValues": null, "nullable": true, "plural": false, "type": "ID" }, "me.conversation.items": { "enumValues": null, "nullable": true, "plural": true, "type": "ConversationItem" }, "me.conversation.items.item": { "enumValues": null, "nullable": true, "plural": false, "type": "ConversationItemType" }, "me.conversation.items.item.__isNode": (v17/*: any*/), "me.conversation.items.item.__typename": (v17/*: any*/), "me.conversation.items.item.artistNames": (v19/*: any*/), "me.conversation.items.item.coverImage": (v20/*: any*/), "me.conversation.items.item.coverImage.aspectRatio": (v21/*: any*/), "me.conversation.items.item.coverImage.url": (v19/*: any*/), "me.conversation.items.item.date": (v19/*: any*/), "me.conversation.items.item.fair": { "enumValues": null, "nullable": true, "plural": false, "type": "Fair" }, "me.conversation.items.item.fair.id": (v18/*: any*/), "me.conversation.items.item.fair.name": (v19/*: any*/), "me.conversation.items.item.href": (v19/*: any*/), "me.conversation.items.item.id": (v18/*: any*/), "me.conversation.items.item.image": (v20/*: any*/), "me.conversation.items.item.image.aspectRatio": (v21/*: any*/), "me.conversation.items.item.image.url": (v19/*: any*/), "me.conversation.items.item.internalID": (v18/*: any*/), "me.conversation.items.item.name": (v19/*: any*/), "me.conversation.items.item.partner": { "enumValues": null, "nullable": true, "plural": false, "type": "PartnerTypes" }, "me.conversation.items.item.partner.__isNode": (v17/*: any*/), "me.conversation.items.item.partner.__typename": (v17/*: any*/), "me.conversation.items.item.partner.id": (v18/*: any*/), "me.conversation.items.item.partner.name": (v19/*: any*/), "me.conversation.items.item.slug": (v18/*: any*/), "me.conversation.items.item.title": (v19/*: any*/), "me.conversation.lastMessageID": (v19/*: any*/), "me.conversation.messagesConnection": { "enumValues": null, "nullable": true, "plural": false, "type": "MessageConnection" }, "me.conversation.messagesConnection.edges": { "enumValues": null, "nullable": true, "plural": true, "type": "MessageEdge" }, "me.conversation.messagesConnection.edges.cursor": (v17/*: any*/), "me.conversation.messagesConnection.edges.node": { "enumValues": null, "nullable": true, "plural": false, "type": "Message" }, "me.conversation.messagesConnection.edges.node.__typename": (v17/*: any*/), "me.conversation.messagesConnection.edges.node.attachments": { "enumValues": null, "nullable": true, "plural": true, "type": "Attachment" }, "me.conversation.messagesConnection.edges.node.attachments.contentType": (v17/*: any*/), "me.conversation.messagesConnection.edges.node.attachments.downloadURL": (v17/*: any*/), "me.conversation.messagesConnection.edges.node.attachments.fileName": (v17/*: any*/), "me.conversation.messagesConnection.edges.node.attachments.id": (v18/*: any*/), "me.conversation.messagesConnection.edges.node.attachments.internalID": (v18/*: any*/), "me.conversation.messagesConnection.edges.node.body": (v19/*: any*/), "me.conversation.messagesConnection.edges.node.createdAt": (v19/*: any*/), "me.conversation.messagesConnection.edges.node.from": { "enumValues": null, "nullable": true, "plural": false, "type": "MessageInitiator" }, "me.conversation.messagesConnection.edges.node.from.email": (v19/*: any*/), "me.conversation.messagesConnection.edges.node.from.name": (v19/*: any*/), "me.conversation.messagesConnection.edges.node.id": (v18/*: any*/), "me.conversation.messagesConnection.edges.node.internalID": (v18/*: any*/), "me.conversation.messagesConnection.edges.node.isFirstMessage": (v22/*: any*/), "me.conversation.messagesConnection.edges.node.isFromUser": (v22/*: any*/), "me.conversation.messagesConnection.pageInfo": { "enumValues": null, "nullable": false, "plural": false, "type": "PageInfo" }, "me.conversation.messagesConnection.pageInfo.endCursor": (v19/*: any*/), "me.conversation.messagesConnection.pageInfo.hasNextPage": (v23/*: any*/), "me.conversation.messagesConnection.pageInfo.hasPreviousPage": (v23/*: any*/), "me.conversation.messagesConnection.pageInfo.startCursor": (v19/*: any*/), "me.conversation.orderConnection": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceOrderConnectionWithTotalCount" }, "me.conversation.orderConnection.edges": { "enumValues": null, "nullable": true, "plural": true, "type": "CommerceOrderEdge" }, "me.conversation.orderConnection.edges.node": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceOrder" }, "me.conversation.orderConnection.edges.node.__typename": (v17/*: any*/), "me.conversation.orderConnection.edges.node.id": (v18/*: any*/), "me.conversation.orderConnection.edges.node.orderHistory": { "enumValues": null, "nullable": false, "plural": true, "type": "CommerceOrderEventUnion" }, "me.conversation.orderConnection.edges.node.orderHistory.__isCommerceOrderEventUnion": (v17/*: any*/), "me.conversation.orderConnection.edges.node.orderHistory.__typename": (v17/*: any*/), "me.conversation.orderConnection.edges.node.orderHistory.createdAt": (v17/*: any*/), "me.conversation.orderConnection.edges.node.orderHistory.offer": { "enumValues": null, "nullable": false, "plural": false, "type": "CommerceOffer" }, "me.conversation.orderConnection.edges.node.orderHistory.offer.amount": (v19/*: any*/), "me.conversation.orderConnection.edges.node.orderHistory.offer.definesTotal": (v23/*: any*/), "me.conversation.orderConnection.edges.node.orderHistory.offer.fromParticipant": (v24/*: any*/), "me.conversation.orderConnection.edges.node.orderHistory.offer.id": (v18/*: any*/), "me.conversation.orderConnection.edges.node.orderHistory.offer.offerAmountChanged": (v23/*: any*/), "me.conversation.orderConnection.edges.node.orderHistory.offer.respondsTo": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceOffer" }, "me.conversation.orderConnection.edges.node.orderHistory.offer.respondsTo.fromParticipant": (v24/*: any*/), "me.conversation.orderConnection.edges.node.orderHistory.offer.respondsTo.id": (v18/*: any*/), "me.conversation.orderConnection.edges.node.orderHistory.state": { "enumValues": [ "ABANDONED", "APPROVED", "CANCELED", "FULFILLED", "PENDING", "REFUNDED", "SUBMITTED" ], "nullable": false, "plural": false, "type": "CommerceOrderStateEnum" }, "me.conversation.orderConnection.edges.node.orderHistory.stateReason": (v19/*: any*/), "me.conversation.to": { "enumValues": null, "nullable": false, "plural": false, "type": "ConversationResponder" }, "me.conversation.to.id": (v18/*: any*/), "me.conversation.to.name": (v17/*: any*/), "me.id": (v18/*: any*/) } }, "name": "MessagesTestsQuery", "operationKind": "query", "text": null } }; })(); (node as any).hash = '38039b9d5008865ff651a2149b9218e6'; export default node;
the_stack
import { Dec } from "./decimal"; import { Int } from "./int"; describe("Test decimals", () => { // (2 ** (256 + 60) - 1) / (10 ** 18) const maxDec = "133499189745056880149688856635597007162669032647290798121690100488888732861290.034376435130433535"; // maxDec + 0.000000000000000001 const overflowedDec = "133499189745056880149688856635597007162669032647290798121690100488888732861290.034376435130433536"; it("dec should be parsed properly", () => { expect(() => new Dec(1, 0)).not.toThrow(); expect(() => new Dec(1, -1)).toThrow(); expect(() => new Dec(1, Dec.precision)).not.toThrow(); expect(() => new Dec(1, Dec.precision + 1)).toThrow(); let dec = new Dec("10.009"); expect(dec.toString()).toBe("10.009000000000000000"); expect(dec.toString(2)).toBe("10.00"); dec = new Dec("-123.45678900"); expect(dec.toString()).toBe("-123.456789000000000000"); expect(dec.toString(3)).toBe("-123.456"); dec = new Dec("10"); expect(dec.toString()).toBe("10.000000000000000000"); dec = new Dec(10); expect(dec.toString()).toBe("10.000000000000000000"); dec = new Dec(10.009); expect(dec.toString()).toBe("10.009000000000000000"); expect(dec.toString(2)).toBe("10.00"); dec = new Dec(-123.456789); expect(dec.toString()).toBe("-123.456789000000000000"); expect(dec.toString(3)).toBe("-123.456"); expect(() => { new Dec(""); }).toThrow(); expect(() => { new Dec("0.-75"); }).toThrow(); expect(() => { new Dec("0.489234893284938249348923849283408"); }).not.toThrow(); expect(() => { new Dec("foobar"); }).toThrow(); expect(() => { new Dec("0.foobar"); }).toThrow(); expect(() => { new Dec("foobar.0"); }).toThrow(); }); it("Test Dec overflow", () => { expect(new Dec(maxDec).toString()).toBe(maxDec); expect(new Dec("-" + maxDec).toString()).toBe("-" + maxDec); expect(() => new Dec(overflowedDec)).toThrow(); expect(() => new Dec("-" + overflowedDec)).toThrow(); const max = new Dec(maxDec); expect(() => max.add(new Dec(1, Dec.precision))).toThrow(); const min = new Dec("-" + maxDec); expect(() => min.sub(new Dec(1, Dec.precision))).toThrow(); }); it("Test Dec neg/abs", () => { expect(new Dec(1).neg().toString()).toBe("-1.000000000000000000"); expect(new Dec(1).neg().equals(new Dec(-1))).toBe(true); expect(new Dec(-1).neg().toString()).toBe("1.000000000000000000"); expect(new Dec(-1).neg().equals(new Dec(1))).toBe(true); expect(new Dec(1).abs().toString()).toBe("1.000000000000000000"); expect(new Dec(1).abs().equals(new Dec(1))).toBe(true); expect(new Dec(-1).abs().toString()).toBe("1.000000000000000000"); expect(new Dec(-1).abs().equals(new Dec(1))).toBe(true); }); it("Test Dec isPositive/isNegative/isInteger/isZero", () => { expect(new Dec(1).isPositive()).toBe(true); expect(new Dec(-1).isPositive()).toBe(false); expect(new Dec(1).isNegative()).toBe(false); expect(new Dec(-1).isNegative()).toBe(true); expect(new Dec(1).isInteger()).toBe(true); expect(new Dec(-1).isInteger()).toBe(true); expect(new Dec(1.1).isInteger()).toBe(false); expect(new Dec(-1.1).isInteger()).toBe(false); expect(new Dec(0).isZero()).toBe(true); expect(new Dec(-0).isZero()).toBe(true); expect(new Dec(-1.1).isZero()).toBe(false); expect(new Dec(1.1).isZero()).toBe(false); }); it("Test Dec comparison", () => { const dec1 = new Dec(1); const dec2 = new Dec(2); expect(dec1.gt(dec2)).toBe(false); expect(dec1.gte(dec1)).toBe(true); expect(dec1.lt(dec2)).toBe(true); expect(dec1.lte(dec1)).toBe(true); expect(dec1.equals(dec2)).toBe(false); expect(dec1.equals(dec1)).toBe(true); }); it("Test Dec power", () => { const tests: { d1: Dec; i1: Int; exp: Dec; }[] = [ { d1: new Dec(0), i1: new Int(12), exp: new Dec(0), }, { d1: new Dec(0), i1: new Int(0), exp: new Dec(1), }, { d1: new Dec(12), i1: new Int(0), exp: new Dec(1), }, { d1: new Dec(-12), i1: new Int(0), exp: new Dec(1), }, { d1: new Dec(-12), i1: new Int(1), exp: new Dec(-12), }, { d1: new Dec(-12), i1: new Int(2), exp: new Dec(144), }, { d1: new Dec(12), i1: new Int(3), exp: new Dec(1728), }, { d1: new Dec(12), i1: new Int(-1), exp: new Dec("0.083333333333333333"), }, { d1: new Dec(12), i1: new Int(-2), exp: new Dec("0.006944444444444444"), }, { d1: new Dec(12), i1: new Int(-3), exp: new Dec("0.000578703703703704"), }, { d1: new Dec(10), i1: new Int(4), exp: new Dec("10000"), }, { d1: new Dec(10), i1: new Int(5), exp: new Dec("100000"), }, { d1: new Dec(10), i1: new Int(-5), exp: new Dec("0.00001"), }, ]; for (const test of tests) { const res = test.d1.pow(test.i1); expect(res.toString()).toBe(test.exp.toString()); } }); it("dec should be caculated properly", () => { const tests: { d1: Dec; d2: Dec; expMul: Dec; expMulTruncate: Dec; expQuo: Dec; expQuoRoundUp: Dec; expQuoTruncate: Dec; expAdd: Dec; expSub: Dec; }[] = [ { d1: new Dec(0), d2: new Dec(0), expMul: new Dec(0), expMulTruncate: new Dec(0), expQuo: new Dec(0), expQuoRoundUp: new Dec(0), expQuoTruncate: new Dec(0), expAdd: new Dec(0), expSub: new Dec(0), }, { d1: new Dec(0), d2: new Dec(1), expMul: new Dec(0), expMulTruncate: new Dec(0), expQuo: new Dec(0), expQuoRoundUp: new Dec(0), expQuoTruncate: new Dec(0), expAdd: new Dec(1), expSub: new Dec(-1), }, { d1: new Dec(-1), d2: new Dec(0), expMul: new Dec(0), expMulTruncate: new Dec(0), expQuo: new Dec(0), expQuoRoundUp: new Dec(0), expQuoTruncate: new Dec(0), expAdd: new Dec(-1), expSub: new Dec(-1), }, { d1: new Dec(-1), d2: new Dec(1), expMul: new Dec(-1), expMulTruncate: new Dec(-1), expQuo: new Dec(-1), expQuoRoundUp: new Dec(-1), expQuoTruncate: new Dec(-1), expAdd: new Dec(0), expSub: new Dec(-2), }, { d1: new Dec(3), d2: new Dec(7), expMul: new Dec(21), expMulTruncate: new Dec(21), expQuo: new Dec("428571428571428571", 18), expQuoRoundUp: new Dec("428571428571428572", 18), expQuoTruncate: new Dec("428571428571428571", 18), expAdd: new Dec(10), expSub: new Dec(-4), }, { d1: new Dec(100), d2: new Dec(100), expMul: new Dec(10000), expMulTruncate: new Dec(10000), expQuo: new Dec(1), expQuoRoundUp: new Dec(1), expQuoTruncate: new Dec(1), expAdd: new Dec(200), expSub: new Dec(0), }, { d1: new Dec(3333, 4), d2: new Dec(333, 4), expMul: new Dec(1109889, 8), expMulTruncate: new Dec(1109889, 8), expQuo: new Dec("10.009009009009009009"), expQuoRoundUp: new Dec("10.009009009009009010"), expQuoTruncate: new Dec("10.009009009009009009"), expAdd: new Dec(3666, 4), expSub: new Dec(3, 1), }, ]; for (const test of tests) { const resAdd = test.d1.add(test.d2); const resSub = test.d1.sub(test.d2); const resMul = test.d1.mul(test.d2); const resMulTruncate = test.d1.mulTruncate(test.d2); // invalid result of add expect(resAdd.toString()).toBe(test.expAdd.toString()); // invalid result of sub expect(resSub.toString()).toBe(test.expSub.toString()); // invalid result of mul expect(resMul.toString()).toBe(test.expMul.toString()); // invalid result of mul expect(resMulTruncate.toString()).toBe(test.expMulTruncate.toString()); if (test.d2.isZero()) { expect(() => { test.d1.quo(test.d2); }).toThrow(); } else { const resQuo = test.d1.quo(test.d2); const resQuoRoundUp = test.d1.quoRoundUp(test.d2); const resQuoTruncate = test.d1.quoTruncate(test.d2); // invalid result of quo expect(resQuo.toString()).toBe(test.expQuo.toString()); // invalid result of quo round up expect(resQuoRoundUp.toString()).toBe(test.expQuoRoundUp.toString()); // invalid result of quo truncate expect(resQuoTruncate.toString()).toBe(test.expQuoTruncate.toString()); } } }); it("dec should be round up properly", () => { const tests: { d1: Dec; exp: Int; }[] = [ { d1: new Dec("0.25"), exp: new Int("1"), }, { d1: new Dec("0"), exp: new Int("0"), }, { d1: new Dec("1"), exp: new Int("1"), }, { d1: new Dec("0.75"), exp: new Int("1"), }, { d1: new Dec("0.5"), exp: new Int("1"), }, { d1: new Dec("7.5"), exp: new Int("8"), }, { d1: new Dec("0.545"), exp: new Int("1"), }, { d1: new Dec("1.545"), exp: new Int("2"), }, { d1: new Dec("-1.545"), exp: new Int("-1"), }, { d1: new Dec("-0.545"), exp: new Int("0"), }, ]; for (const test of tests) { const resPos = test.d1.roundUp(); expect(resPos.toString()).toBe(test.exp.toString()); const resPosDec = test.d1.roundUpDec(); expect(resPosDec.toString()).toBe( test.exp.toString() + ".000000000000000000" ); } }); it("dec should be round properly", () => { const tests: { d1: Dec; exp: Int; }[] = [ { d1: new Dec("0.25"), exp: new Int("0"), }, { d1: new Dec("0"), exp: new Int("0"), }, { d1: new Dec("1"), exp: new Int("1"), }, { d1: new Dec("0.75"), exp: new Int("1"), }, { d1: new Dec("0.5"), exp: new Int("0"), }, { d1: new Dec("7.5"), exp: new Int("8"), }, { d1: new Dec("0.545"), exp: new Int("1"), }, { d1: new Dec("1.545"), exp: new Int("2"), }, ]; for (const test of tests) { const resNeg = test.d1.neg().round(); expect(resNeg.toString()).toBe(test.exp.neg().toString()); const resNegDec = test.d1.neg().roundDec(); expect(resNegDec.toString()).toBe( test.exp.neg().toString() + ".000000000000000000" ); const resPos = test.d1.round(); expect(resPos.toString()).toBe(test.exp.toString()); const resPosDec = test.d1.roundDec(); expect(resPosDec.toString()).toBe( test.exp.toString() + ".000000000000000000" ); } }); it("dec should be truncated properly", () => { const tests: { d1: Dec; exp: Int; }[] = [ { d1: new Dec("0"), exp: new Int("0"), }, { d1: new Dec("0.25"), exp: new Int("0"), }, { d1: new Dec("0.75"), exp: new Int("0"), }, { d1: new Dec("1"), exp: new Int("1"), }, { d1: new Dec("7.5"), exp: new Int("7"), }, { d1: new Dec("7.6"), exp: new Int("7"), }, { d1: new Dec("8.5"), exp: new Int("8"), }, { d1: new Dec("100.000000001"), exp: new Int("100"), }, ]; for (const test of tests) { const resNeg = test.d1.neg().truncate(); expect(resNeg.toString()).toBe(test.exp.neg().toString()); const resNegDec = test.d1.neg().truncateDec(); expect(resNegDec.toString()).toBe( test.exp.neg().toString() + ".000000000000000000" ); const resPos = test.d1.truncate(); expect(resPos.toString()).toBe(test.exp.toString()); const resPosDec = test.d1.truncateDec(); expect(resPosDec.toString()).toBe( test.exp.toString() + ".000000000000000000" ); } }); it("dec should be parsed to string properly", () => { const tests: { d1: Dec; precision: number; exp: string; }[] = [ { d1: new Dec("0"), precision: 0, exp: "0", }, { d1: new Dec("1.25"), precision: 0, exp: "1", }, { d1: new Dec("0.75"), precision: 1, exp: "0.7", }, { d1: new Dec("1"), precision: 5, exp: "1.00000", }, { d1: new Dec(new Int("1")), precision: 5, exp: "1.00000", }, { d1: new Dec("7.5"), precision: 3, exp: "7.500", }, { d1: new Dec("100.000000001"), precision: 0, exp: "100", }, { d1: new Dec(100.000000001), precision: 0, exp: "100", }, { d1: new Dec("-0.25"), precision: 0, exp: "0", }, { d1: new Dec("-1.25"), precision: 0, exp: "-1", }, { d1: new Dec("-0.75"), precision: 1, exp: "-0.7", }, { d1: new Dec("-1"), precision: 5, exp: "-1.00000", }, { d1: new Dec(-1), precision: 5, exp: "-1.00000", }, { d1: new Dec("-7.5"), precision: 3, exp: "-7.500", }, { d1: new Dec(-7.5), precision: 3, exp: "-7.500", }, { d1: new Dec("-100.000000001"), precision: 0, exp: "-100", }, { d1: new Dec(-100.000000001), precision: 0, exp: "-100", }, ]; for (const test of tests) { const res = test.d1.toString(test.precision); expect(res).toBe(test.exp); } }); it("Test case that input decimals exceeds 18", () => { const tests: { input: number | string; res: Dec; resStr: string; }[] = [ { input: "0.489234893284938249348923849283408", res: new Dec("0.489234893284938249"), resStr: "0.489234893284938249", }, { input: 0.0000010000000249348, res: new Dec("0.000001000000024934"), resStr: "0.000001000000024934", }, { input: "0.0000000000000000001", res: new Dec("0"), resStr: "0.000000000000000000", }, { input: 0.0000000000000000001, res: new Dec("0"), resStr: "0.000000000000000000", }, ]; for (const test of tests) { const dec = new Dec(test.input); expect(dec.equals(test.res)).toBe(true); expect(dec.toString()).toBe(test.resStr); } }); it("Test Int/Uint from exponent number", () => { const tests: { num: number; str: string; expect: Dec; }[] = [ { num: 12345678901234567890123, str: "1.2345678901234568e+22", expect: new Dec("12345678901234568000000"), }, { num: -12345678901234567890123, str: "-1.2345678901234568e+22", expect: new Dec("-12345678901234568000000"), }, { num: 0.0000000000001, str: "1e-13", expect: new Dec("0.0000000000001"), }, { num: 0.000000000000123, str: "1.23e-13", expect: new Dec("0.000000000000123"), }, { num: 0.000000000000000001, str: "1e-18", expect: new Dec("0.000000000000000001"), }, { num: 0.0000000000000000001, str: "1e-19", expect: new Dec("0"), }, { num: 0.00000000000000000123, str: "1.23e-18", expect: new Dec("0.000000000000000001"), }, { num: 0.000000000000000000123, str: "1.23e-19", expect: new Dec("0"), }, ]; for (const test of tests) { expect(test.num.toString()).toBe(test.str); expect(new Dec(test.num).equals(test.expect)).toBe(true); } }); });
the_stack
import ConduitGrpcSdk, { ConduitBoolean, ConduitJson, ConduitNumber, ConduitRouteActions, ConduitRouteObject, ConduitRouteReturnDefinition, ConduitString, constructConduitRoute, GrpcServer, RouteOptionType, TYPE, } from '@conduitplatform/grpc-sdk'; import { SequelizeSchema } from '../adapters/sequelize-adapter/SequelizeSchema'; import { MongooseSchema } from '../adapters/mongoose-adapter/MongooseSchema'; import { DatabaseAdapter } from '../adapters/DatabaseAdapter'; import { CustomEndpointsAdmin } from './customEndpoints/customEndpoints.admin'; import { DocumentsAdmin } from './documents.admin'; import { SchemaAdmin } from './schema.admin'; import { SchemaController } from '../controllers/cms/schema.controller'; import { CustomEndpointController } from '../controllers/customEndpoints/customEndpoint.controller'; import { DeclaredSchema, CustomEndpoints, PendingSchemas } from '../models'; export class AdminHandlers { private readonly schemaAdmin: SchemaAdmin; private readonly documentsAdmin: DocumentsAdmin; private readonly customEndpointsAdmin: CustomEndpointsAdmin; constructor( private readonly server: GrpcServer, private readonly grpcSdk: ConduitGrpcSdk, private readonly _activeAdapter: DatabaseAdapter<MongooseSchema | SequelizeSchema>, private readonly schemaController: SchemaController, private readonly customEndpointController: CustomEndpointController, ) { this.schemaAdmin = new SchemaAdmin( this.grpcSdk, this._activeAdapter, this.schemaController, this.customEndpointController, ); this.documentsAdmin = new DocumentsAdmin(this.grpcSdk, _activeAdapter); this.customEndpointsAdmin = new CustomEndpointsAdmin( this.grpcSdk, this._activeAdapter, this.customEndpointController, ); this.registerAdminRoutes(); } private registerAdminRoutes() { const paths = this.getRegisteredRoutes(); this.grpcSdk.admin .registerAdminAsync(this.server, paths, { // Schemas getSchema: this.schemaAdmin.getSchema.bind(this.schemaAdmin), getSchemas: this.schemaAdmin.getSchemas.bind(this.schemaAdmin), getSchemasExtensions: this.schemaAdmin.getSchemasExtensions.bind( this.schemaAdmin, ), createSchema: this.schemaAdmin.createSchema.bind(this.schemaAdmin), patchSchema: this.schemaAdmin.patchSchema.bind(this.schemaAdmin), deleteSchema: this.schemaAdmin.deleteSchema.bind(this.schemaAdmin), deleteSchemas: this.schemaAdmin.deleteSchemas.bind(this.schemaAdmin), toggleSchema: this.schemaAdmin.toggleSchema.bind(this.schemaAdmin), toggleSchemas: this.schemaAdmin.toggleSchemas.bind(this.schemaAdmin), setSchemaExtension: this.schemaAdmin.setSchemaExtension.bind(this.schemaAdmin), setSchemaPerms: this.schemaAdmin.setSchemaPerms.bind(this.schemaAdmin), getSchemaOwners: this.schemaAdmin.getSchemaOwners.bind(this.schemaAdmin), getIntrospectionStatus: this.schemaAdmin.getIntrospectionStatus.bind( this.schemaAdmin, ), introspectDatabase: this.schemaAdmin.introspectDatabase.bind(this.schemaAdmin), getPendingSchema: this.schemaAdmin.getPendingSchema.bind(this.schemaAdmin), getPendingSchemas: this.schemaAdmin.getPendingSchemas.bind(this.schemaAdmin), finalizeSchemas: this.schemaAdmin.finalizeSchemas.bind(this.schemaAdmin), // Documents getDocument: this.documentsAdmin.getDocument.bind(this.documentsAdmin), getDocuments: this.documentsAdmin.getDocuments.bind(this.documentsAdmin), createDocument: this.documentsAdmin.createDocument.bind(this.documentsAdmin), createDocuments: this.documentsAdmin.createDocuments.bind(this.documentsAdmin), updateDocument: this.documentsAdmin.updateDocument.bind(this.documentsAdmin), updateDocuments: this.documentsAdmin.updateDocuments.bind(this.documentsAdmin), deleteDocument: this.documentsAdmin.deleteDocument.bind(this.documentsAdmin), // Custom Endpoints getCustomEndpoints: this.customEndpointsAdmin.getCustomEndpoints.bind( this.customEndpointsAdmin, ), createCustomEndpoint: this.customEndpointsAdmin.createCustomEndpoint.bind( this.customEndpointsAdmin, ), patchCustomEndpoint: this.customEndpointsAdmin.patchCustomEndpoint.bind( this.customEndpointsAdmin, ), deleteCustomEndpoint: this.customEndpointsAdmin.deleteCustomEndpoint.bind( this.customEndpointsAdmin, ), getSchemasWithCustomEndpoints: this.customEndpointsAdmin.getSchemasWithCustomEndpoints.bind( this.customEndpointsAdmin, ), }) .catch((err: Error) => { console.log('Failed to register admin routes for module!'); console.error(err); }); } private getRegisteredRoutes(): ConduitRouteObject[] { return [ // Schemas constructConduitRoute( { path: '/schemas/owners', action: ConduitRouteActions.GET, }, new ConduitRouteReturnDefinition('GetSchemaOwners', { modules: [ConduitString.Required], }), 'getSchemaOwners', ), constructConduitRoute( { path: '/schemas/extensions', action: ConduitRouteActions.GET, queryParams: { skip: ConduitNumber.Optional, limit: ConduitNumber.Optional, }, }, new ConduitRouteReturnDefinition('GetSchemasExtensions', { schemasExtensions: [ConduitJson.Required], count: ConduitNumber.Required, }), 'getSchemasExtensions', ), constructConduitRoute( { path: '/schemas/:id', action: ConduitRouteActions.GET, urlParams: { id: { type: RouteOptionType.String, required: true }, }, }, new ConduitRouteReturnDefinition('GetSchema', DeclaredSchema.fields), 'getSchema', ), constructConduitRoute( { path: '/schemas', action: ConduitRouteActions.GET, queryParams: { skip: ConduitNumber.Optional, limit: ConduitNumber.Optional, search: ConduitString.Optional, sort: ConduitString.Optional, enabled: ConduitBoolean.Optional, owner: [ConduitString.Optional], }, }, new ConduitRouteReturnDefinition('GetSchemas', { schemas: [DeclaredSchema.fields], count: ConduitNumber.Required, }), 'getSchemas', ), constructConduitRoute( { path: '/schemas', action: ConduitRouteActions.POST, bodyParams: { name: ConduitString.Required, fields: ConduitJson.Required, modelOptions: ConduitJson.Optional, enabled: ConduitBoolean.Optional, // move inside modelOptions (frontend-compat) crudOperations: { create: { enabled: ConduitBoolean.Optional, authenticated: ConduitBoolean.Required, }, read: { enabled: ConduitBoolean.Optional, authenticated: ConduitBoolean.Required, }, update: { enabled: ConduitBoolean.Optional, authenticated: ConduitBoolean.Required, }, delete: { enabled: ConduitBoolean.Optional, authenticated: ConduitBoolean.Required, }, }, permissions: { extendable: ConduitBoolean.Optional, canCreate: ConduitBoolean.Optional, canModify: ConduitString.Optional, canDelete: ConduitBoolean.Optional, }, }, }, new ConduitRouteReturnDefinition('CreateSchema', DeclaredSchema.fields), 'createSchema', ), constructConduitRoute( { path: '/schemas/:id', action: ConduitRouteActions.PATCH, urlParams: { id: { type: RouteOptionType.String, required: true }, }, bodyParams: { name: ConduitString.Optional, fields: ConduitJson.Optional, modelOptions: ConduitJson.Optional, enabled: ConduitBoolean.Optional, // move inside modelOptions (frontend-compat) crudOperations: { create: { enabled: ConduitBoolean.Optional, authenticated: ConduitBoolean.Optional, }, read: { enabled: ConduitBoolean.Optional, authenticated: ConduitBoolean.Optional, }, update: { enabled: ConduitBoolean.Optional, authenticated: ConduitBoolean.Optional, }, delete: { enabled: ConduitBoolean.Optional, authenticated: ConduitBoolean.Optional, }, }, permissions: { extendable: ConduitBoolean.Optional, canCreate: ConduitBoolean.Optional, canModify: ConduitString.Optional, canDelete: ConduitBoolean.Optional, }, }, }, new ConduitRouteReturnDefinition('PatchSchema', DeclaredSchema.fields), 'patchSchema', ), constructConduitRoute( { path: '/schemas', action: ConduitRouteActions.DELETE, queryParams: { ids: { type: [TYPE.JSON], required: true }, // handler array check is still required }, }, new ConduitRouteReturnDefinition('DeleteSchemas', 'String'), 'deleteSchemas', ), constructConduitRoute( { path: '/schemas/:id', action: ConduitRouteActions.DELETE, urlParams: { id: { type: RouteOptionType.String, required: true }, }, bodyParams: { deleteData: ConduitBoolean.Required, }, }, new ConduitRouteReturnDefinition('DeleteSchema', 'String'), 'deleteSchema', ), constructConduitRoute( { path: '/schemas/toggle', action: ConduitRouteActions.POST, bodyParams: { ids: { type: [TYPE.JSON], required: true }, // handler array check is still required enabled: ConduitBoolean.Required, }, }, new ConduitRouteReturnDefinition('ToggleSchemas', { updatedSchemas: [DeclaredSchema.fields], enabled: ConduitBoolean.Required, }), 'toggleSchemas', ), constructConduitRoute( { path: '/schemas/:id/toggle', action: ConduitRouteActions.POST, urlParams: { id: { type: RouteOptionType.String, required: true }, }, }, new ConduitRouteReturnDefinition('ToggleSchema', { name: ConduitString.Required, enabled: ConduitBoolean.Required, }), 'toggleSchema', ), constructConduitRoute( { path: '/schemas/:schemaId/extensions', action: ConduitRouteActions.POST, urlParams: { schemaId: { type: RouteOptionType.String, required: true }, }, bodyParams: { fields: ConduitJson.Required, }, }, new ConduitRouteReturnDefinition('SetSchemaExtension', DeclaredSchema.fields), 'setSchemaExtension', ), constructConduitRoute( { path: '/schemas/:id/permissions', action: ConduitRouteActions.PATCH, urlParams: { id: { type: RouteOptionType.String, required: true }, }, bodyParams: { extendable: ConduitBoolean.Optional, canCreate: ConduitBoolean.Optional, canModify: ConduitString.Optional, canDelete: ConduitBoolean.Optional, }, }, new ConduitRouteReturnDefinition('SetSchemaPermissions', 'String'), 'setSchemaPerms', ), constructConduitRoute( { path: '/introspection', action: ConduitRouteActions.GET, }, new ConduitRouteReturnDefinition('GetIntrospectionStatus', { foreignSchemas: [ConduitString.Required], foreignSchemaCount: ConduitNumber.Required, importedSchemas: [ConduitString.Required], importedSchemaCount: ConduitNumber.Required, }), 'getIntrospectionStatus', ), constructConduitRoute( { path: '/introspection', action: ConduitRouteActions.POST, }, new ConduitRouteReturnDefinition('IntrospectDatabase', 'String'), 'introspectDatabase', ), constructConduitRoute( { path: '/introspection/schemas/:id', action: ConduitRouteActions.GET, urlParams: { id: { type: RouteOptionType.String, required: true }, }, }, new ConduitRouteReturnDefinition('GetSPendingSchema', PendingSchemas.fields), 'getPendingSchema', ), constructConduitRoute( { path: '/introspection/schemas', action: ConduitRouteActions.GET, queryParams: { skip: ConduitNumber.Optional, limit: ConduitNumber.Optional, sort: ConduitString.Optional, search: ConduitString.Optional, }, }, new ConduitRouteReturnDefinition('GetPendingSchemas', { schemas: [PendingSchemas.fields], }), 'getPendingSchemas', ), constructConduitRoute( { path: '/introspection/schemas/finalize', action: ConduitRouteActions.POST, bodyParams: { schemas: { type: [PendingSchemas.fields], required: true }, }, }, new ConduitRouteReturnDefinition('FinalizeSchemas', TYPE.String), 'finalizeSchemas', ), // Documents constructConduitRoute( { path: '/schemas/:schemaName/docs/:id', action: ConduitRouteActions.GET, urlParams: { schemaName: { type: RouteOptionType.String, required: true }, id: { type: RouteOptionType.String, required: true }, }, }, new ConduitRouteReturnDefinition('GetDocument', TYPE.JSON), 'getDocument', ), constructConduitRoute( { path: '/schemas/:schemaName/query', action: ConduitRouteActions.POST, urlParams: { schemaName: { type: RouteOptionType.String, required: true }, }, queryParams: { skip: ConduitNumber.Optional, limit: ConduitNumber.Optional, }, bodyParams: { query: ConduitJson.Required, }, }, new ConduitRouteReturnDefinition('GetDocuments', { documents: ConduitJson.Required, count: ConduitNumber.Required, }), 'getDocuments', ), constructConduitRoute( { path: '/schemas/:schemaName/docs', action: ConduitRouteActions.POST, urlParams: { schemaName: { type: RouteOptionType.String, required: true }, }, bodyParams: { inputDocument: ConduitJson.Required, }, }, new ConduitRouteReturnDefinition('CreateDocument', TYPE.JSON), 'createDocument', ), constructConduitRoute( { path: '/schemas/:schemaName/docs/many', action: ConduitRouteActions.POST, urlParams: { schemaName: { type: RouteOptionType.String, required: true }, }, bodyParams: { inputDocuments: { type: [TYPE.JSON], required: true }, }, }, new ConduitRouteReturnDefinition('CreateDocuments', { docs: [ConduitJson.Required], }), 'createDocuments', ), constructConduitRoute( { path: '/schemas/:schemaName/docs', action: ConduitRouteActions.UPDATE, urlParams: { schemaName: { type: RouteOptionType.String, required: true }, }, bodyParams: { changedDocuments: { type: [TYPE.JSON], required: true }, }, }, new ConduitRouteReturnDefinition('UpdateDocuments', { docs: [ConduitJson.Required], }), 'updateDocuments', ), constructConduitRoute( { path: '/schemas/:schemaName/docs/:id', action: ConduitRouteActions.UPDATE, urlParams: { schemaName: { type: RouteOptionType.String, required: true }, id: { type: RouteOptionType.String, required: true }, }, bodyParams: { changedDocument: ConduitJson.Required, }, }, new ConduitRouteReturnDefinition('UpdateDocument', TYPE.JSON), 'UpdateDocument', ), constructConduitRoute( { path: '/schemas/:schemaName/docs/:id', action: ConduitRouteActions.DELETE, urlParams: { schemaName: { type: RouteOptionType.String, required: true }, id: { type: RouteOptionType.String, required: true }, }, }, new ConduitRouteReturnDefinition('DeleteDocument', 'String'), 'deleteDocument', ), // Custom Endpoints constructConduitRoute( { path: '/customEndpoints/schemas', action: ConduitRouteActions.GET, }, new ConduitRouteReturnDefinition('GetSchemasWithCustomEndpoints', { schemaNames: [ConduitString.Required], schemaIds: [ConduitNumber.Required], }), 'getSchemasWithCustomEndpoints', ), constructConduitRoute( { path: '/customEndpoints', action: ConduitRouteActions.GET, queryParams: { skip: ConduitNumber.Optional, limit: ConduitNumber.Optional, search: ConduitString.Optional, operation: ConduitString.Optional, schemaName: [ConduitString.Optional], }, }, new ConduitRouteReturnDefinition('GetCustomEndpoints', { customEndpoints: [CustomEndpoints.fields], count: ConduitNumber.Required, }), 'getCustomEndpoints', ), constructConduitRoute( { path: '/customEndpoints', action: ConduitRouteActions.POST, bodyParams: { name: ConduitString.Required, operation: ConduitNumber.Required, selectedSchema: ConduitString.Optional, selectedSchemaName: ConduitString.Optional, query: ConduitJson.Optional, inputs: { type: [TYPE.JSON], required: false }, assignments: { type: [TYPE.JSON], required: false }, authentication: ConduitBoolean.Optional, sorted: ConduitBoolean.Optional, paginated: ConduitBoolean.Optional, }, }, new ConduitRouteReturnDefinition('CreateCustomEndpoint', CustomEndpoints.fields), 'createCustomEndpoint', ), constructConduitRoute( { path: '/customEndpoints/:id', action: ConduitRouteActions.PATCH, urlParams: { id: { type: RouteOptionType.String, required: true }, }, bodyParams: { selectedSchema: ConduitString.Optional, selectedSchemaName: ConduitString.Optional, query: ConduitJson.Optional, inputs: { type: [TYPE.JSON], required: false }, assignments: { type: [TYPE.JSON], required: false }, // authentication: ConduitBoolean.Optional, // TODO: Support modifying auth sorted: ConduitBoolean.Optional, paginated: ConduitBoolean.Optional, }, }, new ConduitRouteReturnDefinition('PatchCustomEndpoint', CustomEndpoints.fields), 'patchCustomEndpoint', ), constructConduitRoute( { path: '/customEndpoints/:id', action: ConduitRouteActions.DELETE, urlParams: { id: { type: RouteOptionType.String, required: true }, }, }, new ConduitRouteReturnDefinition('deleteCustomEndpoint', 'String'), 'deleteCustomEndpoint', ), ]; } }
the_stack
import { assert } from 'chai' import { test, run } from '../src/SlimRunner' import { getTestReporter } from './helpers' describe('SlimRunner', () => { it('create test using exported function', async () => { const reporter = getTestReporter() test.configure({ reporterFn: reporter.fn.bind(reporter) }) let executed = false test('hello', () => { executed = true }) await run(false) assert.isTrue(executed) assert.deepEqual(reporter.events, [ { event: 'group:started', data: { error: null, status: 'pending', title: 'root', }, }, { event: 'test:started', data: { duration: 0, error: null, regression: false, regressionMessage: '', status: 'pending', title: 'hello', }, }, { event: 'test:completed', data: { duration: reporter.events[2].data.duration, error: null, regression: false, regressionMessage: '', status: 'passed', title: 'hello', }, }, { event: 'group:completed', data: { error: null, status: 'passed', title: 'root', }, }, ]) }) it('create test inside a group', async () => { const reporter = getTestReporter() test.configure({ reporterFn: reporter.fn.bind(reporter) }) let executed = false test.group('foo', () => { test('hello', () => { executed = true }) }) await run(false) assert.isTrue(executed) assert.deepEqual(reporter.events, [ { event: 'group:started', data: { error: null, status: 'pending', title: 'foo', }, }, { event: 'test:started', data: { duration: 0, error: null, regression: false, regressionMessage: '', status: 'pending', title: 'hello', }, }, { event: 'test:completed', data: { duration: reporter.events[2].data.duration, error: null, regression: false, regressionMessage: '', status: 'passed', title: 'hello', }, }, { event: 'group:completed', data: { error: null, status: 'passed', title: 'foo', }, }, ]) }) it('tests created outside of the group must be part of root group', async () => { const reporter = getTestReporter() test.configure({ reporterFn: reporter.fn.bind(reporter) }) test.group('foo', () => { test('hello', () => { }) }) test('hello', () => { }) await run(false) assert.deepEqual(reporter.events, [ { event: 'group:started', data: { error: null, status: 'pending', title: 'foo', }, }, { event: 'test:started', data: { duration: 0, error: null, regression: false, regressionMessage: '', status: 'pending', title: 'hello', }, }, { event: 'test:completed', data: { duration: reporter.events[2].data.duration, error: null, regression: false, regressionMessage: '', status: 'passed', title: 'hello', }, }, { event: 'group:completed', data: { error: null, status: 'passed', title: 'foo', }, }, { event: 'group:started', data: { error: null, status: 'pending', title: 'root', }, }, { event: 'test:started', data: { duration: 0, error: null, regression: false, regressionMessage: '', status: 'pending', title: 'hello', }, }, { event: 'test:completed', data: { duration: reporter.events[5].data.duration, error: null, regression: false, regressionMessage: '', status: 'passed', title: 'hello', }, }, { event: 'group:completed', data: { error: null, status: 'passed', title: 'root', }, }, ]) }) it('create skippable function', async () => { const reporter = getTestReporter() test.configure({ reporterFn: reporter.fn.bind(reporter) }) let executed = false test.skip('hello', () => { executed = true }) await run(false) assert.isFalse(executed) assert.deepEqual(reporter.events, [ { event: 'group:started', data: { error: null, status: 'pending', title: 'root', }, }, { event: 'test:started', data: { duration: 0, error: null, regression: false, regressionMessage: '', status: 'skipped', title: 'hello', }, }, { event: 'test:completed', data: { duration: reporter.events[2].data.duration, error: null, regression: false, regressionMessage: '', status: 'skipped', title: 'hello', }, }, { event: 'group:completed', data: { error: null, status: 'passed', title: 'root', }, }, ]) }) it('create regression function using runInCI', async () => { const reporter = getTestReporter() test.configure({ reporterFn: reporter.fn.bind(reporter) }) test.failing('hello', () => { throw new Error('See it fails') }) await run(false) assert.deepEqual(reporter.events, [ { event: 'group:started', data: { error: null, status: 'pending', title: 'root', }, }, { event: 'test:started', data: { duration: 0, error: null, regression: true, regressionMessage: '', status: 'pending', title: 'hello', }, }, { event: 'test:completed', data: { duration: reporter.events[2].data.duration, error: reporter.events[2].data.error, regression: true, regressionMessage: 'See it fails', status: 'passed', title: 'hello', }, }, { event: 'group:completed', data: { error: null, status: 'passed', title: 'root', }, }, ]) }) it('stop tests after failing test when bail is true', async () => { const reporter = getTestReporter() test.configure({ reporterFn: reporter.fn.bind(reporter), bail: true }) let executed = false const error = new Error('failed') test.group('foo', () => { test('hi', () => { throw error }) test('hello', () => { executed = true }) }) await run(false) assert.isFalse(executed) assert.deepEqual(reporter.events, [ { event: 'group:started', data: { error: null, status: 'pending', title: 'foo', }, }, { event: 'test:started', data: { duration: 0, error: null, regression: false, regressionMessage: '', status: 'pending', title: 'hi', }, }, { event: 'test:completed', data: { duration: reporter.events[2].data.duration, error: error, regression: false, regressionMessage: '', status: 'failed', title: 'hi', }, }, { event: 'group:completed', data: { error: null, status: 'passed', title: 'foo', }, }, ]) }) it('only run tests matching the grep string', async () => { const reporter = getTestReporter() test.configure({ reporterFn: reporter.fn.bind(reporter), bail: true, grep: 'hi', }) let executed = false test.group('foo', () => { test('hi', () => { }) test('hello', () => { executed = true }) }) await run(false) assert.isFalse(executed) assert.deepEqual(reporter.events, [ { event: 'group:started', data: { error: null, status: 'pending', title: 'foo', }, }, { event: 'test:started', data: { duration: 0, error: null, regression: false, regressionMessage: '', status: 'pending', title: 'hi', }, }, { event: 'test:completed', data: { duration: reporter.events[2].data.duration, error: null, regression: false, regressionMessage: '', status: 'passed', title: 'hi', }, }, { event: 'group:completed', data: { error: null, status: 'passed', title: 'foo', }, }, ]) }) it('only run tests matching the grep regex like string', async () => { const reporter = getTestReporter() test.configure({ reporterFn: reporter.fn.bind(reporter), bail: true, grep: 'h(i|ey)', }) let executed = false test.group('foo', () => { test('hi', () => { }) test('hey', () => { }) test('hello', () => { executed = true }) }) await run(false) assert.isFalse(executed) assert.deepEqual(reporter.events, [ { event: 'group:started', data: { error: null, status: 'pending', title: 'foo', }, }, { event: 'test:started', data: { duration: 0, error: null, regression: false, regressionMessage: '', status: 'pending', title: 'hi', }, }, { event: 'test:completed', data: { duration: reporter.events[2].data.duration, error: null, regression: false, regressionMessage: '', status: 'passed', title: 'hi', }, }, { event: 'test:started', data: { duration: 0, error: null, regression: false, regressionMessage: '', status: 'pending', title: 'hey', }, }, { event: 'test:completed', data: { duration: reporter.events[4].data.duration, error: null, regression: false, regressionMessage: '', status: 'passed', title: 'hey', }, }, { event: 'group:completed', data: { error: null, status: 'passed', title: 'foo', }, }, ]) }) it('only run tests matching the grep regex', async () => { const reporter = getTestReporter() test.configure({ reporterFn: reporter.fn.bind(reporter), bail: true, grep: /h(i|ey)/, }) let executed = false test.group('foo', () => { test('hi', () => { }) test('hey', () => { }) test('hello', () => { executed = true }) }) await run(false) assert.isFalse(executed) assert.deepEqual(reporter.events, [ { event: 'group:started', data: { error: null, status: 'pending', title: 'foo', }, }, { event: 'test:started', data: { duration: 0, error: null, regression: false, regressionMessage: '', status: 'pending', title: 'hi', }, }, { event: 'test:completed', data: { duration: reporter.events[2].data.duration, error: null, regression: false, regressionMessage: '', status: 'passed', title: 'hi', }, }, { event: 'test:started', data: { duration: 0, error: null, regression: false, regressionMessage: '', status: 'pending', title: 'hey', }, }, { event: 'test:completed', data: { duration: reporter.events[4].data.duration, error: null, regression: false, regressionMessage: '', status: 'passed', title: 'hey', }, }, { event: 'group:completed', data: { error: null, status: 'passed', title: 'foo', }, }, ]) }) it('cherry pick test using the .only method', async () => { const reporter = getTestReporter() test.configure({ reporterFn: reporter.fn.bind(reporter), bail: true, grep: undefined, }) let executed = false test.group('foo', () => { test('hi', () => { }) test('hey', () => { }) test.only('hello', () => { executed = true }) }) await run(false) assert.isTrue(executed) assert.deepEqual(reporter.events, [ { event: 'group:started', data: { error: null, status: 'pending', title: 'foo', }, }, { event: 'test:started', data: { duration: 0, error: null, regression: false, regressionMessage: '', status: 'pending', title: 'hello', }, }, { event: 'test:completed', data: { duration: reporter.events[2].data.duration, error: null, regression: false, regressionMessage: '', status: 'passed', title: 'hello', }, }, { event: 'group:completed', data: { error: null, status: 'passed', title: 'foo', }, }, ]) }) })
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/connectedClusterOperationsMappers"; import * as Parameters from "../models/parameters"; import { ConnectedKubernetesClientContext } from "../connectedKubernetesClientContext"; /** Class representing a ConnectedClusterOperations. */ export class ConnectedClusterOperations { private readonly client: ConnectedKubernetesClientContext; /** * Create a ConnectedClusterOperations. * @param {ConnectedKubernetesClientContext} client Reference to the service client. */ constructor(client: ConnectedKubernetesClientContext) { this.client = client; } /** * API to register a new Kubernetes cluster and create a tracked resource in Azure Resource Manager * (ARM). * @summary Register a new Kubernetes cluster with Azure Resource Manager. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param clusterName The name of the Kubernetes cluster on which get is called. * @param connectedCluster Parameters supplied to Create a Connected Cluster. * @param [options] The optional parameters * @returns Promise<Models.ConnectedClusterCreateResponse> */ create(resourceGroupName: string, clusterName: string, connectedCluster: Models.ConnectedCluster, options?: msRest.RequestOptionsBase): Promise<Models.ConnectedClusterCreateResponse> { return this.beginCreate(resourceGroupName,clusterName,connectedCluster,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ConnectedClusterCreateResponse>; } /** * API to update certain properties of the connected cluster resource * @summary Updates a connected cluster. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param clusterName The name of the Kubernetes cluster on which get is called. * @param connectedClusterPatch Parameters supplied to update Connected Cluster. * @param [options] The optional parameters * @returns Promise<Models.ConnectedClusterUpdateResponse> */ update(resourceGroupName: string, clusterName: string, connectedClusterPatch: Models.ConnectedClusterPatch, options?: msRest.RequestOptionsBase): Promise<Models.ConnectedClusterUpdateResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param clusterName The name of the Kubernetes cluster on which get is called. * @param connectedClusterPatch Parameters supplied to update Connected Cluster. * @param callback The callback */ update(resourceGroupName: string, clusterName: string, connectedClusterPatch: Models.ConnectedClusterPatch, callback: msRest.ServiceCallback<Models.ConnectedCluster>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param clusterName The name of the Kubernetes cluster on which get is called. * @param connectedClusterPatch Parameters supplied to update Connected Cluster. * @param options The optional parameters * @param callback The callback */ update(resourceGroupName: string, clusterName: string, connectedClusterPatch: Models.ConnectedClusterPatch, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ConnectedCluster>): void; update(resourceGroupName: string, clusterName: string, connectedClusterPatch: Models.ConnectedClusterPatch, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ConnectedCluster>, callback?: msRest.ServiceCallback<Models.ConnectedCluster>): Promise<Models.ConnectedClusterUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, clusterName, connectedClusterPatch, options }, updateOperationSpec, callback) as Promise<Models.ConnectedClusterUpdateResponse>; } /** * Returns the properties of the specified connected cluster, including name, identity, properties, * and additional cluster details. * @summary Get the properties of the specified connected cluster. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param clusterName The name of the Kubernetes cluster on which get is called. * @param [options] The optional parameters * @returns Promise<Models.ConnectedClusterGetResponse> */ get(resourceGroupName: string, clusterName: string, options?: msRest.RequestOptionsBase): Promise<Models.ConnectedClusterGetResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param clusterName The name of the Kubernetes cluster on which get is called. * @param callback The callback */ get(resourceGroupName: string, clusterName: string, callback: msRest.ServiceCallback<Models.ConnectedCluster>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param clusterName The name of the Kubernetes cluster on which get is called. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, clusterName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ConnectedCluster>): void; get(resourceGroupName: string, clusterName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ConnectedCluster>, callback?: msRest.ServiceCallback<Models.ConnectedCluster>): Promise<Models.ConnectedClusterGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, clusterName, options }, getOperationSpec, callback) as Promise<Models.ConnectedClusterGetResponse>; } /** * Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM). * @summary Delete a connected cluster. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param clusterName The name of the Kubernetes cluster on which get is called. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(resourceGroupName: string, clusterName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginDeleteMethod(resourceGroupName,clusterName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * API to enumerate registered connected K8s clusters under a Resource Group * @summary Lists all connected clusters * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param [options] The optional parameters * @returns Promise<Models.ConnectedClusterListByResourceGroupResponse> */ listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.ConnectedClusterListByResourceGroupResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param callback The callback */ listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.ConnectedClusterList>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param options The optional parameters * @param callback The callback */ listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ConnectedClusterList>): void; listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ConnectedClusterList>, callback?: msRest.ServiceCallback<Models.ConnectedClusterList>): Promise<Models.ConnectedClusterListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec, callback) as Promise<Models.ConnectedClusterListByResourceGroupResponse>; } /** * API to enumerate registered connected K8s clusters under a Subscription * @summary Lists all connected clusters * @param [options] The optional parameters * @returns Promise<Models.ConnectedClusterListBySubscriptionResponse> */ listBySubscription(options?: msRest.RequestOptionsBase): Promise<Models.ConnectedClusterListBySubscriptionResponse>; /** * @param callback The callback */ listBySubscription(callback: msRest.ServiceCallback<Models.ConnectedClusterList>): void; /** * @param options The optional parameters * @param callback The callback */ listBySubscription(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ConnectedClusterList>): void; listBySubscription(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ConnectedClusterList>, callback?: msRest.ServiceCallback<Models.ConnectedClusterList>): Promise<Models.ConnectedClusterListBySubscriptionResponse> { return this.client.sendOperationRequest( { options }, listBySubscriptionOperationSpec, callback) as Promise<Models.ConnectedClusterListBySubscriptionResponse>; } /** * API to register a new Kubernetes cluster and create a tracked resource in Azure Resource Manager * (ARM). * @summary Register a new Kubernetes cluster with Azure Resource Manager. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param clusterName The name of the Kubernetes cluster on which get is called. * @param connectedCluster Parameters supplied to Create a Connected Cluster. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreate(resourceGroupName: string, clusterName: string, connectedCluster: Models.ConnectedCluster, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, clusterName, connectedCluster, options }, beginCreateOperationSpec, options); } /** * Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM). * @summary Delete a connected cluster. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param clusterName The name of the Kubernetes cluster on which get is called. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(resourceGroupName: string, clusterName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, clusterName, options }, beginDeleteMethodOperationSpec, options); } /** * API to enumerate registered connected K8s clusters under a Resource Group * @summary Lists all connected clusters * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.ConnectedClusterListByResourceGroupNextResponse> */ listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ConnectedClusterListByResourceGroupNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ConnectedClusterList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ConnectedClusterList>): void; listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ConnectedClusterList>, callback?: msRest.ServiceCallback<Models.ConnectedClusterList>): Promise<Models.ConnectedClusterListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByResourceGroupNextOperationSpec, callback) as Promise<Models.ConnectedClusterListByResourceGroupNextResponse>; } /** * API to enumerate registered connected K8s clusters under a Subscription * @summary Lists all connected clusters * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.ConnectedClusterListBySubscriptionNextResponse> */ listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ConnectedClusterListBySubscriptionNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listBySubscriptionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ConnectedClusterList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listBySubscriptionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ConnectedClusterList>): void; listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ConnectedClusterList>, callback?: msRest.ServiceCallback<Models.ConnectedClusterList>): Promise<Models.ConnectedClusterListBySubscriptionNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listBySubscriptionNextOperationSpec, callback) as Promise<Models.ConnectedClusterListBySubscriptionNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Kubernetes/connectedClusters/{clusterName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.clusterName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "connectedClusterPatch", mapper: { ...Mappers.ConnectedClusterPatch, required: true } }, responses: { 200: { bodyMapper: Mappers.ConnectedCluster }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Kubernetes/connectedClusters/{clusterName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.clusterName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ConnectedCluster }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByResourceGroupOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Kubernetes/connectedClusters", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ConnectedClusterList }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listBySubscriptionOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/providers/Microsoft.Kubernetes/connectedClusters", urlParameters: [ Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ConnectedClusterList }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const beginCreateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Kubernetes/connectedClusters/{clusterName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.clusterName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "connectedCluster", mapper: { ...Mappers.ConnectedCluster, required: true } }, responses: { 200: { bodyMapper: Mappers.ConnectedCluster }, 201: { bodyMapper: Mappers.ConnectedCluster }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Kubernetes/connectedClusters/{clusterName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.clusterName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByResourceGroupNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ConnectedClusterList }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listBySubscriptionNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ConnectedClusterList }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer };
the_stack
import { assert } from '@canvas-ui/assert' import { IllegalStateError } from '../error' import { Log } from '../foundation' import { Point, Rect, Size } from '../math' import { HitTestResult } from './hit-test' import { PaintingContext } from './painting-context' import { RenderContainer } from './render-container' import { RenderObject, Visitor } from './render-object' import { RenderPipeline } from './render-pipeline' import { RenderView, ViewParentData } from './render-view' export class ChunkParentData<ChildType extends RenderObject = RenderObject> extends ViewParentData<ChildType> { /** * 子节点渲染时关联的虚拟父节点 */ chunk?: Chunk<ChildType> /** * 指向位于 Chunk 内的 nextSibling */ nextSiblingInChunk?: ChildType /** * 指向位于 Chunk 内的 prevSibling */ prevSiblingInChunk?: ChildType override detach() { super.detach() assert(!this.chunk) assert(!this.nextSiblingInChunk) assert(!this.prevSiblingInChunk) } } export class RenderChunk<ChildType extends RenderObject<ChunkParentData<ChildType>> = RenderObject> extends RenderView<ChildType> { /** * 默认分块渲染容量 */ static readonly DEFAULT_CAPACITY = 6 /** * 设置或获取节点间分块渲染容量,修改 [capacity] 只会影响之后的分块策略,而不会影响之前的 */ get capacity() { return this._capacity } set capacity(value) { this._capacity = value } private _capacity = RenderChunk.DEFAULT_CAPACITY /** * 设置或获取 Chunk 的离屏检查函数 * * 返回 true 表示节点已离屏 */ get isOffstage() { return this.chunks.isOffstage } set isOffstage(value) { this.chunks.isOffstage = value } /** * 默认的离屏检查函数 */ static get defaultIsOffstage() { return ChunkContainer.defaultIsOffstage } /** * [RenderChunk] 恒为重绘边界 */ override get repaintBoundary() { return true } /** * 通过 [ChunkContainer] 代持 [Chunk]s,并且他不是 [RenderChunk] 的逻辑子节点 */ private chunks = new ChunkContainer() protected override setupParentData(child: RenderObject) { if (!(child.parentData instanceof ChunkParentData)) { child.parentData = new ChunkParentData() } } protected override internalInsertAfter(child: ChildType, after?: ChildType) { super.internalInsertAfter(child, after) // 也要将 child 插入到 chunk this.insertIntoChunk(child) } protected override internalRemoveChild(child: ChildType) { super.internalRemoveChild(child) // 也要将 child 移出 chunk this.removeFromChunk(child) } private insertIntoChunk(child: ChildType) { this.mergeIntoChunk(child, this._capacity) } /** * 合并 child 到某个 [Chunk],如果不能合并则会尝试拆分 chunk */ private mergeIntoChunk(child: ChildType, chunkCapacity: number) { assert(child.parentData, 'child 不能没有 parentData') assert(!child.parentData.chunk, 'child 不能已分配 chunk') const prevChunk = child.parentData.prevSibling?.parentData?.chunk const nextChunk = child.parentData.nextSibling?.parentData?.chunk // child 介于两个 chunk 之间 if (prevChunk !== nextChunk) { if (prevChunk && prevChunk.childCount < chunkCapacity) { // prevChunk 如果容量够就放进去 assert(prevChunk.lastChild === child.parentData.prevSibling) prevChunk.insertAfter(child, prevChunk.lastChild) } else if (nextChunk && nextChunk.childCount < chunkCapacity) { // nextChunk 如果容量够就放进去 assert(nextChunk.firstChild === child.parentData.nextSibling) nextChunk.insertBefore(child, nextChunk.firstChild) } else { const chunk = this.createChunkAfter(prevChunk) chunk.appendChild(child) } } else if (prevChunk) { // 此时 prevChunk 就是要插入的 Chunk prevChunk.insertAfter(child, child.parentData.prevSibling) // 空间不足时,将最后一个节点移出,尝试重新合并 if (prevChunk.childCount >= chunkCapacity) { const lastChild = prevChunk.lastChild assert(lastChild) prevChunk.removeChild(lastChild) this.mergeIntoChunk(lastChild, chunkCapacity) } } else { // 创建新的 chunk const chunk = this.createChunkAfter(prevChunk) chunk.appendChild(child) } } private createChunkAfter(after?: Chunk<ChildType>) { const chunk = new Chunk<ChildType>() this.chunks.insertAfter(chunk, after) return chunk } private removeFromChunk(child: ChildType) { const chunk = child.parentData?.chunk if (!chunk) { return } // 将 child 从 chunk 移出 chunk.removeChild(child) // 同时删除空的 chunk if (chunk.childCount === 0) { this.chunks.removeChild(chunk) } } override attach(owner: RenderPipeline) { super.attach(owner) // chunks 作为渲染代理,也要 attach,即使他不是 [RenderChunk] 的子节点 this.chunks.attach(owner) } override detach() { super.detach() // chunks 作为渲染代理,也要 detach,即使他不是 [RenderChunk] 的子节点 this.chunks.detach() } protected override _paint(context: PaintingContext, offset: Point) { // 通过 ChunkContainer 渲染子节点 this.chunks.paintChildren(context, offset, this.viewportOffset, this._viewport) } override markLayoutDirty(cause?: ChildType) { super.markLayoutDirty() if (cause) { const chunk = cause.parentData?.chunk // 子节点被 append 时也会调用该方法,此时子节点的 chunk 可能尚未分配 if (chunk) { chunk._layoutDirty = true } } } override markPaintDirty(cause?: ChildType) { super.markPaintDirty() if (cause) { const chunk = cause.parentData?.chunk // 造成 chunk 不存在的原因只有节点刚被 adopt 时,trackStyle 中处理了样式,此时又直接调用了 markPaintDirty(this),就会导致此处 Chunk 不存在 // assert(chunk, '无法定位子节点所在 chunk') if (chunk) { chunk._paintDirty = true } } } override performLayout() { // 先调用 [RenderView] 的布局方法,对所有子节点进行布局 super.performLayout() // 随后,调用 chunks 的布局方法 this.chunks.performLayout() } override hitTestChildren(result: HitTestResult, position: Point) { let child = this._lastChild const { viewportOffset } = this while (child) { // 通过关联 chunk 的 offstage 进行优化 const isHit = !child.parentData!.chunk!.offstage && result.addWithPaintOffset( Point.add(child._offset, viewportOffset), position, (result, transformed) => { assert(Point.eq(transformed, Point.add(position, Point.invert(Point.add(child!._offset, viewportOffset))))) return child!.hitTest(result, transformed) } ) if (isHit) { return true } child = child.parentData?.prevSibling } return false } } class ChunkContainer<ChildType extends RenderObject<ChunkParentData<ChildType>>> extends RenderView<Chunk<ChildType>> { override performLayout() { let child = this._firstChild while (child) { // ChunkContainer 需要了解子节点 Chunk 的 size child.layoutAsChild(true, false) child = child.parentData!.nextSibling } } isOffstage = ChunkContainer.defaultIsOffstage static defaultIsOffstage(viewport: Rect, childBounds: Rect) { return !Rect.overlaps(viewport, childBounds) } override paintChildren( context: PaintingContext, offset: Point, viewportOffset: Point, viewport: Rect, ) { let child = this._firstChild const viewportNotEmpty = !Rect.isEmpty(viewport) while (child) { child.offstage = viewportNotEmpty && this.isOffstage(viewport, child.bounds) if (!child.offstage) { context.paintChild(child, Point.add3(child._offset, offset, viewportOffset)) } child = child.parentData!.nextSibling } } } class Chunk<ChildType extends RenderObject<ChunkParentData<ChildType>>> extends RenderObject<ViewParentData<Chunk<ChildType>>> implements RenderContainer<ChildType> { paint(context: PaintingContext, offset: Point): void { let child = this._firstChild const invOffset = Point.invert(this._offset) while (child) { context.paintChild(child, Point.add3(child._offset, offset, invOffset)) child = child.parentData!.nextSiblingInChunk } } override hitTestChildren(_result: HitTestResult, _position: Point): boolean { throw new IllegalStateError(`Chunk 只提供分块渲染功能,不提供命中检测功能,如果你遇到了这个错误,这通常是 glui 的问题。`) } @Log() override performLayout() { let bounds: Rect | undefined let child = this._firstChild while (child) { const childBounds = Rect.fromOffsetAndSize(child._offset, child._size) if (!bounds) { bounds = childBounds } else { bounds = Rect.expandToInclude(bounds, childBounds) } child = child.parentData!.nextSiblingInChunk } assert(bounds, 'bounds 是 undefined,说明当前 Chunk 是空的,不应该执行布局流程') this.offset = Point.fromXY(bounds.left, bounds.top) this.size = Size.fromWH(bounds.width, bounds.height) } override get repaintBoundary() { return true } get childCount() { return this._childCount } protected _childCount = 0 get firstChild() { return this._firstChild } protected _firstChild?: ChildType get lastChild() { return this._lastChild } protected _lastChild?: ChildType childBefore(child: ChildType) { assert(child.parent instanceof Chunk) return child.parentData?.prevSiblingInChunk } childAfter(child: ChildType) { assert(child.parent instanceof Chunk) return child.parentData?.nextSiblingInChunk } redepthChildren() { let child = this._firstChild while (child) { this.redepthChild(child) const childParentData = child.parentData! child = childParentData.nextSiblingInChunk } } visitChildren(visitor: Visitor<ChildType>) { let child = this._firstChild while (child) { visitor(child) child = child.parentData!.nextSiblingInChunk } } private debugUltimatePrevSiblingOf(child: ChildType, equals: ChildType | undefined) { let childParentData = child.parentData! while (childParentData.prevSiblingInChunk) { assert(childParentData.prevSiblingInChunk !== child) child = childParentData.prevSiblingInChunk childParentData = child.parentData! } return child === equals } private debugUltimateNextSiblingOf(child: ChildType, equals: ChildType | undefined) { let childParentData = child.parentData! while (childParentData.nextSiblingInChunk) { assert(childParentData.nextSiblingInChunk !== child) child = childParentData.nextSiblingInChunk! childParentData = child.parentData! } return child === equals } private internalInsertAfter(child: ChildType, after?: ChildType) { const childParentData = child.parentData! assert(!childParentData.nextSiblingInChunk, 'child 不能已关联 nextSiblingInChunk') assert(!childParentData.prevSiblingInChunk, 'child 不能已关联 prevSiblingInChunk') assert(!childParentData.chunk, 'child 不能已分配 chunk') childParentData.chunk = this child.offstage = false this._childCount++ assert(this._childCount > 0) if (!after) { // 从头部插入 (_firstChild) childParentData.nextSiblingInChunk = this._firstChild if (this._firstChild) { const firstChildParentData = this._firstChild.parentData assert(firstChildParentData) firstChildParentData.prevSiblingInChunk = child } this._firstChild = child this._lastChild ??= child } else { assert(this._firstChild) assert(this._lastChild) assert(this.debugUltimatePrevSiblingOf(after, this._firstChild)) assert(this.debugUltimateNextSiblingOf(after, this._lastChild)) const afterParentData = after.parentData! if (!afterParentData.nextSiblingInChunk) { // 从尾部插入 (_lastChild) assert(after === this._lastChild) childParentData.prevSiblingInChunk = after afterParentData.nextSiblingInChunk = child this._lastChild = child } else { // 从中间插入 childParentData.nextSiblingInChunk = afterParentData.nextSiblingInChunk childParentData.prevSiblingInChunk = after const childPrevSiblingParentData = childParentData.prevSiblingInChunk!.parentData! const childNextSiblingParentData = childParentData.nextSiblingInChunk!.parentData! childPrevSiblingParentData.nextSiblingInChunk = child childNextSiblingParentData.prevSiblingInChunk = child assert(afterParentData.nextSiblingInChunk === child) } } this._layoutDirty = true this._paintDirty = true } insertAfter(child: ChildType, after?: ChildType) { assert(child as unknown !== this) assert(after as unknown !== this) assert(child !== after, '节点不能把自己添加到自己后面') assert(child !== this._firstChild, '节点已经是 firstChild') assert(child !== this._lastChild, '节点已经是 lastChild') this.internalInsertAfter(child, after) } insertBefore(child: ChildType, before?: ChildType) { this.insertAfter(child, before?.parentData?.prevSiblingInChunk) } appendChild(child: ChildType) { this.insertAfter(child, this._lastChild) } private internalRemoveChild(child: ChildType) { const childParentData = child.parentData! assert(this.debugUltimatePrevSiblingOf(child, this._firstChild)) assert(this.debugUltimateNextSiblingOf(child, this._lastChild)) assert(childParentData.chunk === this, 'child 已分配的 chunk 不是自己') assert(this._childCount >= 0) if (!childParentData.prevSiblingInChunk) { // 子节点是 firstChild assert(this._firstChild === child) this._firstChild = childParentData.nextSiblingInChunk } else { const childPrevSiblingParentData = childParentData.prevSiblingInChunk.parentData! childPrevSiblingParentData.nextSiblingInChunk = childParentData.nextSiblingInChunk } if (!childParentData.nextSiblingInChunk) { // 子节点是 lastChild assert(this._lastChild === child) this._lastChild = childParentData.prevSiblingInChunk } else { const childNextSiblingParentData = childParentData.nextSiblingInChunk.parentData! childNextSiblingParentData.prevSiblingInChunk = childParentData.prevSiblingInChunk } childParentData.prevSiblingInChunk = undefined childParentData.nextSiblingInChunk = undefined childParentData.chunk = undefined child.offstage = true this._childCount -= 1 this._layoutDirty = true this._paintDirty = true } removeChild(child: ChildType) { this.internalRemoveChild(child) } removeAllChildren() { let child = this._firstChild while (child) { const childParentData = child.parentData! const next = childParentData.nextSiblingInChunk childParentData.prevSiblingInChunk = undefined childParentData.nextSiblingInChunk = undefined childParentData.chunk = undefined child = next } this._firstChild = undefined this._lastChild = undefined this._childCount = 0 } get debugChildren() { const children: ChildType[] = [] if (this._firstChild) { let child = this._firstChild // eslint-disable-next-line no-constant-condition while (true) { children.push(child) if (child === this._lastChild) { break } child = child.parentData!.nextSiblingInChunk! } } return children } }
the_stack
import { DOCUMENT } from '@angular/common'; import { ChangeDetectorRef, Component, ElementRef, HostListener, Inject, NgZone, OnDestroy, OnInit, Optional, SkipSelf, ViewChild, ViewContainerRef } from '@angular/core'; import { FieldWrapper, FormlyFieldConfig } from '@ngx-formly/core'; import { isString } from 'lodash'; import { fromEvent, NEVER, Subscription, timer } from 'rxjs'; import { catchError, map, tap } from 'rxjs/operators'; import { DragDropService, FieldsService, FormlyDesignerService } from '../'; import { DragDropType } from '../models'; import { Parent } from '../parent'; import { ParentService } from '../parent.service'; import { cloneDeep } from '../util'; export enum DropPlacement { self, before, after, } @Component({ selector: 'formly-designer-field-wrapper', template: ` <div #content class="designer-content" [title]="title" [ngClass]="{ 'designer-subject': isSubject, 'designer-drag-source': isDragSource, 'designer-drop-hint': isDragging, 'designer-drop-target': isDropTargetSelf, 'designer-hover': isHovering && !isDragging }" draggable="true" (dragstart)="onDragStart($event)" (dragend)="onDragEnd()" (dragenter)="onDragEnter($event)" (dragleave)="onDragLeave($event)" (drop)="onDrop($event)" (mouseout)="onMouseOut()"> <ng-template #fieldComponent></ng-template> </div> <div *ngIf="isDropTargetBefore" class="designer-drop-target-before"></div> <div *ngIf="isDropTargetAfter" class="designer-drop-target-after"></div> `, styles: [` :host { display: flex; position: relative; justify-content: flex-start; align-content: flex-start; align-items: flex-start; margin: .25rem; } .designer-content { border: 1px dashed #000; border-radius: 5px; min-height: 2rem; padding: .25em 1em; width: 100%; } .designer-content.designer-hover { background-color: #f0f4c3; border-color: #00c853; cursor: pointer; } .designer-content.designer-subject { border-color: #00c853; border-style: solid; border-width: 2px; } .designer-content.designer-drop-hint { background-color: pink; border-color: #bbdefb; } .designer-content.designer-drop-target { background-color: #f0f4c3; border-color: #00c853; } .designer-drag-source { opacity: .4; } .designer-drop-target-before { position: absolute; top: 0; left: 0; right: 0; background-color: aqua; height: 12px; pointer-events: none; z-index: 1; } .designer-drop-target-after { position: absolute; bottom: 0; left: 0; right: 0; background-color: yellow; height: 12px; pointer-events: none; z-index: 1; } `], providers: [ ParentService, ], }) export class FormlyDesignerFieldWrapperComponent extends FieldWrapper implements OnInit, OnDestroy, Parent { @ViewChild('fieldComponent', { read: ViewContainerRef, static: true }) fieldComponent!: ViewContainerRef; @ViewChild('content', { read: ElementRef, static: true }) content?: ElementRef<HTMLElement>; dropTargetCounter = 0; private subscriptions: Subscription[] = []; get title(): string | null { return this._title; } set title(value: string | null) { if (value !== this._title) { this._title = value; this.changeDetector.markForCheck(); } } private _title: string | null = null; get isDragging() { return this._isDragging; } set isDragging(value: boolean) { if (value !== this._isDragging) { this._isDragging = value; this.changeDetector.markForCheck(); } } private _isDragging = false; get isHovering() { return this._isHovering; } set isHovering(value: boolean) { if (value !== this._isHovering) { this._isHovering = value; this.changeDetector.markForCheck(); } } private _isHovering = false; get parent(): Parent | undefined { return this.parentParentService?.parent; } get dropTargetPlacement(): DropPlacement | null { return this._dropTargetPlacement; } set dropTargetPlacement(value: DropPlacement | null) { if (value !== this._dropTargetPlacement) { this._dropTargetPlacement = value; this.changeDetector.markForCheck(); } } private _dropTargetPlacement: DropPlacement | null = null; get designerId(): string | undefined { return this.field.templateOptions?.$designerId; } get isFieldGroup(): boolean { return Array.isArray(this.field.fieldGroup); } get isDragSource(): boolean { return this.dragDropService.dragging === this.designerId; } get isDropTarget(): boolean { return this.dragDropService.dropTarget === this.designerId; } get isDropTargetSelf(): boolean { return this.isDropTarget && !this.dropTargetPlacement && this.isFieldGroup; } get isDropTargetBefore(): boolean { return this.isDropTarget && this.dropTargetPlacement === DropPlacement.before; } get isDropTargetAfter(): boolean { return this.isDropTarget && this.dropTargetPlacement === DropPlacement.after; } get isSubject(): boolean { return this.formlyDesignerService.selectedDesignerId === this.designerId; } constructor( private changeDetector: ChangeDetectorRef, private dragDropService: DragDropService, private fieldsService: FieldsService, public formlyDesignerService: FormlyDesignerService, private zone: NgZone, parentService: ParentService, @Inject(DOCUMENT) private document?: any, @SkipSelf() @Optional() private parentParentService?: ParentService, ) { super(); parentService.parent = this; if (parentParentService) { parentParentService.addChild(this); } } ngOnInit(): void { if (!this.document?.defaultView) { return; } const content = this.content?.nativeElement; if (!content) { return; } this.subscriptions.push( this.dragDropService.dragging$.subscribe(dragging => this.isDragging = dragging != null), fromEvent(this.document.defaultView, 'mouseup').subscribe(this.onWindowMouseUp.bind(this)), ); this.zone.runOutsideAngular(() => { this.subscriptions.push( fromEvent(content, 'dragover').subscribe(e => this.onDragOver(e as DragEvent)), fromEvent(content, 'mouseover').subscribe(e => this.onMouseOver(e as MouseEvent)), ); }); } ngOnDestroy(): void { this.subscriptions.splice(0).forEach(subscription => subscription.unsubscribe()); this.parentParentService?.removeChild(this); } @HostListener('click', ['$event']) onClick(event: MouseEvent): void { event.stopPropagation(); this.formlyDesignerService.didClickField(this.field); } onDragStart(event: DragEvent): void { if (this.dragDropService.dragging) { return; } event.dataTransfer?.setData(DragDropType.Field, this.designerId ?? ''); this.dragDropService.beginDrag(this.designerId ?? null); } onDragEnd(): void { this.dragDropService.endDrag(); } onDragEnter(event: DragEvent): void { if (!this.shouldHandleDragEvent(event)) { return; } event.preventDefault(); this.dropTargetCounter++; } onDragLeave(event: DragEvent): void { if (!this.shouldHandleDragEvent(event)) { return; } if (this.dropTargetCounter > 0) { this.dropTargetCounter--; if (this.dropTargetCounter === 0) { this.dropTargetPlacement = null; } } } onDragOver(event: DragEvent): void { if (event.defaultPrevented || !this.shouldHandleDragEvent(event)) { return; } this.zone.run(() => { this.dropTargetPlacement = this.getDropTargetPlacement(event); this.dragDropService.dropTarget = this.field.templateOptions?.$designerId ?? null; }); event.preventDefault(); } private shouldHandleDragEvent(event: DragEvent): boolean { if (event.dataTransfer?.types.some(t => t === DragDropType.Field)) { return this.dragDropService.dragging !== this.designerId; } return !!event.dataTransfer?.types.some(t => t === DragDropType.Type) && isString(this.dragDropService.dragging); } private getDropTargetPlacement(event: DragEvent): DropPlacement { const rect = this.content?.nativeElement.getBoundingClientRect(); if (rect) { const threshold = rect.height * .33; if (event.clientY < rect.top + threshold) { return DropPlacement.before; } if (event.clientY > rect.bottom - threshold) { return DropPlacement.after; } } return DropPlacement.self; } onDrop(event: DragEvent): void { if (this.shouldHandleDragEvent(event)) { event.stopPropagation(); if (event.dataTransfer?.types.includes(DragDropType.Field)) { const designerId = this.dragDropService.dragging; const field = this.fieldsService.find(designerId, this.formlyDesignerService.designerFields); if (field) { // Get placement index before the fields refresh caused by removal const index = this.getDropPlacementIndex(field); this.formlyDesignerService.removeField(field); if (this.parent && this.dropTargetPlacement !== DropPlacement.self) { this.parent.addChildField(field, index); } else { this.addChildField(field); } } } else if (event.dataTransfer?.types.includes(DragDropType.Type)) { if (this.dragDropService.dragging) { if (this.parent && this.dropTargetPlacement !== DropPlacement.self) { this.parent.addChildType(this.dragDropService.dragging, this.getDropPlacementIndex()); } else { this.addChildType(this.dragDropService.dragging); } } } } this.dragDropService.endDrag(); this.resetDrop(); } onMouseOver(event: MouseEvent): void { event.stopPropagation(); this.zone.run(() => { this.isHovering = true; this.title = this.dragDropService.dragging == null ? `Click to edit ${this.formlyDesignerService.getTypeName(this.field.type)}` : null; }); } onMouseOut(): void { this.isHovering = false; } onWindowMouseUp(): void { this.resetDrop(); } async addChildField(field: FormlyFieldConfig, index?: number): Promise<void> { if (!this.isFieldGroup) { return; } if (!this.fieldsService.checkField(field, this.formlyDesignerService.designerFields, this.field)) { return; } const updatedField = cloneDeep(this.field); if (!updatedField.fieldGroup) { return; } const fieldIndex = (index == null || isNaN(index)) ? updatedField.fieldGroup.length : Math.min(updatedField.fieldGroup.length, Math.max(0, index)); updatedField.fieldGroup.splice(fieldIndex, 0, field); return timer(0) .pipe( tap(() => this.formlyDesignerService.updateField(this.field, updatedField)), catchError(() => NEVER), map(() => undefined) ).toPromise(); } async addChildType(type: string, index?: number): Promise<void> { const field = this.formlyDesignerService.createField(type); await this.addChildField(field, index); } /** * @param dropField - field to ignore for index determination */ private getDropPlacementIndex(dropField?: FormlyFieldConfig): number | undefined { if (this.parent && this.dropTargetPlacement !== DropPlacement.self) { const parentChildren = dropField ? this.parentParentService?.children.filter(fd => fd.designerId !== dropField.templateOptions?.$designerId) : this.parentParentService?.children; const dropIndex = parentChildren?.indexOf(this) ?? 0; return this.dropTargetPlacement === DropPlacement.before ? dropIndex : dropIndex + 1; } return; } private resetDrop(): void { this.dropTargetCounter = 0; this.dropTargetPlacement = null; if (this.isDropTarget) { this.dragDropService.dropTarget = null; } } }
the_stack
import MeshStyle from "./../../starling/styles/MeshStyle"; import DistanceFieldEffect from "./../../starling/styles/DistanceFieldEffect"; import Color from "./../../starling/utils/Color"; import MathUtil from "./../../starling/utils/MathUtil"; import VertexDataFormat from "./../rendering/VertexDataFormat"; import MeshEffect from "./../rendering/MeshEffect"; import Matrix from "openfl/geom/Matrix"; import RenderState from "./../rendering/RenderState"; declare namespace starling.styles { /** Provides support for signed distance fields to Starling meshes. * * <p>Signed distance field rendering allows bitmap fonts and other single colored shapes to * be drawn without jagged edges, even at high magnifications. The technique was introduced in * the SIGGRAPH paper <a href="http://tinyurl.com/AlphaTestedMagnification">Improved * Alpha-Tested Magnification for Vector Textures and Special Effects</a> by Valve Software. * </p> * * <p>While bitmap fonts are a great solution to render text in a GPU-friendly way, they * don't scale well. For best results, one has to embed the font in all the sizes used within * the app. The distance field style solves this issue: instead of providing a standard * black and white image of the font, it uses a <em>signed distance field texture</em> as * its input (a texture that encodes, for each pixel, the distance to the closest edge of a * vector shape). With this data, the shape can be rendered smoothly at almost any scale.</p> * * <p>Here are some tools that support creation of such distance field textures:</p> * * <ul> * <li>Field Agent - a Ruby script that uses ImageMagick to create single-channel distance * field textures. Part of the Starling download ('util' directory).</li> * <li><a href="https://github.com/Chlumsky/msdfgen">msdfgen</a> - an excellent and fast * open source command line tool that creates multi- and single-channel distance field * textures.</li> * </ul> * * <p>The former tools convert arbitrary SVG or PNG images to distance field textures. * To create distance field <em>fonts</em>, have a look at the following alternatives:</p> * * <ul> * <li><a href="https://github.com/soimy/msdf-bmfont-xml/">msdf-bmfont-xml</a> - a command * line tool powered by msdf and thus producing excellent multi-channel output.</li> * <li><a href="http://kvazars.com/littera/">Littera</a> - a free online bitmap font * generator.</li> * <li><a href="http://github.com/libgdx/libgdx/wiki/Hiero">Hiero</a> - a cross platform * tool.</li> * <li><a href="http://www.angelcode.com/products/bmfont/">BMFont</a> - Windows-only, from * AngelCode.</li> * </ul> * * <strong>Single-Channel vs. Multi-Channel</strong> * * <p>The original approach for distance field textures uses just a single channel (encoding * the distance of each pixel to the shape that's being represented). By utilizing * all three color channels, however, the results can be greatly enhanced - a technique * developed by Viktor Chlumský.</p> * * <p>Starling supports such multi-channel DF textures, as well. When using an appropriate * texture, don't forget to enable the style's <code>multiChannel</code> property.</p> * * <strong>Special effects</strong> * * <p>Another advantage of this rendering technique: it supports very efficient rendering of * some popular filter effects, in just one pass, directly on the GPU. You can add an * <em>outline</em> around the shape, let it <em>glow</em> in an arbitrary color, or add * a <em>drop shadow</em>.</p> * * <p>The type of effect currently used is called the 'mode'. * Meshes with the same mode will be batched together on rendering.</p> */ export class DistanceFieldStyle extends MeshStyle { /** The vertex format expected by this style. */ public static VERTEX_FORMAT:VertexDataFormat; /** Basic distance field rendering, without additional effects. */ public static MODE_BASIC:string; /** Adds an outline around the edge of the shape. */ public static MODE_OUTLINE:string; /** Adds a smooth glow effect around the shape. */ public static MODE_GLOW:string; /** Adds a drop shadow behind the shape. */ public static MODE_SHADOW:string; /** Creates a new distance field style. * * @param softness adds a soft transition between the inside and the outside. * This should typically be 1.0 divided by the spread (in points) * used when creating the distance field texture. * @param threshold the value separating the inside from the outside of the shape. * Range: 0 - 1. */ public constructor(softness?:number, threshold?:number); /** @protected */ /*override*/ public copyFrom(meshStyle:MeshStyle):void; /** @protected */ /*override*/ public createEffect():MeshEffect; /** @protected */ /*override*/ public batchVertexData(targetStyle:MeshStyle, targetVertexID?:number, matrix?:Matrix, vertexID?:number, numVertices?:number):void; /** @protected */ /*override*/ public updateEffect(effect:MeshEffect, state:RenderState):void; /** @protected */ /*override*/ public canBatchWith(meshStyle:MeshStyle):boolean; // simplified setup /** Restores basic render mode, i.e. smooth rendering of the shape. */ public setupBasic():void; /** Sets up outline rendering mode. The 'width' determines the threshold where the * outline ends; 'width + threshold' must not exceed '1.0'. */ public setupOutline(width?:number, color?:number, alpha?:number):void; /** Sets up glow rendering mode. The 'blur' determines the threshold where the * blur ends; 'blur + threshold' must not exceed '1.0'. */ public setupGlow(blur?:number, color?:number, alpha?:number):void; /** Sets up shadow rendering mode. The 'blur' determines the threshold where the drop * shadow ends; 'offsetX' and 'offsetY' are expected in points. * * <p>Beware that the style can only act within the limits of the mesh's vertices. * This means that not all combinations of blur and offset are possible; too high values * will cause the shadow to be cut off on the sides. Reduce either blur or offset to * compensate.</p> */ public setupDropShadow(blur?:number, offsetX?:number, offsetY?:number, color?:number, alpha?:number):void; // properties /** The current render mode. It's recommended to use one of the 'setup...'-methods to * change the mode, as those provide useful standard settings, as well. @default basic */ public mode:string; protected get_mode():string; protected set_mode(value:string):string; /** Indicates if the distance field texture utilizes multiple channels. This improves * render quality, but requires specially created DF textures. @default false */ public multiChannel:boolean; protected get_multiChannel():boolean; protected set_multiChannel(value:boolean):boolean; /** The threshold that will separate the inside from the outside of the shape. On the * distance field texture, '0' means completely outside, '1' completely inside; the * actual edge runs along '0.5'. @default 0.5 */ public threshold:number; protected get_threshold():number; protected set_threshold(value:number):number; /** Indicates how soft the transition between inside and outside should be rendered. * A value of '0' will lead to a hard, jagged edge; '1' will be just as blurry as the * actual distance field texture. The recommend value should be <code>1.0 / spread</code> * (you determine the spread when creating the distance field texture). @default 0.125 */ public softness:number; protected get_softness():number; protected set_softness(value:number):number; /** The alpha value with which the inner area (what's rendered in 'basic' mode) is drawn. * @default 1.0 */ public alpha:number; protected get_alpha():number; protected set_alpha(value:number):number; /** The threshold that determines where the outer area (outline, glow, or drop shadow) * ends. Ignored in 'basic' mode. */ public outerThreshold:number; protected get_outerThreshold():number; protected set_outerThreshold(value:number):number; /** The alpha value on the inner side of the outer area's gradient. * Used for outline, glow, and drop shadow modes. */ public outerAlphaStart:number; protected get_outerAlphaStart():number; protected set_outerAlphaStart(value:number):number; /** The alpha value on the outer side of the outer area's gradient. * Used for outline, glow, and drop shadow modes. */ public outerAlphaEnd:number; protected get_outerAlphaEnd():number; protected set_outerAlphaEnd(value:number):number; /** The color with which the outer area (outline, glow, or drop shadow) will be filled. * Ignored in 'basic' mode. */ public outerColor:number; protected get_outerColor():number; protected set_outerColor(value:number):number; /** The x-offset of the shadow in points. Note that certain combinations of offset and * blur value can lead the shadow to be cut off at the edges. Reduce blur or offset to * counteract. */ public shadowOffsetX:number; protected get_shadowOffsetX():number; protected set_shadowOffsetX(value:number):number; /** The y-offset of the shadow in points. Note that certain combinations of offset and * blur value can lead the shadow to be cut off at the edges. Reduce blur or offset to * counteract. */ public shadowOffsetY:number; protected get_shadowOffsetY():number; protected set_shadowOffsetY(value:number):number; } export class DistanceFieldEffect extends MeshEffect { public static VERTEX_FORMAT:VertexDataFormat; public static MAX_OUTER_OFFSET:number; public static MAX_SCALE:number; public constructor(); public scale:number; protected get_scale():number; protected set_scale(value:number):number; public mode:string; protected get_mode():string; protected set_mode(value:string):string; public multiChannel:boolean; protected get_multiChannel():boolean; protected set_multiChannel(value:boolean):boolean; } } export default starling.styles.DistanceFieldStyle;
the_stack
import BoxClient from '../box-client'; import urlPath from '../util/url-path'; // ----------------------------------------------------------------------------- // Typedefs // ----------------------------------------------------------------------------- /** * Enum of valid retention policy types, which specify how long the policy should * remain in effect. * @readonly * @enum {RetentionPolicyType} */ enum RetentionPolicyType { FINITE = 'finite', INDEFINITE = 'indefinite', } /** * Enum of valid retention policy disposition actions, which specify what should * be done when the retention period is over * @readonly * @enum {RetentionPolicyDispositionAction} */ enum RetentionPolicyDispositionAction { PERMANENTLY_DELETE = 'permanently_delete', REMOVE_RETENTION = 'remove_retention', } /** * Enum of valid policy assignment types, which specify what object the policy applies to * @readonly * @enum {RetentionPolicyAssignmentType} */ enum RetentionPolicyAssignmentType { FOLDER = 'folder', ENTERPRISE = 'enterprise', METADATA = 'metadata_template', } /** * Metadata template fields to filter on for assigning a retention policy * @typedef {Object} MetadataFilterField * @property {string} field The field to filter on * @property {string|int} value The value to filter against */ type MetadataFilterField = { field: string; value: string | number; }; // ----------------------------------------------------------------------------- // Private // ----------------------------------------------------------------------------- const BASE_PATH = '/retention_policies', ASSIGNMENTS_PATH = '/retention_policy_assignments', FILE_VERSION_RETENTIONS_PATH = '/file_version_retentions', ASSIGNMENTS_SUBRESOURCE = 'assignments', FILES_UNDER_RETENTION_SUBRESOURCE = 'files_under_retention', FILES_VERSIONS_UNDER_RETENTION_SUBRESOURCE = 'file_versions_under_retention'; // ----------------------------------------------------------------------------- // Public // ----------------------------------------------------------------------------- /** * Simple manager for interacting with all Retention Policies endpoints and actions. * * @constructor * @param {BoxClient} client - The Box API Client that is responsible for making calls to the API * @returns {void} */ class RetentionPolicies { client: BoxClient; policyTypes!: typeof RetentionPolicyType; dispositionActions!: typeof RetentionPolicyDispositionAction; assignmentTypes!: typeof RetentionPolicyAssignmentType; constructor(client: BoxClient) { this.client = client; } /** * Used to create a single retention policy for an enterprise * * API Endpoint: '/retention_policies' * Method: POST * * @param {string} name - The name of the retention policy to be created * @param {RetentionPolicyType} type - The type of policy to create * @param {RetentionPolicyDispositionAction} action - The disposition action for the new policy * @param {Object} [options] - Additional parameters * @param {int} [options.retention_length] - For finite policies, the number of days to retain the content * @param {Function} [callback] - Passed the new policy information if it was acquired successfully, error otherwise * @returns {Promise<Object>} A promise resolving to the new policy object */ create( name: string, type: RetentionPolicyType, action: RetentionPolicyDispositionAction, options?: { retention_length?: number; }, callback?: Function ) { var apiPath = urlPath(BASE_PATH), params = { body: { policy_name: name, policy_type: type, disposition_action: action, }, }; Object.assign(params.body, options); return this.client.wrapWithDefaultHandler(this.client.post)( apiPath, params, callback ); } /** * Fetches details about a specific retention policy * * API Endpoint: '/retention_policies/:policyID' * Method: GET * * @param {string} policyID - The Box ID of the retention 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 retention policy. * * API Endpoint: '/retention_policies/:policyID' * Method: PUT * * @param {string} policyID - The Box ID of the retention policy to update * @param {Object} updates - The information to be updated * @param {string} [updates.policy_name] - The name of the retention policy * @param {RetentionPolicyDispositionAction} [updates.disposition_action] - The disposition action for the updated policy * @param {string} [updates.status] - Used to retire a retention policy if status is set to retired * @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 object */ update( policyID: string, updates: { policy_name?: string; disposition_action?: RetentionPolicyDispositionAction; status?: 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 retention policies for the enterprise * * API Endpoint: '/retention_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 retention policies by * @param {RetentionPolicyType} [options.policy_type] - A policy type to filter the retention policies by * @param {string} [options.created_by_user_id] - A user id to filter the retention policies by * @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; policy_type?: RetentionPolicyType; created_by_user_id?: string; }, callback?: Function ) { var apiPath = urlPath(BASE_PATH), params = { qs: options, }; return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Fetch a list of assignments for a given retention policy * * API Endpoint: '/retention_policies/:policyID/assignments' * Method: GET * * @param {string} policyID - The Box ID of the retention policy to get assignments for * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {RetentionPolicyAssignmentType} [options.type] - The type of the retention policy assignment to retrieve * @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?: { type?: RetentionPolicyAssignmentType; }, callback?: Function ) { var apiPath = urlPath(BASE_PATH, policyID, ASSIGNMENTS_SUBRESOURCE), params = { qs: options, }; return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Assign a retention policy to a folder or the entire enterprise. * * API Endpoint: '/retention_policy_assignments * Method: POST * * @param {string} policyID - The ID of the policy to assign * @param {RetentionPolicyAssignmentType} assignType - The type of object the policy will be assigned to * @param {string} assignID - The Box ID of the object to assign the retention policy to * @param {Object} [options] - Optional parameters for the request * @param {MetadataFilterField[]} [options.filter_fields] - Metadata fields to filter against, if assigning to a metadata template * @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: RetentionPolicyAssignmentType, assignID: string, options?: | { filter_fields?: MetadataFilterField[]; } | Function | null, callback?: Function ) { // Shuffle optional arguments if (typeof options === 'function') { callback = options; options = null; } var apiPath = urlPath(ASSIGNMENTS_PATH), params = { body: { policy_id: policyID, assign_to: { type: assignType, id: assignID, }, }, }; Object.assign(params.body, options); return this.client.wrapWithDefaultHandler(this.client.post)( apiPath, params, callback ); } /** * Fetch a specific policy assignment * * API Endpoint: '/retention_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 ); } /** * Get the specific retention record for a retained file version. To use this feature, * you must have the manage retention policies scope enabled for your API key * via your application management console. * * API Endpoint: '/file_version_retentions/:retentionID' * Method: GET * * @param {string} retentionID - The ID for the file retention 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 retention record if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the retention record */ getFileVersionRetention( retentionID: string, options?: Record<string, any>, callback?: Function ) { var apiPath = urlPath(FILE_VERSION_RETENTIONS_PATH, retentionID), params = { qs: options, }; return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Get a list of retention records for a retained file versions in an enterprise. * To use this feature, you must have the manage retention policies scope enabled * for your API key via your application management console. * * API Endpoint: '/file_version_retentions' * Method: GET * * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {string} [options.file_id] - A file id to filter the file version retentions by * @param {string} [options.file_version_id] - A file version id to filter the file version retentions by * @param {string} [options.policy_id] - A policy id to filter the file version retentions by * @param {RetentionPolicyDispositionAction} [options.disposition_action] - The disposition action of the retention policy to filter by * @param {string} [options.disposition_before] - Filter by retention policies which will complete before a certain time * @param {string} [options.disposition_after] - Filter by retention policies which will complete after a certain time * @param {int} [options.limit] - The maximum number of items to return in a page * @param {string} [options.marker] - Paging marker, left blank to begin paging from the beginning * @param {Function} [callback] - Pass the file version retention record if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the collection of retention records */ getAllFileVersionRetentions( options?: { file_id?: string; file_version_id?: string; policy_id?: string; disposition_action?: RetentionPolicyDispositionAction; disposition_before?: string; disposition_after?: string; limit?: number; marker?: string; }, callback?: Function ) { var apiPath = urlPath(FILE_VERSION_RETENTIONS_PATH), params = { qs: options, }; return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Get files under retention by each assignment * To use this feature, you must have the manage retention policies scope enabled * for your API key via your application management console. * * API Endpoint: '/retention_policy_assignments/:assignmentID/files_under_retention' * 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 {int} [options.limit] - The maximum number of items to return in a page * @param {string} [options.marker] - Paging marker, left blank to begin paging from the beginning * @param {Function} [callback] - Pass the file version retention record if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the collection of retention records */ getFilesUnderRetentionForAssignment( assignmentID: string, options?: { limit?: number; marker?: string; }, callback?: Function ) { var apiPath = urlPath( ASSIGNMENTS_PATH, assignmentID, FILES_UNDER_RETENTION_SUBRESOURCE ), params = { qs: options, }; return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Get file versions under retention by each assignment * To use this feature, you must have the manage retention policies scope enabled * for your API key via your application management console. * * API Endpoint: '/retention_policy_assignments/:assignmentID/file_versions_under_retention' * 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 {int} [options.limit] - The maximum number of items to return in a page * @param {string} [options.marker] - Paging marker, left blank to begin paging from the beginning * @param {Function} [callback] - Pass the file version retention record if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the collection of retention records */ getFileVersionsUnderRetentionForAssignment( assignmentID: string, options?: { limit?: number; market?: string; }, callback?: Function ) { var apiPath = urlPath( ASSIGNMENTS_PATH, assignmentID, FILES_VERSIONS_UNDER_RETENTION_SUBRESOURCE ), params = { qs: options, }; return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } } /** * Enum of valid retention policy types, which specify how long the policy should * remain in effect. * @readonly * @enum {RetentionPolicyType} */ RetentionPolicies.prototype.policyTypes = RetentionPolicyType; /** * Enum of valid retention policy disposition actions, which specify what should * be done when the retention period is over * @readonly * @enum {RetentionPolicyDispositionAction} */ RetentionPolicies.prototype.dispositionActions = RetentionPolicyDispositionAction; /** * Enum of valid policy assignment types, which specify what object the policy applies to * @readonly * @enum {RetentionPolicyAssignmentType} */ RetentionPolicies.prototype.assignmentTypes = RetentionPolicyAssignmentType; export = RetentionPolicies;
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * SKU details */ export interface Sku { /** * SKU name to specify whether the key vault is a standard vault or a premium vault. Possible * values include: 'standard', 'premium' */ name: SkuName; } /** * Permissions the identity has for keys, secrets, certificates and storage. */ export interface Permissions { /** * Permissions to keys */ keys?: KeyPermissions[]; /** * Permissions to secrets */ secrets?: SecretPermissions[]; /** * Permissions to certificates */ certificates?: CertificatePermissions[]; /** * Permissions to storage accounts */ storage?: StoragePermissions[]; } /** * An identity that have access to the key vault. All identities in the array must use the same * tenant ID as the key vault's tenant ID. */ export interface AccessPolicyEntry { /** * The Azure Active Directory tenant ID that should be used for authenticating requests to the * key vault. */ tenantId: string; /** * The object ID of a user, service principal or security group in the Azure Active Directory * tenant for the vault. The object ID must be unique for the list of access policies. */ objectId: string; /** * Application ID of the client making request on behalf of a principal */ applicationId?: string; /** * Permissions the identity has for keys, secrets and certificates. */ permissions: Permissions; } /** * A rule governing the accessibility of a vault from a specific ip address or ip range. */ export interface IPRule { /** * An IPv4 address range in CIDR notation, such as '124.56.78.91' (simple IP address) or * '124.56.78.0/24' (all addresses that start with 124.56.78). */ value: string; } /** * A rule governing the accessibility of a vault from a specific virtual network. */ export interface VirtualNetworkRule { /** * Full resource id of a vnet subnet, such as * '/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/subnet1'. */ id: string; } /** * A set of rules governing the network accessibility of a vault. */ export interface NetworkRuleSet { /** * Tells what traffic can bypass network rules. This can be 'AzureServices' or 'None'. If not * specified the default is 'AzureServices'. Possible values include: 'AzureServices', 'None' */ bypass?: NetworkRuleBypassOptions; /** * The default action when no rule from ipRules and from virtualNetworkRules match. This is only * used after the bypass property has been evaluated. Possible values include: 'Allow', 'Deny' */ defaultAction?: NetworkRuleAction; /** * The list of IP address rules. */ ipRules?: IPRule[]; /** * The list of virtual network rules. */ virtualNetworkRules?: VirtualNetworkRule[]; } /** * Private endpoint object properties. */ export interface PrivateEndpoint { /** * Full identifier of the private endpoint resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; } /** * An object that represents the approval state of the private link connection. */ export interface PrivateLinkServiceConnectionState { /** * Indicates whether the connection has been approved, rejected or removed by the key vault * owner. Possible values include: 'Pending', 'Approved', 'Rejected', 'Disconnected' */ status?: PrivateEndpointServiceConnectionStatus; /** * The reason for approval or rejection. */ description?: string; /** * A message indicating if changes on the service provider require any updates on the consumer. */ actionRequired?: string; } /** * Private endpoint connection item. */ export interface PrivateEndpointConnectionItem { /** * Properties of the private endpoint object. */ privateEndpoint?: PrivateEndpoint; /** * Approval state of the private link connection. */ privateLinkServiceConnectionState?: PrivateLinkServiceConnectionState; /** * Provisioning state of the private endpoint connection. Possible values include: 'Succeeded', * 'Creating', 'Updating', 'Deleting', 'Failed', 'Disconnected' */ provisioningState?: PrivateEndpointConnectionProvisioningState; } /** * Properties of the vault */ export interface VaultProperties { /** * The Azure Active Directory tenant ID that should be used for authenticating requests to the * key vault. */ tenantId: string; /** * SKU details */ sku: Sku; /** * An array of 0 to 1024 identities that have access to the key vault. All identities in the * array must use the same tenant ID as the key vault's tenant ID. When `createMode` is set to * `recover`, access policies are not required. Otherwise, access policies are required. */ accessPolicies?: AccessPolicyEntry[]; /** * The URI of the vault for performing operations on keys and secrets. */ vaultUri?: string; /** * Property to specify whether Azure Virtual Machines are permitted to retrieve certificates * stored as secrets from the key vault. */ enabledForDeployment?: boolean; /** * Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the * vault and unwrap keys. */ enabledForDiskEncryption?: boolean; /** * Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the * key vault. */ enabledForTemplateDeployment?: boolean; /** * Property to specify whether the 'soft delete' functionality is enabled for this key vault. If * it's not set to any value(true or false) when creating new key vault, it will be set to true * by default. Once set to true, it cannot be reverted to false. Default value: true. */ enableSoftDelete?: boolean; /** * softDelete data retention days. It accepts >=7 and <=90. Default value: 90. */ softDeleteRetentionInDays?: number; /** * Property that controls how data actions are authorized. When true, the key vault will use Role * Based Access Control (RBAC) for authorization of data actions, and the access policies * specified in vault properties will be ignored (warning: this is a preview feature). When * false, the key vault will use the access policies specified in vault properties, and any * policy stored on Azure Resource Manager will be ignored. If null or not specified, the vault * is created with the default value of false. Note that management actions are always authorized * with RBAC. Default value: false. */ enableRbacAuthorization?: boolean; /** * The vault's create mode to indicate whether the vault need to be recovered or not. Possible * values include: 'recover', 'default' */ createMode?: CreateMode; /** * Property specifying whether protection against purge is enabled for this vault. Setting this * property to true activates protection against purge for this vault and its content - only the * Key Vault service may initiate a hard, irrecoverable deletion. The setting is effective only * if soft delete is also enabled. Enabling this functionality is irreversible - that is, the * property does not accept false as its value. */ enablePurgeProtection?: boolean; /** * Rules governing the accessibility of the key vault from specific network locations. */ networkAcls?: NetworkRuleSet; /** * List of private endpoint connections associated with the key vault. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly privateEndpointConnections?: PrivateEndpointConnectionItem[]; } /** * Properties of the vault */ export interface VaultPatchProperties { /** * The Azure Active Directory tenant ID that should be used for authenticating requests to the * key vault. */ tenantId?: string; /** * SKU details */ sku?: Sku; /** * An array of 0 to 16 identities that have access to the key vault. All identities in the array * must use the same tenant ID as the key vault's tenant ID. */ accessPolicies?: AccessPolicyEntry[]; /** * Property to specify whether Azure Virtual Machines are permitted to retrieve certificates * stored as secrets from the key vault. */ enabledForDeployment?: boolean; /** * Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the * vault and unwrap keys. */ enabledForDiskEncryption?: boolean; /** * Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the * key vault. */ enabledForTemplateDeployment?: boolean; /** * Property to specify whether the 'soft delete' functionality is enabled for this key vault. * Once set to true, it cannot be reverted to false. */ enableSoftDelete?: boolean; /** * Property that controls how data actions are authorized. When true, the key vault will use Role * Based Access Control (RBAC) for authorization of data actions, and the access policies * specified in vault properties will be ignored (warning: this is a preview feature). When * false, the key vault will use the access policies specified in vault properties, and any * policy stored on Azure Resource Manager will be ignored. If null or not specified, the value * of this property will not change. */ enableRbacAuthorization?: boolean; /** * softDelete data retention days. It accepts >=7 and <=90. */ softDeleteRetentionInDays?: number; /** * The vault's create mode to indicate whether the vault need to be recovered or not. Possible * values include: 'recover', 'default' */ createMode?: CreateMode; /** * Property specifying whether protection against purge is enabled for this vault. Setting this * property to true activates protection against purge for this vault and its content - only the * Key Vault service may initiate a hard, irrecoverable deletion. The setting is effective only * if soft delete is also enabled. Enabling this functionality is irreversible - that is, the * property does not accept false as its value. */ enablePurgeProtection?: boolean; /** * A collection of rules governing the accessibility of the vault from specific network * locations. */ networkAcls?: NetworkRuleSet; } /** * Properties of the vault access policy */ export interface VaultAccessPolicyProperties { /** * An array of 0 to 16 identities that have access to the key vault. All identities in the array * must use the same tenant ID as the key vault's tenant ID. */ accessPolicies: AccessPolicyEntry[]; } /** * Properties of the deleted vault. */ export interface DeletedVaultProperties { /** * The resource id of the original vault. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly vaultId?: string; /** * The location of the original vault. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly location?: string; /** * The deleted date. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly deletionDate?: Date; /** * The scheduled purged date. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly scheduledPurgeDate?: Date; /** * Tags of the original vault. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly tags?: { [propertyName: string]: string }; } /** * Parameters for creating or updating a vault */ export interface VaultCreateOrUpdateParameters extends BaseResource { /** * The supported Azure location where the key vault should be created. */ location: string; /** * The tags that will be assigned to the key vault. */ tags?: { [propertyName: string]: string }; /** * Properties of the vault */ properties: VaultProperties; } /** * Parameters for creating or updating a vault */ export interface VaultPatchParameters extends BaseResource { /** * The tags that will be assigned to the key vault. */ tags?: { [propertyName: string]: string }; /** * Properties of the vault */ properties?: VaultPatchProperties; } /** * Parameters for updating the access policy in a vault */ export interface VaultAccessPolicyParameters extends BaseResource { /** * The resource id of the access policy. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The resource name of the access policy. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The resource name of the access policy. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * The resource type of the access policy. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly location?: string; /** * Properties of the access policy */ properties: VaultAccessPolicyProperties; } /** * Resource information with extended details. */ export interface Vault extends BaseResource { /** * Fully qualified identifier of the key vault resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Name of the key vault resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Resource type of the key vault resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Azure location of the key vault resource. */ location?: string; /** * Tags assigned to the key vault resource. */ tags?: { [propertyName: string]: string }; /** * Properties of the vault */ properties: VaultProperties; } /** * Deleted vault information with extended details. */ export interface DeletedVault { /** * The resource ID for the deleted key vault. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The name of the key vault. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The resource type of the key vault. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Properties of the vault */ properties?: DeletedVaultProperties; } /** * Key Vault resource */ export interface Resource extends BaseResource { /** * Fully qualified identifier of the key vault resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Name of the key vault resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Resource type of the key vault resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Azure location of the key vault resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly location?: string; /** * Tags assigned to the key vault resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly tags?: { [propertyName: string]: string }; } /** * The parameters used to check the availability of the vault name. */ export interface VaultCheckNameAvailabilityParameters { /** * The vault name. */ name: string; } /** * The CheckNameAvailability operation response. */ export interface CheckNameAvailabilityResult { /** * A boolean value that indicates whether the name is available for you to use. If true, the name * is available. If false, the name has already been taken or is invalid and cannot be used. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nameAvailable?: boolean; /** * The reason that a vault name could not be used. The Reason element is only returned if * NameAvailable is false. Possible values include: 'AccountNameInvalid', 'AlreadyExists' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly reason?: Reason; /** * An error message explaining the Reason value in more detail. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly message?: string; } /** * Private endpoint connection resource. */ export interface PrivateEndpointConnection extends BaseResource { /** * Properties of the private endpoint object. */ privateEndpoint?: PrivateEndpoint; /** * Approval state of the private link connection. */ privateLinkServiceConnectionState?: PrivateLinkServiceConnectionState; /** * Provisioning state of the private endpoint connection. Possible values include: 'Succeeded', * 'Creating', 'Updating', 'Deleting', 'Failed', 'Disconnected' */ provisioningState?: PrivateEndpointConnectionProvisioningState; } /** * A private link resource */ export interface PrivateLinkResource extends Resource { /** * Group identifier of private link resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly groupId?: string; /** * Required member names of private link resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly requiredMembers?: string[]; /** * Required DNS zone names of the the private link resource. */ requiredZoneNames?: string[]; } /** * A list of private link resources */ export interface PrivateLinkResourceListResult { /** * Array of private link resources */ value?: PrivateLinkResource[]; } /** * Display metadata associated with the operation. */ export interface OperationDisplay { /** * Service provider: Microsoft Key Vault. */ provider?: string; /** * Resource on which the operation is performed etc. */ resource?: string; /** * Type of operation: get, read, delete, etc. */ operation?: string; /** * Description of operation. */ description?: string; } /** * Log specification of operation. */ export interface LogSpecification { /** * Name of log specification. */ name?: string; /** * Display name of log specification. */ displayName?: string; /** * Blob duration of specification. */ blobDuration?: string; } /** * One property of operation, include log specifications. */ export interface ServiceSpecification { /** * Log specifications of operation. */ logSpecifications?: LogSpecification[]; } /** * Key Vault REST API operation definition. */ export interface Operation { /** * Operation name: {provider}/{resource}/{operation} */ name?: string; /** * Display metadata associated with the operation. */ display?: OperationDisplay; /** * The origin of operations. */ origin?: string; /** * One property of operation, include metric specifications. */ serviceSpecification?: ServiceSpecification; } /** * The object attributes managed by the KeyVault service. */ export interface Attributes { /** * Determines whether the object is enabled. */ enabled?: boolean; /** * Not before date in seconds since 1970-01-01T00:00:00Z. */ notBefore?: Date; /** * Expiry date in seconds since 1970-01-01T00:00:00Z. */ expires?: Date; /** * Creation time in seconds since 1970-01-01T00:00:00Z. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly created?: Date; /** * Last updated time in seconds since 1970-01-01T00:00:00Z. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly updated?: Date; } /** * The secret management attributes. */ export interface SecretAttributes extends Attributes { } /** * Properties of the secret */ export interface SecretProperties { /** * The value of the secret. NOTE: 'value' will never be returned from the service, as APIs using * this model are is intended for internal use in ARM deployments. Users should use the * data-plane REST service for interaction with vault secrets. */ value?: string; /** * The content type of the secret. */ contentType?: string; /** * The attributes of the secret. */ attributes?: SecretAttributes; /** * The URI to retrieve the current version of the secret. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly secretUri?: string; /** * The URI to retrieve the specific version of the secret. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly secretUriWithVersion?: string; } /** * Properties of the secret */ export interface SecretPatchProperties { /** * The value of the secret. */ value?: string; /** * The content type of the secret. */ contentType?: string; /** * The attributes of the secret. */ attributes?: SecretAttributes; } /** * Parameters for creating or updating a secret */ export interface SecretCreateOrUpdateParameters extends BaseResource { /** * The tags that will be assigned to the secret. */ tags?: { [propertyName: string]: string }; /** * Properties of the secret */ properties: SecretProperties; } /** * Parameters for patching a secret */ export interface SecretPatchParameters extends BaseResource { /** * The tags that will be assigned to the secret. */ tags?: { [propertyName: string]: string }; /** * Properties of the secret */ properties?: SecretPatchProperties; } /** * Resource information with extended details. */ export interface Secret extends Resource { /** * Properties of the secret */ properties: SecretProperties; } /** * Optional Parameters. */ export interface VaultsListByResourceGroupOptionalParams extends msRest.RequestOptionsBase { /** * Maximum number of results to return. */ top?: number; } /** * Optional Parameters. */ export interface VaultsListBySubscriptionOptionalParams extends msRest.RequestOptionsBase { /** * Maximum number of results to return. */ top?: number; } /** * Optional Parameters. */ export interface VaultsListOptionalParams extends msRest.RequestOptionsBase { /** * Maximum number of results to return. */ top?: number; } /** * Optional Parameters. */ export interface SecretsListOptionalParams extends msRest.RequestOptionsBase { /** * Maximum number of results to return. */ top?: number; } /** * An interface representing KeyVaultManagementClientOptions. */ export interface KeyVaultManagementClientOptions extends AzureServiceClientOptions { baseUri?: string; } /** * Defines headers for Put operation. */ export interface PrivateEndpointConnectionsPutHeaders { /** * (specified only if operation does not finish synchronously) The recommended number of seconds * to wait before calling the URI specified in Azure-AsyncOperation. */ retryAfter: number; /** * (specified only if operation does not finish synchronously) The URI to poll for completion * status. The response of this URI may be synchronous or asynchronous. */ azureAsyncOperation: string; } /** * Defines headers for Delete operation. */ export interface PrivateEndpointConnectionsDeleteHeaders { /** * The recommended number of seconds to wait before calling the URI specified in the location * header. */ retryAfter: number; /** * The URI to poll for completion status. */ locationHeader: string; } /** * @interface * List of vaults * @extends Array<Vault> */ export interface VaultListResult extends Array<Vault> { /** * The URL to get the next set of vaults. */ nextLink?: string; } /** * @interface * List of vaults * @extends Array<DeletedVault> */ export interface DeletedVaultListResult extends Array<DeletedVault> { /** * The URL to get the next set of deleted vaults. */ nextLink?: string; } /** * @interface * List of vault resources. * @extends Array<Resource> */ export interface ResourceListResult extends Array<Resource> { /** * The URL to get the next set of vault resources. */ nextLink?: string; } /** * @interface * Result of the request to list Storage operations. It contains a list of operations and a URL * link to get the next set of results. * @extends Array<Operation> */ export interface OperationListResult extends Array<Operation> { /** * The URL to get the next set of operations. */ nextLink?: string; } /** * @interface * List of secrets * @extends Array<Secret> */ export interface SecretListResult extends Array<Secret> { /** * The URL to get the next set of secrets. */ nextLink?: string; } /** * Defines values for SkuName. * Possible values include: 'standard', 'premium' * @readonly * @enum {string} */ export type SkuName = 'standard' | 'premium'; /** * Defines values for KeyPermissions. * Possible values include: 'all', 'encrypt', 'decrypt', 'wrapKey', 'unwrapKey', 'sign', 'verify', * 'get', 'list', 'create', 'update', 'import', 'delete', 'backup', 'restore', 'recover', 'purge' * @readonly * @enum {string} */ export type KeyPermissions = 'all' | 'encrypt' | 'decrypt' | 'wrapKey' | 'unwrapKey' | 'sign' | 'verify' | 'get' | 'list' | 'create' | 'update' | 'import' | 'delete' | 'backup' | 'restore' | 'recover' | 'purge'; /** * Defines values for SecretPermissions. * Possible values include: 'all', 'get', 'list', 'set', 'delete', 'backup', 'restore', 'recover', * 'purge' * @readonly * @enum {string} */ export type SecretPermissions = 'all' | 'get' | 'list' | 'set' | 'delete' | 'backup' | 'restore' | 'recover' | 'purge'; /** * Defines values for CertificatePermissions. * Possible values include: 'all', 'get', 'list', 'delete', 'create', 'import', 'update', * 'managecontacts', 'getissuers', 'listissuers', 'setissuers', 'deleteissuers', 'manageissuers', * 'recover', 'purge', 'backup', 'restore' * @readonly * @enum {string} */ export type CertificatePermissions = 'all' | 'get' | 'list' | 'delete' | 'create' | 'import' | 'update' | 'managecontacts' | 'getissuers' | 'listissuers' | 'setissuers' | 'deleteissuers' | 'manageissuers' | 'recover' | 'purge' | 'backup' | 'restore'; /** * Defines values for StoragePermissions. * Possible values include: 'all', 'get', 'list', 'delete', 'set', 'update', 'regeneratekey', * 'recover', 'purge', 'backup', 'restore', 'setsas', 'listsas', 'getsas', 'deletesas' * @readonly * @enum {string} */ export type StoragePermissions = 'all' | 'get' | 'list' | 'delete' | 'set' | 'update' | 'regeneratekey' | 'recover' | 'purge' | 'backup' | 'restore' | 'setsas' | 'listsas' | 'getsas' | 'deletesas'; /** * Defines values for CreateMode. * Possible values include: 'recover', 'default' * @readonly * @enum {string} */ export type CreateMode = 'recover' | 'default'; /** * Defines values for NetworkRuleBypassOptions. * Possible values include: 'AzureServices', 'None' * @readonly * @enum {string} */ export type NetworkRuleBypassOptions = 'AzureServices' | 'None'; /** * Defines values for NetworkRuleAction. * Possible values include: 'Allow', 'Deny' * @readonly * @enum {string} */ export type NetworkRuleAction = 'Allow' | 'Deny'; /** * Defines values for PrivateEndpointServiceConnectionStatus. * Possible values include: 'Pending', 'Approved', 'Rejected', 'Disconnected' * @readonly * @enum {string} */ export type PrivateEndpointServiceConnectionStatus = 'Pending' | 'Approved' | 'Rejected' | 'Disconnected'; /** * Defines values for PrivateEndpointConnectionProvisioningState. * Possible values include: 'Succeeded', 'Creating', 'Updating', 'Deleting', 'Failed', * 'Disconnected' * @readonly * @enum {string} */ export type PrivateEndpointConnectionProvisioningState = 'Succeeded' | 'Creating' | 'Updating' | 'Deleting' | 'Failed' | 'Disconnected'; /** * Defines values for Reason. * Possible values include: 'AccountNameInvalid', 'AlreadyExists' * @readonly * @enum {string} */ export type Reason = 'AccountNameInvalid' | 'AlreadyExists'; /** * Defines values for AccessPolicyUpdateKind. * Possible values include: 'add', 'replace', 'remove' * @readonly * @enum {string} */ export type AccessPolicyUpdateKind = 'add' | 'replace' | 'remove'; /** * Contains response data for the createOrUpdate operation. */ export type VaultsCreateOrUpdateResponse = Vault & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Vault; }; }; /** * Contains response data for the update operation. */ export type VaultsUpdateResponse = Vault & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Vault; }; }; /** * Contains response data for the get operation. */ export type VaultsGetResponse = Vault & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Vault; }; }; /** * Contains response data for the updateAccessPolicy operation. */ export type VaultsUpdateAccessPolicyResponse = VaultAccessPolicyParameters & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: VaultAccessPolicyParameters; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type VaultsListByResourceGroupResponse = VaultListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: VaultListResult; }; }; /** * Contains response data for the listBySubscription operation. */ export type VaultsListBySubscriptionResponse = VaultListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: VaultListResult; }; }; /** * Contains response data for the listDeleted operation. */ export type VaultsListDeletedResponse = DeletedVaultListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DeletedVaultListResult; }; }; /** * Contains response data for the getDeleted operation. */ export type VaultsGetDeletedResponse = DeletedVault & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DeletedVault; }; }; /** * Contains response data for the list operation. */ export type VaultsListResponse = ResourceListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ResourceListResult; }; }; /** * Contains response data for the checkNameAvailability operation. */ export type VaultsCheckNameAvailabilityResponse = CheckNameAvailabilityResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CheckNameAvailabilityResult; }; }; /** * Contains response data for the beginCreateOrUpdate operation. */ export type VaultsBeginCreateOrUpdateResponse = Vault & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Vault; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type VaultsListByResourceGroupNextResponse = VaultListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: VaultListResult; }; }; /** * Contains response data for the listBySubscriptionNext operation. */ export type VaultsListBySubscriptionNextResponse = VaultListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: VaultListResult; }; }; /** * Contains response data for the listDeletedNext operation. */ export type VaultsListDeletedNextResponse = DeletedVaultListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DeletedVaultListResult; }; }; /** * Contains response data for the listNext operation. */ export type VaultsListNextResponse = ResourceListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ResourceListResult; }; }; /** * Contains response data for the get operation. */ export type PrivateEndpointConnectionsGetResponse = PrivateEndpointConnection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PrivateEndpointConnection; }; }; /** * Contains response data for the put operation. */ export type PrivateEndpointConnectionsPutResponse = PrivateEndpointConnection & PrivateEndpointConnectionsPutHeaders & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The parsed HTTP response headers. */ parsedHeaders: PrivateEndpointConnectionsPutHeaders; /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PrivateEndpointConnection; }; }; /** * Contains response data for the deleteMethod operation. */ export type PrivateEndpointConnectionsDeleteResponse = PrivateEndpointConnection & PrivateEndpointConnectionsDeleteHeaders & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The parsed HTTP response headers. */ parsedHeaders: PrivateEndpointConnectionsDeleteHeaders; /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PrivateEndpointConnection; }; }; /** * Contains response data for the listByVault operation. */ export type PrivateLinkResourcesListByVaultResponse = PrivateLinkResourceListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PrivateLinkResourceListResult; }; }; /** * Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the createOrUpdate operation. */ export type SecretsCreateOrUpdateResponse = Secret & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Secret; }; }; /** * Contains response data for the update operation. */ export type SecretsUpdateResponse = Secret & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Secret; }; }; /** * Contains response data for the get operation. */ export type SecretsGetResponse = Secret & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Secret; }; }; /** * Contains response data for the list operation. */ export type SecretsListResponse = SecretListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SecretListResult; }; }; /** * Contains response data for the listNext operation. */ export type SecretsListNextResponse = SecretListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SecretListResult; }; };
the_stack
import * as utils from '../src/util'; import * as service from '../src/service'; import * as embed from '../src/embed'; import * as report from '../src/report'; import * as page from '../src/page'; import * as Hpm from 'http-post-message'; import * as models from 'powerbi-models'; import * as factories from '../src/factories'; import * as util from '../src/util'; import { spyApp, setupEmbedMockApp } from './utility/mockEmbed'; import { logMessages, iframeSrc } from './constsants'; describe('SDK-to-MockApp', function () { let element: HTMLDivElement; let iframe: HTMLIFrameElement; let iframeHpm: Hpm.HttpPostMessage; let powerbi: service.Service; let report: report.Report; let page1: page.Page; const embedConfiguration: embed.IEmbedConfiguration = { type: "report", id: "fakeReportIdInitialEmbed", accessToken: 'fakeTokenInitialEmbed', embedUrl: iframeSrc }; beforeEach(async function () { powerbi = new service.Service(factories.hpmFactory, factories.wpmpFactory, factories.routerFactory, { wpmpName: 'SDK-to-MockApp HostWpmp', logMessages }); element = document.createElement('div'); element.id = "reportContainer1"; element.className = 'powerbi-report-container2'; document.body.appendChild(element); report = <report.Report>powerbi.embed(element, embedConfiguration); page1 = report.page('ReportSection1'); iframe = element.getElementsByTagName('iframe')[0]; /** * Note: For testing we need to configure the eventSourceOverrideWindow to allow the host to respond to * the iframe window; however, the iframe window doesn't exist until the first embed is created. * * To work around this we create a service for the initial embed, embed a report, then set the private variable */ (<any>powerbi.wpmp).eventSourceOverrideWindow = iframe.contentWindow; // Register Iframe side let hpmPostSpy = spyOn(powerbi.hpm, "post").and.returnValue(Promise.resolve(<any>{})); iframeHpm = setupEmbedMockApp(iframe.contentWindow, window, logMessages, 'SDK-to-MockApp IframeWpmp'); await new Promise<void>((resolve, _reject) => { iframe.addEventListener('load', () => { resolve(null); }); }); hpmPostSpy.and.callThrough(); }); afterEach(function () { powerbi.reset(element); element.remove(); powerbi.wpmp?.stop(); spyApp.reset(); }); describe('report', function () { beforeEach(function () { spyOn(utils, "getTimeDiffInMilliseconds").and.callFake(() => 700); // Prevent requests from being throttled. }); describe('load', function () { it('report.load() returns promise that resolves with null if the report load successful', async function () { try { const response = await report.load(undefined); // Assert expect(response).toEqual({} as any); } catch (error) { fail("lod shouldn't fail"); } }); }); describe('pages', function () { it('report.getPages() return promise that rejects with server error if there was error getting pages', async function () { // Arrange const testData = { expectedError: { message: 'internal server error' } }; try { spyApp.getPages.and.callFake(() => Promise.reject(testData.expectedError)); // Act await report.getPages(); fail("getPagesshouldn't succeed"); } catch (error) { // Assert expect(spyApp.getPages).toHaveBeenCalled(); expect(error).toEqual(jasmine.objectContaining(testData.expectedError)); } }); it('report.getPages() returns promise that resolves with list of page names', async function () { // Arrange const testData = { pages: [ { name: "page1", displayName: "Page 1", isActive: true } ] }; try { spyApp.getPages.and.returnValue(Promise.resolve(testData.pages)); const pages = await report.getPages(); // Assert expect(spyApp.getPages).toHaveBeenCalled(); // Workaround to compare pages pages.forEach(page => { const testPage = util.find(p => p.name === page.name, testData.pages); if (testPage) { expect(page.name).toEqual(testPage.name); expect(page.isActive).toEqual(testPage.isActive); } else { expect(true).toBe(false); } }); } catch (error) { console.log("getPages failed with", error); fail("getPages failed"); } }); }); describe('filters', function () { it('report.getFilters() returns promise that rejects with server error if there was problem getting filters', async function () { // Arrange const testData = { expectedError: { message: 'could not serialize filters' } }; try { spyApp.getFilters.and.callFake(() => Promise.reject(testData.expectedError)); await report.getFilters(); fail("getFilters shouldn't succeed"); } catch (error) { // Assert expect(spyApp.getFilters).toHaveBeenCalled(); expect(error).toEqual(jasmine.objectContaining(testData.expectedError)); } }); it('report.getFilters() returns promise that resolves with filters is request is successful', async function () { // Arrange const testData = { filters: [ { x: 'fakeFilter' } ] }; spyApp.getFilters.and.returnValue(Promise.resolve(testData.filters)); try { // Act const filters = await report.getFilters(); // Assert expect(spyApp.getFilters).toHaveBeenCalled(); // @ts-ignore as testData is not of type IFilter expect(filters).toEqual(testData.filters); } catch (error) { fail("get filtershousln't fails"); } }); it('report.setFilters(filters) returns promise that rejects with validation errors if filter is invalid', async function () { // Arrange const testData = { filters: [ (new models.BasicFilter({ table: "cars", column: "make" }, "In", ["subaru", "honda"])).toJSON() ], expectedErrors: [ { message: 'invalid filter' } ] }; spyApp.validateFilter.and.callFake(() => Promise.reject(testData.expectedErrors)); try { // Act await report.setFilters(testData.filters); fail("et filter should fail"); } catch (error) { // Assert expect(spyApp.validateFilter).toHaveBeenCalledWith(testData.filters[0]); expect(spyApp.setFilters).not.toHaveBeenCalled(); expect(error).toEqual(jasmine.objectContaining(testData.expectedErrors)); } }); it('report.setFilters(filters) returns promise that resolves with null if filter was valid and request is accepted', async function () { // Arrange const testData = { filters: [(new models.BasicFilter({ table: "cars", column: "make" }, "In", ["subaru", "honda"])).toJSON()] }; spyApp.validateFilter.and.returnValue(Promise.resolve(null)); spyApp.setFilters.and.returnValue(Promise.resolve(null)); try { // Act await report.setFilters(testData.filters); expect(spyApp.validateFilter).toHaveBeenCalledWith(testData.filters[0]); expect(spyApp.setFilters).toHaveBeenCalledWith(testData.filters); } catch (error) { fail("why fail"); } }); it('report.removeFilters() returns promise that resolves with null if the request was accepted', async function () { // Arrange let spy = spyOn(report, 'updateFilters').and.callFake(() => Promise.resolve(null)); try { // Act await report.removeFilters(); // Assert expect(spy).toHaveBeenCalledWith(models.FiltersOperations.RemoveAll); } catch (error) { fail("remove fialter shouldn't fail"); } }); }); describe('print', function () { it('report.print() returns promise that resolves with null if the report print command was accepted', async function () { // Arrange spyApp.print.and.returnValue(Promise.resolve({})); // Act const response = await report.print(); // Assert expect(spyApp.print).toHaveBeenCalled(); expect(response).toEqual(); }); }); describe('refresh', function () { it('report.refresh() returns promise that resolves with null if the report refresh command was accepted', async function () { // Arrange spyApp.refreshData.and.returnValue(Promise.resolve(null)); // Act const response = await report.refresh(); // Assert expect(spyApp.refreshData).toHaveBeenCalled(); expect(response).toEqual(undefined); }); }); describe('settings', function () { it('report.updateSettings(setting) returns promise that rejects with validation error if object is invalid', async function () { // Arrange const testData = { settings: { filterPaneEnabled: false }, expectedErrors: [ { message: 'invalid target' } ] }; spyApp.validateSettings.and.callFake(() => Promise.reject(testData.expectedErrors)); try { // Act await report.updateSettings(testData.settings); fail("shouldfail"); } catch (errors) { // Assert expect(spyApp.validateSettings).toHaveBeenCalledWith(testData.settings); expect(spyApp.updateSettings).not.toHaveBeenCalled(); expect(errors).toEqual(jasmine.objectContaining(testData.expectedErrors)); } }); it('report.updateSettings(settings) returns promise that resolves with null if requst is valid and accepted', async function () { // Arrange const testData = { settings: { filterPaneEnabled: false }, expectedErrors: [ { message: 'invalid target' } ] }; try { spyApp.validateSettings.and.returnValue(Promise.resolve(null)); spyApp.updateSettings.and.returnValue(Promise.resolve(null)); // Act await report.updateSettings(testData.settings); // Assert expect(spyApp.validateSettings).toHaveBeenCalledWith(testData.settings); expect(spyApp.updateSettings).toHaveBeenCalledWith(testData.settings); } catch (error) { console.log("updateSettings failed with", error); fail("updateSettings failed"); } }); }); describe('page', function () { describe('filters', function () { beforeEach(() => { spyApp.validatePage.and.returnValue(Promise.resolve(null)); }); it('page.getFilters() returns promise that rejects with server error if there was problem getting filters', async function () { // Arrange const testData = { expectedError: { message: 'could not serialize filters' } }; try { spyApp.getFilters.and.callFake(() => Promise.reject(testData.expectedError)); await page1.getFilters(); } catch (error) { // Assert expect(spyApp.getFilters).toHaveBeenCalled(); expect(error).toEqual(jasmine.objectContaining(testData.expectedError)); } }); it('page.getFilters() returns promise that resolves with filters is request is successful', async function () { // Arrange const testData = { filters: [ { x: 'fakeFilter' } ] }; try { spyApp.getFilters.and.returnValue(Promise.resolve(testData.filters)); const filters = await page1.getFilters(); // Assert expect(spyApp.getFilters).toHaveBeenCalled(); // @ts-ignore as testData is not of type IFilter as testData is not of type IFilter expect(filters).toEqual(testData.filters); } catch (error) { fail("getFilters shouldn't fail"); } }); it('page.setFilters(filters) returns promise that rejects with validation errors if filter is invalid', async function () { // Arrange const testData = { filters: [ (new models.BasicFilter({ table: "cars", column: "make" }, "In", ["subaru", "honda"])).toJSON() ], expectedErrors: [ { message: 'invalid filter' } ] }; // await iframeLoaded; try { spyApp.validateFilter.and.callFake(() => Promise.reject(testData.expectedErrors)); await page1.setFilters(testData.filters); fail("setilters shouldn't fail"); } catch (error) { expect(spyApp.validateFilter).toHaveBeenCalledWith(testData.filters[0]); expect(spyApp.setFilters).not.toHaveBeenCalled(); expect(error).toEqual(jasmine.objectContaining(testData.expectedErrors)); } }); it('page.setFilters(filters) returns promise that resolves with null if filter was valid and request is accepted', async function () { // Arrange const testData = { filters: [(new models.BasicFilter({ table: "cars", column: "make" }, "In", ["subaru", "honda"])).toJSON()] }; spyApp.validateFilter.and.returnValue(Promise.resolve(null)); spyApp.setFilters.and.returnValue(Promise.resolve(null)); try { await page1.setFilters(testData.filters); expect(spyApp.validateFilter).toHaveBeenCalledWith(testData.filters[0]); expect(spyApp.setFilters).toHaveBeenCalledWith(testData.filters); } catch (error) { console.log("setFilters failed with", error); fail("setilters failed"); } }); it('page.removeFilters() returns promise that resolves with null if the request was accepted', async function () { // Arrange try { spyApp.updateFilters.and.returnValue(Promise.resolve(null)); // Act await page1.removeFilters(); } catch (error) { console.log("removeFilters failed with", error); fail("removeFilters failed"); } // Assert expect(spyApp.updateFilters).toHaveBeenCalledWith(models.FiltersOperations.RemoveAll, undefined); }); describe('setActive', function () { it('page.setActive() returns promise that rejects if page is invalid', async function () { // Arrange const testData = { errors: [ { message: 'page xyz was not found in report' } ] }; spyApp.validatePage.and.callFake(() => Promise.reject(testData.errors)); try { // Act await page1.setActive(); fail("setActive shouldn't succeed"); } catch (errors) { expect(spyApp.validatePage).toHaveBeenCalled(); expect(spyApp.setPage).not.toHaveBeenCalled(); expect(errors).toEqual(jasmine.objectContaining(testData.errors)); } spyApp.validatePage.and.callThrough(); }); it('page.setActive() returns promise that resolves with null if request is successful', async function () { // Act spyApp.validatePage.and.returnValue(Promise.resolve(null)); spyApp.setPage.and.returnValue(Promise.resolve(null)); try { await page1.setActive(); expect(spyApp.validatePage).toHaveBeenCalled(); expect(spyApp.setPage).toHaveBeenCalled(); } catch (error) { console.log("setActive failed with ", error); fail("setActive failed"); } }); }); }); }); describe('SDK-to-Router (Event subscription)', function () { it(`report.on(eventName, handler) should throw error if eventName is not supported`, function () { // Arrange const testData = { eventName: 'xyz', handler: jasmine.createSpy('handler') }; try { report.on(testData.eventName, testData.handler); fail("should throw exception"); } catch (error) { expect(1).toEqual(1); } }); it(`report.on(eventName, handler) should register handler and be called when POST /report/:uniqueId/events/:eventName is received`, async function () { // Arrange const testData = { reportId: 'fakeReportId', eventName: 'pageChanged', handler: jasmine.createSpy('handler'), simulatedPageChangeBody: { initiator: 'sdk', newPage: { name: 'page1', displayName: 'Page 1' } }, expectedEvent: { detail: { initiator: 'sdk', newPage: report.page('page1') } } }; report.on(testData.eventName, testData.handler); try { // Act await iframeHpm.post(`/reports/${report.config.uniqueId}/events/${testData.eventName}`, testData.simulatedPageChangeBody); } catch (error) { fail("testshouldn't fail"); } // Assert expect(testData.handler).toHaveBeenCalledWith(jasmine.any(CustomEvent)); // Workaround to compare pages which prevents recursive loop in jasmine equals // expect(testData.handler2).toHaveBeenCalledWith(jasmine.objectContaining({ detail: testData.simulatedPageChangeBody })); expect(testData.handler.calls.mostRecent().args[0].detail.newPage.name).toEqual(testData.expectedEvent.detail.newPage.name); }); it(`if multiple reports with the same id are loaded into the host, and event occurs on one of them, only one report handler should be called`, async function () { // Arrange const testData = { reportId: 'fakeReportId', eventName: 'pageChanged', handler: jasmine.createSpy('handler'), handler2: jasmine.createSpy('handler2'), simulatedPageChangeBody: { initiator: 'sdk', newPage: { name: 'page1', displayName: 'Page 1' } } }; // Create a second iframe and report const element2 = document.createElement('div'); element2.id = "reportContainer2"; element2.className = 'powerbi-report-container3'; document.body.appendChild(element2); const report2 = <report.Report>powerbi.embed(element2, embedConfiguration); const iframe2 = element2.getElementsByTagName('iframe')[0]; setupEmbedMockApp(iframe2.contentWindow, window, logMessages, 'SDK-to-MockApp IframeWpmp2'); await new Promise<void>((resolve, _reject) => { iframe2.addEventListener('load', () => { resolve(null); }); }); report.on(testData.eventName, testData.handler); report2.on(testData.eventName, testData.handler2); try { await iframeHpm.post(`/reports/${report2.config.uniqueId}/events/${testData.eventName}`, testData.simulatedPageChangeBody); } catch (error) { powerbi.reset(element2); element2.remove(); fail("hpm post shouldn't fail"); } // Act expect(testData.handler).not.toHaveBeenCalled(); expect(testData.handler2).toHaveBeenCalledWith(jasmine.any(CustomEvent)); // Workaround to compare pages which prevents recursive loop in jasmine equals // expect(testData.handler).toHaveBeenCalledWith(jasmine.objectContaining(testData.expectedEvent)); expect(testData.handler2.calls.mostRecent().args[0].detail.newPage.name).toEqual(testData.simulatedPageChangeBody.newPage.name); powerbi.reset(element2); element2.remove(); }); it(`ensure load event is allowed`, async function () { // Arrange const testData = { reportId: 'fakeReportId', eventName: 'loaded', handler: jasmine.createSpy('handler3'), simulatedBody: { initiator: 'sdk' } }; report.on(testData.eventName, testData.handler); // Act try { await iframeHpm.post(`/reports/${report.config.uniqueId}/events/${testData.eventName}`, testData.simulatedBody); } catch (error) { fail("ensure load event is allowed failed"); } // Assert expect(testData.handler).toHaveBeenCalledWith(jasmine.any(CustomEvent)); expect(testData.handler).toHaveBeenCalledWith(jasmine.objectContaining({ detail: testData.simulatedBody })); }); }); }); });
the_stack
import { CloudErrorMapper, BaseResourceMapper } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export const CloudError = CloudErrorMapper; export const BaseResource = BaseResourceMapper; export const ClusterNode: msRest.CompositeMapper = { serializedName: "ClusterNode", type: { name: "Composite", className: "ClusterNode", modelProperties: { name: { readOnly: true, serializedName: "name", type: { name: "String" } }, id: { readOnly: true, serializedName: "id", type: { name: "Number" } }, manufacturer: { readOnly: true, serializedName: "manufacturer", type: { name: "String" } }, model: { readOnly: true, serializedName: "model", type: { name: "String" } }, osName: { readOnly: true, serializedName: "osName", type: { name: "String" } }, osVersion: { readOnly: true, serializedName: "osVersion", type: { name: "String" } }, serialNumber: { readOnly: true, serializedName: "serialNumber", type: { name: "String" } }, coreCount: { readOnly: true, serializedName: "coreCount", type: { name: "Number" } }, memoryInGiB: { readOnly: true, serializedName: "memoryInGiB", type: { name: "Number" } } } } }; export const ClusterReportedProperties: msRest.CompositeMapper = { serializedName: "ClusterReportedProperties", type: { name: "Composite", className: "ClusterReportedProperties", modelProperties: { clusterName: { readOnly: true, serializedName: "clusterName", type: { name: "String" } }, clusterId: { readOnly: true, serializedName: "clusterId", type: { name: "String" } }, clusterVersion: { readOnly: true, serializedName: "clusterVersion", type: { name: "String" } }, nodes: { readOnly: true, serializedName: "nodes", type: { name: "Sequence", element: { type: { name: "Composite", className: "ClusterNode" } } } }, lastUpdated: { readOnly: true, serializedName: "lastUpdated", type: { name: "DateTime" } } } } }; export const Resource: msRest.CompositeMapper = { serializedName: "Resource", type: { name: "Composite", className: "Resource", modelProperties: { id: { readOnly: true, serializedName: "id", type: { name: "String" } }, name: { readOnly: true, serializedName: "name", type: { name: "String" } }, type: { readOnly: true, serializedName: "type", type: { name: "String" } } } } }; export const TrackedResource: msRest.CompositeMapper = { serializedName: "TrackedResource", type: { name: "Composite", className: "TrackedResource", modelProperties: { ...Resource.type.modelProperties, tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } }, location: { required: true, serializedName: "location", type: { name: "String" } } } } }; export const Cluster: msRest.CompositeMapper = { serializedName: "Cluster", type: { name: "Composite", className: "Cluster", modelProperties: { ...TrackedResource.type.modelProperties, provisioningState: { readOnly: true, serializedName: "properties.provisioningState", type: { name: "String" } }, status: { readOnly: true, serializedName: "properties.status", type: { name: "String" } }, cloudId: { readOnly: true, serializedName: "properties.cloudId", type: { name: "String" } }, aadClientId: { required: true, serializedName: "properties.aadClientId", type: { name: "String" } }, aadTenantId: { required: true, serializedName: "properties.aadTenantId", type: { name: "String" } }, reportedProperties: { serializedName: "properties.reportedProperties", type: { name: "Composite", className: "ClusterReportedProperties" } }, trialDaysRemaining: { readOnly: true, serializedName: "properties.trialDaysRemaining", type: { name: "Number" } }, billingModel: { readOnly: true, serializedName: "properties.billingModel", type: { name: "String" } }, registrationTimestamp: { readOnly: true, serializedName: "properties.registrationTimestamp", type: { name: "DateTime" } }, lastSyncTimestamp: { readOnly: true, serializedName: "properties.lastSyncTimestamp", type: { name: "DateTime" } }, lastBillingTimestamp: { readOnly: true, serializedName: "properties.lastBillingTimestamp", type: { name: "DateTime" } } } } }; export const ClusterUpdate: msRest.CompositeMapper = { serializedName: "ClusterUpdate", type: { name: "Composite", className: "ClusterUpdate", modelProperties: { tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } } } } }; export const OperationDisplay: msRest.CompositeMapper = { serializedName: "OperationDisplay", type: { name: "Composite", className: "OperationDisplay", modelProperties: { provider: { serializedName: "provider", type: { name: "String" } }, resource: { serializedName: "resource", type: { name: "String" } }, operation: { serializedName: "operation", type: { name: "String" } }, description: { serializedName: "description", type: { name: "String" } } } } }; export const OperationDetail: msRest.CompositeMapper = { serializedName: "OperationDetail", type: { name: "Composite", className: "OperationDetail", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, isDataAction: { serializedName: "isDataAction", type: { name: "Boolean" } }, display: { serializedName: "display", type: { name: "Composite", className: "OperationDisplay" } }, origin: { serializedName: "origin", type: { name: "String" } }, properties: { serializedName: "properties", type: { name: "Object" } } } } }; export const AvailableOperations: msRest.CompositeMapper = { serializedName: "AvailableOperations", type: { name: "Composite", className: "AvailableOperations", modelProperties: { value: { serializedName: "value", type: { name: "Sequence", element: { type: { name: "Composite", className: "OperationDetail" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } }; export const ProxyResource: msRest.CompositeMapper = { serializedName: "ProxyResource", type: { name: "Composite", className: "ProxyResource", modelProperties: { ...Resource.type.modelProperties } } }; export const AzureEntityResource: msRest.CompositeMapper = { serializedName: "AzureEntityResource", type: { name: "Composite", className: "AzureEntityResource", modelProperties: { ...Resource.type.modelProperties, etag: { readOnly: true, serializedName: "etag", type: { name: "String" } } } } }; export const ErrorAdditionalInfo: msRest.CompositeMapper = { serializedName: "ErrorAdditionalInfo", type: { name: "Composite", className: "ErrorAdditionalInfo", modelProperties: { type: { readOnly: true, serializedName: "type", type: { name: "String" } }, info: { readOnly: true, serializedName: "info", type: { name: "Object" } } } } }; export const ErrorResponseError: msRest.CompositeMapper = { serializedName: "ErrorResponse_error", type: { name: "Composite", className: "ErrorResponseError", modelProperties: { code: { readOnly: true, serializedName: "code", type: { name: "String" } }, message: { readOnly: true, serializedName: "message", type: { name: "String" } }, target: { readOnly: true, serializedName: "target", type: { name: "String" } }, details: { readOnly: true, serializedName: "details", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorResponse" } } } }, additionalInfo: { readOnly: true, serializedName: "additionalInfo", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorAdditionalInfo" } } } } } } }; export const ErrorResponse: msRest.CompositeMapper = { serializedName: "ErrorResponse", type: { name: "Composite", className: "ErrorResponse", modelProperties: { error: { serializedName: "error", type: { name: "Composite", className: "ErrorResponseError" } } } } }; export const ClusterList: msRest.CompositeMapper = { serializedName: "ClusterList", type: { name: "Composite", className: "ClusterList", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "Cluster" } } } }, nextLink: { readOnly: true, serializedName: "nextLink", type: { name: "String" } } } } };
the_stack
import { TokenFactory, ERC721ExchangeV0, ERC1155ExchangeV0, SocialTokenV0, ERC721Mock, ERC1155Mock, ERC20Mock, NFT1155V2, NFT721V1, } from "./typechain"; import { getMint1155Digest, getMint721Digest, getPark721Digest, getMintSocialTokenDigest, sign, } from "./utils/sign-utils"; import { ethers } from "hardhat"; import { expect, assert } from "chai"; const { constants } = ethers; const { AddressZero } = constants; ethers.utils.Logger.setLogLevel(ethers.utils.Logger.levels.ERROR); // turn off warnings const setupTest = async () => { const signers = await ethers.getSigners(); const [deployer, protocolVault, operationalVault, alice, bob, carol] = signers; const TokenFactoryContract = await ethers.getContractFactory("TokenFactory"); const factory = (await TokenFactoryContract.deploy( protocolVault.address, 25, operationalVault.address, 5, "https://nft721.sushi.com/", "https://nft1155.sushi.com/" )) as TokenFactory; const ERC721ExchangeContract = await ethers.getContractFactory("ERC721ExchangeV0"); const erc721Exchange = (await ERC721ExchangeContract.deploy(factory.address)) as ERC721ExchangeV0; const ERC1155ExchangeContract = await ethers.getContractFactory("ERC1155ExchangeV0"); const erc1155Exchange = (await ERC1155ExchangeContract.deploy(factory.address)) as ERC1155ExchangeV0; const NFT721Contract = await ethers.getContractFactory("NFT721V1"); const nft721 = (await NFT721Contract.deploy()) as NFT721V1; const NFT1155Contract = await ethers.getContractFactory("NFT1155V2"); const nft1155 = (await NFT1155Contract.deploy()) as NFT1155V2; const SocialTokenContract = await ethers.getContractFactory("SocialTokenV0"); const socialToken = (await SocialTokenContract.deploy()) as SocialTokenV0; const ERC721MockContract = await ethers.getContractFactory("ERC721Mock"); const erc721Mock = (await ERC721MockContract.deploy()) as ERC721Mock; const ERC1155MockContract = await ethers.getContractFactory("ERC1155Mock"); const erc1155Mock = (await ERC1155MockContract.deploy()) as ERC1155Mock; const ERC20MockContract = await ethers.getContractFactory("ERC20Mock"); const erc20Mock = (await ERC20MockContract.deploy()) as ERC20Mock; return { deployer, protocolVault, operationalVault, factory, erc721Exchange, erc1155Exchange, nft721, nft1155, socialToken, alice, bob, carol, erc721Mock, erc1155Mock, erc20Mock, }; }; async function getNFT721(factory: TokenFactory): Promise<NFT721V1> { let events: any = await factory.queryFilter(factory.filters.DeployNFT721AndMintBatch(), "latest"); if (events.length == 0) events = await factory.queryFilter(factory.filters.DeployNFT721AndPark(), "latest"); const NFT721Contract = await ethers.getContractFactory("NFT721V1"); return (await NFT721Contract.attach(events[0].args[0])) as NFT721V1; } async function getNFT1155(factory: TokenFactory): Promise<NFT1155V2> { const events = await factory.queryFilter(factory.filters.DeployNFT1155AndMintBatch(), "latest"); const NFT1155Contract = await ethers.getContractFactory("NFT1155V2"); return (await NFT1155Contract.attach(events[0].args[0])) as NFT1155V2; } async function getSocialToken(factory: TokenFactory): Promise<SocialTokenV0> { const events = await factory.queryFilter(factory.filters.DeploySocialToken(), "latest"); const SocialTokenContract = await ethers.getContractFactory("SocialTokenV0"); return (await SocialTokenContract.attach(events[0].args[0])) as SocialTokenV0; } describe("TokenFactory", () => { beforeEach(async () => { await ethers.provider.send("hardhat_reset", []); }); it("should be FeeInfo functions return proper value", async () => { const { protocolVault, operationalVault, factory } = await setupTest(); expect((await factory.protocolFeeInfo())[0]).to.be.equal(protocolVault.address); expect((await factory.protocolFeeInfo())[1]).to.be.equal(25); expect((await factory.operationalFeeInfo())[0]).to.be.equal(operationalVault.address); expect((await factory.operationalFeeInfo())[1]).to.be.equal(5); }); it("should be fail if non-owner calls onlyOwner functions", async () => { const { factory, alice } = await setupTest(); await expect(factory.connect(alice).setBaseURI721("https://shoyu.sushi.com/nft721/")).to.be.revertedWith( "Ownable: caller is not the owner" ); await expect(factory.connect(alice).setBaseURI1155("https://shoyu.sushi.com/nft1155/")).to.be.revertedWith( "Ownable: caller is not the owner" ); await expect(factory.connect(alice).setProtocolFeeRecipient(alice.address)).to.be.revertedWith( "Ownable: caller is not the owner" ); await expect(factory.connect(alice).setOperationalFeeRecipient(alice.address)).to.be.revertedWith( "Ownable: caller is not the owner" ); await expect(factory.connect(alice).setOperationalFee(10)).to.be.revertedWith( "Ownable: caller is not the owner" ); await expect(factory.connect(alice).setDeployerWhitelisted(alice.address, true)).to.be.revertedWith( "Ownable: caller is not the owner" ); await expect(factory.connect(alice).setStrategyWhitelisted(alice.address, true)).to.be.revertedWith( "Ownable: caller is not the owner" ); await expect(factory.connect(alice).upgradeNFT721(alice.address)).to.be.revertedWith( "Ownable: caller is not the owner" ); await expect(factory.connect(alice).upgradeNFT1155(alice.address)).to.be.revertedWith( "Ownable: caller is not the owner" ); await expect(factory.connect(alice).upgradeSocialToken(alice.address)).to.be.revertedWith( "Ownable: caller is not the owner" ); await expect(factory.connect(alice).upgradeERC721Exchange(alice.address)).to.be.revertedWith( "Ownable: caller is not the owner" ); await expect(factory.connect(alice).upgradeERC1155Exchange(alice.address)).to.be.revertedWith( "Ownable: caller is not the owner" ); }); it("should be that NFT721, NFT1155, SocialToken can't be deployed if upgradeXXX functions are not called before", async () => { const { factory, alice, bob, carol, erc20Mock, nft721, nft1155, socialToken } = await setupTest(); await factory.setDeployerWhitelisted(AddressZero, true); await expect(factory.connect(alice).deployNFT721AndMintBatch(alice.address, "N", "S", [0, 2], bob.address, 10)) .to.be.reverted; await expect(factory.connect(bob).deployNFT721AndPark(carol.address, "N", "S", 10, alice.address, 10)).to.be .reverted; await expect(factory.connect(carol).deployNFT1155AndMintBatch(alice.address, [0, 2], [11, 33], bob.address, 10)) .to.be.reverted; await expect(factory.deploySocialToken(alice.address, "N", "S", erc20Mock.address, 100)).to.be.reverted; await factory.upgradeNFT721(nft721.address); await factory.connect(alice).deployNFT721AndMintBatch(alice.address, "N", "S", [0, 2], bob.address, 10); await factory.connect(bob).deployNFT721AndPark(carol.address, "N", "S", 10, alice.address, 10); await expect(factory.connect(carol).deployNFT1155AndMintBatch(alice.address, [0, 2], [11, 33], bob.address, 10)) .to.be.reverted; await expect(factory.deploySocialToken(alice.address, "N", "S", erc20Mock.address, 100)).to.be.reverted; await factory.upgradeNFT1155(nft1155.address); await factory.connect(carol).deployNFT1155AndMintBatch(alice.address, [0, 2], [11, 33], bob.address, 10); await expect(factory.deploySocialToken(alice.address, "N", "S", erc20Mock.address, 100)).to.be.reverted; await factory.upgradeSocialToken(socialToken.address); await factory.deploySocialToken(alice.address, "N", "S", erc20Mock.address, 100); }); it("should be that only accounts in DeployerWhitelist can deploy proxies if isDeployerWhitelisted(address(0)) is false", async () => { const { factory, alice, bob, nft721 } = await setupTest(); await factory.upgradeNFT721(nft721.address); expect(await factory.isDeployerWhitelisted(AddressZero)).to.be.false; expect(await factory.isDeployerWhitelisted(bob.address)).to.be.false; await expect( factory.connect(bob).deployNFT721AndMintBatch(alice.address, "N", "S", [0, 2], bob.address, 10) ).to.be.revertedWith("SHOYU: FORBIDDEN"); await factory.setDeployerWhitelisted(alice.address, true); expect(await factory.isDeployerWhitelisted(alice.address)).to.be.true; await factory.connect(alice).deployNFT721AndMintBatch(alice.address, "N", "S", [0, 2], bob.address, 10); }); it("should be that accounts not in DeployerWhitelist can deploy proxies if isDeployerWhitelisted(address(0)) is true", async () => { const { factory, alice, bob, carol, nft721, nft1155 } = await setupTest(); await factory.setDeployerWhitelisted(AddressZero, true); expect(await factory.isDeployerWhitelisted(AddressZero)).to.be.true; expect(await factory.isDeployerWhitelisted(alice.address)).to.be.false; expect(await factory.isDeployerWhitelisted(bob.address)).to.be.false; await factory.upgradeNFT721(nft721.address); await factory.connect(alice).deployNFT721AndMintBatch(alice.address, "N", "S", [0, 2], bob.address, 10); await factory.connect(bob).deployNFT721AndPark(carol.address, "N", "S", 10, alice.address, 10); await factory.upgradeNFT1155(nft1155.address); await factory.connect(alice).deployNFT1155AndMintBatch(alice.address, [0, 2], [11, 33], bob.address, 10); await factory.connect(bob).deployNFT1155AndMintBatch(bob.address, [11, 25], [1, 2], carol.address, 5); }); it("should be that someone who has NFT721 contract owner's signature can call mintBatch721/park functions", async () => { const { factory, alice, bob, nft721 } = await setupTest(); const signer = ethers.Wallet.createRandom(); await factory.setDeployerWhitelisted(AddressZero, true); await factory.upgradeNFT721(nft721.address); await factory.connect(alice).deployNFT721AndMintBatch(signer.address, "N", "S", [0, 2], bob.address, 10); const nft721_0 = await getNFT721(factory); await factory.connect(bob).deployNFT721AndPark(signer.address, "N", "S", 10, alice.address, 10); const nft721_1 = await getNFT721(factory); const digest721_0 = await getMint721Digest( ethers.provider, nft721_0.address, alice.address, [1], [], factory.address, 0 ); const { v: v0, r: r0, s: s0 } = sign(digest721_0, signer); await expect( factory.connect(bob).mintBatch721(nft721_0.address, bob.address, [1], [], v0, r0, s0) ).to.be.revertedWith("SHOYU: UNAUTHORIZED"); await expect( factory.connect(alice).mintBatch721(nft721_0.address, alice.address, [2], [], v0, r0, s0) ).to.be.revertedWith("SHOYU: UNAUTHORIZED"); await factory.connect(alice).mintBatch721(nft721_0.address, alice.address, [1], [], v0, r0, s0); const digest721_1 = await getMint721Digest( ethers.provider, nft721_1.address, alice.address, [3, 6, 9], [], factory.address, 1 ); const { v: v1, r: r1, s: s1 } = sign(digest721_1, signer); const fakeSigner = ethers.Wallet.createRandom(); const { v: fv1, r: fr1, s: fs1 } = sign(digest721_1, fakeSigner); await expect( factory.connect(bob).mintBatch721(nft721_1.address, alice.address, [3, 6, 9], [], fv1, fr1, fs1) ).to.be.revertedWith("SHOYU: UNAUTHORIZED"); await expect( factory.connect(bob).mintBatch721(nft721_1.address, alice.address, [3, 6, 8], [], v1, r1, s1) ).to.be.revertedWith("SHOYU: UNAUTHORIZED"); await factory.connect(bob).mintBatch721(nft721_1.address, alice.address, [3, 6, 9], [], v1, r1, s1); const digest721_2 = await getPark721Digest(ethers.provider, nft721_0.address, 20, factory.address, 2); const { v: v2, r: r2, s: s2 } = sign(digest721_2, signer); await expect(factory.connect(bob).parkTokenIds721(nft721_1.address, 20, v2, r2, s2)).to.be.revertedWith( "SHOYU: UNAUTHORIZED" ); await expect(factory.connect(alice).parkTokenIds721(nft721_0.address, 30, v2, r2, s2)).to.be.revertedWith( "SHOYU: UNAUTHORIZED" ); await factory.connect(alice).parkTokenIds721(nft721_0.address, 20, v2, r2, s2); const digest721_3 = await getPark721Digest(ethers.provider, nft721_1.address, 60, factory.address, 3); const { v: v3, r: r3, s: s3 } = sign(digest721_3, signer); const { v: fv2, r: fr2, s: fs2 } = sign(digest721_3, fakeSigner); await expect(factory.connect(bob).parkTokenIds721(nft721_1.address, 60, fv2, fr2, fs2)).to.be.revertedWith( "SHOYU: UNAUTHORIZED" ); await factory.connect(bob).parkTokenIds721(nft721_1.address, 60, v3, r3, s3); }); it("should be that someone who has NFT1155 contract owner's signature can call mint1155 functions", async () => { const { factory, alice, bob, carol, nft1155 } = await setupTest(); const signer = ethers.Wallet.createRandom(); await factory.setDeployerWhitelisted(AddressZero, true); await factory.upgradeNFT1155(nft1155.address); await factory.connect(alice).deployNFT1155AndMintBatch(signer.address, [0, 2], [11, 33], bob.address, 10); const nft1155_0 = await getNFT1155(factory); await factory.connect(bob).deployNFT1155AndMintBatch(signer.address, [11, 25], [1, 2], signer.address, 5); const nft1155_1 = await getNFT1155(factory); const digest1155_0 = await getMint1155Digest( ethers.provider, nft1155_0.address, alice.address, [12], [345], [], factory.address, 0 ); const { v: v0, r: r0, s: s0 } = sign(digest1155_0, signer); await expect( factory.connect(bob).mintBatch1155(nft1155_0.address, alice.address, [12], [3450], [], v0, r0, s0) ).to.be.revertedWith("SHOYU: UNAUTHORIZED"); await expect( factory.connect(bob).mintBatch1155(nft1155_0.address, alice.address, [12], [123], [], v0, r0, s0) ).to.be.revertedWith("SHOYU: UNAUTHORIZED"); await expect( factory.connect(alice).mintBatch1155(nft1155_0.address, bob.address, [12], [345], [], v0, r0, s0) ).to.be.revertedWith("SHOYU: UNAUTHORIZED"); await factory.connect(alice).mintBatch1155(nft1155_0.address, alice.address, [12], [345], [], v0, r0, s0); const digest1155_1 = await getMint1155Digest( ethers.provider, nft1155_1.address, carol.address, [11, 21], [1, 9], [], factory.address, 1 ); const { v: v1, r: r1, s: s1 } = sign(digest1155_1, signer); const fakeSigner = ethers.Wallet.createRandom(); const { v: fv1, r: fr1, s: fs1 } = sign(digest1155_1, fakeSigner); await expect( factory.connect(bob).mintBatch1155(nft1155_1.address, carol.address, [11, 21], [1, 9], [], fv1, fr1, fs1) ).to.be.revertedWith("SHOYU: UNAUTHORIZED"); await factory.connect(bob).mintBatch1155(nft1155_1.address, carol.address, [11, 21], [1, 9], [], v1, r1, s1); }); it("should be that someone who has SocialToken contract owner's signature can call mintSocialToken functions", async () => { const { factory, alice, bob, carol, socialToken, erc20Mock } = await setupTest(); const signer = ethers.Wallet.createRandom(); await factory.setDeployerWhitelisted(AddressZero, true); await factory.upgradeSocialToken(socialToken.address); await factory.connect(alice).deploySocialToken(signer.address, "N", "S", erc20Mock.address, 100); const socialToken_0 = await getSocialToken(factory); await factory.connect(bob).deploySocialToken(signer.address, "N", "S", erc20Mock.address, 0); const socialToken_1 = await getSocialToken(factory); expect(await socialToken_0.totalSupply()).to.be.equal(100); expect(await socialToken_1.totalSupply()).to.be.equal(0); const digestST_0 = await getMintSocialTokenDigest( ethers.provider, socialToken_0.address, alice.address, 300, factory.address, 0 ); const { v: v0, r: r0, s: s0 } = sign(digestST_0, signer); await expect( factory.connect(bob).mintSocialToken(socialToken_0.address, alice.address, 3000, v0, r0, s0) ).to.be.revertedWith("SHOYU: UNAUTHORIZED"); await expect( factory.connect(alice).mintSocialToken(socialToken_0.address, bob.address, 300, v0, r0, s0) ).to.be.revertedWith("SHOYU: UNAUTHORIZED"); await factory.connect(alice).mintSocialToken(socialToken_0.address, alice.address, 300, v0, r0, s0); const digestST_1 = await getMintSocialTokenDigest( ethers.provider, socialToken_1.address, carol.address, 500, factory.address, 1 ); const { v: v1, r: r1, s: s1 } = sign(digestST_1, signer); const fakeSigner = ethers.Wallet.createRandom(); const { v: fv1, r: fr1, s: fs1 } = sign(digestST_1, fakeSigner); await expect( factory.connect(bob).mintSocialToken(socialToken_1.address, carol.address, 500, fv1, fr1, fs1) ).to.be.revertedWith("SHOYU: UNAUTHORIZED"); await factory.connect(bob).mintSocialToken(socialToken_1.address, carol.address, 500, v1, r1, s1); expect(await socialToken_0.totalSupply()).to.be.equal(400); expect(await socialToken_1.totalSupply()).to.be.equal(500); }); it("should be fail when users try to deploy NFT721 with invalid parameters", async () => { const { factory, alice, bob, carol, nft721 } = await setupTest(); await factory.setDeployerWhitelisted(AddressZero, true); await factory.upgradeNFT721(nft721.address); await expect( factory.connect(bob).deployNFT721AndMintBatch(alice.address, "", "S", [7, 2], carol.address, 10) ).to.be.revertedWith("SHOYU: INVALID_NAME"); await expect( factory.connect(bob).deployNFT721AndMintBatch(alice.address, "N", "", [7, 2], carol.address, 10) ).to.be.revertedWith("SHOYU: INVALID_SYMBOL"); await expect( factory.connect(bob).deployNFT721AndMintBatch(AddressZero, "N", "S", [7, 2], carol.address, 10) ).to.be.revertedWith("SHOYU: INVALID_ADDRESS"); await expect( factory.connect(bob).deployNFT721AndMintBatch(alice.address, "N", "S", [1, 2, 2], carol.address, 10) ).to.be.revertedWith("SHOYU: CALL_FAILURE"); //can't mint duplicate nft await expect( factory.connect(bob).deployNFT721AndMintBatch(alice.address, "N", "S", [1, 2, 3], AddressZero, 250) ).to.be.revertedWith("SHOYU: CALL_FAILURE"); //can't set royalty fee recipient as AddressZero await expect( factory.connect(bob).deployNFT721AndMintBatch(alice.address, "N", "S", [1, 2, 3], carol.address, 255) ).to.be.revertedWith("SHOYU: CALL_FAILURE"); //can't set royalty fee more than 250 //deployNFT721 with parking await expect( factory.connect(bob).deployNFT721AndPark(alice.address, "", "S", 5, carol.address, 10) ).to.be.revertedWith("SHOYU: INVALID_NAME"); await expect( factory.connect(bob).deployNFT721AndPark(alice.address, "N", "", 3, carol.address, 10) ).to.be.revertedWith("SHOYU: INVALID_SYMBOL"); await expect( factory.connect(bob).deployNFT721AndPark(AddressZero, "N", "S", 7, carol.address, 10) ).to.be.revertedWith("SHOYU: INVALID_ADDRESS"); await expect( factory.connect(bob).deployNFT721AndPark(alice.address, "N", "S", 0, carol.address, 10) ).to.be.revertedWith("SHOYU: CALL_FAILURE"); //can't part nft 0 amount await expect( factory.connect(bob).deployNFT721AndPark(alice.address, "N", "S", 5, AddressZero, 250) ).to.be.revertedWith("SHOYU: CALL_FAILURE"); //can't set royalty fee recipient as AddressZero await expect( factory.connect(bob).deployNFT721AndPark(alice.address, "N", "S", 3, carol.address, 255) ).to.be.revertedWith("SHOYU: CALL_FAILURE"); //can't set royalty fee more than 250 }); it("should be fail when users try to deploy NFT1155 with invalid parameters", async () => { const { factory, alice, bob, nft1155 } = await setupTest(); await factory.setDeployerWhitelisted(AddressZero, true); await factory.upgradeNFT1155(nft1155.address); await expect( factory.connect(alice).deployNFT1155AndMintBatch(AddressZero, [2, 4, 6], [11, 33, 55], bob.address, 10) ).to.be.revertedWith("SHOYU: INVALID_ADDRESS"); await expect( factory.connect(alice).deployNFT1155AndMintBatch(bob.address, [2, 4, 6], [33, 55], bob.address, 10) ).to.be.revertedWith("SHOYU: LENGTHS_NOT_EQUAL"); await expect( factory.connect(alice).deployNFT1155AndMintBatch(bob.address, [2, 4, 6], [11, 33, 55], AddressZero, 10) ).to.be.revertedWith("SHOYU: CALL_FAILURE"); //can't set royalty fee recipient as AddressZero await expect( factory.connect(alice).deployNFT1155AndMintBatch(bob.address, [2, 4, 6], [11, 33, 55], bob.address, 255) ).to.be.revertedWith("SHOYU: CALL_FAILURE"); //can't set royalty fee more than 250 }); it("should be fail when users try to deploy SocialToken with invalid parameters", async () => { const { factory, alice, socialToken, erc20Mock } = await setupTest(); await factory.setDeployerWhitelisted(AddressZero, true); await factory.upgradeSocialToken(socialToken.address); await expect( factory.connect(alice).deploySocialToken(alice.address, "", "S", erc20Mock.address, 100) ).to.be.revertedWith("SHOYU: INVALID_NAME"); await expect( factory.connect(alice).deploySocialToken(alice.address, "N", "", erc20Mock.address, 100) ).to.be.revertedWith("SHOYU: INVALID_SYMBOL"); await expect( factory.connect(alice).deploySocialToken(AddressZero, "N", "S", erc20Mock.address, 100) ).to.be.revertedWith("SHOYU: INVALID_ADDRESS"); await factory.connect(alice).deploySocialToken(alice.address, "N", "S", erc20Mock.address, 0); await factory.connect(alice).deploySocialToken(alice.address, "N", "S", erc20Mock.address, 100); }); it("should work well checking isNFT721/1155/SocialToken functions", async () => { const { factory, alice, bob, carol, nft721, nft1155, socialToken, erc20Mock } = await setupTest(); await factory.setDeployerWhitelisted(AddressZero, true); await factory.upgradeNFT721(nft721.address); await factory.upgradeNFT1155(nft1155.address); await factory.upgradeSocialToken(socialToken.address); await factory.connect(bob).deployNFT721AndMintBatch(alice.address, "N", "S", [7, 2], carol.address, 10); const nft721_0 = await getNFT721(factory); await factory.connect(alice).deployNFT1155AndMintBatch(alice.address, [0, 2], [11, 33], bob.address, 10); const nft1155_0 = await getNFT1155(factory); await factory.connect(alice).deploySocialToken(alice.address, "N", "S", erc20Mock.address, 100); const socialT_0 = await getSocialToken(factory); const NFT721Contract = await ethers.getContractFactory("NFT721V1"); const nft721_new = (await NFT721Contract.deploy()) as NFT721V1; const NFT1155Contract = await ethers.getContractFactory("NFT1155V2"); const nft1155_new = (await NFT1155Contract.deploy()) as NFT1155V2; const SocialTokenContract = await ethers.getContractFactory("SocialTokenV0"); const socialToken_new = (await SocialTokenContract.deploy()) as SocialTokenV0; await factory.upgradeNFT721(nft721_new.address); await factory.upgradeNFT1155(nft1155_new.address); await factory.upgradeSocialToken(socialToken_new.address); await factory.connect(carol).deployNFT721AndPark(bob.address, "N", "S", 10, alice.address, 10); const nft721_1 = await getNFT721(factory); await factory.connect(bob).deployNFT1155AndMintBatch(alice.address, [11, 25], [1, 2], alice.address, 5); const nft1155_1 = await getNFT1155(factory); await factory.connect(bob).deploySocialToken(bob.address, "N", "S", erc20Mock.address, 100); const socialT_1 = await getSocialToken(factory); assert.isTrue(await factory.isNFT721(nft721_0.address)); assert.isTrue(await factory.isNFT721(nft721_1.address)); assert.isFalse(await factory.isNFT721(nft1155_0.address)); assert.isFalse(await factory.isNFT721(nft1155_1.address)); assert.isFalse(await factory.isNFT721(socialT_0.address)); assert.isFalse(await factory.isNFT721(socialT_1.address)); assert.isFalse(await factory.isNFT1155(nft721_0.address)); assert.isFalse(await factory.isNFT1155(nft721_1.address)); assert.isTrue(await factory.isNFT1155(nft1155_0.address)); assert.isTrue(await factory.isNFT1155(nft1155_1.address)); assert.isFalse(await factory.isNFT1155(socialT_0.address)); assert.isFalse(await factory.isNFT1155(socialT_1.address)); assert.isFalse(await factory.isSocialToken(nft721_0.address)); assert.isFalse(await factory.isSocialToken(nft721_1.address)); assert.isFalse(await factory.isSocialToken(nft1155_0.address)); assert.isFalse(await factory.isSocialToken(nft1155_1.address)); assert.isTrue(await factory.isSocialToken(socialT_0.address)); assert.isTrue(await factory.isSocialToken(socialT_1.address)); }); });
the_stack
import { should } from 'chai'; import { RankedListMockInstance } from '../../../types/truffle-contracts'; const RankedList = artifacts.require('RankedListMock') as Truffle.Contract<RankedListMockInstance>; should(); const emptyData = '0x0000000000000000000000000000000000000000'; const headData = '0x0000000000000000000000000000000000000001'; const middleData = '0x0000000000000000000000000000000000000002'; const tailData = '0x0000000000000000000000000000000000000003'; const headRank = 30; const middleRank = 20; const tailRank = 10; /** @test {RankedList} contract */ contract('RankedList - add', (accounts) => { let rankedList: RankedListMockInstance; beforeEach(async () => { rankedList = await RankedList.new(); }); /** * @test {RankedList#new} and {RankedList#idCounter} */ it('Constructor variables.', async () => { (await rankedList.idCounter()).toNumber().should.be.equal(1); }); /** * @test {RankedList#get} */ it('get on a non existing object returns (0,0,0,0,0).', async () => { const result = (await rankedList.get(0)); assertEqualObjects(result, [0, 0, 0, 0, emptyData]); }); /** * @test {RankedList#addHead} */ it('adds an object at the head - event emission.', async () => { const transaction = ( await rankedList.addHead(headRank, headData) ); transaction.logs[0].event.should.be.equal('ObjectCreated'); transaction.logs[0].args.id.toNumber().should.be.equal(1); transaction.logs[0].args.rank.toNumber().should.be.equal(headRank); transaction.logs[0].args.data.should.be.equal(headData); transaction.logs[1].event.should.be.equal('NewHead'); transaction.logs[1].args.id.toNumber().should.be.equal(1); transaction.logs[2].event.should.be.equal('NewTail'); transaction.logs[2].args.id.toNumber().should.be.equal(1); }); /** * @test {RankedList#addHead} */ it('adds an object at the head - data storage.', async () => { const objectId = ( await rankedList.addHead(headRank, headData) ).logs[0].args.id.toNumber(); const result = (await rankedList.get(objectId)); assertEqualObjects(result, [objectId, 0, 0, headRank, headData]); }); /** * @test {RankedList#addHead} */ it('adds two objects from the head.', async () => { const objectOneId = ( await rankedList.addHead(middleRank, middleData) ).logs[0].args.id.toNumber(); const objectTwoId = ( await rankedList.addHead(headRank, headData) ).logs[0].args.id.toNumber(); const objectOne = (await rankedList.get(objectOneId)); assertEqualObjects(objectOne, [objectOneId, 0, objectTwoId, middleRank, middleData]); const objectTwo = (await rankedList.get(objectTwoId)); assertEqualObjects(objectTwo, [objectTwoId, objectOneId, 0, headRank, headData]); ((await rankedList.head()).toNumber()).should.be.equal(objectTwoId); }); /** * @test {RankedList#addTail} */ it('adds an object at the tail - event emission.', async () => { const objectEvent = ( await rankedList.addTail(headRank, headData) ).logs[0]; objectEvent.args.id.toNumber().should.be.equal(1); objectEvent.args.rank.toNumber().should.be.equal(headRank); objectEvent.args.data.should.be.equal(headData); }); /** * @test {RankedList#addTail} */ it('adds an object at the tail - data storage.', async () => { const objectId = ( await rankedList.addTail(headRank, headData) ).logs[0].args.id.toNumber(); const result = (await rankedList.get(objectId)); assertEqualObjects(result, [objectId, 0, 0, headRank, headData]); }); /** * @test {RankedList#addTail} */ it('adds two objects from the tail.', async () => { const objectOneId = ( await rankedList.addTail(middleRank, middleData) ).logs[0].args.id.toNumber(); const objectTwoId = ( await rankedList.addTail(headRank, headData) ).logs[0].args.id.toNumber(); const objectOne = (await rankedList.get(objectOneId)); assertEqualObjects(objectOne, [objectOneId, objectTwoId, 0, middleRank, middleData]); const objectTwo = (await rankedList.get(objectTwoId)); assertEqualObjects(objectTwo, [objectTwoId, 0, objectOneId, headRank, headData]); ((await rankedList.head()).toNumber()).should.be.equal(objectOneId); }); }); /** @test {rankedList} contract */ contract('RankedList - remove', (accounts) => { let rankedList: RankedListMockInstance; let headId: number; let middleId: number; let tailId: number; beforeEach(async () => { rankedList = await RankedList.new(); tailId = ( await rankedList.addHead(tailRank, tailData) ).logs[0].args.id.toNumber(); middleId = ( await rankedList.addHead(middleRank, middleData) ).logs[0].args.id.toNumber(); headId = ( await rankedList.addHead(headRank, headData) ).logs[0].args.id.toNumber(); }); /** * @test {RankedList#remove} */ it('removes the head.', async () => { const removedId = ( await rankedList.remove(headId) ).logs[1].args.id.toNumber(); ((await rankedList.head()).toNumber()).should.be.equal(middleId); const middleObject = (await rankedList.get(middleId)); assertEqualObjects(middleObject, [middleId, tailId, 0, middleRank, middleData]); const tailObject = (await rankedList.get(tailId)); assertEqualObjects(tailObject, [tailId, 0, middleId, tailRank, tailData]); }); /** * @test {RankedList#remove} */ it('removes the tail.', async () => { const removedId = ( await rankedList.remove(tailId) ).logs[1].args.id.toNumber(); ((await rankedList.head()).toNumber()).should.be.equal(headId); const headObject = (await rankedList.get(headId)); assertEqualObjects(headObject, [headId, middleId, 0, headRank, headData]); const middleObject = (await rankedList.get(middleId)); assertEqualObjects(middleObject, [middleId, 0, headId, middleRank, middleData]); }); /** * @test {RankedList#remove} */ it('removes the middle.', async () => { const removedId = ( await rankedList.remove(middleId) ).logs[1].args.id.toNumber(); ((await rankedList.head()).toNumber()).should.be.equal(headId); const headObject = (await rankedList.get(headId)); assertEqualObjects(headObject, [headId, tailId, 0, headRank, headData]); const tailObject = (await rankedList.get(tailId)); assertEqualObjects(tailObject, [tailId, 0, headId, tailRank, tailData]); }); /** * @test {RankedList#remove} */ it('removes all.', async () => { (await rankedList.remove(headId)).logs[1].args.id.toNumber(); ((await rankedList.head()).toNumber()).should.be.equal(middleId); (await rankedList.remove(tailId)).logs[1].args.id.toNumber(); ((await rankedList.head()).toNumber()).should.be.equal(middleId); ((await rankedList.tail()).toNumber()).should.be.equal(middleId); (await rankedList.remove(middleId)).logs[1].args.id.toNumber(); ((await rankedList.head()).toNumber()).should.be.equal(0); ((await rankedList.tail()).toNumber()).should.be.equal(0); }); }); /** @test {rankedList} contract */ contract('RankedList - insert', (accounts) => { const insertedData = '0x0000000000000000000000000000000000000004'; const insertedRank = 4; let rankedList: RankedListMockInstance; let headId: number; let middleId: number; let tailId: number; beforeEach(async () => { rankedList = await RankedList.new(); tailId = ( await rankedList.addHead(tailRank, tailData) ).logs[0].args.id.toNumber(); middleId = ( await rankedList.addHead(middleRank, middleData) ).logs[0].args.id.toNumber(); headId = ( await rankedList.addHead(headRank, headData) ).logs[0].args.id.toNumber(); }); it('inserts after the head.', async () => { const insertedId = ( await rankedList.insertAfter(headId, insertedRank, insertedData) ).logs[0].args.id.toNumber(); ((await rankedList.head()).toNumber()).should.be.equal(headId); const headObject = (await rankedList.get(headId)); assertEqualObjects(headObject, [headId, insertedId, 0, headRank, headData]); const insertedObject = (await rankedList.get(insertedId)); assertEqualObjects(insertedObject, [insertedId, middleId, headId, insertedRank, insertedData]); const middleObject = (await rankedList.get(middleId)); assertEqualObjects(middleObject, [middleId, tailId, insertedId, middleRank, middleData]); const tailObject = (await rankedList.get(tailId)); assertEqualObjects(tailObject, [tailId, 0, middleId, tailRank, tailData]); }); it('inserts after the tail.', async () => { const insertedId = ( await rankedList.insertAfter(tailId, insertedRank, insertedData) ).logs[0].args.id.toNumber(); ((await rankedList.head()).toNumber()).should.be.equal(headId); const headObject = (await rankedList.get(headId)); assertEqualObjects(headObject, [headId, middleId, 0, headRank, headData]); const middleObject = (await rankedList.get(middleId)); assertEqualObjects(middleObject, [middleId, tailId, headId, middleRank, middleData]); const tailObject = (await rankedList.get(tailId)); assertEqualObjects(tailObject, [tailId, insertedId, middleId, tailRank, tailData]); const insertedObject = (await rankedList.get(insertedId)); assertEqualObjects(insertedObject, [insertedId, 0, tailId, insertedRank, insertedData]); }); it('inserts after the middle.', async () => { const insertedId = ( await rankedList.insertAfter(middleId, insertedRank, insertedData) ).logs[0].args.id.toNumber(); ((await rankedList.head()).toNumber()).should.be.equal(headId); const headObject = (await rankedList.get(headId)); assertEqualObjects(headObject, [headId, middleId, 0, headRank, headData]); const middleObject = (await rankedList.get(middleId)); assertEqualObjects(middleObject, [middleId, insertedId, headId, middleRank, middleData]); const insertedObject = (await rankedList.get(insertedId)); assertEqualObjects(insertedObject, [insertedId, tailId, middleId, insertedRank, insertedData]); const tailObject = (await rankedList.get(tailId)); assertEqualObjects(tailObject, [tailId, 0, insertedId, tailRank, tailData]); }); it('inserts before the head.', async () => { const insertedId = ( await rankedList.insertBefore(headId, insertedRank, insertedData) ).logs[0].args.id.toNumber(); ((await rankedList.head()).toNumber()).should.be.equal(insertedId); const insertedObject = (await rankedList.get(insertedId)); assertEqualObjects(insertedObject, [insertedId, headId, 0, insertedRank, insertedData]); const headObject = (await rankedList.get(headId)); assertEqualObjects(headObject, [headId, middleId, insertedId, headRank, headData]); const middleObject = (await rankedList.get(middleId)); assertEqualObjects(middleObject, [middleId, tailId, headId, middleRank, middleData]); const tailObject = (await rankedList.get(tailId)); assertEqualObjects(tailObject, [tailId, 0, middleId, tailRank, tailData]); }); it('inserts before the tail.', async () => { const insertedId = ( await rankedList.insertBefore(tailId, insertedRank, insertedData) ).logs[0].args.id.toNumber(); ((await rankedList.head()).toNumber()).should.be.equal(headId); const headObject = (await rankedList.get(headId)); assertEqualObjects(headObject, [headId, middleId, 0, headRank, headData]); const middleObject = (await rankedList.get(middleId)); assertEqualObjects(middleObject, [middleId, insertedId, headId, middleRank, middleData]); const insertedObject = (await rankedList.get(insertedId)); assertEqualObjects(insertedObject, [insertedId, tailId, middleId, insertedRank, insertedData]); const tailObject = (await rankedList.get(tailId)); assertEqualObjects(tailObject, [tailId, 0, insertedId, tailRank, tailData]); }); it('inserts before the middle.', async () => { const insertedId = ( await rankedList.insertBefore(middleId, insertedRank, insertedData) ).logs[0].args.id.toNumber(); ((await rankedList.head()).toNumber()).should.be.equal(headId); const headObject = (await rankedList.get(headId)); assertEqualObjects(headObject, [headId, insertedId, 0, headRank, headData]); const insertedObject = (await rankedList.get(insertedId)); assertEqualObjects(insertedObject, [insertedId, middleId, headId, insertedRank, insertedData]); const middleObject = (await rankedList.get(middleId)); assertEqualObjects(middleObject, [middleId, tailId, insertedId, middleRank, middleData]); const tailObject = (await rankedList.get(tailId)); assertEqualObjects(tailObject, [tailId, 0, middleId, tailRank, tailData]); }); }); contract('RankedList - find and insert', (accounts) => { let rankedList: RankedListMockInstance; let headId: number; let middleId: number; let tailId: number; const insertedData = '0x0000000000000000000000000000000000000004'; beforeEach(async () => { rankedList = await RankedList.new(); tailId = ( await rankedList.addHead(tailRank, tailData) ).logs[0].args.id.toNumber(); middleId = ( await rankedList.addHead(middleRank, middleData) ).logs[0].args.id.toNumber(); headId = ( await rankedList.addHead(headRank, headData) ).logs[0].args.id.toNumber(); }); it('finds the id for the first object with equal or lower rank.', async () => { let resultId = (await rankedList.findRank(headRank)); resultId.toNumber().should.be.equal(headId); resultId = (await rankedList.findRank(middleRank)); resultId.toNumber().should.be.equal(middleId); resultId = (await rankedList.findRank(tailRank)); resultId.toNumber().should.be.equal(tailId); resultId = (await rankedList.findRank(tailRank - 1)); resultId.toNumber().should.be.equal(0); }); it('inserts before the tail.', async () => { const insertedId = ( await rankedList.insert(5, insertedData) ).logs[0].args.id.toNumber(); const headObject = (await rankedList.get(headId)); assertEqualObjects(headObject, [headId, middleId, 0, headRank, headData]); const middleObject = (await rankedList.get(middleId)); assertEqualObjects(middleObject, [middleId, tailId, headId, middleRank, middleData]); const tailObject = (await rankedList.get(tailId)); assertEqualObjects(tailObject, [tailId, insertedId, middleId, tailRank, tailData]); const insertedObject = (await rankedList.get(insertedId)); assertEqualObjects(insertedObject, [insertedId, 0, tailId, 5, insertedData]); }); it('inserts in the middle.', async () => { const insertedId = ( await rankedList.insert(25, insertedData) ).logs[0].args.id.toNumber(); const headObject = (await rankedList.get(headId)); assertEqualObjects(headObject, [headId, insertedId, 0, headRank, headData]); const insertedObject = (await rankedList.get(insertedId)); assertEqualObjects(insertedObject, [insertedId, middleId, headId, 25, insertedData]); const middleObject = (await rankedList.get(middleId)); assertEqualObjects(middleObject, [middleId, tailId, insertedId, middleRank, middleData]); const tailObject = (await rankedList.get(tailId)); assertEqualObjects(tailObject, [tailId, 0, middleId, tailRank, tailData]); }); it('inserts after the head.', async () => { const insertedId = ( await rankedList.insert(35, insertedData) ).logs[0].args.id.toNumber(); const insertedObject = (await rankedList.get(insertedId)); assertEqualObjects(insertedObject, [insertedId, headId, 0, 35, insertedData]); const headObject = (await rankedList.get(headId)); assertEqualObjects(headObject, [headId, middleId, insertedId, headRank, headData]); const middleObject = (await rankedList.get(middleId)); assertEqualObjects(middleObject, [middleId, tailId, headId, middleRank, middleData]); const tailObject = (await rankedList.get(tailId)); assertEqualObjects(tailObject, [tailId, 0, middleId, tailRank, tailData]); }); }); /* contract('RankedList - gas tests', (accounts) => { let rankedList: RankedListInstance; const dummyData = '0x0000000000000000000000000000000000000001'; beforeEach(async () => { rankedList = await RankedList.new(); for (let i = 0; i < 100; i++) { await rankedList.addHead(dummyData); } }); it('Add Head.', async () => { await rankedList.addHead(dummyData); }); it('Add Tail.', async () => { await rankedList.addTail(dummyData); }); it('Insert After.', async () => { const tailId = await rankedList.tail(); await rankedList.insertAfter(tailId, dummyData); }); it('Insert Before.', async () => { const tailId = await rankedList.tail(); await rankedList.insertBefore(tailId, dummyData); }); it('Remove.', async () => { const tailId = await rankedList.tail(); await rankedList.remove(tailId); }); }); */ function assertEqualObjects( object1: [any, any, any, any, any], object2: [any, any, any, any, any], ) { object1[0].toNumber().should.be.equal(object2[0]); object1[1].toNumber().should.be.equal(object2[1]); object1[2].toNumber().should.be.equal(object2[2]); object1[3].toNumber().should.be.equal(object2[3]); object1[4].should.be.equal(object2[4]); }
the_stack
import type { BuildPlatformContext, BuildPlatformEvents } from '@jovotech/cli-command-build'; import { ANSWER_BACKUP, ANSWER_CANCEL, deleteFolderRecursive, DISK, flags, getResolvedLocales, InstallContext, isJovoCliError, JovoCliError, Log, mergeArrayCustomizer, OK_HAND, printHighlight, printStage, printSubHeadline, promptOverwriteReverseBuild, REVERSE_ARROWS, STATION, Task, wait, } from '@jovotech/cli-core'; import { FileBuilder, FileObject } from '@jovotech/filebuilder'; import { JovoModelData, JovoModelDataV3, NativeFileInformation } from '@jovotech/model'; import { JovoModelAlexa } from '@jovotech/model-alexa'; import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'fs'; import { copySync, moveSync } from 'fs-extra'; import _get from 'lodash.get'; import _has from 'lodash.has'; import _merge from 'lodash.merge'; import _mergeWith from 'lodash.mergewith'; import _set from 'lodash.set'; import { join as joinPaths } from 'path'; import { SupportedLocales } from '../constants'; import DefaultFiles from '../DefaultFiles.json'; import { AlexaContext, SupportedLocalesType } from '../interfaces'; import { AlexaHook } from './AlexaHook'; export interface AlexaBuildPlatformContext extends AlexaContext, BuildPlatformContext { flags: BuildPlatformContext['flags'] & { 'ask-profile'?: string }; } export class BuildHook extends AlexaHook<BuildPlatformEvents> { $context!: AlexaBuildPlatformContext; install(): void { this.middlewareCollection = { 'install': [this.addCliOptions.bind(this)], 'before.build:platform': [ this.updatePluginContext.bind(this), this.checkForPlatform.bind(this), this.checkForCleanBuild.bind(this), this.validateLocales.bind(this), ], 'build:platform': [this.validateModels.bind(this), this.build.bind(this)], 'build:platform.reverse': [this.buildReverse.bind(this)], }; } /** * Add platform-specific CLI options, including flags and args. * @param context - Context providing an access point to command flags and args. */ addCliOptions(context: InstallContext): void { if (context.command !== 'build:platform') { return; } context.flags['ask-profile'] = flags.string({ description: 'Name of used ASK profile', }); } /** * Updates the current plugin context with platform-specific values. */ updatePluginContext(): void { super.updatePluginContext(); this.$context.alexa.askProfile = this.$context.flags['ask-profile'] || this.$plugin.config.askProfile || 'default'; } /** * Checks if the currently selected platform matches this CLI plugin. */ checkForPlatform(): void { // Check if this plugin should be used or not. if (!this.$context.platforms.includes(this.$plugin.id)) { this.uninstall(); } } /** * Checks if any provided locale is not supported, thus invalid. */ validateLocales(): void { for (const locale of this.$context.locales) { const resolvedLocales = getResolvedLocales( locale, SupportedLocales, this.$plugin.config.locales, ); for (const resolvedLocale of resolvedLocales) { if (!SupportedLocales.includes(resolvedLocale as SupportedLocalesType)) { throw new JovoCliError({ message: `Locale ${printHighlight(resolvedLocale)} is not supported by Amazon Alexa.`, module: this.$plugin.name, hint: resolvedLocale.length === 2 ? 'Alexa does not support generic locales, please specify locales in your project configuration.' : '', learnMore: 'https://www.jovo.tech/marketplace/platform-alexa/project-config#locales', }); } } } } /** * Validates Jovo models with platform-specific validators. */ async validateModels(): Promise<void> { // Validate Jovo model const validationTask: Task = new Task(`${OK_HAND} Validating Alexa model files`); for (const locale of this.$context.locales) { const localeTask = new Task(locale, async () => { const model: JovoModelData | JovoModelDataV3 = await this.$cli.project!.getModel(locale); await this.$cli.project!.validateModel( locale, model, JovoModelAlexa.getValidator(model), this.$plugin.name, ); await wait(500); }); validationTask.add(localeTask); } await validationTask.run(); } /** * Checks if --clean has been set and deletes the platform folder accordingly */ checkForCleanBuild(): void { // If --clean has been set, delete the respective platform folders before building if (this.$context.flags.clean) { deleteFolderRecursive(this.$plugin.platformPath); } } async build(): Promise<void> { const buildPath = `Path: ./${joinPaths( this.$cli.project!.getBuildDirectory(), this.$plugin.platformDirectory, )}`; const buildTaskTitle = `${STATION} Building Alexa Skill files${printStage( this.$cli.project!.stage, )}\n${printSubHeadline(buildPath)}`; // Define main build task. const buildTask: Task = new Task(buildTaskTitle); // Update or create Alexa project files, depending on whether it has already been built or not. const projectFilesTask: Task = new Task(`Project files`, this.buildProjectFiles.bind(this)); const interactionModelTask: Task = new Task( `Interaction model`, this.buildInteractionModel.bind(this), { enabled: this.$cli.project!.config.getParameter('models.enabled') !== false && this.$cli.project!.hasModelFiles(this.$context.locales), }, ); const buildConversationFilesTask: Task = new Task( `Alexa Conversations files`, this.buildConversationsFiles.bind(this), { enabled: this.$context.alexa.isACSkill }, ); const buildResponseFilesTask: Task = new Task( `Response files`, this.buildResponseFiles.bind(this), { enabled: this.$context.alexa.isACSkill }, ); buildTask.add( interactionModelTask, projectFilesTask, buildConversationFilesTask, buildResponseFilesTask, ); await buildTask.run(); } /** * Builds Jovo model files from platform-specific files. */ async buildReverse(): Promise<void> { // Since platform can be prompted for, check if this plugin should actually be executed again. if (!this.$context.platforms.includes(this.$plugin.id)) { return; } this.updatePluginContext(); const reverseBuildTask: Task = new Task(`${REVERSE_ARROWS} Reversing Alexa files`); if (this.$cli.project!.config.getParameter('models.enabled') !== false) { // Get locales to reverse build from. // If --locale is not specified, reverse build from every locale available in the platform folder. const selectedLocales: string[] = []; const platformLocales: string[] = this.getPlatformLocales(); if (!this.$context.flags.locale) { selectedLocales.push(...platformLocales); } else { // Otherwise only reverse build from the specified locale if it exists inside the platform folder. for (const locale of this.$context.flags.locale) { if (platformLocales.includes(locale)) { selectedLocales.push(locale); } else { throw new JovoCliError({ message: `Could not find platform models for locale: ${printHighlight(locale)}`, module: this.$plugin.name, hint: `Available locales include: ${platformLocales.join(', ')}`, }); } } } // Try to resolve the locale according to the locale map provided in this.$plugin.config.locales. // If en resolves to en-US, this loop will generate { 'en-US': 'en' } const buildLocaleMap: { [locale: string]: string } = selectedLocales.reduce( (localeMap: { [locale: string]: string }, locale: string) => { localeMap[locale] = locale; return localeMap; }, {}, ); for (const modelLocale in this.$plugin.config.locales) { const resolvedLocales: string[] = getResolvedLocales( modelLocale, SupportedLocales, this.$plugin.config.locales, ); for (const selectedLocale of selectedLocales) { if (resolvedLocales.includes(selectedLocale)) { buildLocaleMap[selectedLocale] = modelLocale; } } } // If Jovo model files for the current locales or resource files exist, ask whether to back them up or not. if ( this.$cli.project!.hasModelFiles(Object.values(buildLocaleMap)) || (this.$context.alexa.isACSkill && existsSync(this.$plugin.resourcesDirectory)) ) { const answer = await promptOverwriteReverseBuild(); if (answer.overwrite === ANSWER_CANCEL) { return; } if (answer.overwrite === ANSWER_BACKUP) { Log.spacer(); // Backup old files. const backupTask: Task = new Task(`${DISK} Creating backups`); const date: string = new Date().toISOString(); if (existsSync(this.$cli.project!.getModelsDirectory())) { const modelsBackupDirectory = `${this.$cli.project!.getModelsDirectory()}.${date}`; const modelTask: Task = new Task( `${this.$cli.project!.getModelsDirectory()} -> ${modelsBackupDirectory}`, () => { moveSync(this.$cli.project!.getModelsDirectory(), modelsBackupDirectory, { overwrite: true, }); }, ); backupTask.add(modelTask); } if (existsSync(this.$plugin.resourcesDirectory)) { const resourcesBackupDirectory = `${this.$plugin.resourcesDirectory}.${date}`; const resourcesTask: Task = new Task( `${this.$plugin.resourcesDirectory} -> ${resourcesBackupDirectory}`, () => { moveSync(this.$plugin.resourcesDirectory, resourcesBackupDirectory, { overwrite: true, }); }, ); backupTask.add(resourcesTask); } await backupTask.run(); } } for (const [platformLocale, modelLocale] of Object.entries(buildLocaleMap)) { const taskDetails: string = platformLocale === modelLocale ? '' : `(${modelLocale})`; const localeTask: Task = new Task(`${platformLocale} ${taskDetails}`, async () => { const alexaModelFiles: NativeFileInformation[] = [ { path: [], content: this.getPlatformModel(platformLocale), }, ]; const jovoModel = new JovoModelAlexa(); jovoModel.importNative(alexaModelFiles, modelLocale); const nativeData: JovoModelData | undefined = jovoModel.exportJovoModel(); if (!nativeData) { throw new JovoCliError({ message: 'Something went wrong while exporting your Jovo model.', module: this.$plugin.name, }); } this.$cli.project!.saveModel(nativeData, modelLocale); await wait(500); }); reverseBuildTask.add(localeTask); } } if (this.$context.alexa.isACSkill && this.$plugin.config.conversations?.directory) { if ( this.$plugin.config.conversations?.acdlDirectory && existsSync(this.$plugin.conversationsDirectory) ) { const acdlPath: string = joinPaths( this.$plugin.config.conversations.directory, this.$plugin.config.conversations.acdlDirectory, ); const copyAcdlFilesTask: Task = new Task( `Copying Alexa Conversations files into ${acdlPath}`, () => copySync(this.$plugin.conversationsDirectory, acdlPath), ); reverseBuildTask.add(copyAcdlFilesTask); } if ( this.$plugin.config.conversations?.responsesDirectory && existsSync(this.$plugin.responseDirectory) ) { const responsesPath: string = joinPaths( this.$plugin.config.conversations.directory, this.$plugin.config.conversations.responsesDirectory, ); const copyResponseFilesTask: Task = new Task( `Copying Response files into ${responsesPath}`, () => copySync(this.$plugin.responseDirectory, responsesPath), ); reverseBuildTask.add(copyResponseFilesTask); } } await reverseBuildTask.run(); } /** * Builds the Alexa skill manifest. */ buildProjectFiles(): void { const files: FileObject = FileBuilder.normalizeFileObject( _get(this.$plugin.config, 'files', {}), ); // If platforms folder doesn't exist, take default files and parse them with project.js config into FileBuilder. const projectFiles: FileObject = this.$cli.project!.hasPlatform(this.$plugin.platformDirectory) ? files : _merge(DefaultFiles, files); // Merge global project.js properties with platform files. const endpoint: string = this.getPluginEndpoint(); const endpointPath = 'skill-package/["skill.json"].manifest.apis.custom.endpoint'; // If a global endpoint is given and one is not already specified, set the global one. if (!_has(projectFiles, endpointPath)) { // If endpoint is of type ARN, omit the Wildcard certificate. const certificate: string | null = !endpoint.startsWith('arn') ? 'Wildcard' : null; // Create basic HTTPS endpoint from Wildcard SSL. _set(projectFiles, endpointPath, { sslCertificateType: certificate, uri: endpoint, }); } // replace ${JOVO_WEBHOOK_URL} in event uri with the Jovo Webhook url const eventEndpointUriPath = 'skill-package/["skill.json"].manifest.events.endpoint.uri'; if (_has(projectFiles, eventEndpointUriPath)) { _set( projectFiles, eventEndpointUriPath, this.$cli.resolveEndpoint(_get(projectFiles, eventEndpointUriPath).toString()), ); } // Create entries for Alexa Conversations const conversationsPath = 'skill-package/["skill.json"].manifest.apis.custom.dialogManagement'; if (this.$context.alexa.isACSkill && !_has(projectFiles, conversationsPath)) { _set(projectFiles, conversationsPath, { sessionStartDelegationStrategy: { target: this.$plugin.config.conversations?.sessionStartDelegationStrategy?.target, }, dialogManagers: [ { type: 'AMAZON.Conversations', }, ], }); } // Create ask profile entry const askResourcesPath = `["ask-resources.json"].profiles.${this.$context.alexa.askProfile}`; if (!_has(projectFiles, askResourcesPath)) { _set(projectFiles, askResourcesPath, { skillMetadata: { src: './skill-package', }, }); } const askConfigPath = `[".ask/"].["ask-states.json"].profiles.${this.$context.alexa.askProfile}`; const skillId: string | undefined = this.$plugin.config.skillId; const skillIdPath = `${askConfigPath}.skillId`; // Check whether skill id has already been set. if (skillId && !_has(projectFiles, skillIdPath)) { _set(projectFiles, skillIdPath, skillId); } const skillName: string = this.$cli.project!.getProjectName(); const locales: string[] = this.$context.locales.reduce((locales: string[], locale: string) => { locales.push(...getResolvedLocales(locale, SupportedLocales, this.$plugin.config.locales)); return locales; }, []); for (const locale of locales) { // Check whether publishing information has already been set. const publishingInformationPath = `skill-package/["skill.json"].manifest.publishingInformation.locales.${locale}`; if (!_has(projectFiles, publishingInformationPath)) { _set(projectFiles, publishingInformationPath, { summary: 'Sample Short Description', examplePhrases: ['Alexa open hello world'], keywords: ['hello', 'world'], name: skillName, description: 'Sample Full Description', smallIconUri: 'https://via.placeholder.com/108/09f/09f.png', largeIconUri: 'https://via.placeholder.com/512/09f/09f.png', }); } const privacyAndCompliancePath = `skill-package/["skill.json"].manifest.privacyAndCompliance.locales.${locale}`; // Check whether privacy and compliance information has already been set. if (!_has(projectFiles, privacyAndCompliancePath)) { _set(projectFiles, privacyAndCompliancePath, { privacyPolicyUrl: 'http://example.com/policy', termsOfUseUrl: '', }); } } FileBuilder.buildDirectory(projectFiles, this.$plugin.platformPath); } /** * Creates and returns tasks for each locale to build the interaction model for Alexa. */ async buildInteractionModel(): Promise<string[]> { const output: string[] = []; for (const locale of this.$context.locales) { const resolvedLocales: string[] = getResolvedLocales( locale, SupportedLocales, this.$plugin.config.locales, ); const resolvedLocalesOutput: string = resolvedLocales.join(', '); // If the model locale is resolved to different locales, provide task details, i.e. "en (en-US, en-CA)"". const taskDetails: string = resolvedLocalesOutput === locale ? '' : `(${resolvedLocalesOutput})`; await this.buildLanguageModel(locale, resolvedLocales); await wait(500); output.push(`${locale} ${taskDetails}`); } return output; } /** * Builds and saves an Alexa model from a Jovo model. * @param modelLocale - Locale of the Jovo model. * @param resolvedLocales - Locales to which to resolve the modelLocale. */ async buildLanguageModel(modelLocale: string, resolvedLocales: string[]): Promise<void> { const model = _merge( await this.getJovoModel(modelLocale), this.$cli.project!.config.getParameter(`models.override.${modelLocale}`), ); try { for (const locale of resolvedLocales) { const jovoModel: JovoModelAlexa = new JovoModelAlexa(model as JovoModelData, locale); const alexaModelFiles: NativeFileInformation[] = jovoModel.exportNative() as NativeFileInformation[]; if (!alexaModelFiles || !alexaModelFiles.length) { // Should actually never happen but who knows throw new JovoCliError({ message: `Could not build Alexa files for locale "${locale}"!`, module: this.$plugin.name, }); } const modelsPath: string = this.$plugin.modelsPath; if (!existsSync(modelsPath)) { mkdirSync(modelsPath, { recursive: true }); } writeFileSync( this.$plugin.getModelPath(locale), JSON.stringify(alexaModelFiles[0].content, null, 2), ); } } catch (error) { if (!isJovoCliError(error)) { throw new JovoCliError({ message: error.message, module: this.$plugin.name }); } throw error; } } buildConversationsFiles(): void { const src: string = joinPaths( this.$plugin.config.conversations!.directory!, this.$plugin.config.conversations!.acdlDirectory!, ); if (!existsSync(src)) { throw new JovoCliError({ message: `Directory for Alexa Conversations files does not exist at ${src}`, module: this.$plugin.name, hint: `Try creating your .acdl files in ${src} or specify the directory of your choice in the project configuration`, }); } copySync(src, this.$plugin.conversationsDirectory); } buildResponseFiles(): void { const src: string = joinPaths( this.$plugin.config.conversations!.directory!, this.$plugin.config.conversations!.responsesDirectory!, ); if (!existsSync(src)) { throw new JovoCliError({ message: `Directory for Alexa response files does not exist at ${src}`, module: this.$plugin.name, hint: `Try creating your APL-A response files in ${src} or specify the directory of your choice in the project configuration`, }); } copySync(src, this.$plugin.responseDirectory); } /** * Get plugin-specific endpoint. */ getPluginEndpoint(): string { const endpoint: string = _get(this.$plugin.config, 'endpoint') || (this.$cli.project!.config.getParameter('endpoint') as string); if (!endpoint) { throw new JovoCliError({ message: 'endpoint has to be set', hint: 'Try setting your endpoint in the project configuration', learnMore: 'https://www.jovo.tech/docs/project-config#endpoint', }); } return this.$cli.resolveEndpoint(endpoint); } /** * Loads a platform-specific model. * @param locale - Locale of the model. */ getPlatformModel(locale: string): JovoModelData { const content: string = readFileSync(this.$plugin.getModelPath(locale), 'utf-8'); return JSON.parse(content); } /** * Returns all locales for the current platform. */ getPlatformLocales(): string[] { const files: string[] = readdirSync(this.$plugin.modelsPath); if (!existsSync(this.$plugin.modelsPath)) { throw new JovoCliError({ message: 'Could not find Alexa language models', details: `"${this.$plugin.modelsPath}" does not exist`, hint: 'Please validate that you configured the "buildDirectory" or "stage" correctly', }); } // Map each file to it's identifier, without file extension. return files.map((file: string) => { const localeRegex = /(.*)\.(?:[^.]+)$/; const match = localeRegex.exec(file); // ToDo: Test! if (!match) { return file; } return match[1]; }); } /** * Loads a Jovo model specified by a locale and merges it with plugin-specific models. * @param locale - The locale that specifies which model to load. */ async getJovoModel(locale: string): Promise<JovoModelData | JovoModelDataV3> { const model: JovoModelData | JovoModelDataV3 = await this.$cli.project!.getModel(locale); // Merge model with configured language model in project.js. _mergeWith( model, this.$cli.project!.config.getParameter(`languageModel.${locale}`) || {}, mergeArrayCustomizer, ); // Merge model with configured, platform-specific language model in project.js. _mergeWith( model, _get(this.$plugin.config, `options.languageModel.${locale}`, {}), mergeArrayCustomizer, ); return model; } }
the_stack
import OS = require("os"); import Process = require("process"); import File = require("fs"); import Path = require("path"); import { EventEmitter } from "events"; // Note: The 'import * as Foo from "./Foo' syntax avoids the "compiler re-write problem" that breaks debugger hover inspection import * as Configuration from "../Configuration"; import * as Utils from "../Utils/Utils-Index"; import { RejectedPromise } from "../ICProcess"; // There is no re-write issue here as this is just a type export const ENTER_KEY: string = "\r"; // Same on ALL platforms (Windows, Linux and MacOS) export const NEW_LINE: string = OS.EOL; // "\r\n" on Windows, "\n" on Linux and MacOS /** * A utility type that's an object with a property name indexer.\ * This allows indexed property lookups when using 'noImplicitAny'. */ export interface SimpleObject { [key: string]: any }; // Because the indexer returns an explicit 'any' it's no longer an implicit 'any' /** A type that excludes _undefined_ from T. */ type NeverUndefined<T> = T extends undefined ? never : T; /** * Throws if the supplied value is _undefined_ (_null_ is allowed).\ * Returns (via casting) the supplied value as a T with _undefined_ removed from its type space. * This informs the compiler that the value cannot be _undefined_, which is useful when 'strictNullChecks' is enabled. */ export function assertDefined<T>(value: T, valueNameOrError?: string | Error): NeverUndefined<T> { if (value === undefined) { throw (valueNameOrError instanceof Error) ? valueNameOrError : new Error(`Encountered unexpected undefined value${valueNameOrError? ` for '${valueNameOrError}'` : ""}`); } return (value as NeverUndefined<T>); } /** * Class used to create a GUID.\ * Be careful how this is used: it returns a non-deterministic value. */ export class Guid { /** * Returns a random GUID as a string.\ * For example "{d30f4d65-9950-4f02-822d-c33c2d88ce72}". */ static newGuid(): string { // 4 = version 4 (random), V = variant (encoded, in our case, into the 2 most-significant bits only) return ("{xxxxxxxx-xxxx-4xxx-Vxxx-xxxxxxxxxxxx}".replace(/[xV]/g, function replacer(char: string) { let randomByteValue: number = Math.floor(Math.random() * 16); // Note: Math.random() will never return 1 let byteValue: number = (char === 'x') ? randomByteValue : (randomByteValue & 0x3 | 0x8); // For the 'V' byte we set the random variant to 1 (10xx) [see https://en.wikipedia.org/wiki/Universally_unique_identifier] return (byteValue.toString(16)); })); } } /** Returns true if the specified IPv4 address is an address that refers to the local machine. */ export function isLocalIPAddress(ipv4Address: string): boolean { return (ipv4Address ? getLocalIPAddresses().indexOf(ipv4Address.trim()) !== -1 : false); } /** Returns a list of all IPv4 addresses for the local machine, including the loopback address (typically 127.0.0.1). */ export function getLocalIPAddresses(): string[] { const localIPv4Addresses: string[] = []; const NICs: NodeJS.Dict<OS.NetworkInterfaceInfo[]> = OS.networkInterfaces(); for (const name of Object.keys(NICs)) { const nic: OS.NetworkInterfaceInfo[] | undefined = NICs[name]; if (nic) { for (const net of nic) { if (net.family === "IPv4") { localIPv4Addresses.push(net.address); } } } } return (localIPv4Addresses); } /** Returns the specified XML as a formatted string (with indenting and new-lines). */ export function formatXml(xml: string, tab: string = " ") { // See https://stackoverflow.com/questions/376373/pretty-printing-xml-with-javascript/ [in the post by 'arcturus' (https://stackoverflow.com/a/49458964)] let formattedXml: string = ""; let indent: string = ""; xml.split(/>\s*</).forEach((node: string) => { if (node.match(/^\/\w/)) // Eg. "/test>" { indent = indent.substring(tab.length); // Decrease indent by one 'tab' } formattedXml += `${indent}<${node}>${OS.EOL}`; if (node.match(/^<?\w[^>]*[^\/]$/)) // Eg. "<test" (Note: Only the first [split] node will start with '<') { indent += tab; // Increase indent by one 'tab' } }); return (formattedXml.substring(1, formattedXml.length - (1 + OS.EOL.length))); // Remove extraneous leading '<' and trailing '>\r\n' } /** Encodes a string so that it can be used as an XML value (eg. as an attribute value or as entity content). */ export function encodeXmlValue(value: string) { return (value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;")); } /** Decodes XML which may contain values encoded using encodeXmlValue(). */ export function decodeXml(xml: string) { return (xml.replace(/&apos;/g, "'").replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&')); } /** Escapes a string (that might contain RegExp special characters) for use in a 'new RegExp()' (or 'RegExp()') call. */ export function regexEscape(value: string): string { return (value.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&")); } /** * Defines the type of a compiled 'enum' object in TypeScript 3.6 (an object with string keys (property names) and string or number property values). * This allows enums to be processed as objects when needed, but may break in future versions of TypeScript. */ export interface EnumType { [key: string]: string | number; } /** * Returns the available values of an specified enum type (eg. "1=Foo,2=Bar").\ * Will throw if enumType contains any non-integer valued members. */ export function getEnumValues(typeName: string, enumType: EnumType): string { let enumValues: string = ""; checkEnumForNonIntegerValues(typeName, enumType); for (let propName in enumType) { if (typeof enumType[propName] === "number") { enumValues += `${enumValues.length === 0 ? "" : ","}${enumType[propName]}=${propName}`; } } return (enumValues); } /** * Returns all the value names (keys) from the specified enum.\ * Will throw if enumType contains any non-integer valued members. */ export function getEnumKeys(typeName: string, enumType: EnumType): string[] { const enumKeys: string[] = []; checkEnumForNonIntegerValues(typeName, enumType); for (const propName in enumType) { if (typeof enumType[propName] === "number") { enumKeys.push(propName); } } return (enumKeys); } /** Throws if the specified enum contains any non-integer valued members. */ function checkEnumForNonIntegerValues(typeName: string, enumType: EnumType): void { let nonIntegerValuedKeys: string[] = Object.keys(enumType).filter(k => !Number.isInteger(parseInt(k)) && !RegExp("^-?[0-9]+$").test(enumType[k].toString())); if (nonIntegerValuedKeys.length > 0) { throw new Error(`The '${typeName}' enum contains a member ('${nonIntegerValuedKeys[0]}') which does not have an integer value ('${enumType[nonIntegerValuedKeys[0]]}')`); } } const _knownCommandLineArgs: string [] = ["ambrosiaConfigFile", "autoRegister", "registerInstance", "eraseInstance", "eraseInstanceAndReplicas"]; /** * Returns true if the named command-line argument (eg. "arg1") is present without a value. Use this to detect an argument that does not require a value; * its presence alone is sufficient (eg. "--help"). See also: getCommandLineArg(). * * Most command-line args will belong to the app; Ambrosia uses ambrosiaConfig.json to specify start-up parameters. * * Note: 'argName' does not need to match on case. Further, 'argName' is a specifier so it can be of the form "[-]acronym|fullName" in addition to simply "name". * For example, "-t|test" means the name can be either "-t" or "--test", and "fn|fileName" means either "fn" or "fileName". */ export function hasCommandLineArg(argName: string): boolean { return (getCommandLineArg(argName, "[N/A]") === "[present]"); } /** * Returns the value of a named command-line argument (eg. "arg1=foo"), or returns 'defaultValue' if the named argument is not found. If 'defaultValue' is not * supplied, this indicates that the argument is required and the method will throw if it's missing from the command-line. See also: hasCommandLineArg(). * * Most command-line args will belong to the app; Ambrosia uses ambrosiaConfig.json to specify start-up parameters. * * Note: 'argName' does not need to match on case. Further, 'argName' is a specifier so it can be of the form "[-]acronym|fullName" in addition to simply "name". * For example, "-t|test" means the name can be either "-t" or "--test", and "fn|fileName" means either "fn" or "fileName". */ export function getCommandLineArg(argName: string, defaultValue?: string): string { argName = argName.replace(/\s/g, ""); const args: string[] = Process.argv; const isRequired: boolean = (defaultValue === undefined); const requiresLeadingDash: boolean = argName.startsWith("-"); let argNameVariants: string[] = []; if (argName.split("|").length > 2) { throw new Error(`Malformed Ambrosia command-line parameter name specifier '${argName}'; Too many '|' characters`); } if (argName.indexOf("|") !== -1) { // Note: We want to allow "-f|foo-bar", but not "--f|foo-bar" if (argName.startsWith("--")) { throw new Error(`Malformed Ambrosia command-line parameter name specifier '${argName}'; Too many '-' characters`); } // Eg. "-acf|ambrosiaConfigFile" becomes ["-acf", "--ambrosiaConfigFile"] // "acf|ambrosiaConfigFile" becomes ["acf", "ambrosiaConfigFile"] argNameVariants = argName.replace(/^-*/g, "").split("|").map((name, i) => (requiresLeadingDash ? "-".repeat(i + 1) : "") + name); } else { argNameVariants.push(argName); } // We keep track of all "known" arg names so that getUnknownCommandLineArg() can work for (const argName of argNameVariants) { if (_knownCommandLineArgs.indexOf(argName) === -1) { _knownCommandLineArgs.push(argName); } } // 'args' will be: [NodeExe] [JSFile] [Arg1] [Arg2] ... // eg. "C:\Program Files\nodejs\node.exe C:\src\Git\AMBROSIA\Clients\AmbrosiaJS\TestApp-Node\out\TestApp.js appArg1 appArg2 appArg3 ambrosiaConfigFile=testConfig.json" for (let i = 2; i < args.length; i++) { if (args[i].indexOf("=") !== -1) { let parts: string[] = args[i].split("="); let name: string = parts[0]; let value: string = parts[1]; for (let v = 0; v < argNameVariants.length; v++) { const argNameVariant: string = argNameVariants[v]; if (equalIgnoringCase(name, argNameVariant)) { if (isRequired && (value.length === 0)) { throw new Error(`No value was specified for the required Ambrosia command-line parameter '${argNameVariant}'`); } if (defaultValue === "[N/A]") { throw new Error(`Malformed Ambrosia command-line parameter '${args[i]}'; An "=(value)" is not expected`); } return (value); } // Is the arg missing leading dash(es)? if (equalIgnoringCase(name, argNameVariant.replace(/^-*/g, ""))) { throw new Error(`Malformed Ambrosia command-line parameter '${name}'; Expected ${argNameVariant}`); } } } else { if (argNameVariants.indexOf(args[i]) !== -1) { // This is how we handle args like "h|help" which simply need to be present to have meaning (and so don't follow the "arg=value" format) if (defaultValue === "[N/A]") { return ("[present]"); } throw new Error(`Malformed Ambrosia command-line parameter '${args[i]}'; Missing "=(value)"`); } } } if (defaultValue === undefined) // We can't use 'isRequired' here because we need to make the compiler happy when using 'strictNullChecks' { throw new Error(`The Ambrosia command-line parameter '${argNameVariants.join("' or '")}' is required`); } return (defaultValue); } /** * Returns the names of command-line parameters that are known to either Ambrosia, or to your app * (**after** retrieving all valid app parameters using getCommandLineArg() and/or hasCommandLineArg()). */ export function getKnownCommandLineArgs(): readonly string[] { return (_knownCommandLineArgs); } /** * Returns the first unknown command-line parameter name (if any).\ * Otherwise, returns null. * Should only be called **after** retrieving all valid app parameters with getCommandLineArg() and/or hasCommandLineArg(). */ export function getUnknownCommandLineArg(): string | null { const args: string[] = Process.argv; for (let i = 2; i < args.length; i++) { const argName: string = (args[i].indexOf("=") !== -1) ? args[i].split("=")[0] : args[i]; if (_knownCommandLineArgs.indexOf(argName) === -1) { return (argName); } } return (null); } /** Converts an array of bytes to a string to enable the byte array to be viewed. Set 'base' to 16 to view as hex. The string will contain, at most, maxDisplayBytes (defaults to 2048). */ export function makeDisplayBytes(bytes: Uint8Array, startIndex: number = 0, length: number = bytes.length - startIndex, base: number = 10, maxDisplayBytes: number = 2048): string { let bytesAsString: string = ""; let requestedEndIndex: number = Math.min(startIndex + length, bytes.length); let endIndex: number = requestedEndIndex; let outputTruncated: boolean = (endIndex - startIndex) > maxDisplayBytes; if (outputTruncated) { endIndex = startIndex + maxDisplayBytes - 1; } for (let i = startIndex; i < endIndex; i++) { switch (base) { case 16: bytesAsString += ("0" + bytes[i].toString(base)).slice(-2) + " "; break; case 10: bytesAsString += bytes[i].toString(base) + " "; break; default: throw new Error("Only base 16 (hex) and base 10 (decimal) are currently supported"); } } if (outputTruncated) { let omitted: string = ((requestedEndIndex - endIndex - 1) > 0) ? `...(${requestedEndIndex - endIndex - 1} bytes omitted)... ` : ""; bytesAsString += `${omitted}${bytes[requestedEndIndex - 1]}`; } return (bytesAsString.trim()); } /** Return a byte value (0..255) as a fixed 2-digit hex string. */ export function byteToFixedHex(byte: number) { return (("0" + (byte & 0xFF).toString(16)).slice(-2)); } /** Returns true if the 2 specified strings are equal, regardless of case (but not accent). So "Ambrosia" = "AMBROSIA", but "ámbrosiá" != "ambrosia". */ export function equalIgnoringCase(s1: string, s2: string): boolean { return ((s1.length !== s2.length) ? false : (s1.toLowerCase() === s2.toLowerCase())); } /** Deletes [synchronously] the specified fully-pathed file, if it exists. Returns true if the file was deleted. */ export function deleteFile(fullyPathedFileName: string): boolean { if (File.existsSync(fullyPathedFileName)) { File.unlinkSync(fullyPathedFileName); return (true); } return (false); } /** * Creates a [test] file of arbitrary size, overwriting the file if it already exists. * The last byte will always be 0x7F (127). Returns the supplied fileName. * Example usage: let data: Uint8Array = fs.readFileSync(Utils.createTestFile("./TestCheckpoint.dat", 2050)); */ export function createTestFile(fileName: string, sizeInBytes: number, byteValue: number = -1): string { let data: Uint8Array = new Uint8Array(sizeInBytes); for (let i = 0; i < sizeInBytes; i++) { data[i] = (byteValue === -1) ? i % 256 : (byteValue % 256); } data[sizeInBytes - 1] = 127; // 0x7F File.writeFileSync(fileName, data); return (fileName); } /** Returns the size of the specified file. */ export function getFileSize(fileName: string): number { return (File.statSync(fileName)["size"]); } /** Returns the 'last modified' date of the file. For an executable binary [which doesn't ever change], 'last modified ' is effectively the true creation date. */ export function getFileLastModifiedTime(fileName: string): Date { let creationTime: Date = new Date(File.statSync(fileName)["mtimeMs"]); return (creationTime); } /** * Creates (or restarts) a one-time only timer. The timer is restarted (using the original timeout) * at each subsequent call until the timer ticks, after which the timer will no longer restart. * Returns the timer, which is created if the supplied timer is null. */ export function restartOnceOnlyTimer(timer: NodeJS.Timeout & SimpleObject, timeoutInMs: number, onTick: () => void): NodeJS.Timeout { if (timer && timer["__hasTicked__"] === true) { // The timer has already ticked return (timer); } if (!timer) { // Create the timer let newTimer: NodeJS.Timeout & SimpleObject = setTimeout(() => { newTimer["__hasTicked__"] = true; onTick(); }, timeoutInMs); return (newTimer); } else { // The timer is already running timer.refresh(); // Restart the timer return (timer); } } /** * Returns the size (in bytes) of node's long-term ("old") GC heap. * * If needed, set the V8 parameter '--max-old-space-size' to raise the size of the heap. */ export function getNodeLongTermHeapSizeInBytes(): number { // Related: https://nodejs.org/api/cli.html#cli_max_old_space_size_size_in_megabytes // https://github.com/nodejs/node/issues/7937 // If node's --max-old-space-size parameter is left at its default value (0), node will use [up to] 1400MB on a 64 bit OS (or 700MB on an 32-bit OS) // for the GC's "old generation" heap (see https://v8.dev/blog/trash-talk), which is where objects that survive 2 GC's will end up // (see https://github.com/nodejs/node/blob/ec02b811a8a5c999bab4de312be2d732b7d9d50b/deps/v8/src/heap/heap.cc#L82). const is64BitNodeExe: boolean = RegExp("64").test(OS.arch()); const v8MaxOldSpaceSize: number = parseInt(Utils.getCommandLineArg("--max-old-space-size", "0")); const nodeMaxOldGenerationSize: number = v8MaxOldSpaceSize ? v8MaxOldSpaceSize : ((is64BitNodeExe ? 1400 : 700) * 1024 * 1024); return (nodeMaxOldGenerationSize); } /** A dictionary of the currently active spin waits, which are used to wait (using a timer) for a [non-awaitable] asynchronous operation to complete. */ let _spinWaiters: { [waitName: string]: { timer: NodeJS.Timeout, iteration: number, startTime: number, intervalInMs: number } } = {}; // Key = Name of operation being waited on, value = Spin-wait details /** * Waits for a [non-awaitable] asynchronous operation to complete. Calls continueWaiting() every waitIntervalInMs, which can be no smaller than 50ms.\ * When continueWaiting() returns false, onWaitComplete() will be called - which, typically, should simply re-call the caller of spinWait().\ * If timeoutInMs (defaults to 8000ms) elapses without continueWaiting() returning false, the wait will be aborted and onWaitTimeout() - if supplied - * will be called. Set timeoutInMs to -1 for no timeout.\ * Returns true if a wait is required (ie. the caller should not continue) or false otherwise (ie. the caller can continue). */ export function spinWait(waitName: string, continueWaiting: () => boolean, onWaitComplete: () => void, waitIntervalInMs: number = 100, timeoutInMs: number = 8000, onWaitTimeout?: (elapsedMs: number) => void): boolean { if (!continueWaiting()) { return (false); // No need to wait (ie. the caller can continue) } // Ensure waitIntervalInMs is at least 50ms (to avoid a "tight-spin" on whatever continueWaiting() does) waitIntervalInMs = Math.max(50, waitIntervalInMs); // Ensure that timeoutInMs is not less than waitIntervalInMs if (timeoutInMs !== -1) { timeoutInMs = Math.max(waitIntervalInMs, timeoutInMs); } Utils.log(`Waiting for '${waitName}'...`); if (_spinWaiters[waitName] === undefined) { let timer: NodeJS.Timeout = setInterval(function checkSpinWait() { if (!continueWaiting()) { // We can stop waiting clearInterval(_spinWaiters[waitName].timer); delete _spinWaiters[waitName]; Utils.log(`Wait for '${waitName}' complete`); onWaitComplete(); } else { // Keep waiting (but only until timeoutInMs is reached, unless the timeout is -1 [infinite]) _spinWaiters[waitName].iteration++; let totalElapsedMs: number = Date.now() - _spinWaiters[waitName].startTime; if ((timeoutInMs !== -1) && (totalElapsedMs >= timeoutInMs)) { Utils.log(`Error: spinWait '${waitName}' timed out after ${totalElapsedMs}ms (${_spinWaiters[waitName].iteration} iterations of ${waitIntervalInMs}ms)`); clearInterval(_spinWaiters[waitName].timer); delete _spinWaiters[waitName]; if (onWaitTimeout) { onWaitTimeout(totalElapsedMs); } } } }, waitIntervalInMs); _spinWaiters[waitName] = { timer: timer, iteration: 0, startTime: Date.now(), intervalInMs: waitIntervalInMs }; } else { throw new Error(`The waitName '${waitName}' already exists`); } return (true); // Wait required (ie. the caller should NOT continue) } /** Returns the fully qualified path to the IC executable. Will throw if the path/executable does not exist. */ export function getICExecutable(ambrosiaToolsDir: string = "", useNetCore: boolean = false, isTimeTravelDebugging: boolean = false): string { let fullyPathedExecutable: string = ""; let fullyPathedExecutableFallback: string = ""; let executableName: string = isTimeTravelDebugging ? "Ambrosia" : "ImmortalCoordinator"; let ambrosiaToolsDirs: string[] = []; let exMessages: string[] = []; if (ambrosiaToolsDir) { for (let dir of ambrosiaToolsDir.split(";")) { dir = dir.trim(); if (!File.existsSync(dir)) { throw new Error(`The specified 'ambrosiaToolsDir' (${dir}) does not exist; check that the 'icBinFolder' setting is correct in ${Configuration.loadedConfigFileName()}`); } ambrosiaToolsDirs.push(dir); } } else { if (!Process.env["AMBROSIATOOLS"]) { throw new Error("The 'AMBROSIATOOLS' environment variable is missing"); } ambrosiaToolsDir = Process.env["AMBROSIATOOLS"]; if (!File.existsSync(ambrosiaToolsDir)) { throw new Error(`The 'AMBROSIATOOLS' environment variable references a folder (${ambrosiaToolsDir}) that does not exist`); } ambrosiaToolsDirs.push(ambrosiaToolsDir); } for (const dir of ambrosiaToolsDirs) { if (isWindows()) { // Note: In .Net Core 2.1 is was necessary to run the app (a [potentially] cross-platform DLL) using "dotnet <filename.dll>", // and this still works in later versions of .Net Core. However, from .Net Core 3.0 onwards, if the .csproj specifies // <OutputType>Exe</OutputType> (which ImmortalCoordinator.csproj does) it also produces a platform-specific executable // (eg. an .exe on Windows) that will launch the app (as an alternative to, but not a replacement for, using "dotnet <filename.dll>" // as the launcher). We continue to use the "dotnet <filename.dll>" approach to start the IC [when 'useNetCore' is true] - see IC.start(). fullyPathedExecutable = Path.join(dir, `${useNetCore ? "netcoreapp3.1" : "net461"}`, `${executableName}.${useNetCore ? "dll" : "exe"}`); // The "fallback" folder handles the case where the user has copied the binaries to a different location than either the local build folder (which // has net461/netcoreapp3.1 folders) or the folder structure in Ambrosia-win-x64.zip from https://github.com/microsoft/AMBROSIA/releases (which // also has net461/netcoreapp3.1 folders) fullyPathedExecutableFallback = Path.join(dir, `${executableName}.${useNetCore ? "dll" : "exe"}`); } else { // Note: The pre-built Ambrosia-linux.tgz (https://github.com/microsoft/AMBROSIA/releases) doesn't have // either "netcoreapp3.1" or "net461" folders (even though Ambrosia-win-x64.zip does), because the // .Net Framework (eg. net461) is for Windows ONLY (Linux can only use .Net Core). // For non-Windows platforms, the pre-built binaries (eg. from Ambrosia-linux.tgz) are published as // framework-dependent apps (see https://docs.microsoft.com/en-us/dotnet/core/deploying/#publish-framework-dependent). // This produces a cross-platform binary as a dll file, and a platform-specific executable that targets // the specified platform (eg. "Linux-x64"). // Note that executables (ie. the equivalent of a .exe on Windows) have no extension on Linux and MacOS. fullyPathedExecutable = Path.join(dir, executableName); // Eg. "/ambrosia/bin/ImmortalCoordinator" } if (!File.existsSync(fullyPathedExecutable)) { if (fullyPathedExecutableFallback) { if (!File.existsSync(fullyPathedExecutableFallback)) { exMessages.push(`The computed executable path (${fullyPathedExecutableFallback}) does not exist`); } else { fullyPathedExecutable = fullyPathedExecutableFallback; exMessages.length = 0; break; } } else { exMessages.push(`The computed executable path (${fullyPathedExecutable}) does not exist`); } } else { exMessages.length = 0; break; } } if (exMessages.length > 0) { throw new Error(exMessages.join("; ")); } return (fullyPathedExecutable); } /** Ensures that the supplied path ends with the path-separator character (eg. "/"). */ export function ensurePathEndsWithSeparator(path: string): string { if (path) { path = path.trim(); if (path.trim().length > 0) { let separator: string = (path.indexOf("\\") !== -1) ? "\\" : "/"; if (!path.endsWith(separator)) { path += separator; } } } return (path); } /** Returns the specified 'value' with any trailing 'char' character removed. */ export function trimTrailingChar(value: string, char: string): string { if (value.substr(value.length - 1, 1) === char[0]) { return (value.substr(0, value.length - 1)); } return (value); } let _isJsPlatformNode: boolean | null = null; /** Returns true if the JavaScript platform is Node.js. */ export function isNode(): boolean { if (_isJsPlatformNode === null) { _isJsPlatformNode = (typeof process === "object") && (typeof process.versions === "object") && (typeof process.versions.node !== "undefined"); } return (_isJsPlatformNode); } /** Returns true if OS is little-endian. */ export function isLittleEndian(): boolean { return (OS.endianness() === "LE"); } /** Returns true if the OS is Windows. */ export function isWindows(): boolean { return (OS.platform() === "win32"); } /** * Starts accepting user input from the terminal. Calls the supplied callback whenever a character is entered at the terminal (stdin).\ * Note: If using VSCode, using this method requires this setting in launch.json:\ * _"console": "integratedTerminal"_ */ export function consoleInputStart(callback: (char: string) => void) { // When Node.js detects that it is being run with a text terminal ("TTY") attached, process.stdin will, by default, be initialized as an instance of tty.ReadStream if (Process.stdin.isTTY) { Process.stdin.setRawMode(true); // Process input character-by-character (rather than waiting until 'Enter' is pressed) Process.stdin.setEncoding("utf8"); // Specify that the input is string (character) data, not Buffer data Process.stdin.on("data", function onCharacter(key: string) { callback(key); }); } else { throw new Error("No text terminal is attached to Node; if using VSCode, try setting \"console\": \"integratedTerminal\" in launch.json"); } } /** * Asynchronously waits for one of the specified 'chars' keys to pressed.\ * To wait for any key, omit the 'chars' parameter. Returns the key pressed.\ * 'chars' will always be converted to lower-case.\ * When using this method, do **not** also use consoleInputStart().\ * Note: If using VSCode, using this method requires this setting in launch.json:\ * _"console": "integratedTerminal"_ */ export async function consoleReadKeyAsync(chars: string[] = []): Promise<string> { let promise: Promise<string> = new Promise<string>((resolve, reject: RejectedPromise) => { try { for (const char of chars) { if (!((char.length === 1) || ((char.length === 2) && (char[0] === "\\")))) { throw new Error(`Invalid 'chars' value "${char}"; only single character strings are allowed`); } } const lowerCaseChars: string[] = chars.map(ch => ch.toLowerCase()); consoleInputStart((char: string) => { try { char = char.toLowerCase(); if ((lowerCaseChars.length === 0) || (lowerCaseChars.indexOf(char) !== -1)) { resolve(char); consoleInputStop(); } } catch (error: unknown) { reject(Utils.makeError(error)); consoleInputStop(); } }); } catch (error: unknown) { reject(Utils.makeError(error)); consoleInputStop(); } }); return (promise); } /** Stops accepting user input from the terminal, as started by calling consoleInputStart(). */ export function consoleInputStop() { if (Process.stdin.isTTY) { Process.stdin.push(null); } } /** * [Internal] Basic utility method to measure performance.\ * Returns the number of elapsed milliseconds for 'iterations' executions of 'task'. */ export function basicPerfTest(task: (iteration?: number) => void, iterations: number, logResult: boolean = true): number { const startTime: number = Date.now(); for (let i = 0; i < iterations; i++) { task(i); } const elapsedMs: number = Date.now() - startTime; if (logResult) { Utils.log(`Elapsed: ${elapsedMs}ms (for ${iterations.toLocaleString()} iterations); ${Math.ceil(elapsedMs / iterations)}ms average`); } return (elapsedMs); } /** Returns the FNV-1a (Fowler/Noll/Vo) 32-bit hash value for the specified Buffer. */ // See: https://papa.bretmulvey.com/post/124027987928/hash-functions // FNV test cases can be found here: http://www.isthe.com/chongo/src/fnv/test_fnv.c // Spot checks [test #38]: console.log(Utils.computeHash(Buffer.from("chongo was here!")).toString(16)); // Should return 448524fd // : console.log(Utils.computeHash(Buffer.alloc((8 * 1024 * 1024)).fill(205)).toString(16)); // Should return 8b9c9dc5 function computeHash(data: Buffer): number { const FNV_32_PRIME: number = 16777619; const FNV_32_OFFSET_BASIS: number = 2166136261; const numBytes: number = data.byteLength; let hash: number = FNV_32_OFFSET_BASIS; for (let i = 0; i < numBytes; i++) { hash = multiply_uint32(hash ^ data[i], FNV_32_PRIME); } return (hash); /** [Local function] Multiplies two unsigned 32-bit integers, and returns the "wrapped" result as a Uint32. */ // See https://stackoverflow.com/questions/6232939/is-there-a-way-to-correctly-multiply-two-32-bit-integers-in-javascript/6422061 function multiply_uint32(a: number, b: number): number { const aHigh: number = (a >> 16) & 0xffff; const aLow: number = a & 0xffff; const bHigh: number = (b >> 16) & 0xffff; const bLow: number = b & 0xffff; const high = ((aHigh * bLow) + (aLow * bHigh)) & 0xffff; return ((((high << 16) >>> 0) + (aLow * bLow)) >>> 0); // Note: Using '>>> 0' to "cast" the result to a Uint32 // Note: To do the complete multiplication (ie. a * b): // result = (((aHigh << 16) >>> 0) * ((bHigh << 16) >>> 0)) + // (((aHigh << 16) >>> 0) * bLow) + // (aLow * ((bHigh << 16) >>> 0)) + // (aLow * bLow); } } /** * Base exception for all errors raised by Ambrosia. * Note: We don't use this because (in VSCode at least) the top of the call stack will * always be reported (file/line) as the constructor method below, making it harder * to jump to the method that actually threw the exception. /* export class AmbrosiaException extends Error { constructor(message: string, stack?: string) { super(message); this.name = "AmbrosiaException"; if (stack) { this.stack = stack; } } } */ /** * A utility class used to wrap an async function as a callback function.\ * The async method should call complete() on the supplied AsyncCompleteWrapper from its 'finally' block.\ * The async method must also have a 'catch' block to enable it to be called synchronously (ie. without being awaited).\ * Note: If the wrapped async function doesn't call await, it will run synchronously then call onComplete(). */ export class AsyncCompleteWrapper extends EventEmitter { private static readonly ASYNC_OP_COMPLETE_EVENT: string = "AsyncOpComplete"; constructor(onComplete: (error?: Error) => void) { super(); this.once(AsyncCompleteWrapper.ASYNC_OP_COMPLETE_EVENT, onComplete); } /** Called from the 'finally' block of an async method to signal that the async operation has completed (either successfully, or with an error). */ complete(error?: Error): void { this.emit(AsyncCompleteWrapper.ASYNC_OP_COMPLETE_EVENT, error); } }
the_stack
class RegExLexer { // \ ^ $ . | ? * + ( ) [ { static readonly CHAR_TYPES = { '.': 'dot', '|': 'alt', '$': 'eof', '^': 'bof', '?': 'opt', // also: "lazy" '+': 'plus', '*': 'star', } static readonly ESC_CHARS_SPECIAL = { w: 'word', W: 'notword', d: 'digit', D: 'notdigit', s: 'whitespace', S: 'notwhitespace', b: 'wordboundary', B: 'notwordboundary', // u-uni, x-hex, c-ctrl, oct handled in parseEsc } static readonly UNQUANTIFIABLE = { quant: true, plus: true, star: true, opt: true, eof: true, bof: true, group: true, // group open lookaround: true, // lookaround open wordboundary: true, notwordboundary: true, lazy: true, alt: true, open: true, } static readonly ESC_CHAR_CODES = { 0: 0, // null t: 9, // tab n: 10, // lf v: 11, // vertical tab f: 12, // form feed r: 13, // cr } public static parse = (str): IToken => { if (str === RegExLexer.string) { return RegExLexer.token } RegExLexer.token = null RegExLexer.string = str RegExLexer.errors = [] const capgroups = RegExLexer.captureGroups = [] const groups = [] let i = 0 const l = str.length let o let c let token let prev = null let charset = null const unquantifiable = RegExLexer.UNQUANTIFIABLE const charTypes = RegExLexer.CHAR_TYPES const closeIndex = str.lastIndexOf('/') while (i < l) { c = str[i] token = { i, l: 1, prev } if (i === 0 || i >= closeIndex) { RegExLexer.parseFlag(str, token) } else if (c === '(' && !charset) { RegExLexer.parseGroup(str, token) token.depth = groups.length groups.push(token) if (token.capture) { capgroups.push(token) token.num = capgroups.length } } else if (c === ')' && !charset) { token.type = 'groupclose' if (groups.length) { o = token.open = groups.pop() o.close = token } else { token.err = 'groupclose' } } else if (c === '[' && !charset) { token.type = token.clss = 'set' charset = token if (str[i + 1] === '^') { token.l++ token.type += 'not' } } else if (c === ']' && charset) { token.type = 'setclose' token.open = charset charset.close = token charset = null } else if ((c === '+' || c === '*') && !charset) { token.type = charTypes[c] token.clss = 'quant' token.min = (c === '+' ? 1 : 0) token.max = -1 } else if (c === '{' && !charset && str.substr(i).search(/^{\d+,?\d*}/) !== -1) { RegExLexer.parseQuant(str, token) } else if (c === '\\') { RegExLexer.parseEsc(str, token, charset, capgroups, closeIndex) } else if (c === '?' && !charset) { if (!prev || prev.clss !== 'quant') { token.type = charTypes[c] token.clss = 'quant' token.min = 0 token.max = 1 } else { token.type = 'lazy' token.related = [prev] } } else if (c === '-' && charset && prev.code != null && prev.prev && prev.prev.type !== 'range') { // this may be the start of a range, but we'll need to validate after the next token. token.type = 'range' } else { RegExLexer.parseChar(str, token, charset) } if (prev) { prev.next = token } // post processing: if (token.clss === 'quant') { if (!prev || unquantifiable[prev.type]) { token.err = 'quanttarg' } else { token.related = [prev.open || prev] } } if (prev && prev.type === 'range' && prev.l === 1) { token = RegExLexer.validateRange(str, prev) } if (token.open && !token.clss) { token.clss = token.open.clss } if (!RegExLexer.token) { RegExLexer.token = token } i = token.end = token.i + token.l if (token.err) { RegExLexer.errors.push(token.err) } prev = token } while (groups.length) { RegExLexer.errors.push(groups.pop().err = 'groupopen') } if (charset) { RegExLexer.errors.push(charset.err = 'setopen') } return RegExLexer.token } private static string = null private static token = null private static errors = null private static captureGroups = null private static parseFlag = (str, token) => { // note that this doesn't deal with misformed patterns or incorrect flags. const i = token.i const c = str[i] if (str[i] === '/') { token.type = (i === 0) ? 'open' : 'close' if (i !== 0) { token.related = [RegExLexer.token] RegExLexer.token.related = [token] } } else { token.type = 'flag_' + c } token.clear = true } private static parseChar = (str, token, charset?) => { const c = str[token.i] token.type = (!charset && RegExLexer.CHAR_TYPES[c]) || 'char' if (!charset && c === '/') { token.err = 'fwdslash' } if (token.type === 'char') { token.code = c.charCodeAt(0) } else if (token.type === 'bof' || token.type === 'eof') { token.clss = 'anchor' } else if (token.type === 'dot') { token.clss = 'charclass' } return token } private static parseGroup = (str, token) => { token.clss = 'group' const match = str.substr(token.i + 1).match(/^\?(?::|<?[!=])/) const s = match && match[0] if (s === '?:') { token.l = 3 token.type = 'noncapgroup' } else if (s) { token.behind = s[1] === '<' token.negative = s[1 + token.behind] === '!' token.clss = 'lookaround' token.type = (token.negative ? 'neg' : 'pos') + 'look' + (token.behind ? 'behind' : 'ahead') token.l = s.length + 1 if (token.behind) { token.err = 'lookbehind' } // not supported in JS } else { token.type = 'group' token.capture = true } return token } private static parseEsc = (str, token, charset, capgroups, closeIndex) => { // jsMode tries to read escape chars as a JS string which is less permissive than JS RegExp, and doesn't support \c or backreferences, used for subst // Note: \8 & \9 are treated differently: IE & Chrome match "8", Safari & FF match "\8", we support the former case since Chrome & IE are dominant // Note: Chrome does weird things with \x & \u depending on a number of factors, we ignore RegExLexer. const i = token.i const jsMode = token.js let match let o let sub = str.substr(i + 1) const c = sub[0] if (i + 1 === (closeIndex || str.length)) { token.err = 'esccharopen' return } // tslint:disable-next-line:no-conditional-assignment if (!jsMode && !charset && (match = sub.match(/^\d\d?/)) && (o = capgroups[parseInt(match[0], 10) - 1])) { // back reference - only if there is a matching capture group token.type = 'backref' token.related = [o] token.group = o token.l += match[0].length return token } // tslint:disable-next-line:no-conditional-assignment if (match = sub.match(/^u[\da-fA-F]{4}/)) { // unicode: \uFFFF sub = match[0].substr(1) token.type = 'escunicode' token.l += 5 token.code = parseInt(sub, 16) // tslint:disable-next-line:no-conditional-assignment } else if (match = sub.match(/^x[\da-fA-F]{2}/)) { // hex ascii: \xFF // \x{} not supported in JS regexp sub = match[0].substr(1) token.type = 'eschexadecimal' token.l += 3 token.code = parseInt(sub, 16) // tslint:disable-next-line:no-conditional-assignment } else if (!jsMode && (match = sub.match(/^c[a-zA-Z]/))) { // control char: \cA \cz // not supported in JS strings sub = match[0].substr(1) token.type = 'esccontrolchar' token.l += 2 const code = sub.toUpperCase().charCodeAt(0) - 64 // A=65 if (code > 0) { token.code = code } // tslint:disable-next-line:no-conditional-assignment } else if (match = sub.match(/^[0-7]{1,3}/)) { // octal ascii sub = match[0] if (parseInt(sub, 8) > 255) { sub = sub.substr(0, 2) } token.type = 'escoctal' token.l += sub.length token.code = parseInt(sub, 8) } else if (!jsMode && c === 'c') { // control char without a code - strangely, this is decomposed into literals equivalent to "\\c" return RegExLexer.parseChar(str, token, charset) // this builds the "/" token } else { // single char token.l++ if (jsMode && (c === 'x' || c === 'u')) { token.err = 'esccharbad' } if (!jsMode) { token.type = RegExLexer.ESC_CHARS_SPECIAL[c] } if (token.type) { token.clss = (c.toLowerCase() === 'b') ? 'anchor' : 'charclass' return token } token.type = 'escchar' token.code = RegExLexer.ESC_CHAR_CODES[c] if (token.code == null) { token.code = c.charCodeAt(0) } } token.clss = 'esc' return token } private static parseQuant = (str, token) => { token.type = token.clss = 'quant' const i = token.i const end = str.indexOf('}', i + 1) token.l += end - i const arr = str.substring(i + 1, end).split(',') token.min = parseInt(arr[0], 10) token.max = (arr[1] == null) ? token.min : (arr[1] === '') ? -1 : parseInt(arr[1], 10) if (token.max !== -1 && token.min > token.max) { token.err = 'quantrev' } return token } private static validateRange = (str, token) => { const prev = token.prev const next = token.next if (prev.code == null || next.code == null) { // not a range, rewrite as a char: RegExLexer.parseChar(str, token) } else { token.clss = 'set' if (prev.code > next.code) { token.err = 'rangerev' } // preserve as separate tokens, but treat as one in the UI: next.proxy = prev.proxy = token token.set = [prev, token, next] } return next } } interface IToken { i: number l: number end: number next?: IToken prev: IToken type: TokenType } type TokenType = 'open' | 'dot' | 'word' | 'notword' | 'digit' | 'notdigit' | 'whitespace' | 'notwhitespace' | 'set' | 'setnot' | 'range' | 'bof' | 'eof' | 'wordboundary' | 'notwordboundary' | 'escoctal' | 'eschexadecimal' | 'escunicode' | 'esccontrolchar' | 'group' | 'backref' | 'noncapgroup' | 'poslookahead' | 'neglookahead' | 'poslookbehind' | 'neglookbehind' | 'plus' | 'star' | 'quant' | 'opt' | 'lazy' | 'alt' | 'subst_match' | 'subst_num' | 'subst_pre' | 'subst_post' | 'subst_$' | 'flag_i' | 'flag_g' | 'flag_m' export { RegExLexer }
the_stack
import { ArchiveTag } from "../../../ComplexProperties/ArchiveTag"; import { AttachmentsPropertyDefinition } from "../../../PropertyDefinitions/AttachmentsPropertyDefinition"; import { BoolPropertyDefinition } from "../../../PropertyDefinitions/BoolPropertyDefinition"; import { ByteArrayPropertyDefinition } from "../../../PropertyDefinitions/ByteArrayPropertyDefinition"; import { ComplexPropertyDefinition } from "../../../PropertyDefinitions/ComplexPropertyDefinition"; import { ConversationId } from "../../../ComplexProperties/ConversationId"; import { DateTimePropertyDefinition } from "../../../PropertyDefinitions/DateTimePropertyDefinition"; import { EffectiveRightsPropertyDefinition } from "../../../PropertyDefinitions/EffectiveRightsPropertyDefinition"; import { EntityExtractionResult } from "../../../ComplexProperties/EntityExtractionResult"; import { ExchangeVersion } from "../../../Enumerations/ExchangeVersion"; import { Flag } from "../../../ComplexProperties/Flag"; import { FolderId } from "../../../ComplexProperties/FolderId"; import { GenericPropertyDefinition } from "../../../PropertyDefinitions/GenericPropertyDefinition"; import { IconIndex } from "../../../Enumerations/IconIndex"; import { Importance } from "../../../Enumerations/Importance"; import { IntPropertyDefinition } from "../../../PropertyDefinitions/IntPropertyDefinition"; import { InternetMessageHeaderCollection } from "../../../ComplexProperties/InternetMessageHeaderCollection"; import { ItemId } from "../../../ComplexProperties/ItemId"; import { MessageBody } from "../../../ComplexProperties/MessageBody"; import { MimeContent } from "../../../ComplexProperties/MimeContent"; import { NormalizedBody } from "../../../ComplexProperties/NormalizedBody"; import { PolicyTag } from "../../../ComplexProperties/PolicyTag"; import { PropertyDefinition } from "../../../PropertyDefinitions/PropertyDefinition"; import { PropertyDefinitionFlags } from "../../../Enumerations/PropertyDefinitionFlags"; import { ResponseObjectsPropertyDefinition } from "../../../PropertyDefinitions/ResponseObjectsPropertyDefinition"; import { Schemas } from "./Schemas"; import { ScopedDateTimePropertyDefinition } from "../../../PropertyDefinitions/ScopedDateTimePropertyDefinition"; import { Sensitivity } from "../../../Enumerations/Sensitivity"; import { StringList } from "../../../ComplexProperties/StringList"; import { StringPropertyDefinition } from "../../../PropertyDefinitions/StringPropertyDefinition"; import { TextBody } from "../../../ComplexProperties/TextBody"; import { UniqueBody } from "../../../ComplexProperties/UniqueBody"; import { XmlElementNames } from "../../XmlElementNames"; import { ServiceObjectSchema } from "./ServiceObjectSchema"; /** * Field URIs for Item. */ module FieldUris { export var ArchiveTag: string = "item:ArchiveTag"; export var Attachments: string = "item:Attachments"; export var Body: string = "item:Body"; export var Categories: string = "item:Categories"; export var ConversationId: string = "item:ConversationId"; export var Culture: string = "item:Culture"; export var DateTimeCreated: string = "item:DateTimeCreated"; export var DateTimeReceived: string = "item:DateTimeReceived"; export var DateTimeSent: string = "item:DateTimeSent"; export var DisplayCc: string = "item:DisplayCc"; export var DisplayTo: string = "item:DisplayTo"; export var EffectiveRights: string = "item:EffectiveRights"; export var EntityExtractionResult: string = "item:EntityExtractionResult"; export var Flag: string = "item:Flag"; export var HasAttachments: string = "item:HasAttachments"; export var IconIndex: string = "item:IconIndex"; export var Importance: string = "item:Importance"; export var InReplyTo: string = "item:InReplyTo"; export var InstanceKey: string = "item:InstanceKey"; export var InternetMessageHeaders: string = "item:InternetMessageHeaders"; export var IsAssociated: string = "item:IsAssociated"; export var IsDraft: string = "item:IsDraft"; export var IsFromMe: string = "item:IsFromMe"; export var IsResend: string = "item:IsResend"; export var IsSubmitted: string = "item:IsSubmitted"; export var IsUnmodified: string = "item:IsUnmodified"; export var ItemClass: string = "item:ItemClass"; export var ItemId: string = "item:ItemId"; export var LastModifiedName: string = "item:LastModifiedName"; export var LastModifiedTime: string = "item:LastModifiedTime"; export var MimeContent: string = "item:MimeContent"; export var NormalizedBody: string = "item:NormalizedBody"; export var ParentFolderId: string = "item:ParentFolderId"; export var PolicyTag: string = "item:PolicyTag"; export var Preview: string = "item:Preview"; export var ReminderDueBy: string = "item:ReminderDueBy"; export var ReminderIsSet: string = "item:ReminderIsSet"; export var ReminderMinutesBeforeStart: string = "item:ReminderMinutesBeforeStart"; export var ResponseObjects: string = "item:ResponseObjects"; export var RetentionDate: string = "item:RetentionDate"; export var Sensitivity: string = "item:Sensitivity"; export var Size: string = "item:Size"; export var StoreEntryId: string = "item:StoreEntryId"; export var Subject: string = "item:Subject"; export var TextBody: string = "item:TextBody"; export var UniqueBody: string = "item:UniqueBody"; export var WebClientEditFormQueryString: string = "item:WebClientEditFormQueryString"; export var WebClientReadFormQueryString: string = "item:WebClientReadFormQueryString"; } /** * Represents the schema for generic items. */ export class ItemSchema extends ServiceObjectSchema { /** * Defines the **Id** property. */ public static Id: PropertyDefinition = new ComplexPropertyDefinition<ItemId>( "Id", XmlElementNames.ItemId, FieldUris.ItemId, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, () => { return new ItemId(); } ); /** * Defines the **Body** property. */ public static Body: PropertyDefinition = new ComplexPropertyDefinition<MessageBody>( "Body", XmlElementNames.Body, FieldUris.Body, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete, ExchangeVersion.Exchange2007_SP1, () => { return new MessageBody(); } ); /** * Defines the **ItemClass** property. */ public static ItemClass: PropertyDefinition = new StringPropertyDefinition( "ItemClass", XmlElementNames.ItemClass, FieldUris.ItemClass, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **Subject** property. */ public static Subject: PropertyDefinition = new StringPropertyDefinition( "Subject", XmlElementNames.Subject, FieldUris.Subject, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **MimeContent** property. */ public static MimeContent: PropertyDefinition = new ComplexPropertyDefinition<MimeContent>( "MimeContent", XmlElementNames.MimeContent, FieldUris.MimeContent, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.MustBeExplicitlyLoaded, ExchangeVersion.Exchange2007_SP1, () => { return new MimeContent(); } ); /** * Defines the **ParentFolderId** property. */ public static ParentFolderId: PropertyDefinition = new ComplexPropertyDefinition<FolderId>( "ParentFolderId", XmlElementNames.ParentFolderId, FieldUris.ParentFolderId, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, () => { return new FolderId(); } ); /** * Defines the **Sensitivity** property. */ public static Sensitivity: PropertyDefinition = new GenericPropertyDefinition<Sensitivity>( "Sensitivity", XmlElementNames.Sensitivity, FieldUris.Sensitivity, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, Sensitivity ); /** * Defines the **Attachments** property. */ public static Attachments: PropertyDefinition = new AttachmentsPropertyDefinition("Attachments"); /** * Defines the **DateTimeReceived** property. */ public static DateTimeReceived: PropertyDefinition = new DateTimePropertyDefinition( "DateTimeReceived", XmlElementNames.DateTimeReceived, FieldUris.DateTimeReceived, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **Size** property. */ public static Size: PropertyDefinition = new IntPropertyDefinition( "Size", XmlElementNames.Size, FieldUris.Size, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **Categories** property. */ public static Categories: PropertyDefinition = new ComplexPropertyDefinition<StringList>( "Categories", XmlElementNames.Categories, FieldUris.Categories, PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, () => { return new StringList(); } ); /** * Defines the **Importance** property. */ public static Importance: PropertyDefinition = new GenericPropertyDefinition<Importance>( "Importance", XmlElementNames.Importance, FieldUris.Importance, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, Importance ); /** * Defines the **InReplyTo** property. */ public static InReplyTo: PropertyDefinition = new StringPropertyDefinition( "InReplyTo", XmlElementNames.InReplyTo, FieldUris.InReplyTo, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **IsSubmitted** property. */ public static IsSubmitted: PropertyDefinition = new BoolPropertyDefinition( "IsSubmitted", XmlElementNames.IsSubmitted, FieldUris.IsSubmitted, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **IsAssociated** property. */ public static IsAssociated: PropertyDefinition = new BoolPropertyDefinition( "IsAssociated", XmlElementNames.IsAssociated, FieldUris.IsAssociated, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010 ); /** * Defines the **IsDraft** property. */ public static IsDraft: PropertyDefinition = new BoolPropertyDefinition( "IsDraft", XmlElementNames.IsDraft, FieldUris.IsDraft, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **IsFromMe** property. */ public static IsFromMe: PropertyDefinition = new BoolPropertyDefinition( "IsFromMe", XmlElementNames.IsFromMe, FieldUris.IsFromMe, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **IsResend** property. */ public static IsResend: PropertyDefinition = new BoolPropertyDefinition( "IsResend", XmlElementNames.IsResend, FieldUris.IsResend, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **IsUnmodified** property. */ public static IsUnmodified: PropertyDefinition = new BoolPropertyDefinition( "IsUnmodified", XmlElementNames.IsUnmodified, FieldUris.IsUnmodified, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **InternetMessageHeaders** property. */ public static InternetMessageHeaders: PropertyDefinition = new ComplexPropertyDefinition<InternetMessageHeaderCollection>( "InternetMessageHeaders", XmlElementNames.InternetMessageHeaders, FieldUris.InternetMessageHeaders, PropertyDefinitionFlags.None, ExchangeVersion.Exchange2007_SP1, () => { return new InternetMessageHeaderCollection(); } ); /** * Defines the **DateTimeSent** property. */ public static DateTimeSent: PropertyDefinition = new DateTimePropertyDefinition( "DateTimeSent", XmlElementNames.DateTimeSent, FieldUris.DateTimeSent, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **DateTimeCreated** property. */ public static DateTimeCreated: PropertyDefinition = new DateTimePropertyDefinition( "DateTimeCreated", XmlElementNames.DateTimeCreated, FieldUris.DateTimeCreated, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **AllowedResponseActions** property. */ public static AllowedResponseActions: PropertyDefinition = new ResponseObjectsPropertyDefinition( "ResponseObjects", XmlElementNames.ResponseObjects, FieldUris.ResponseObjects, PropertyDefinitionFlags.None, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **ReminderDueBy** property. */ public static ReminderDueBy: PropertyDefinition = new ScopedDateTimePropertyDefinition( "ReminderDueBy", XmlElementNames.ReminderDueBy, FieldUris.ReminderDueBy, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, (version: ExchangeVersion) => { debugger; return Schemas.AppointmentSchema.StartTimeZone; } ); /** * Defines the **IsReminderSet** property. */ public static IsReminderSet: PropertyDefinition = new BoolPropertyDefinition( "ReminderIsSet", XmlElementNames.ReminderIsSet, FieldUris.ReminderIsSet, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **ReminderMinutesBeforeStart** property. */ public static ReminderMinutesBeforeStart: PropertyDefinition = new IntPropertyDefinition( "ReminderMinutesBeforeStart", XmlElementNames.ReminderMinutesBeforeStart, FieldUris.ReminderMinutesBeforeStart, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **DisplayCc** property. */ public static DisplayCc: PropertyDefinition = new StringPropertyDefinition( "DisplayCc", XmlElementNames.DisplayCc, FieldUris.DisplayCc, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **DisplayTo** property. */ public static DisplayTo: PropertyDefinition = new StringPropertyDefinition( "DisplayTo", XmlElementNames.DisplayTo, FieldUris.DisplayTo, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **HasAttachments** property. */ public static HasAttachments: PropertyDefinition = new BoolPropertyDefinition( "HasAttachments", XmlElementNames.HasAttachments, FieldUris.HasAttachments, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **Culture** property. */ public static Culture: PropertyDefinition = new StringPropertyDefinition( "Culture", XmlElementNames.Culture, FieldUris.Culture, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **EffectiveRights** property. */ public static EffectiveRights: PropertyDefinition = new EffectiveRightsPropertyDefinition( "EffectiveRights", XmlElementNames.EffectiveRights, FieldUris.EffectiveRights, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **LastModifiedName** property. */ public static LastModifiedName: PropertyDefinition = new StringPropertyDefinition( "LastModifiedName", XmlElementNames.LastModifiedName, FieldUris.LastModifiedName, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **LastModifiedTime** property. */ public static LastModifiedTime: PropertyDefinition = new DateTimePropertyDefinition( "LastModifiedTime", XmlElementNames.LastModifiedTime, FieldUris.LastModifiedTime, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **WebClientReadFormQueryString** property. */ public static WebClientReadFormQueryString: PropertyDefinition = new StringPropertyDefinition( "WebClientReadFormQueryString", XmlElementNames.WebClientReadFormQueryString, FieldUris.WebClientReadFormQueryString, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010 ); /** * Defines the **WebClientEditFormQueryString** property. */ public static WebClientEditFormQueryString: PropertyDefinition = new StringPropertyDefinition( "WebClientEditFormQueryString", XmlElementNames.WebClientEditFormQueryString, FieldUris.WebClientEditFormQueryString, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010 ); /** * Defines the **ConversationId** property. */ public static ConversationId: PropertyDefinition = new ComplexPropertyDefinition<ConversationId>( "ConversationId", XmlElementNames.ConversationId, FieldUris.ConversationId, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010, () => { return new ConversationId(); } ); /** * Defines the **UniqueBody** property. */ public static UniqueBody: PropertyDefinition = new ComplexPropertyDefinition<UniqueBody>( "UniqueBody", XmlElementNames.UniqueBody, FieldUris.UniqueBody, PropertyDefinitionFlags.MustBeExplicitlyLoaded, ExchangeVersion.Exchange2010, () => { return new UniqueBody(); } ); /** * Defines the **StoreEntryId** property. */ public static StoreEntryId: PropertyDefinition = new ByteArrayPropertyDefinition( "StoreEntryId", XmlElementNames.StoreEntryId, FieldUris.StoreEntryId, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010_SP2 ); /** * Defines the **InstanceKey** property. */ public static InstanceKey: PropertyDefinition = new ByteArrayPropertyDefinition( "InstanceKey", XmlElementNames.InstanceKey, FieldUris.InstanceKey, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2013 ); /** * Defines the **NormalizedBody** property. */ public static NormalizedBody: PropertyDefinition = new ComplexPropertyDefinition<NormalizedBody>( "NormalizedBody", XmlElementNames.NormalizedBody, FieldUris.NormalizedBody, PropertyDefinitionFlags.MustBeExplicitlyLoaded, ExchangeVersion.Exchange2013, () => { return new NormalizedBody(); } ); /** * Defines the **EntityExtractionResult** property. */ public static EntityExtractionResult: PropertyDefinition = new ComplexPropertyDefinition<EntityExtractionResult>( "EntityExtractionResult", XmlElementNames.NlgEntityExtractionResult, FieldUris.EntityExtractionResult, PropertyDefinitionFlags.MustBeExplicitlyLoaded, ExchangeVersion.Exchange2013, () => { return new EntityExtractionResult(); } ); /** * Defines the **Flag** property. */ public static Flag: PropertyDefinition = new ComplexPropertyDefinition<Flag>( "Flag", XmlElementNames.Flag, FieldUris.Flag, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2013, () => { return new Flag(); } ); /** * Defines the **PolicyTag** property. */ public static PolicyTag: PropertyDefinition = new ComplexPropertyDefinition<PolicyTag>( "PolicyTag", XmlElementNames.PolicyTag, FieldUris.PolicyTag, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2013, () => { return new PolicyTag(); } ); /** * Defines the **ArchiveTag** property. */ public static ArchiveTag: PropertyDefinition = new ComplexPropertyDefinition<ArchiveTag>( "ArchiveTag", XmlElementNames.ArchiveTag, FieldUris.ArchiveTag, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2013, () => { return new ArchiveTag(); } ); /** * Defines the **RetentionDate** property. */ public static RetentionDate: PropertyDefinition = new DateTimePropertyDefinition( "RetentionDate", XmlElementNames.RetentionDate, FieldUris.RetentionDate, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2013, true ); /** * Defines the **Preview** property. */ public static Preview: PropertyDefinition = new StringPropertyDefinition( "Preview", XmlElementNames.Preview, FieldUris.Preview, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2013 ); /** * Defines the **TextBody** property. */ public static TextBody: PropertyDefinition = new ComplexPropertyDefinition<TextBody>( "TextBody", XmlElementNames.TextBody, FieldUris.TextBody, PropertyDefinitionFlags.MustBeExplicitlyLoaded, ExchangeVersion.Exchange2013, () => { return new TextBody(); } ); /** * Defines the **IconIndex** property. */ public static IconIndex: PropertyDefinition = new GenericPropertyDefinition<IconIndex>( "IconIndex", XmlElementNames.IconIndex, FieldUris.IconIndex, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2013, IconIndex ); /** * @internal Instance of **ItemSchema** */ static Instance: ItemSchema = new ItemSchema(); /** * Registers properties. * * /remarks/ IMPORTANT NOTE: PROPERTIES MUST BE REGISTERED IN SCHEMA ORDER (i.e. the same order as they are defined in types.xsd) */ RegisterProperties(): void { super.RegisterProperties(); this.RegisterProperty(ItemSchema, ItemSchema.MimeContent); this.RegisterProperty(ItemSchema, ItemSchema.Id); this.RegisterProperty(ItemSchema, ItemSchema.ParentFolderId); this.RegisterProperty(ItemSchema, ItemSchema.ItemClass); this.RegisterProperty(ItemSchema, ItemSchema.Subject); this.RegisterProperty(ItemSchema, ItemSchema.Sensitivity); this.RegisterProperty(ItemSchema, ItemSchema.Body); this.RegisterProperty(ItemSchema, ItemSchema.Attachments); this.RegisterProperty(ItemSchema, ItemSchema.DateTimeReceived); this.RegisterProperty(ItemSchema, ItemSchema.Size); this.RegisterProperty(ItemSchema, ItemSchema.Categories); this.RegisterProperty(ItemSchema, ItemSchema.Importance); this.RegisterProperty(ItemSchema, ItemSchema.InReplyTo); this.RegisterProperty(ItemSchema, ItemSchema.IsSubmitted); this.RegisterProperty(ItemSchema, ItemSchema.IsDraft); this.RegisterProperty(ItemSchema, ItemSchema.IsFromMe); this.RegisterProperty(ItemSchema, ItemSchema.IsResend); this.RegisterProperty(ItemSchema, ItemSchema.IsUnmodified); this.RegisterProperty(ItemSchema, ItemSchema.InternetMessageHeaders); this.RegisterProperty(ItemSchema, ItemSchema.DateTimeSent); this.RegisterProperty(ItemSchema, ItemSchema.DateTimeCreated); this.RegisterProperty(ItemSchema, ItemSchema.AllowedResponseActions); this.RegisterProperty(ItemSchema, ItemSchema.ReminderDueBy); this.RegisterProperty(ItemSchema, ItemSchema.IsReminderSet); this.RegisterProperty(ItemSchema, ItemSchema.ReminderMinutesBeforeStart); this.RegisterProperty(ItemSchema, ItemSchema.DisplayCc); this.RegisterProperty(ItemSchema, ItemSchema.DisplayTo); this.RegisterProperty(ItemSchema, ItemSchema.HasAttachments); this.RegisterProperty(ItemSchema, ServiceObjectSchema.ExtendedProperties); this.RegisterProperty(ItemSchema, ItemSchema.Culture); this.RegisterProperty(ItemSchema, ItemSchema.EffectiveRights); this.RegisterProperty(ItemSchema, ItemSchema.LastModifiedName); this.RegisterProperty(ItemSchema, ItemSchema.LastModifiedTime); this.RegisterProperty(ItemSchema, ItemSchema.IsAssociated); this.RegisterProperty(ItemSchema, ItemSchema.WebClientReadFormQueryString); this.RegisterProperty(ItemSchema, ItemSchema.WebClientEditFormQueryString); this.RegisterProperty(ItemSchema, ItemSchema.ConversationId); this.RegisterProperty(ItemSchema, ItemSchema.UniqueBody); this.RegisterProperty(ItemSchema, ItemSchema.Flag); this.RegisterProperty(ItemSchema, ItemSchema.StoreEntryId); this.RegisterProperty(ItemSchema, ItemSchema.InstanceKey); this.RegisterProperty(ItemSchema, ItemSchema.NormalizedBody); this.RegisterProperty(ItemSchema, ItemSchema.EntityExtractionResult); this.RegisterProperty(ItemSchema, ItemSchema.PolicyTag); this.RegisterProperty(ItemSchema, ItemSchema.ArchiveTag); this.RegisterProperty(ItemSchema, ItemSchema.RetentionDate); this.RegisterProperty(ItemSchema, ItemSchema.Preview); this.RegisterProperty(ItemSchema, ItemSchema.TextBody); this.RegisterProperty(ItemSchema, ItemSchema.IconIndex); } } /** * Represents the schema for generic items. */ export interface ItemSchema { /** * Defines the **Id** property. */ Id: PropertyDefinition; /** * Defines the **Body** property. */ Body: PropertyDefinition; /** * Defines the **ItemClass** property. */ ItemClass: PropertyDefinition; /** * Defines the **Subject** property. */ Subject: PropertyDefinition; /** * Defines the **MimeContent** property. */ MimeContent: PropertyDefinition; /** * Defines the **ParentFolderId** property. */ ParentFolderId: PropertyDefinition; /** * Defines the **Sensitivity** property. */ Sensitivity: PropertyDefinition; /** * Defines the **Attachments** property. */ Attachments: PropertyDefinition; /** * Defines the **DateTimeReceived** property. */ DateTimeReceived: PropertyDefinition; /** * Defines the **Size** property. */ Size: PropertyDefinition; /** * Defines the **Categories** property. */ Categories: PropertyDefinition; /** * Defines the **Importance** property. */ Importance: PropertyDefinition; /** * Defines the **InReplyTo** property. */ InReplyTo: PropertyDefinition; /** * Defines the **IsSubmitted** property. */ IsSubmitted: PropertyDefinition; /** * Defines the **IsAssociated** property. */ IsAssociated: PropertyDefinition; /** * Defines the **IsDraft** property. */ IsDraft: PropertyDefinition; /** * Defines the **IsFromMe** property. */ IsFromMe: PropertyDefinition; /** * Defines the **IsResend** property. */ IsResend: PropertyDefinition; /** * Defines the **IsUnmodified** property. */ IsUnmodified: PropertyDefinition; /** * Defines the **InternetMessageHeaders** property. */ InternetMessageHeaders: PropertyDefinition; /** * Defines the **DateTimeSent** property. */ DateTimeSent: PropertyDefinition; /** * Defines the **DateTimeCreated** property. */ DateTimeCreated: PropertyDefinition; /** * Defines the **AllowedResponseActions** property. */ AllowedResponseActions: PropertyDefinition; /** * Defines the **ReminderDueBy** property. */ ReminderDueBy: PropertyDefinition; /** * Defines the **IsReminderSet** property. */ IsReminderSet: PropertyDefinition; /** * Defines the **ReminderMinutesBeforeStart** property. */ ReminderMinutesBeforeStart: PropertyDefinition; /** * Defines the **DisplayCc** property. */ DisplayCc: PropertyDefinition; /** * Defines the **DisplayTo** property. */ DisplayTo: PropertyDefinition; /** * Defines the **HasAttachments** property. */ HasAttachments: PropertyDefinition; /** * Defines the **Culture** property. */ Culture: PropertyDefinition; /** * Defines the **EffectiveRights** property. */ EffectiveRights: PropertyDefinition; /** * Defines the **LastModifiedName** property. */ LastModifiedName: PropertyDefinition; /** * Defines the **LastModifiedTime** property. */ LastModifiedTime: PropertyDefinition; /** * Defines the **WebClientReadFormQueryString** property. */ WebClientReadFormQueryString: PropertyDefinition; /** * Defines the **WebClientEditFormQueryString** property. */ WebClientEditFormQueryString: PropertyDefinition; /** * Defines the **ConversationId** property. */ ConversationId: PropertyDefinition; /** * Defines the **UniqueBody** property. */ UniqueBody: PropertyDefinition; /** * Defines the **StoreEntryId** property. */ StoreEntryId: PropertyDefinition; /** * Defines the **InstanceKey** property. */ InstanceKey: PropertyDefinition; /** * Defines the **NormalizedBody** property. */ NormalizedBody: PropertyDefinition; /** * Defines the **EntityExtractionResult** property. */ EntityExtractionResult: PropertyDefinition; /** * Defines the **Flag** property. */ Flag: PropertyDefinition; /** * Defines the **PolicyTag** property. */ PolicyTag: PropertyDefinition; /** * Defines the **ArchiveTag** property. */ ArchiveTag: PropertyDefinition; /** * Defines the **RetentionDate** property. */ RetentionDate: PropertyDefinition; /** * Defines the **Preview** property. */ Preview: PropertyDefinition; /** * Defines the **TextBody** property. */ TextBody: PropertyDefinition; /** * Defines the **IconIndex** property. */ IconIndex: PropertyDefinition; /** * @internal Instance of **ItemSchema** */ Instance: ItemSchema; } /** * Represents the schema for generic items. */ export interface ItemSchemaStatic extends ItemSchema { }
the_stack
import { DeleteOutlined, PlusOutlined, CodeTwoTone, UsergroupAddOutlined } from '@ant-design/icons'; import { Button, Divider, Modal, message, Menu, Tooltip } from 'antd'; import type { ProColumns, ActionType } from '@ant-design/pro-table'; import React, { useState, useRef, useEffect } from 'react'; import { PageHeaderWrapper } from '@ant-design/pro-layout'; import ProTable, { TableDropdown } from '@ant-design/pro-table'; import CreateForm from './components/CreateForm'; import UpdateForm from './components/UpdateForm'; import RecordModal from './components/RecordModal'; import { queryHosts, deleteHost, queryHostGroups } from '@/services/anew/host'; import { useAccess, Access, useModel } from 'umi'; export type optionsType = { label: string, value: string, } const HostList: React.FC = () => { const { initialState } = useModel('@@initialState'); if (!initialState || !initialState.DictObj) { return null; } const authType: optionsType[] = initialState.DictObj.auth_type.map((item: any) => ({ label: item.dict_value, value: item.dict_key })); const hostType: optionsType[] = initialState.DictObj.host_type.map((item: any) => ({ label: item.dict_value, value: item.dict_key })); const [createVisible, setCreateVisible] = useState<boolean>(false); const [updateVisible, setUpdateVisible] = useState<boolean>(false); const [recordVisible, setRecordVisible] = useState<boolean>(false); const actionRef = useRef<ActionType>(); const [formValues, setFormValues] = useState<API.HostList>(); const [hostGroup, setHostGroup] = useState<API.HostGroupList[]>([]); const [group_id, setGroupId] = useState<string>(); const [hostId, setHostId] = useState<number>(); const access = useAccess(); const { consoleWin, setConsoleWin } = useModel('global'); const handleDelete = (record: API.Ids) => { if (!record) return; if (Array.isArray(record.ids) && !record.ids.length) return; const content = `您是否要删除这${Array.isArray(record.ids) ? record.ids.length : ''}项?`; Modal.confirm({ title: '注意', content, onOk: () => { deleteHost(record).then((res) => { if (res.code === 200 && res.status === true) { message.success(res.message); if (actionRef.current) { actionRef.current.reload(); } } }); }, onCancel() { }, }); }; const saveTtys = (val: API.TtyList) => { let hosts = JSON.parse(localStorage.getItem('TABS_TTY_HOSTS') as string) if (hosts) { hosts.push(val) } else { hosts = [] hosts.push(val) } localStorage.setItem('TABS_TTY_HOSTS', JSON.stringify(hosts)); } useEffect(() => { queryHostGroups({ all: true, not_null: true }).then((res) => { if (Array.isArray(res.data.data)) { setHostGroup([{ id: 0, name: '所有主机' }, ...res.data.data]); } }); }, []); const columns: ProColumns<API.HostList>[] = [ { title: '主机名', dataIndex: 'host_name', }, { title: '地址', dataIndex: 'ip_address', }, { title: '端口', dataIndex: 'port', }, { title: '主机类型', dataIndex: 'host_type', valueType: 'select', fieldProps: { options: hostType, }, }, { title: '认证类型', dataIndex: 'auth_type', valueType: 'select', fieldProps: { options: authType, }, }, { title: '创建人', dataIndex: 'creator', }, { title: '操作', dataIndex: 'option', valueType: 'option', render: (_, record) => ( <> <Tooltip title="控制台"> <CodeTwoTone style={{ fontSize: '17px', color: 'blue' }} onClick={() => { let actKey = "tty1" let hosts = JSON.parse(localStorage.getItem('TABS_TTY_HOSTS') as string) || [] if (hosts) { actKey = "tty" + (hosts.length + 1).toString() } const hostsObj: API.TtyList = { hostname: record.host_name, ipaddr: record.ip_address, port: record.port, id: record.id.toString(), actKey: actKey, secKey: null } saveTtys(hostsObj) if (consoleWin) { if (!consoleWin.closed) { consoleWin.focus(); } else { setConsoleWin(window.open('/asset/console', 'consoleTrm')); } } else { setConsoleWin(window.open('/asset/console', 'consoleTrm')); } }} /> </Tooltip> {/* <Divider type="vertical" /> <Tooltip title="详情"> <FileDoneOutlined style={{ fontSize: '17px', color: '#52c41a' }} onClick={() => { setFormValues(record); handleDescModalVisible(true); }} /> </Tooltip> */} <Divider type="vertical" /> <TableDropdown key="actionGroup" onSelect={(key) => { switch (key) { case 'delete': handleDelete({ ids: [record.id] }); break; case 'edit': setFormValues(record); setUpdateVisible(true); break; case 'record': setHostId(record.id) setRecordVisible(true); break; } }} menus={[ { key: 'edit', name: '修改' }, { key: 'record', name: '操作录像' }, { key: 'delete', name: '删除' }, ]} /> </> ), }, ]; return ( <PageHeaderWrapper> {/* 权限控制显示内容 */} {access.hasPerms(['admin', 'host:list']) && <ProTable actionRef={actionRef} rowKey="id" toolBarRender={(action, { selectedRows }) => [ <Access accessible={access.hasPerms(['admin', 'host:create'])}> <Button key="1" type="primary" onClick={() => setCreateVisible(true)}> <PlusOutlined /> 新建 </Button> </Access>, selectedRows && selectedRows.length > 0 && ( <Access accessible={access.hasPerms(['admin', 'host:delete'])}> <Button key="2" type="primary" onClick={() => handleDelete({ ids: selectedRows.map((item) => item.id) })} danger > <DeleteOutlined /> 删除 </Button> </Access> ), ]} tableAlertRender={({ selectedRowKeys, selectedRows }) => ( <div> 已选择{' '} <a style={{ fontWeight: 600, }} > {selectedRowKeys.length} </a>{' '} 项&nbsp;&nbsp; </div> )} request={async (params) => queryHosts({ params }).then((res) => res.data)} params={{ group_id, }} columns={columns} rowSelection={{}} tableRender={(_, dom) => hostGroup.length > 1 ? ( <div style={{ display: 'flex', width: '100%', }}> <Menu onSelect={(e) => { if (e.key === '0') { setGroupId(''); } else { setGroupId(e.key); } }} style={{ width: 156 }} defaultSelectedKeys={['0']} defaultOpenKeys={['sub1']} mode="inline" > <Menu.SubMenu key="sub1" title={ <span> <UsergroupAddOutlined /> <span>主机分组</span> </span> } > {hostGroup && hostGroup.map((item) => <Menu.Item key={item.id}>{item.name}</Menu.Item>)} </Menu.SubMenu> </Menu> <div style={{ flex: 1, }}> {dom} </div> </div> ) : <div style={{ flex: 1, }}> {dom} </div>} />} {createVisible && ( <CreateForm actionRef={actionRef} handleChange={setCreateVisible} modalVisible={createVisible} /> )} {updateVisible && ( <UpdateForm actionRef={actionRef} handleChange={setUpdateVisible} modalVisible={updateVisible} values={formValues} /> )} {recordVisible && ( <RecordModal handleChange={setRecordVisible} modalVisible={recordVisible} hostId={hostId} /> )} </PageHeaderWrapper> ); }; export default HostList;
the_stack