text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { createTestDriver } from '../../test-utils/create-test-driver';
import { ICortexTestDriver } from '../../test-utils/test-driver';
import {
pioIN,
pioIRQ,
pioJMP,
pioMOV,
pioOUT,
pioPULL,
pioPUSH,
pioSET,
pioWAIT,
PIO_COND_ALWAYS,
PIO_COND_NOTEMPTYOSR,
PIO_COND_NOTX,
PIO_COND_NOTY,
PIO_COND_XDEC,
PIO_COND_XNEY,
PIO_COND_YDEC,
PIO_DEST_EXEC,
PIO_DEST_NULL,
PIO_DEST_PC,
PIO_DEST_PINS,
PIO_DEST_X,
PIO_DEST_Y,
PIO_MOV_DEST_ISR,
PIO_MOV_DEST_OSR,
PIO_MOV_DEST_PC,
PIO_MOV_DEST_X,
PIO_MOV_DEST_Y,
PIO_OP_BITREV,
PIO_OP_INVERT,
PIO_OP_NONE,
PIO_SRC_NULL,
PIO_SRC_STATUS,
PIO_SRC_X,
PIO_SRC_Y,
PIO_WAIT_SRC_IRQ,
} from '../utils/pio-assembler';
const CTRL = 0x50200000;
const FLEVEL = 0x5020000c;
const TXF0 = 0x50200010;
const RXF0 = 0x50200020;
const IRQ = 0x50200030;
const INSTR_MEM0 = 0x50200048;
const INSTR_MEM1 = 0x5020004c;
const INSTR_MEM2 = 0x50200050;
const INSTR_MEM3 = 0x50200054;
const SM0_SHIFTCTRL = 0x502000d0;
const SM0_EXECCTRL = 0x502000cc;
const SM0_ADDR = 0x502000d4;
const SM0_INSTR = 0x502000d8;
const SM0_PINCTRL = 0x502000dc;
const SM2_INSTR = 0x50200108;
const INTR = 0x50200128;
const IRQ0_INTE = 0x5020012c;
const NVIC_ISPR = 0xe000e200;
const NVIC_ICPR = 0xe000e280;
// Interrupt flags
const PIO_IRQ0 = 1 << 7;
const INTR_SM0_RXNEMPTY = 1 << 0;
const INTR_SM0_TXNFULL = 1 << 4;
// SHIFTs for FLEVEL
const TX0_SHIFT = 0;
const RX0_SHIFT = 4;
// SM0_SHIFTCTRL bits:
const FJOIN_RX = 1 << 30;
const IN_SHIFTDIR = 1 << 18;
const OUT_SHIFTDIR = 1 << 19;
const SHIFTCTRL_AUTOPULL = 1 << 17;
const SHIFTCTRL_AUTOPUSH = 1 << 16;
const SHIFTCTRL_PULL_THRESH_SHIFT = 25;
const SHIFTCTRL_PUSH_THRESH_SHIFT = 20;
// EXECCTRL bits:
const EXECCTRL_EXEC_STALLED = 1 << 31;
const EXECCTRL_STATUS_SEL = 1 << 4;
const EXECCTRL_WRAP_BOTTOM_SHIFT = 7;
const EXECCTRL_WRAP_TOP_SHIFT = 12;
const EXECCTRL_STATUS_N_SHIFT = 0;
const DBG_PADOUT = 0x5020003c;
const SET_COUNT_SHIFT = 26;
const SET_COUNT_BASE = 5;
const OUT_COUNT_SHIFT = 20;
const VALID_PINS_MASK = 0x3fffffff;
describe('PIO', () => {
let cpu: ICortexTestDriver;
beforeEach(async () => {
cpu = await createTestDriver();
});
afterEach(async () => {
await cpu.tearDown();
});
async function resetStateMachines() {
await cpu.writeUint32(CTRL, 0xf0);
await cpu.writeUint32(SM0_INSTR, pioJMP(PIO_COND_ALWAYS, 0)); // Jump machine 0 to address 0
// Clear FIFOs
await cpu.writeUint32(SM0_SHIFTCTRL, FJOIN_RX);
// Values at reset
await cpu.writeUint32(SM0_SHIFTCTRL, IN_SHIFTDIR | OUT_SHIFTDIR);
await cpu.writeUint32(SM0_PINCTRL, 5 << SET_COUNT_SHIFT);
}
it('should execute a `SET PINS` instruction correctly', async () => {
// SET PINS, 13
// then check the debug register and verify that that output from the pins matches the PINS value
const shiftAmount = 0;
const pinsQty = 5;
const pinsValue = 13;
await resetStateMachines();
await cpu.writeUint32(
SM0_PINCTRL,
(pinsQty << SET_COUNT_SHIFT) | (shiftAmount << SET_COUNT_BASE)
);
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_PINS, pinsValue));
expect((await cpu.readUint32(DBG_PADOUT)) & (((1 << pinsQty) - 1) << shiftAmount)).toBe(
pinsValue << shiftAmount
);
});
it('should execute a `MOV PINS, X` instruction correctly', async () => {
await resetStateMachines();
await cpu.writeUint32(SM0_PINCTRL, 32 << OUT_COUNT_SHIFT);
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_X, 8));
await cpu.writeUint32(SM0_INSTR, pioMOV(PIO_DEST_PINS, PIO_OP_NONE, PIO_SRC_X));
expect(await cpu.readUint32(DBG_PADOUT)).toBe(8);
});
it('should execute a `MOV PINS, ~X` instruction', async () => {
await resetStateMachines();
await cpu.writeUint32(SM0_PINCTRL, 32 << OUT_COUNT_SHIFT);
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_X, 29));
await cpu.writeUint32(SM0_INSTR, pioMOV(PIO_DEST_PINS, PIO_OP_INVERT, PIO_SRC_X));
expect(await cpu.readUint32(DBG_PADOUT)).toBe(~29 & VALID_PINS_MASK);
});
it('should correctly `MOV PINS, ::X` instruction', async () => {
await resetStateMachines();
await cpu.writeUint32(SM0_PINCTRL, 32 << OUT_COUNT_SHIFT);
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_X, 0b11001));
await cpu.writeUint32(SM0_INSTR, pioMOV(PIO_DEST_PINS, PIO_OP_BITREV, PIO_SRC_X));
expect(await cpu.readUint32(DBG_PADOUT)).toBe(0x98000000 & VALID_PINS_MASK);
});
it('should correctly a `MOV Y, X` instruction', async () => {
await resetStateMachines();
await cpu.writeUint32(SM0_PINCTRL, 32 << OUT_COUNT_SHIFT);
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_X, 11));
await cpu.writeUint32(SM0_INSTR, pioMOV(PIO_MOV_DEST_Y, PIO_OP_NONE, PIO_SRC_X));
await cpu.writeUint32(SM0_INSTR, pioMOV(PIO_DEST_PINS, PIO_OP_NONE, PIO_SRC_Y));
expect(await cpu.readUint32(DBG_PADOUT)).toBe(11);
});
it('should correctly a `MOV PC, Y` instruction', async () => {
await resetStateMachines();
expect(await cpu.readUint32(SM0_ADDR)).toBe(0);
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_Y, 23));
await cpu.writeUint32(SM0_INSTR, pioMOV(PIO_MOV_DEST_PC, PIO_OP_NONE, PIO_SRC_Y));
expect(await cpu.readUint32(SM0_ADDR)).toBe(23);
});
it('should correctly a `MOV ISR, STATUS` instruction when the STATUS_SEL is 0 (TX FIFO)', async () => {
await resetStateMachines();
await cpu.writeUint32(SM0_EXECCTRL, 2 << EXECCTRL_STATUS_N_SHIFT);
await cpu.writeUint32(SM0_INSTR, pioMOV(PIO_MOV_DEST_ISR, PIO_OP_NONE, PIO_SRC_STATUS));
await cpu.writeUint32(SM0_INSTR, pioPUSH(false, false));
expect(await cpu.readUint32(RXF0)).toBe(0xffffffff);
await cpu.writeUint32(TXF0, 1);
await cpu.writeUint32(TXF0, 2);
await cpu.writeUint32(SM0_INSTR, pioMOV(PIO_MOV_DEST_ISR, PIO_OP_NONE, PIO_SRC_STATUS));
await cpu.writeUint32(SM0_INSTR, pioPUSH(false, false));
expect(await cpu.readUint32(RXF0)).toBe(0);
});
it('should correctly a `MOV ISR, STATUS` instruction when the STATUS_SEL is 1 (RX FIFO)', async () => {
await resetStateMachines();
await cpu.writeUint32(SM0_EXECCTRL, (1 << EXECCTRL_STATUS_N_SHIFT) | EXECCTRL_STATUS_SEL);
await cpu.writeUint32(SM0_INSTR, pioMOV(PIO_MOV_DEST_ISR, PIO_OP_NONE, PIO_SRC_STATUS));
await cpu.writeUint32(SM0_INSTR, pioPUSH(false, false));
await cpu.writeUint32(SM0_INSTR, pioMOV(PIO_MOV_DEST_ISR, PIO_OP_NONE, PIO_SRC_STATUS));
await cpu.writeUint32(SM0_INSTR, pioPUSH(false, false));
expect(await cpu.readUint32(RXF0)).toBe(0xffffffff);
expect(await cpu.readUint32(RXF0)).toBe(0);
});
it('should correctly execute a `JMP` (always) instruction', async () => {
await resetStateMachines();
await cpu.writeUint32(SM0_INSTR, pioJMP(PIO_COND_ALWAYS, 10));
expect(await cpu.readUint32(SM0_ADDR)).toBe(10);
});
it('should correctly execute a `JMP !X` instruction', async () => {
await resetStateMachines();
expect(await cpu.readUint32(SM0_ADDR)).toBe(0);
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_X, 5));
await cpu.writeUint32(SM0_INSTR, pioJMP(PIO_COND_NOTX, 8));
expect(await cpu.readUint32(SM0_ADDR)).toBe(0);
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_X, 0));
await cpu.writeUint32(SM0_INSTR, pioJMP(PIO_COND_NOTX, 8));
expect(await cpu.readUint32(SM0_ADDR)).toBe(8);
});
it('should correctly execute a `JMP X--` instruction', async () => {
await resetStateMachines();
await cpu.writeUint32(SM0_PINCTRL, 32 << OUT_COUNT_SHIFT);
expect(await cpu.readUint32(SM0_ADDR)).toBe(0);
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_X, 5));
await cpu.writeUint32(SM0_INSTR, pioJMP(PIO_COND_XDEC, 12));
expect(await cpu.readUint32(SM0_ADDR)).toBe(12);
// X should be 4:
await cpu.writeUint32(SM0_INSTR, pioMOV(PIO_DEST_PINS, PIO_OP_NONE, PIO_SRC_X));
expect(await cpu.readUint32(DBG_PADOUT)).toBe(4);
// now set X to zero and ensure that we don't jump again
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_X, 0));
await cpu.writeUint32(SM0_INSTR, pioJMP(PIO_COND_XDEC, 6));
expect(await cpu.readUint32(SM0_ADDR)).toBe(12);
});
it('should correctly execute a `JMP !Y` instruction', async () => {
await resetStateMachines();
expect(await cpu.readUint32(SM0_ADDR)).toBe(0);
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_Y, 6));
await cpu.writeUint32(SM0_INSTR, pioJMP(PIO_COND_NOTY, 8));
expect(await cpu.readUint32(SM0_ADDR)).toBe(0);
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_Y, 0));
await cpu.writeUint32(SM0_INSTR, pioJMP(PIO_COND_NOTY, 8));
expect(await cpu.readUint32(SM0_ADDR)).toBe(8);
});
it('should correctly execute a `JMP Y--` instruction', async () => {
await resetStateMachines();
await cpu.writeUint32(SM0_PINCTRL, 32 << OUT_COUNT_SHIFT);
expect(await cpu.readUint32(SM0_ADDR)).toBe(0);
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_Y, 15));
await cpu.writeUint32(SM0_INSTR, pioJMP(PIO_COND_YDEC, 12));
expect(await cpu.readUint32(SM0_ADDR)).toBe(12);
// Y should be 14:
await cpu.writeUint32(SM0_INSTR, pioMOV(PIO_DEST_PINS, PIO_OP_NONE, PIO_SRC_Y));
expect(await cpu.readUint32(DBG_PADOUT)).toBe(14);
// now set X to zero and ensure that we don't jump again
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_Y, 0));
await cpu.writeUint32(SM0_INSTR, pioJMP(PIO_COND_YDEC, 6));
expect(await cpu.readUint32(SM0_ADDR)).toBe(12);
});
it('should correctly execute a `JMP X!=Y` instruction', async () => {
await resetStateMachines();
await cpu.writeUint32(SM0_PINCTRL, 32 << OUT_COUNT_SHIFT);
expect(await cpu.readUint32(SM0_ADDR)).toBe(0);
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_X, 23));
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_Y, 23));
await cpu.writeUint32(SM0_INSTR, pioJMP(PIO_COND_XNEY, 26));
expect(await cpu.readUint32(SM0_ADDR)).toBe(0);
// Set X to a value different from Y:
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_X, 3));
await cpu.writeUint32(SM0_INSTR, pioJMP(PIO_COND_XNEY, 26));
expect(await cpu.readUint32(SM0_ADDR)).toBe(26);
});
it('should correctly execute a `JMP OSRE` instruction', async () => {
await resetStateMachines();
await cpu.writeUint32(SM0_PINCTRL, 32 << OUT_COUNT_SHIFT);
expect(await cpu.readUint32(SM0_ADDR)).toBe(0);
// The following command fills the OSR (Output Shift Register)
await cpu.writeUint32(SM0_INSTR, pioMOV(PIO_MOV_DEST_OSR, PIO_OP_NONE, PIO_SRC_NULL));
await cpu.writeUint32(SM0_INSTR, pioJMP(PIO_COND_NOTEMPTYOSR, 11));
expect(await cpu.readUint32(SM0_ADDR)).toBe(11);
// Now empty the OSR by shifting bits out of it, and observe that the JMP isn't taken
await cpu.writeUint32(SM0_INSTR, pioOUT(PIO_DEST_NULL, 32));
await cpu.writeUint32(SM0_INSTR, pioJMP(PIO_COND_NOTEMPTYOSR, 22));
expect(await cpu.readUint32(SM0_ADDR)).toBe(11);
});
it('should correctly execute a program with `PULL` instruction', async () => {
await resetStateMachines();
await cpu.writeUint32(SM0_PINCTRL, 32 << OUT_COUNT_SHIFT);
await cpu.writeUint32(TXF0, 0x42f00d43);
expect(await cpu.readUint32(FLEVEL)).toEqual(1 << TX0_SHIFT); // TX0 should have 1 item
await cpu.writeUint32(SM0_INSTR, pioPULL(false, false));
expect(await cpu.readUint32(FLEVEL)).toEqual(0 << TX0_SHIFT); // TX0 should now have 0 items
await cpu.writeUint32(SM0_INSTR, pioOUT(PIO_DEST_PINS, 32));
expect(await cpu.readUint32(DBG_PADOUT)).toBe(0x42f00d43 & VALID_PINS_MASK);
});
it('should correctly execute the `OUT EXEC` instructions', async () => {
await resetStateMachines();
await cpu.writeUint32(SM0_PINCTRL, 32 << OUT_COUNT_SHIFT);
await cpu.writeUint32(TXF0, pioJMP(PIO_COND_ALWAYS, 16));
await cpu.writeUint32(SM0_INSTR, pioPULL(false, false));
expect(await cpu.readUint32(SM0_ADDR)).toBe(0);
await cpu.writeUint32(SM0_INSTR, pioOUT(PIO_DEST_EXEC, 32));
expect(await cpu.readUint32(SM0_ADDR)).toBe(16);
});
it('should correctly execute the `OUT PC` instruction', async () => {
await resetStateMachines();
await cpu.writeUint32(SM0_PINCTRL, 32 << OUT_COUNT_SHIFT);
await cpu.writeUint32(TXF0, 29);
await cpu.writeUint32(SM0_INSTR, pioPULL(false, false));
expect(await cpu.readUint32(SM0_ADDR)).toBe(0);
await cpu.writeUint32(SM0_INSTR, pioOUT(PIO_DEST_PC, 32));
expect(await cpu.readUint32(SM0_ADDR)).toBe(29);
});
it('should correctly execute a program with a `PUSH` instruction', async () => {
await resetStateMachines();
expect(await cpu.readUint32(FLEVEL)).toEqual(0 << RX0_SHIFT); // RX0 should have 0 items
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_X, 9));
await cpu.writeUint32(SM0_INSTR, pioIN(PIO_SRC_X, 32));
await cpu.writeUint32(SM0_INSTR, pioPUSH(false, false));
expect(await cpu.readUint32(FLEVEL)).toEqual(1 << RX0_SHIFT); // RX0 should now have 1 item
await cpu.writeUint32(SM0_INSTR, pioPUSH(false, false));
expect(await cpu.readUint32(FLEVEL)).toEqual(2 << RX0_SHIFT); // RX0 should now have 2 item
expect(await cpu.readUint32(RXF0)).toBe(9); // What we had in X
expect(await cpu.readUint32(FLEVEL)).toEqual(1 << RX0_SHIFT); // RX0 should now have 1 item
expect(await cpu.readUint32(RXF0)).toBe(0); // ISR should be zeroed after the first push
expect(await cpu.readUint32(FLEVEL)).toEqual(0 << RX0_SHIFT); // RX0 should have 0 items
});
it('should correctly execute a program with an `IRQ 2` instruction', async () => {
await resetStateMachines();
await cpu.writeUint32(IRQ, 0xff);
await cpu.writeUint32(SM0_INSTR, pioIRQ(false, false, 2));
expect(await cpu.readUint32(IRQ)).toEqual(1 << 2);
await cpu.writeUint32(SM0_INSTR, pioIRQ(true, false, 2));
expect(await cpu.readUint32(IRQ)).toEqual(0);
});
it('should correctly execute a program with an `IRQ 3 rel` instruction', async () => {
await resetStateMachines();
await cpu.writeUint32(IRQ, 0xff);
await cpu.writeUint32(SM2_INSTR, pioIRQ(false, false, 0x13));
expect(await cpu.readUint32(IRQ)).toEqual(1 << 1);
await cpu.writeUint32(SM2_INSTR, pioIRQ(true, false, 0x13));
expect(await cpu.readUint32(IRQ)).toEqual(0);
await cpu.writeUint32(SM0_INSTR, pioIRQ(false, false, 0x13));
expect(await cpu.readUint32(IRQ)).toEqual(1 << 3);
});
it('should correctly execute a program with an `WAIT IRQ 7` instruction', async () => {
await resetStateMachines();
await cpu.writeUint32(IRQ, 0xff);
await cpu.writeUint32(INSTR_MEM0, pioMOV(PIO_MOV_DEST_X, PIO_OP_NONE, PIO_SRC_X));
await cpu.writeUint32(INSTR_MEM1, pioWAIT(true, PIO_WAIT_SRC_IRQ, 7));
await cpu.writeUint32(INSTR_MEM2, pioJMP(PIO_COND_ALWAYS, 2));
await cpu.writeUint32(CTRL, 1); // Starts State Machine #0
expect(await cpu.readUint32(SM0_ADDR)).toEqual(1);
await cpu.writeUint32(SM2_INSTR, pioIRQ(false, false, 5)); // Set IRQ 5
expect(await cpu.readUint32(SM0_ADDR)).toEqual(1);
await cpu.writeUint32(SM2_INSTR, pioIRQ(false, false, 7)); // Set IRQ 7
expect(await cpu.readUint32(SM0_ADDR)).toEqual(2);
expect(await cpu.readUint32(IRQ)).toEqual(1 << 5); // Wait should have cleared IRQ 7
});
it('should correctly execute a program with an `WAIT 0 IRQ 7` instruction', async () => {
await resetStateMachines();
await cpu.writeUint32(IRQ, 0xff);
await cpu.writeUint32(SM0_INSTR, pioIRQ(false, false, 7)); // Set IRQ 7
await cpu.writeUint32(INSTR_MEM0, pioMOV(PIO_MOV_DEST_X, PIO_OP_NONE, PIO_SRC_X));
await cpu.writeUint32(INSTR_MEM1, pioWAIT(false, PIO_WAIT_SRC_IRQ, 7));
await cpu.writeUint32(INSTR_MEM2, pioJMP(PIO_COND_ALWAYS, 2));
await cpu.writeUint32(CTRL, 1); // Starts State Machine #0
expect(await cpu.readUint32(SM0_ADDR)).toEqual(1);
await cpu.writeUint32(IRQ, 1 << 7); // Clear IRQ 7
expect(await cpu.readUint32(SM0_ADDR)).toEqual(2);
});
it('should update INTR after executing an `IRQ 2` instruction', async () => {
await resetStateMachines();
await cpu.writeUint32(IRQ, 0xff); // Clear all IRQs
await cpu.writeUint32(SM2_INSTR, pioIRQ(false, false, 0x2));
expect((await cpu.readUint32(INTR)) & 0xf00).toEqual(1 << 10);
});
it('should correctly compare X to 0xffffffff after executing a `mov x, ~null` instruction', async () => {
await resetStateMachines();
await cpu.writeUint32(TXF0, 0xffffffff);
await cpu.writeUint32(SM0_INSTR, pioPULL(false, false));
await cpu.writeUint32(SM0_INSTR, pioMOV(PIO_DEST_X, PIO_OP_INVERT, PIO_SRC_NULL)); // X <- ~0 = 0xffffffff
await cpu.writeUint32(SM0_INSTR, pioOUT(PIO_DEST_Y, 32)); // Y <- 0xffffffff
await cpu.writeUint32(SM0_INSTR, pioJMP(PIO_COND_ALWAYS, 8));
await cpu.writeUint32(SM0_INSTR, pioJMP(PIO_COND_XNEY, 16)); // Shouldn't take the jump
expect(await cpu.readUint32(SM0_ADDR)).toEqual(8); // Assert that the 2nd jump wasn't taken
});
it('should wrap the program when it gets to EXECCTRL_WRAP_TOP', async () => {
await resetStateMachines();
await cpu.writeUint32(
SM0_EXECCTRL,
(1 << EXECCTRL_WRAP_BOTTOM_SHIFT) | (2 << EXECCTRL_WRAP_TOP_SHIFT)
);
// State machine Pseudo code:
// jmp .label2
// .wrap_target
// label1:
// jmp label1
// label2:
// mov x, null
// .wrap
// label3:
// jmp label3
await cpu.writeUint32(INSTR_MEM0, pioJMP(PIO_COND_ALWAYS, 2));
await cpu.writeUint32(INSTR_MEM1, pioJMP(PIO_COND_ALWAYS, 1)); // infinite loop
await cpu.writeUint32(INSTR_MEM2, pioMOV(PIO_DEST_X, PIO_OP_NONE, PIO_SRC_X));
await cpu.writeUint32(INSTR_MEM3, pioJMP(PIO_COND_ALWAYS, 3)); // infinite loop
await cpu.writeUint32(CTRL, 1); // Starts State Machine #0
expect(await cpu.readUint32(SM0_ADDR)).toEqual(1);
});
it('should automatically pull when Autopull is enabled', async () => {
await resetStateMachines();
await cpu.writeUint32(
SM0_SHIFTCTRL,
SHIFTCTRL_AUTOPULL | (4 << SHIFTCTRL_PULL_THRESH_SHIFT) | OUT_SHIFTDIR
);
await cpu.writeUint32(TXF0, 0x5);
await cpu.writeUint32(TXF0, 0x6);
await cpu.writeUint32(TXF0, 0x7);
await cpu.writeUint32(SM0_INSTR, pioOUT(PIO_DEST_X, 4)); // 5
await cpu.writeUint32(SM0_INSTR, pioIN(PIO_SRC_X, 4));
await cpu.writeUint32(SM0_INSTR, pioOUT(PIO_DEST_X, 4)); // 6
await cpu.writeUint32(SM0_INSTR, pioIN(PIO_SRC_X, 4));
await cpu.writeUint32(SM0_INSTR, pioOUT(PIO_DEST_X, 4)); // 7
await cpu.writeUint32(SM0_INSTR, pioIN(PIO_SRC_X, 4));
await cpu.writeUint32(SM0_INSTR, pioPUSH(false, false));
expect(await cpu.readUint32(RXF0)).toEqual(0x567);
});
it('should not Autopull in the middle of OUT instruction', async () => {
await resetStateMachines();
await cpu.writeUint32(
SM0_SHIFTCTRL,
SHIFTCTRL_AUTOPULL | (4 << SHIFTCTRL_PULL_THRESH_SHIFT) | OUT_SHIFTDIR
);
await cpu.writeUint32(TXF0, 0x25);
await cpu.writeUint32(TXF0, 0x36);
await cpu.writeUint32(SM0_INSTR, pioOUT(PIO_DEST_X, 8));
await cpu.writeUint32(SM0_INSTR, pioIN(PIO_SRC_X, 8));
await cpu.writeUint32(SM0_INSTR, pioPUSH(false, false));
expect(await cpu.readUint32(RXF0)).toEqual(0x25);
});
it('should stall until the TX FIFO fills when executing an OUT instruction with Autopull', async () => {
await resetStateMachines();
await cpu.writeUint32(
SM0_SHIFTCTRL,
SHIFTCTRL_AUTOPULL | (4 << SHIFTCTRL_PULL_THRESH_SHIFT) | OUT_SHIFTDIR
);
await cpu.writeUint32(SM0_INSTR, pioOUT(PIO_DEST_X, 4));
expect((await cpu.readUint32(SM0_EXECCTRL)) & EXECCTRL_EXEC_STALLED).toEqual(
EXECCTRL_EXEC_STALLED
);
console.log('now writing to TXF0');
await cpu.writeUint32(TXF0, 0x36); // Unstalls the machine
expect((await cpu.readUint32(SM0_EXECCTRL)) & EXECCTRL_EXEC_STALLED).toEqual(0);
});
it('should automatically push when Autopush is enabled', async () => {
await resetStateMachines();
await cpu.writeUint32(
SM0_SHIFTCTRL,
SHIFTCTRL_AUTOPUSH | (8 << SHIFTCTRL_PUSH_THRESH_SHIFT) | OUT_SHIFTDIR
);
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_X, 0x13));
await cpu.writeUint32(SM0_INSTR, pioIN(PIO_SRC_X, 8));
expect(await cpu.readUint32(RXF0)).toEqual(0x13);
});
it('should only Autopush at the end the the IN instruction', async () => {
await resetStateMachines();
await cpu.writeUint32(
SM0_SHIFTCTRL,
SHIFTCTRL_AUTOPUSH | (8 << SHIFTCTRL_PUSH_THRESH_SHIFT) | OUT_SHIFTDIR
);
await cpu.writeUint32(SM0_INSTR, pioMOV(PIO_DEST_X, PIO_OP_INVERT, PIO_SRC_NULL));
await cpu.writeUint32(SM0_INSTR, pioIN(PIO_SRC_X, 16));
expect(await cpu.readUint32(RXF0)).toEqual(0xffff);
});
it('should stall until the RX FIFO has capacity when executing an IN instruction with Autopush', async () => {
await resetStateMachines();
await cpu.writeUint32(
SM0_SHIFTCTRL,
SHIFTCTRL_AUTOPUSH | (8 << SHIFTCTRL_PUSH_THRESH_SHIFT) | OUT_SHIFTDIR
);
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_X, 15));
await cpu.writeUint32(SM0_INSTR, pioIN(PIO_SRC_X, 8));
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_X, 16));
await cpu.writeUint32(SM0_INSTR, pioIN(PIO_SRC_X, 8));
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_X, 17));
await cpu.writeUint32(SM0_INSTR, pioIN(PIO_SRC_X, 8));
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_X, 18));
await cpu.writeUint32(SM0_INSTR, pioIN(PIO_SRC_X, 8));
await cpu.writeUint32(SM0_INSTR, pioSET(PIO_DEST_X, 19));
await cpu.writeUint32(SM0_INSTR, pioIN(PIO_SRC_X, 8)); // Should fill the RX FIFO and stall!
expect((await cpu.readUint32(SM0_EXECCTRL)) & EXECCTRL_EXEC_STALLED).toEqual(
EXECCTRL_EXEC_STALLED
);
expect(await cpu.readUint16(RXF0)).toEqual(15); // Unstalls the machine
expect((await cpu.readUint32(SM0_EXECCTRL)) & EXECCTRL_EXEC_STALLED).toEqual(0);
expect(await cpu.readUint16(RXF0)).toEqual(16);
expect(await cpu.readUint16(RXF0)).toEqual(17);
expect(await cpu.readUint16(RXF0)).toEqual(18);
expect(await cpu.readUint16(RXF0)).toEqual(19);
});
it('should update TXNFULL flag in INTR according to the level of the TX FIFO (issue #73)', async () => {
await resetStateMachines();
await cpu.writeUint32(IRQ0_INTE, INTR_SM0_TXNFULL);
expect((await cpu.readUint32(INTR)) & INTR_SM0_TXNFULL).toEqual(INTR_SM0_TXNFULL);
expect((await cpu.readUint32(NVIC_ISPR)) & PIO_IRQ0).toEqual(PIO_IRQ0);
await cpu.writeUint32(TXF0, 1);
await cpu.writeUint32(TXF0, 2);
await cpu.writeUint32(TXF0, 3);
await cpu.writeUint32(NVIC_ICPR, PIO_IRQ0);
expect((await cpu.readUint32(INTR)) & INTR_SM0_TXNFULL).toEqual(INTR_SM0_TXNFULL);
await cpu.writeUint32(TXF0, 3);
await cpu.writeUint32(NVIC_ICPR, PIO_IRQ0);
// At this point, TX FIFO should be full and the flag/interrupt will be cleared
expect((await cpu.readUint32(INTR)) & INTR_SM0_TXNFULL).toEqual(0);
expect((await cpu.readUint32(NVIC_ISPR)) & PIO_IRQ0).toEqual(0);
// Pull an item, so TX FIFO should be "not empty" again
await cpu.writeUint32(SM0_INSTR, pioPULL(false, false));
expect((await cpu.readUint32(INTR)) & INTR_SM0_TXNFULL).toEqual(INTR_SM0_TXNFULL);
expect((await cpu.readUint32(NVIC_ISPR)) & PIO_IRQ0).toEqual(PIO_IRQ0);
});
it('should update RXFNEMPTY flag in INTR according to the level of the RX FIFO (issue #73)', async () => {
await resetStateMachines();
await cpu.writeUint32(IRQ0_INTE, INTR_SM0_RXNEMPTY);
await cpu.writeUint32(NVIC_ICPR, PIO_IRQ0);
// RX FIFO starts empty
expect((await cpu.readUint32(INTR)) & INTR_SM0_RXNEMPTY).toEqual(0);
expect((await cpu.readUint32(NVIC_ISPR)) & PIO_IRQ0).toEqual(0);
// Push an item so it's no longer empty...
await cpu.writeUint32(SM0_INSTR, pioPUSH(false, false));
expect((await cpu.readUint32(INTR)) & INTR_SM0_RXNEMPTY).toEqual(INTR_SM0_RXNEMPTY);
expect((await cpu.readUint32(NVIC_ISPR)) & PIO_IRQ0).toEqual(PIO_IRQ0);
// Read the item and it should be empty again
await cpu.readUint32(RXF0);
await cpu.writeUint32(NVIC_ICPR, PIO_IRQ0);
expect((await cpu.readUint32(INTR)) & INTR_SM0_RXNEMPTY).toEqual(0);
expect((await cpu.readUint32(NVIC_ISPR)) & PIO_IRQ0).toEqual(0);
});
}); | the_stack |
import {NotifyDialog} from "./ui/dialog";
import {assert, findElement, findElementAny} from "./util";
interface TestOperation {
/**
* Condition which is evaluated to see whether the test can executed.
*/
cond: () => boolean;
/**
* Operation that executes the test.
*/
cont: () => void;
description: string;
}
/**
* Creates an event for a context menu. This is usually triggered by a right mouse-click.
*/
function contextMenuEvent(): Event {
const evt: MouseEvent = document.createEvent("MouseEvents");
evt.initMouseEvent("contextmenu",
/* canBubble */ true,
/* cancellable */ true,
window,
/* detail */ 0,
/* screenX */ 0,
/* screenY */ 0,
/* clientX */ 0,
/* clientY */ 0,
/* ctrlKey */ false,
/* altKey */ false,
/* shiftKey */ false,
/* metaKey */ false,
/* button */ 2,
/* relatedTarget */ null);
return evt;
}
/**
* Creates a mouse click event with modifiers.
*/
function mouseClickEvent(shift: boolean, control: boolean): Event {
const evt: MouseEvent = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, control, false, shift, false, 0, null);
return evt;
}
function controlClickEvent(): Event {
return mouseClickEvent(false, true);
}
function keyboardEvent(code: string): Event {
return new KeyboardEvent("keydown",
{ code: code, altKey: false, bubbles: true, cancelable: true, ctrlKey: false });
}
/**
* This class is used for testing the UI.
*/
export class Test {
protected testProgram: TestOperation[];
protected programCounter: number;
constructor() {
this.testProgram = [];
this.programCounter = 0;
}
/**
* Singleton instance of this class.
*/
public static instance: Test = new Test();
public addProgram(testOps: TestOperation[]): void {
this.testProgram = this.testProgram.concat(testOps);
}
/**
* Execute next test if is possible.
* If the text is executed the next continuation is reset.
*/
public runNext(): void {
if (this.testProgram.length <= this.programCounter) {
if (this.testProgram.length !== 0)
console.log("Tests are finished");
return;
}
const op = this.testProgram[this.programCounter];
if (op == null)
return;
console.log("Evaluating condition for " + this.programCounter + ". " + op.description);
if (op.cond()) {
console.log("Running test " + this.programCounter + ". " + op.description);
op.cont();
console.log("Test completed " + this.programCounter + ". " + op.description);
this.programCounter++;
console.log("Incremented: " + this.programCounter);
}
}
// noinspection JSMethodCanBeStatic
private next(): void {
// Trigger a request to the remote site using a "ping" request
findElement("#hillviewPage0 .topMenu #Manage #List_machines").click();
}
public runTests(): void {
this.createTestProgram();
this.programCounter = 0;
this.runNext();
}
private static existsElement(cssselector: string): boolean {
const result = findElementAny(cssselector) != null;
console.log("Checking element existence: " + cssselector + "=" + result);
return result;
}
public createTestProgram(): void {
/*
This produces the following pages:
Second tab: ontime small dataset
1: a tabular view
2: schema view
3: table view with 3 columns
4: Histogram of the FlightDate column
5: Histogram of UniqueCarrier, shown as pie chart
6: 2dHistogram of DepTime, Depdelay
7: Table view, filtered flights
8: Trellis 2D histograms (DepTime, DepDelay) grouped by DayOfWeek
9: Trellis Histograms of UniqueCarrier grouped by DayOfWeek
10: Trellis heatmap plot
11: Quartiles plot
12: Non-stacked bar charts plot
13: Filtered table
14: correlation heatmaps
15: Trellis plot of quartiles
16: Histogram of interval column
17: Map view of OriginState
18: Heavy hitters view of Origin
*/
this.addProgram([{
description: "Load rfc5424 logs",
cond: () => true,
cont: () => {
findElement("#hillviewPage0 .topMenu #Generic_logs___").click();
let formField = findElement(".dialog #fileNamePattern");
(formField as HTMLInputElement).value = "data/sample_logs/rfc*";
formField = findElement(".dialog #logFormat");
(formField as HTMLInputElement).value = "%{RFC5424}";
formField = findElement(".dialog #startTime");
(formField as HTMLInputElement).value = "";
formField = findElement(".dialog #endTime");
(formField as HTMLInputElement).value = "";
const confirm = findElement(".dialog .confirm");
confirm.click();
},
}, {
description: "Close this tab",
cond: () => Test.existsElement("#hillviewPage1 .idle"),
cont: () => findElement("#hillviewPage0 .topMenu #Flights__15_columns__CSV_").click(),
}, {
description: "Load all flights",
cond: () => Test.existsElement("#hillviewPage1 .idle"),
cont: () => findElement(".tab .close").click(),
}, {
description: "Show no columns",
cond: () => Test.existsElement("#hillviewPage1 .idle"),
cont: () => findElement("#hillviewPage1 .topMenu #No_columns").click(),
}, {
description: "rename column FlightDate to Date",
cond: () => Test.existsElement("#hillviewPage1 .idle"),
cont: () => {
const date = findElement("#hillviewPage1 thead td[data-colname=FlightDate] .truncated");
date.dispatchEvent(contextMenuEvent());
const rename = findElement("#hillviewPage1 .dropdown #Rename___");
rename.click();
const formField = findElement(".dialog #name");
(formField as HTMLInputElement).value = "Date";
const confirm = findElement(".dialog .confirm");
confirm.click();
}
}, {
description: "drop column Cancelled",
cond: () => Test.existsElement("#hillviewPage1 .idle"),
cont: () => {
// Drop column cancelled
const cancCol = findElement("#hillviewPage1 thead td[data-colname=Cancelled] .truncated");
cancCol.dispatchEvent(contextMenuEvent());
const item = findElement("#hillviewPage1 .dropdown #Drop");
item.click();
},
}, {
description: "show column 0",
cond: () => Test.existsElement("#hillviewPage1 .idle"),
cont: () => {
// Check that Cancelled column does not exist
assert(!Test.existsElement("#hillviewPage1 thead td[data-colname=Cancelled]"));
const col0 = findElement("#hillviewPage1 thead .col0");
col0.dispatchEvent(contextMenuEvent());
findElement("#hillviewPage1 .dropdown #Show").click();
},
}, {
description: "Show column 1",
cond: () => Test.existsElement("#hillviewPage1 .idle"),
cont: () => {
const col1 = findElement("#hillviewPage1 thead .col1");
col1.dispatchEvent(contextMenuEvent());
findElement("#hillviewPage1 .dropdown #Show").click();
},
}, {
description: "Hide column 0",
cond: () => Test.existsElement("#hillviewPage1 .idle"),
cont: () => {
const col0 = findElement("#hillviewPage1 thead .col0");
col0.dispatchEvent(contextMenuEvent());
findElement("#hillviewPage1 .dropdown #Hide").click();
},
}, {
description: "Create column in JavaScript",
cond: () => Test.existsElement("#hillviewPage1 .idle"),
cont: () => {
const cancCol = findElement("#hillviewPage1 thead td[data-colname=OriginCityName] .truncated");
cancCol.dispatchEvent(contextMenuEvent());
const item = findElement("#hillviewPage1 .dropdown #Create_column_in_JS___");
item.click();
(findElement(".dialog #outColName") as HTMLInputElement).value = "O";
(findElement(".dialog #outColKind") as HTMLInputElement).value = "String";
(findElement(".dialog #function") as HTMLInputElement).value = "function map(row) { return row['OriginCityName'][0]; }";
findElement(".dialog .confirm").click();
},
}, {
description: "Show schema view",
cond: () => Test.existsElement("#hillviewPage1 .idle"),
cont: () => {
findElement("#hillviewPage1 .topMenu #View #Schema").click();
// This does not involve an RPC; the result is available right away.
// Produces hillviewPage2
// Select row 0
const row0 = findElement("#hillviewPage2 #row0");
row0.click();
// Add row 1
const row1 = findElement("#hillviewPage2 #row1");
row1.dispatchEvent(controlClickEvent());
// Add row 3
const row3 = findElement("#hillviewPage2 #row3");
row3.dispatchEvent(controlClickEvent());
// Select menu item to show the associated table
findElement("#hillviewPage2 .topMenu #Table_of_selected_columns").click();
this.next(); // no rpc
}
}, {
description: "Display histogram",
cond: () => true,
cont: () => {
const col1 = findElement("#hillviewPage1 thead .col1");
col1.dispatchEvent(contextMenuEvent());
// Produces hillviewPage4
findElement("#hillviewPage1 .dropdown #Histogram").click();
},
}, {
description: "Display a categorical histogram",
cond: () => Test.existsElement("#hillviewPage4 .idle"),
cont: () => {
const col2 = findElement("#hillviewPage1 thead .col2");
col2.dispatchEvent(contextMenuEvent());
// Produces hillviewPage5
findElement("#hillviewPage1 .dropdown #Histogram").click();
},
}, {
description: "Display a pie chart",
cond: () => Test.existsElement("#hillviewPage5 .idle"),
cont: () => {
const pie = findElement("#hillviewPage5 .topMenu #View #pie_chart_histogram");
pie.click();
this.next();
},
}, {
description: "Display a 2D histogram",
cond: () => Test.existsElement("#hillviewPage5 .idle"),
cont: () => {
findElement("#hillviewPage1 thead .col8").click();
const col9 = findElement("#hillviewPage1 thead .col9");
col9.dispatchEvent(controlClickEvent());
col9.dispatchEvent(contextMenuEvent());
// Produces hillviewPage6
findElement("#hillviewPage1 .dropdown #Histogram").click();
},
}, {
description: "Scroll",
cond: () => Test.existsElement("#hillviewPage1 .idle"),
cont: () => {
const evt = keyboardEvent("PageDown");
const tableHead = findElement("#hillviewPage1 #tableContainer");
tableHead.dispatchEvent(evt);
},
}, {
description: "Filter",
cond: () => Test.existsElement("#hillviewPage1 .idle"),
cont: () => {
const col2 = findElement("#hillviewPage1 thead .col2");
col2.dispatchEvent(contextMenuEvent());
findElement("#hillviewPage1 .dropdown #Filter___").click();
(findElement(".dialog #query") as HTMLInputElement).value = "AA";
// Produces hillviewPage7
findElement(".dialog .confirm").click();
},
}, {
description: "Trellis histogram plot",
cond: () => Test.existsElement("#hillviewPage6 .idle"),
cont: () => {
findElement("#hillviewPage6 .topMenu #View #group_by___").click();
// Produces hillviewPage8
(findElement(".dialog .confirm")).click();
}
}, {
description: "Trellis 2d histogram plot",
cond: () => Test.existsElement("#hillviewPage8 .idle"),
cont: () => {
findElement("#hillviewPage5 .topMenu #View #group_by___").click();
// Produces hillviewPage9
(findElement(".dialog .confirm")).click();
}
}, {
description: "Trellis heatmap plot",
cond: () => Test.existsElement("#hillviewPage9 .idle"),
cont: () => {
// Produces hillviewPage10
findElement("#hillviewPage8 .topMenu #View #heatmap").click();
}
}, {
description: "Change buckets",
cond: () => Test.existsElement("#hillviewPage10 .idle"),
cont: () => {
const el2 = findElement("#hillviewPage6 .topMenu #View #__buckets___");
el2.click();
(findElement(".dialog #x_buckets") as HTMLInputElement).value = "10";
findElement(".dialog .confirm").click();
},
}, {
description: "Quartiles vector",
cond: () => Test.existsElement("#hillviewPage6 .idle"),
cont: () => {
findElement("#hillviewPage1 #Chart").click();
findElement("#Quartiles___").click();
(findElement(".dialog #columnName0") as HTMLInputElement).value = "Dest";
(findElement(".dialog #columnName1") as HTMLInputElement).value = "ArrTime";
findElement(".dialog .confirm").click();
}
}, {
description: "Stacked bars 2D histogram",
cond: () => Test.existsElement("#hillviewPage11 .idle"),
cont: () => {
findElement("#hillviewPage1 #Chart").click();
findElement("#I2D_Histogram___").click();
(findElement(".dialog #columnName0") as HTMLInputElement).value = "UniqueCarrier";
(findElement(".dialog #columnName1") as HTMLInputElement).value = "DepDelay";
findElement(".dialog .confirm").click();
}
}, {
description: "Change buckets for 2D histogram",
cond: () => Test.existsElement("#hillviewPage12 .idle"),
cont: () => {
const b = findElement("#hillviewPage12 .topMenu #View #__buckets___");
b.click();
(findElement(".dialog #y_buckets") as HTMLInputElement).value = "10";
findElement(".dialog .confirm").click();
}
}, {
description: "Non-stacked bars 2D histogram",
cond: () => Test.existsElement("#hillviewPage12 .idle"),
cont: () => {
const b = findElement("#hillviewPage12 .topMenu #View #stacked_parallel");
b.click();
this.next(); // no interaction required
}
}, {
description: "Filter based on the first table cell value",
cond: () => Test.existsElement("#hillviewPage12 .idle"),
cont: () => {
const cell = findElement("#hillviewPage1 [data-col=\"3\"][data-row=\"1\"]");
cell.dispatchEvent(contextMenuEvent());
const menu = findElement("#hillviewPage1 #Keep_2016_01_01");
menu.click();
}
}, {
description: "Correlation heatmaps",
cond: () => Test.existsElement("#hillviewPage13 .idle"),
cont: () => {
const cellDep = findElement("#hillviewPage1 thead td[data-colname=DepTime] .truncated");
cellDep.click();
cellDep.scrollIntoView();
const cellArr = findElement("#hillviewPage1 thead td[data-colname=ArrDelay] .truncated");
cellArr.dispatchEvent(mouseClickEvent(true, false));
cellArr.dispatchEvent(contextMenuEvent());
const chart = findElement("#hillviewPage1 .dropdown #Charts");
chart.click();
const qv = findElement("#hillviewPage1 .dropdown #Correlation");
console.log(qv + "," + qv.className + "," + qv.parentElement!.className);
qv.click();
}
}, {
description: "Trellis plots of quartile vectors",
cond: () => Test.existsElement("#hillviewPage14 .idle"),
cont: () => {
findElement("#hillviewPage11 .topMenu #View #group_by___").click();
(findElement(".dialog .confirm")).click();
}
}, {
description: "Create interval column",
cond: () => Test.existsElement("#hillviewPage15 .idle"),
cont: () => {
// click on a new cell, to deselect existing ones
const other = findElement("#hillviewPage1 thead td[data-colname=DayOfWeek] .truncated");
other.scrollIntoView();
other.click();
// start selection
const cellDep = findElement("#hillviewPage1 thead td[data-colname=DepTime] .truncated");
cellDep.click();
const cellArr = findElement("#hillviewPage1 thead td[data-colname=ArrTime] .truncated");
cellArr.dispatchEvent(controlClickEvent());
cellArr.dispatchEvent(contextMenuEvent());
const qv = findElement("#hillviewPage1 .dropdown #Create_interval_column___");
qv.click();
(findElement(".dialog .confirm")).click();
}
}, {
description: "Histogram of interval column",
cond: () => Test.existsElement("#hillviewPage1 .idle"),
cont: () => {
findElement("#hillviewPage1 #Chart").click();
findElement("#I1D_Histogram___").click();
(findElement(".dialog #columnName") as HTMLInputElement).value = "DepTime:ArrTime";
findElement(".dialog .confirm").click();
},
}, {
description: "Map of OriginState",
cond: () => Test.existsElement("#hillviewPage16 .idle"),
cont: () => {
const other = findElement("#hillviewPage1 thead td[data-colname=OriginState] .truncated");
other.click();
other.dispatchEvent(contextMenuEvent());
const qv = findElement("#hillviewPage1 .dropdown #Map");
qv.click();
},
}, {
description: "Heavy hitters view of Origin",
cond: () => Test.existsElement("#hillviewPage17 .idle"),
cont: () => {
const other = findElement("#hillviewPage1 thead td[data-colname=Origin] .truncated");
other.click();
other.dispatchEvent(contextMenuEvent());
const qv = findElement("#hillviewPage1 .dropdown #Frequent_Elements___");
qv.click();
findElement(".dialog .confirm").click();
},
}, {
description: "Close some windows",
cond: () => Test.existsElement("#hillviewPage18 .idle"),
cont: () => {
/*
for (let i = 2; i < 8; i++) {
const el = findElement("#hillviewPage" + i.toString() + " .close");
if (el != null)
el.click();
}
*/
const dialog = new NotifyDialog("Tests are completed", null, "Done.");
dialog.show();
},
}
]);
}
} | the_stack |
import { RuleSetCondition, RuleSetRule, RuleSetUse } from 'webpack';
import postcssPseudoClasses, {
PostCssLoaderPseudoClassesPluginOptions,
} from 'postcss-pseudo-classes';
export interface CssLoaderOptions {
// Enables/Disables url/image-set functions handling
url?: boolean | (() => boolean);
// Enables/Disables @import at-rules handling
import?: boolean | (() => boolean);
// Enables/Disables CSS Modules and their configuration
modules?:
| boolean
| string
| {
localIdentName?: string;
getLocalIdent?: () => string;
};
// Enables/Disables generation of source maps
sourceMap?: boolean;
// Enables/Disables or setups number of loaders applied before CSS loader
importLoaders?: number;
// Style of exported classnames
localsConvention?: string;
// Export only locals
onlyLocals?: boolean;
// Use ES modules syntax
esModule?: boolean;
}
/**
* Interface to enter PostCss Pseudo-States-Plugin Option to Storybook Preset
*/
export interface PseudoStatesPresetOptions {
postCssLoaderPseudoClassesPluginOptions?: PostCssLoaderPseudoClassesPluginOptions;
// rules to apply postcss plugin, if empty set to existing scss rules
rules?: Array<RuleSetCondition>;
cssLoaderOptions?: CssLoaderOptions;
// webpack: 'webpack4' | 'webpack5';
}
const postCssLoaderName = 'postcss-loader';
export const postCSSOptionsDefault: PostCssLoaderPseudoClassesPluginOptions = {
blacklist: [
':root',
':host',
':host-context',
':nth-child',
':nth-of-type',
':export',
],
};
const cssLoaderName = 'css-loader';
export const cssLoaderOptionsDefault: CssLoaderOptions = {
modules: {
// remove [hash] option
// because hash is not predictable or definable for this addon
localIdentName: '[path][name]__[local]',
// getLocalIdent: () => '[path][name]__[local]',
},
};
/**
* Find all rules with matching condition
*
* @param rules of webpack config.
* @param conditions of rules to find in webpack config.
*/
export const filterRules = (
rules: Array<RuleSetRule>,
conditions: Array<RuleSetCondition>
): Array<RuleSetRule> => {
const ruleReferences: Array<RuleSetRule> = [];
for (const rule of rules) {
if (rule?.test) {
const ruleCondition: RuleSetCondition = rule.test;
// compare conditions item with rule
for (let i = 0; i < conditions.length; i += 1) {
const condition: RuleSetCondition = conditions[i];
if (
typeof condition === 'string' &&
ruleCondition.toString().includes(condition as string)
) {
ruleReferences.push(rule);
} else if (condition instanceof RegExp && ruleCondition === condition) {
ruleReferences.push(rule);
}
// TODO test if this is working for all types of ruleCondition
else if (ruleCondition.toString() === condition.toString()) {
ruleReferences.push(rule);
}
}
}
if (rule.oneOf) {
const subRules = rule.oneOf;
// for (const subRule of rule.oneOf) {
const filteredSubRules = filterRules(subRules, conditions);
// ruleReferences.push(...filteredSubRules);
for (const filterdRule of filteredSubRules) {
ruleReferences.push(filterdRule);
}
}
}
return ruleReferences;
};
/**
* Check whether pseudo classes is already available in postcss plugins.
*/
const hasAlreadyPseudoClassesPlugin = (
plugins: string | Array<string | Function> | Function | Object
): boolean => {
if (typeof plugins === 'string') {
return plugins.includes('pseudo-states');
}
if (Array.isArray(plugins)) {
for (const e of plugins) {
if (hasAlreadyPseudoClassesPlugin(e)) return true;
}
}
if (typeof plugins === 'function' || typeof plugins === 'object') {
// @ts-ignore
return plugins?.postcssPlugin === 'postcss-pseudo-classes';
}
return false;
};
/**
* Add postcss pseudo classes plugin options to post-css loader object
* @param plugins
* @param postCssLoaderOptions
*/
const addPostCssClassesPluginOptions = (
plugins: string | Array<any> | Function | Object,
postCssLoaderOptions: PostCssLoaderPseudoClassesPluginOptions
): string | Array<any> | Function | Object => {
if (plugins) {
if (typeof plugins === 'string') {
if (!hasAlreadyPseudoClassesPlugin(plugins)) {
// eslint-disable-next-line no-param-reassign
plugins = [postcssPseudoClasses(postCssLoaderOptions)];
}
} else if (Array.isArray(plugins)) {
if (!hasAlreadyPseudoClassesPlugin(plugins)) {
plugins.push(postcssPseudoClasses(postCssLoaderOptions));
plugins.push(() => postcssPseudoClasses(postCssLoaderOptions));
}
} else if (typeof plugins === 'function') {
if (!hasAlreadyPseudoClassesPlugin(plugins)) {
const replaceFunction = (f: Function): Array<any> => {
return [
// TODO not correct in general but react-scripts returns array
// @ts-ignore
...f(),
postcssPseudoClasses(postCssLoaderOptions),
];
};
// eslint-disable-next-line no-param-reassign
plugins = replaceFunction(plugins);
}
} else {
// is object
// eslint-disable-next-line no-param-reassign
plugins = {
...plugins,
...() => postcssPseudoClasses(postCssLoaderOptions),
};
}
}
return plugins;
};
/**
* add 'postcss-pseudo-classes' plugin to 'postcss-loader`.
* If 'postcss-loader` is not available in rule's use add it ,
* if 'postcss-loader` is already available, append plugin
*
* @param use set of loaders of webpack rule
* @param postCssLoaderOptions configuration of 'postcss-pseudo-classes' plugin
*/
const addPostCssLoader = (
use: RuleSetUse,
postCssLoaderOptions: PostCssLoaderPseudoClassesPluginOptions
): RuleSetUse => {
if (typeof use === 'string' && use.includes(postCssLoaderName)) {
return {
loader: postCssLoaderName,
options: {
// postcss-loader <= 4.3.0 and react-scripts <= v4.0.3
// plugins: () => [postcssPseudoClasses(postCssLoaderOptions)],
// >= 4.3.0
postcssOptions: () => [postcssPseudoClasses(postCssLoaderOptions)],
},
};
}
if (typeof use === 'function') {
// TODO check if this is working
// TODO check for .includes(postCssLoaderName) is missing but done in recursive step
// @ts-ignore
return (data: any): RuleSetUse => {
// return use(data);
const useFnResult = use(data);
return addPostCssLoader(useFnResult, postCssLoaderOptions);
};
}
if (Array.isArray(use)) {
for (const item of use) {
addPostCssLoader(item, postCssLoaderOptions);
}
return use;
}
// use is of type RuleSetLoader
const useItem = use as RuleSetRule;
if (
useItem?.loader &&
typeof useItem?.loader === 'string' &&
useItem.loader.includes(postCssLoaderName)
) {
// add options if not available
if (!useItem.options) {
useItem.options = {
// plugins: [postcssPseudoClasses(postCssLoaderOptions)],
postcssOptions: {
plugins: [postcssPseudoClasses(postCssLoaderOptions)],
},
};
return use;
}
// postcss-loader <= 4.3.0 and react-scripts <= v4.0.3 uses options.plugins instead of options.postcssOptions.plugins
// if options.plugins is available in >= 4.3.0 (for instance CRA) add postcss-pseudo-classes there, too
// @ts-ignore
if (useItem?.options?.plugins) {
// @ts-ignore
useItem.options.plugins = addPostCssClassesPluginOptions(
// @ts-ignore
useItem?.options?.plugins,
postCssLoaderOptions
);
}
const { postcssOptions } = useItem.options as {
plugins: any;
postcssOptions: { plugins: Array<any> };
};
if (!postcssOptions) {
// @ts-ignore
useItem.options.postcssOptions = {
plugins: [postcssPseudoClasses(postCssLoaderOptions)],
};
} else if (typeof postcssOptions === 'function') {
// get function value and append 'postcss-pseudo-classes' to plugins
// @ts-ignore
useItem.options.postcssOptions = (loader: any) => {
// @ts-ignore
const _postcssOptions = postcssOptions(loader);
_postcssOptions.plugins = [
..._postcssOptions.plugins,
postcssPseudoClasses(postCssLoaderOptions),
];
return _postcssOptions;
};
} else if (typeof postcssOptions === 'object') {
if (!postcssOptions.plugins) {
// @ts-ignore
postcssOptions.plugins = [];
}
// add plugin to object
// @ts-ignore
postcssOptions.plugins = addPostCssClassesPluginOptions(
postcssOptions.plugins,
postCssLoaderOptions
);
}
return use;
}
// TODO if not found add automatically after scss-loader or css loader
// if not found, do not alter the RuleSetUse
return use;
};
/**
* add 'postcss-pseudo-classes' plugin to 'postcss-loader`. in rules
* @param rules
* @param postCssLoaderOptions
*/
export const addPostCSSLoaderToRules = (
rules: Array<RuleSetRule>,
postCssLoaderOptions: PostCssLoaderPseudoClassesPluginOptions
) => {
for (const rule of rules) {
if (rule?.rules) {
addPostCSSLoaderToRules(rule.rules, postCssLoaderOptions);
// eslint-disable-next-line no-continue
continue;
}
if (rule?.use) {
rule.use = addPostCssLoader(rule.use, postCssLoaderOptions);
} else if (rule?.oneOf) {
for (const r of rule.oneOf) {
addPostCssLoader(r?.use as RuleSetUse, postCssLoaderOptions);
}
} else {
// TODO
}
}
};
/**
* change or add modules property of 'css-loader'.options
* that are required to display pseudo states properly
* @param use
* @param cssLoaderOptions
*/
const modifyCssLoader = (
use: RuleSetUse,
cssLoaderOptions: CssLoaderOptions
): RuleSetUse => {
if (typeof use === 'string' && use.includes(cssLoaderName)) {
return {
loader: cssLoaderName,
options: {
...cssLoaderOptions,
},
};
}
if (typeof use === 'function') {
// TODO check if this is working
// TODO check for .includes(cssLoaderName) is missing but done in recursive step
// @ts-ignore
return (data: any): RuleSetUse => {
// return use(data);
const useFnResult = use(data);
return modifyCssLoader(useFnResult, cssLoaderOptions);
};
}
if (Array.isArray(use)) {
for (const item of use) {
modifyCssLoader(item, cssLoaderOptions);
}
return use;
}
// use is of type RuleSetLoader
const useItem = use as RuleSetRule;
if (
useItem?.loader &&
typeof useItem?.loader === 'string' &&
useItem.loader.includes(cssLoaderName)
) {
if (useItem.options) {
const { modules } = useItem.options as { modules: any };
if (modules) {
if (typeof modules === 'string' && modules === 'true') {
// @ts-ignore
useItem.options.modules = cssLoaderOptions.modules;
} else if (typeof modules === 'boolean' && modules) {
// @ts-ignore
useItem.options.modules = cssLoaderOptions.modules;
} else {
// is object
if (
useItem.options &&
// @ts-ignore
useItem.options.modules &&
// @ts-ignore
useItem.options.modules.getLocalIdent
) {
// @ts-ignore
delete useItem.options.modules.getLocalIdent;
}
// @ts-ignore
useItem.options.modules = {
// @ts-ignore
...useItem.options.modules,
// @ts-ignore
...cssLoaderOptions?.modules,
};
}
// logger.info(
// `==> modules after ${util.inspect(useItem.options, {
// showHidden: false,
// depth: null,
// })}`
// );
}
} else {
// if there are no options available add default options
useItem.options = {
...cssLoaderOptions,
};
}
return use;
}
// if not found, do not alter the RuleSetUse
return use;
};
/**
*
* @param rules
* @param cssLoaderOptions
*/
export const modifyCssLoaderModuleOption = (
rules: Array<RuleSetRule>,
cssLoaderOptions: CssLoaderOptions
) => {
for (const rule of rules) {
// check if RuleSetRule has use property
if (rule.use) {
rule.use = modifyCssLoader(rule.use, cssLoaderOptions);
} else {
// TODO look deeper (does not work due to filterRules cannot look deeper to find equal rule)
// if there is no use: RuleSetUse, add your own and add PostCssLoader with Plugin
}
}
}; | the_stack |
import React, { useCallback, useRef, useEffect, useReducer } from 'react'
import { Spin } from 'antd'
import { CloseOutlined } from '@ant-design/icons'
import NavBar from './navbar/index'
import './styles/index.less'
import 'antd/dist/antd.css';
import './styles/global.css'
import './styles/toc.less'
import {
getCursorPosition, setSelectionRange, handleTwoSideSymbol,
addTable, addCodeBlock, addLink, addPhoto, addList, addTitle,
addQuote, recordCursorHistoryByElement, recordCursorHistoryByPosition,
} from './utils'
import md from './markdown'
import { PropsType, HistoryLinkType, ModeType, StateType } from './types'
import { INDENTATION } from './const'
let scrolling: 0 | 1 | 2 = 0 // 当前滚动块。0: both none ; 1: edit ; 2: show
let scrollTimer: any; // 改变scrolling值得定时器
let historyTimer: any; // 记录历史输入内容的定时器
let mkRenderTimer: any; // markdown渲染的定时器
let historyLink: HistoryLinkType = {
value: '',
pre: null,
next: null,
selectionStart: 0,
selectionEnd: 0
}
let titleObserver: any = null; // 展示区的标题的监听对象
type ReducerType = (
state: StateType,
{ type, payload }: { type: string, payload?: any }
) => StateType;
const reducer: ReducerType = ( state, { type, payload } ) => {
switch(type) {
case 'toggleMode':
return { ...state, mode: payload };
case 'toggleLoading':
return { ...state, loading: payload };
case 'changeHtmlString':
return { ...state, htmlString: payload };
case 'toggleTOC':
return {
...state,
showTOC: typeof payload === 'undefined'
? !state.showTOC
: payload
};
case 'changeTOC':
return { ...state, toc: payload }
case 'changeActiveTitle':
const toc = state.toc
.replace('class="active"', '') // 删除上一个active标题
.replace(`${payload}"`, `${payload}" class="active"`) // 设置此次的active标题
return { ...state, activeTitle: payload, toc }
}
return state
}
const MarkdownEdit : React.FC<PropsType> = (props) => {
const {
value,
setValue,
mode = ModeType.NORMAL,
showTOC = true,
} = props
const [state, dispatch] = useReducer<ReducerType, StateType>(
reducer,
{
htmlString: '',
mode,
loading: true,
showTOC,
activeTitle: '',
toc: '<p></p><h3>目录</h3>',
},
(initState: StateType) => initState
);
const editRef = useRef<any>(null)
const showRef = useRef<any>(null)
// 区间进行滚动
const handleScroll = useCallback((event) => {
// 若编辑区和展示区没有同时出现,则无序同步滚动
if(state.mode !== ModeType.NORMAL) return;
let { target } = event
let scale = getScale(target)
if(target.nodeName === 'TEXTAREA') {
if(scrolling === 0) scrolling = 1;
else if(scrolling === 2) return; // 当前是「展示区」主动触发的滚动,因此不需要再驱动展示区去滚动
// 驱动「展示区」同步滚动
driveScroll(scale, showRef.current)
} else {
if(scrolling === 0) scrolling = 2;
else if(scrolling === 1) return;
driveScroll(scale, editRef.current)
}
}, [state.mode])
// 驱动元素进行滚动
const driveScroll = useCallback((scale: number, el: HTMLElement) => {
let { scrollHeight, clientHeight } = el
el.scrollTop = (scrollHeight - clientHeight) * scale
if(scrollTimer) clearTimeout(scrollTimer);
scrollTimer = setTimeout(() => {
scrolling = 0
clearTimeout(scrollTimer)
}, 200)
}, [])
// 获取滚动比例
const getScale = useCallback((el: HTMLElement) => {
let { scrollHeight, scrollTop, clientHeight } = el
return scrollTop / (scrollHeight - clientHeight)
}, [])
// 控制键盘的按键
const handleKeyUp = (event: any) => {
let { keyCode, metaKey, ctrlKey, altKey, shiftKey } = event
let el = editRef.current
let [start, end] = getCursorPosition(el)
if(metaKey || ctrlKey) { // ctrl 开头的组合按键
if(altKey) {
if(keyCode === 84) { // ctrl + alt + t 表格
addTable(editRef.current, setValue, value)
event.preventDefault()
} else if(keyCode === 67) { // ctrl + alt + c 代码块
addCodeBlock(editRef.current, setValue, value, '')
event.preventDefault()
} else if(keyCode === 86) { // ctrl + alt + v 行内代码
handleTwoSideSymbol(editRef.current, setValue, value, '`', "行内代码")
event.preventDefault()
} else if(keyCode === 76) { // ctrl + alt + l 图片链接格式
addPhoto(editRef.current, setValue, value)
event.preventDefault()
} else if(keyCode === 85) { // ctrl + alt + u 无序列表
addList(editRef.current, setValue, value, '-', '无序列表')
event.preventDefault()
}
} else {
if(keyCode === 90) { // ctrl + z 撤销
if(!historyLink.pre) return;
else {
let { value, selectionStart, selectionEnd } = historyLink.pre
setValue(value)
historyLink = historyLink.pre
setSelectionRange(el, selectionStart, selectionEnd)
}
event.preventDefault()
} else if(keyCode === 89) { // ctrl + Y 前进
if(!historyLink.next) return;
else {
let { value, selectionStart, selectionEnd } = historyLink.next
setValue(value)
historyLink = historyLink.next
setSelectionRange(el, selectionStart, selectionEnd)
}
event.preventDefault()
} else if(keyCode === 66) { // ctrl + b 加粗
handleTwoSideSymbol(editRef.current, setValue, value, '**', "加粗字体")
event.preventDefault()
} else if(keyCode === 73) { // ctrl + i 斜体
handleTwoSideSymbol(editRef.current, setValue, value, '*', "倾斜字体")
event.preventDefault()
} else if(keyCode === 85) { // ctrl + u 删除线
handleTwoSideSymbol(editRef.current, setValue, value, '~~', "删除文本")
event.preventDefault()
} else if(keyCode === 76) { // ctrl + l 链接
addLink(editRef.current, setValue, value)
event.preventDefault()
} else if(keyCode === 79) { // ctrl + o 无序列表
addList(editRef.current, setValue, value, '1.', '有序列表')
event.preventDefault()
} else if(keyCode === 81) { // ctrl + q 引用 (有点问题)
addQuote(editRef.current, setValue, value)
event.preventDefault()
} else if(keyCode === 49) { // ctrl + 1 一级标题
addTitle(editRef.current, setValue, value, '#', "一级标题")
event.preventDefault()
} else if(keyCode === 50) { // ctrl + 2 二级标题
addTitle(editRef.current, setValue, value, '##', "二级标题")
event.preventDefault()
} else if(keyCode === 51) { // ctrl + 3 三级标题
addTitle(editRef.current, setValue, value, '###', "三级标题")
event.preventDefault()
} else if(keyCode === 52) { // ctrl + 4 四级标题
addTitle(editRef.current, setValue, value, '####', "四级标题")
event.preventDefault()
} else if(keyCode === 53) { // ctrl + 5 五级标题
addTitle(editRef.current, setValue, value, '#####', "五级标题")
event.preventDefault()
} else if(keyCode === 54) { // ctrl + 6 六级标题
addTitle(editRef.current, setValue, value, '######', "六级标题")
event.preventDefault()
}
}
} else if(shiftKey) { // shift 开头的组合按键
if(keyCode === 9) { // shift + tab 取消缩进
let paragraph = value.split('\n'),
stringCount = 0,
selectionStart = start,
selectionEnd = end,
len = paragraph.length,
cancelSpaceCount = 0
for(let i = 0; i < len; i++) {
let item = paragraph[i]
let nextStringCount = stringCount + item.length + 1
// 判断选中的段落的前缀是否有缩进空格并去除空格进行缩进
if(nextStringCount > start && stringCount < end) {
let spaces = item.split(' '.repeat(INDENTATION)) // 判断有多少个缩进字符
// 去前缀空格
if(spaces.length !== 1) {
spaces.shift();
cancelSpaceCount += INDENTATION
}
else {
cancelSpaceCount += spaces[0].length
spaces[0] = spaces[0].trimLeft();
cancelSpaceCount -= spaces[0].length
}
let newParagraph = spaces.join(' '.repeat(INDENTATION))
paragraph[i] = newParagraph
// 获取取消缩进后的光标开始位置和结束位置
if(start > stringCount) selectionStart -= item.length - newParagraph.length;
if(end < nextStringCount) selectionEnd -= cancelSpaceCount
} else if(stringCount > end) break;
stringCount = nextStringCount
}
let newValue = paragraph.join('\n')
setValue(newValue)
setSelectionRange(el, selectionStart, selectionEnd)
event.preventDefault()
}
} else { // 单个按键
if(keyCode === 9) { // Tab缩进
let paragraph = value.split('\n'),
stringCount = 0,
selectionStart = start,
selectionEnd = end,
len = paragraph.length,
addlSpaceCount = 0,
newValue = ''
// 光标未选中文字
if(start === end) {
newValue = value.slice(0, start) + ' '.repeat(INDENTATION) + value.slice(end);
selectionStart += INDENTATION
selectionEnd += INDENTATION
} else { // 光标选中了文字
for(let i = 0; i < len; i++) {
let item = paragraph[i]
let nextStringCount = stringCount + item.length + 1
// 将选中的每段段落前缩进
if(nextStringCount > start && stringCount < end) {
let newParagraph = ' '.repeat(INDENTATION) + item
addlSpaceCount += INDENTATION
paragraph[i] = newParagraph
// 获取取消缩进后的光标开始位置和结束位置
if(start > stringCount) selectionStart += INDENTATION;
if(end < nextStringCount) selectionEnd += addlSpaceCount
} else if(stringCount > end) break;
stringCount = nextStringCount
}
newValue = paragraph.join('\n')
}
setValue(newValue)
setSelectionRange(el, selectionStart, selectionEnd)
event.preventDefault()
}
}
}
// 编辑区的点击事件
const editClick = useCallback((e) => {
recordCursorHistoryByElement(historyLink, e.target)
}, [])
// 初始化
useEffect(() => {
// 设置历史记录的初始状态
historyLink.value = value
// 初始化编辑区内容
setValue(value)
// 初次进入聚焦编辑区
let totalLen = value.length
setSelectionRange(editRef.current, totalLen, totalLen)
recordCursorHistoryByPosition(historyLink, totalLen, totalLen)
// 创建展示区的标题监听对象
if(IntersectionObserver) titleObserver = new IntersectionObserver(entries => {
let rightIndex = entries[0].isIntersecting ? 0 : entries.length - 1;
let active_id = (entries[rightIndex].target.firstChild as HTMLLinkElement).id
dispatch({ type: 'changeActiveTitle', payload: active_id })
}, {
rootMargin: '0% 0% 100% 0%',
root: showRef.current
});
}, [])
// value改变时做的一些操作
useEffect(() => {
// value改变,驱动htmlString的改变
if(mkRenderTimer) clearTimeout(mkRenderTimer);
mkRenderTimer = setTimeout(() => {
// 带上目录一起渲染
let htmlString_withTOC = md.render(`@[toc](目录)\n${value}`)
let rst = new RegExp(/^<p>.*<\/p>/).exec(htmlString_withTOC)
let toc = rst ? rst[0] : ''
let htmlString = htmlString_withTOC.slice(toc.length, -1)
dispatch({ type: 'changeHtmlString', payload: htmlString })
dispatch({ type: 'changeTOC', payload: toc ? toc : '<p><h3>目录</h3></p>' })
clearTimeout(mkRenderTimer)
// 展示区同步滚动
driveScroll(getScale(editRef.current), showRef.current)
}, 200)
// 记录历史记录
let [selectionStart, selectionEnd] = getCursorPosition(editRef.current)
if(historyTimer) clearTimeout(historyTimer);
historyTimer = setTimeout(() => {
historyLink.next = {
value,
pre: historyLink,
next: null,
selectionStart,
selectionEnd
}
historyLink = historyLink.next
clearTimeout(historyTimer)
}, 1000)
}, [value])
useEffect(() => {
// 监听标题元素
showRef.current.querySelectorAll("h1, h2, h3, h4, h5, h6").forEach((node: Element) => titleObserver.observe(node))
}, [state.htmlString])
return (
<div className="__markdown-editor-reactjs-container">
{
state.mode !== ModeType.EXHIBITION &&
<NavBar
value={value}
state={state}
dispatch={dispatch}
editElement={editRef}
setValue={setValue}
/>
}
<Spin
spinning={state.loading}
wrapperClassName="write-spin"
tip="更新主题中..."
>
<main className="__markdown-editor-reactjs-markdown-main">
{
// 编辑区
(state.mode === ModeType.NORMAL || state.mode === ModeType.EDIT) &&
<textarea
id="__markdown-editor-reactjs-edit"
ref={editRef}
onClick={editClick}
onChange={e => setValue(e.target.value)}
onScroll={handleScroll}
onKeyDownCapture={handleKeyUp}
value={value}
/>
}
{
// 展示区
state.mode !== ModeType.EDIT &&
<div
id="write"
ref={showRef}
onScroll={handleScroll}
dangerouslySetInnerHTML={{ __html: state.htmlString }}
/>
}
{
// 目录
state.showTOC &&
<section className="__markdown-editor-reactjs-toc-layout">
<CloseOutlined className="toc-close-icon" onClick={() => dispatch({ type: 'toggleTOC', payload: false })}/>
<div
id="__markdown-editor-reactjs-toc"
dangerouslySetInnerHTML={{ __html: state.toc }}
/>
</section>
}
</main>
</Spin>
</div>
)
}
export default MarkdownEdit | the_stack |
import test from 'tape'
import BN from 'bn.js'
import { ethers } from 'ethers'
import {
NonceTxMiddleware,
CachedNonceTxMiddleware,
SignedEthTxMiddleware,
CryptoUtils,
Client
} from '../../index'
import { LoomProvider } from '../../loom-provider'
import { deployContract } from '../evm-helpers'
import { Address, LocalAddress } from '../../address'
import { createDefaultTxMiddleware } from '../../helpers'
import { EthersSigner, getJsonRPCSignerAsync } from '../../solidity-helpers'
import { createTestHttpClient } from '../helpers'
import { AddressMapper, Coin } from '../../contracts'
// import Web3 from 'web3'
const Web3 = require('web3')
/**
* Requires the SimpleStore solidity contract deployed on a loomchain.
* go-loom/examples/plugins/evmexample/contract/SimpleStore.sol
*
* pragma solidity ^0.4.24;
*
* contract SimpleStore {
* uint256 value;
*
* constructor() public {
* value = 10;
* }
*
* event NewValueSet(uint indexed _value, address sender);
*
* function set(uint _value) public {
* value = _value;
* emit NewValueSet(value, msg.sender);
* }
*
* function get() public view returns (uint) {
* return value;
* }
* }
*
*/
const toCoinE18 = (amount: number): BN => {
return new BN(10).pow(new BN(18)).mul(new BN(amount))
}
async function bootstrapTest(
createClient: () => Client
): Promise<{
client: Client
pubKey: Uint8Array
privKey: Uint8Array
signer: ethers.Signer
loomProvider: LoomProvider
contract: any
ABI: any[]
account: Address
}> {
// Create the client
const privKey = CryptoUtils.B64ToUint8Array(
'D6XCGyCcDZ5TE22h66AlU+Bn6JqL4RnSl4a09RGU9LfM53JFG/T5GAnC0uiuIIiw9Dl0TwEAmdGb+WE0Bochkg=='
)
const pubKey = CryptoUtils.publicKeyFromPrivateKey(privKey)
const client = createClient()
client.on('error', err => console.error(err))
client.txMiddleware = createDefaultTxMiddleware(client, privKey)
const account = new Address(client.chainId, LocalAddress.fromPublicKey(pubKey))
// Create LoomProvider instance
const loomProvider = new LoomProvider(client, privKey)
// Contract data and ABI
const contractData =
'608060405234801561001057600080fd5b50600a60008190555061014e806100286000396000f30060806040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806360fe47b1146100515780636d4ce63c1461007e575b600080fd5b34801561005d57600080fd5b5061007c600480360381019080803590602001909291905050506100a9565b005b34801561008a57600080fd5b50610093610119565b6040518082815260200191505060405180910390f35b806000819055506000547f7e0b7a35f017ec94e71d7012fe8fa8011f1dab6090674f92de08f8092ab30dda33604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a250565b600080549050905600a165627a7a7230582041f33d6a8b78928e192affcb980ca6bef9b6f5b7da5aa4b2d75b1208720caeeb0029'
const ABI = [
{
constant: false,
inputs: [
{
name: '_value',
type: 'uint256'
}
],
name: 'set',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: true,
inputs: [],
name: 'get',
outputs: [
{
name: '',
type: 'uint256'
}
],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
inputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'constructor'
},
{
anonymous: false,
inputs: [
{
indexed: true,
name: '_value',
type: 'uint256'
},
{
indexed: false,
name: 'sender',
type: 'address'
}
],
name: 'NewValueSet',
type: 'event'
}
]
// Deploy the contract using loom provider
const result = await deployContract(loomProvider, contractData)
// Instantiate Contract using web3
const web3 = new Web3(loomProvider)
const contract = new web3.eth.Contract(ABI, result.contractAddress, {
from: LocalAddress.fromPublicKey(pubKey).toString()
})
// And get the signer
const signer = await getJsonRPCSignerAsync('http://localhost:8545')
return { client, pubKey, privKey, signer, loomProvider, contract, ABI, account }
}
test('Test Signed Eth Tx Middleware Type 1', async t => {
try {
const { client, signer, loomProvider, contract } = await bootstrapTest(createTestHttpClient)
// Get address of the account 0 = 0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1
const ethAddress = await signer.getAddress()
const callerChainId = 'eth1'
// Override the default caller chain ID
loomProvider.callerChainId = callerChainId
// Ethereum account needs its own middleware
loomProvider.setMiddlewaresForAddress(ethAddress, [
new NonceTxMiddleware(
new Address(callerChainId, LocalAddress.fromHexString(ethAddress)),
client
),
new SignedEthTxMiddleware(signer)
])
const middlewaresUsed = loomProvider.accountMiddlewares.get(ethAddress.toLowerCase())
t.assert(middlewaresUsed![0] instanceof NonceTxMiddleware, 'Nonce2TxMiddleware used')
t.assert(middlewaresUsed![1] instanceof SignedEthTxMiddleware, 'SignedEthTxMiddleware used')
let tx = await contract.methods.set(1).send({ from: ethAddress })
t.equal(
tx.status,
true,
`SimpleStore.set should return correct status for address (to) ${ethAddress}`
)
t.equal(
tx.events.NewValueSet.returnValues.sender,
ethAddress,
`Sender should be same sender from eth ${ethAddress}`
)
} catch (err) {
console.error(err)
t.fail(err.message)
}
t.end()
})
test('Test Signed Eth Tx Middleware Type 2', async t => {
try {
const { client, signer, pubKey, loomProvider, contract, account } = await bootstrapTest(
createTestHttpClient
)
const addressMapper = await AddressMapper.createAsync(
client,
new Address(client.chainId, LocalAddress.fromPublicKey(pubKey))
)
// Set the mapping
const ethAddress = await signer.getAddress()
const from = new Address(client.chainId, LocalAddress.fromPublicKey(pubKey))
const to = new Address('eth', LocalAddress.fromHexString(ethAddress))
// Add mapping if not added yet
if (!(await addressMapper.hasMappingAsync(from))) {
const ethersSigner = new EthersSigner(signer)
await addressMapper.addIdentityMappingAsync(from, to, ethersSigner)
}
try {
const addressMapped = await addressMapper.getMappingAsync(from)
t.assert(addressMapped.from.equals(from), 'Should be mapped the from address')
t.assert(addressMapped.to.equals(to), 'Should be mapped the to address')
} catch (err) {
t.error(err)
}
const callerChainId = 'eth'
// Override the default caller chain ID
loomProvider.callerChainId = callerChainId
// Ethereum account needs its own middleware
loomProvider.setMiddlewaresForAddress(to.local.toString(), [
new CachedNonceTxMiddleware(account, client),
new SignedEthTxMiddleware(signer)
])
const middlewaresUsed = loomProvider.accountMiddlewares.get(ethAddress.toLowerCase())
t.assert(
middlewaresUsed![0] instanceof CachedNonceTxMiddleware,
'CachedNonceTxMiddleware used'
)
t.assert(middlewaresUsed![1] instanceof SignedEthTxMiddleware, 'SignedEthTxMiddleware used')
let tx = await contract.methods.set(1).send({ from: to.local.toString() })
t.equal(
tx.status,
true,
`SimpleStore.set should return correct status for address (to) ${to.local.toString()}`
)
t.equal(
tx.events.NewValueSet.returnValues.sender.toLowerCase(),
from.local.toString(),
`Should be the same sender from loomchain ${from.local.toString()}`
)
} catch (err) {
console.error(err)
t.fail(err.message)
}
t.end()
})
test('Test Signed Eth Tx Middleware Type 2 with Coin Contract', async t => {
try {
// Create the client
const privKey = CryptoUtils.B64ToUint8Array(
'D6XCGyCcDZ5TE22h66AlU+Bn6JqL4RnSl4a09RGU9LfM53JFG/T5GAnC0uiuIIiw9Dl0TwEAmdGb+WE0Bochkg=='
)
const pubKey = CryptoUtils.publicKeyFromPrivateKey(privKey)
const client = createTestHttpClient()
client.on('error', err => console.error(err))
// <---- From this point using loom common middleware until change
client.txMiddleware = createDefaultTxMiddleware(client, privKey)
// Create AddressMapper wrapper
const addressMapper = await AddressMapper.createAsync(
client,
new Address(client.chainId, LocalAddress.fromPublicKey(pubKey))
)
// And get the signer
const signer = await getJsonRPCSignerAsync('http://localhost:8545')
// Set the mapping
const ethAddress = await signer.getAddress()
const from = new Address(client.chainId, LocalAddress.fromPublicKey(pubKey))
const to = new Address('eth', LocalAddress.fromHexString(ethAddress))
// Add mapping if not added yet
if (!(await addressMapper.hasMappingAsync(from))) {
const ethersSigner = new EthersSigner(signer)
await addressMapper.addIdentityMappingAsync(from, to, ethersSigner)
}
// Check if map exists
try {
const addressMapped = await addressMapper.getMappingAsync(from)
t.assert(addressMapped.from.equals(from), 'Should be mapped the from address')
t.assert(addressMapped.to.equals(to), 'Should be mapped the to address')
} catch (err) {
t.error(err)
}
// <---- From this point it should call using eth sign
// Create Coin wrapper
const coin = await Coin.createAsync(
client,
new Address('eth', LocalAddress.fromHexString(ethAddress))
)
const spender = new Address(client.chainId, LocalAddress.fromPublicKey(pubKey))
client.txMiddleware = [
new CachedNonceTxMiddleware(pubKey, client),
new SignedEthTxMiddleware(signer)
]
// Check approval on coin native contract
await coin.approveAsync(spender, toCoinE18(1))
// Using owner and spender as the same just for test
const allowance = await coin.getAllowanceAsync(spender, spender)
t.equal(allowance.toString(), '1000000000000000000', 'Allowance should ok')
} catch (err) {
console.error(err)
t.fail(err.message)
}
t.end()
}) | the_stack |
import { concat } from './iterators/concat';
import { distinct } from './iterators/distinct';
import { exclude } from './iterators/exclude';
import { fill } from './iterators/fill';
import { filter } from './iterators/filter';
import { flat } from './iterators/flat';
import { groupJoin } from './iterators/groupJoin';
import { intersect } from './iterators/intersect';
import { join } from './iterators/join';
import { leftJoin } from './iterators/leftJoin';
import { map } from './iterators/map';
import { reverse } from './iterators/reverse';
import { shuffle } from './iterators/shuffle';
import { skip } from './iterators/skip';
import { skipWhile } from './iterators/skipWhile';
import { slice } from './iterators/slice';
import { splice } from './iterators/splice';
import { take } from './iterators/take';
import { takeWhile } from './iterators/takeWhile';
import { average } from './reducers/average';
import { first } from './reducers/first';
import { indexOf } from './reducers/indexOf';
import { last } from './reducers/last';
import { lastIndexOf } from './reducers/lastIndexOf';
import { length } from './reducers/length';
import { max } from './reducers/max';
import { min } from './reducers/min';
import { nth } from './reducers/nth';
import { reduce } from './reducers/reduce';
import { sum } from './reducers/sum';
import { toArray } from './reducers/toArray';
import { toGroups } from './reducers/toGroups';
import { toMap } from './reducers/toMap';
import { toSet } from './reducers/toSet';
import { IterableQuery } from './types/IterableQuery';
import { isIterable } from './utils/isIterable';
import { iterable } from './utils/iterable';
import { iterator } from './utils/iterator';
/**
* Creates a queryable iterable.
* @param source can be an array or any other iterable.
*/
export default function itiriri<T>(source: Iterable<T>): IterableQuery<T> {
return new Itiriri(source);
}
export { IterableQuery };
class Itiriri<T> implements IterableQuery<T>{
constructor(private readonly source: Iterable<T>) {
}
[Symbol.iterator](): Iterator<T> {
return iterator(this.source);
}
// #region common methods
entries(): IterableQuery<[number, T]> {
return new Itiriri(
map(this.source, (elem, idx) => <[number, T]>[idx, elem]),
);
}
keys(): IterableQuery<number> {
return new Itiriri(map(this.source, (_, idx) => idx));
}
values(): IterableQuery<T> {
return new Itiriri(this.source);
}
forEach(action: (element: T, index: number) => void): void {
for (const [index, value] of this.entries()) {
action(value, index);
}
}
concat(other: T | Iterable<T>): IterableQuery<T> {
return isIterable(other) ?
new Itiriri(concat(this.source, other)) :
new Itiriri(concat(this.source, [other]));
}
prepend(other: T | Iterable<T>): IterableQuery<T> {
return isIterable(other) ?
new Itiriri(concat(other, this.source)) :
new Itiriri(concat([other], this.source));
}
fill(value: T, start?: number, end?: number): IterableQuery<T> {
return new Itiriri(fill(this.source, value, start, end));
}
// #endregion
// #region IterableValue implementation
nth(index: number): T | undefined {
return nth(this.source, index);
}
indexOf(element: T, fromIndex: number = 0): number {
return indexOf(this.source, (elem, idx) => idx >= fromIndex && elem === element);
}
findIndex(predicate: (element: T, index: number) => boolean): number {
return indexOf(this.source, predicate);
}
lastIndexOf(element: T, fromIndex: number = 0): number {
return lastIndexOf(this.source, (elem, idx) => idx >= fromIndex && elem === element);
}
findLastIndex(predicate: (element: T, index: number) => boolean): number {
return lastIndexOf(this.source, predicate);
}
length(predicate: (element: T, index: number) => boolean = alwaysTrue()): number {
return length(filter(this.source, predicate));
}
first(): T | undefined {
return first(this.source);
}
find(predicate: (element: T, index: number) => boolean): T | undefined {
return first(filter(this.source, predicate));
}
last(): T | undefined {
return last(this.source);
}
findLast(predicate: (element: T, index: number) => boolean): T | undefined {
return last(filter(this.source, predicate));
}
average(selector: (element: T, index: number) => number = element<number>()): number | undefined {
return average(map(this.source, selector));
}
min(compareFn: (element1: T, element2: T) => number = comparer<T>()): T | undefined {
return min(this.source, compareFn);
}
max(compareFn: (element1: T, element2: T) => number = comparer<T>()): T | undefined {
return max(this.source, compareFn);
}
sum(selector: (element: T, index: number) => number = element<number>()): number | undefined {
return sum(map(this.source, selector));
}
reduce<TResult>(
callback: (accumulator: TResult | T, current: T, index: number) => any,
initialValue?: any,
): any {
return reduce(this.source, callback, initialValue);
}
reduceRight<TResult>(
callback: (accumulator: TResult | T, current: T, index: number) => any,
initialValue?: TResult,
): any {
return reduce(reverse(this.source), callback, initialValue);
}
// #endregion
// #region IterablePredicate implementation
every(predicate: (element: T, index: number) => boolean): boolean {
return indexOf(this.source, (e, i) => !predicate(e, i)) === -1;
}
some(predicate: (element: T, index: number) => boolean): boolean {
return indexOf(this.source, predicate) !== -1;
}
includes(element: T, fromIndex: number = 0): boolean {
return this.some((elem, idx) => idx >= fromIndex && elem === element);
}
// #endregion
// #region IterablePermutation implementation
sort(
compareFn: (element1: T, element2: T) => number = comparer<T>(),
): IterableQuery<T> {
const source = this.source;
const sortable = iterable(function* () {
yield* toArray(source).sort(compareFn);
});
return new Itiriri(sortable);
}
shuffle(): IterableQuery<T> {
return new Itiriri(shuffle(this.source));
}
reverse(): IterableQuery<T> {
return new Itiriri(reverse(this.source));
}
// #endregion
// #region IterableFilter implementation
filter(predicate: (element: T, index: number) => boolean): IterableQuery<T> {
return new Itiriri(filter(this.source, predicate));
}
take(count: number): IterableQuery<T> {
return new Itiriri(take(this.source, count));
}
takeWhile(predicate: (element: T, index: number) => boolean): IterableQuery<T> {
return new Itiriri(takeWhile(this.source, predicate));
}
skip(count: number): IterableQuery<T> {
return new Itiriri(skip(this.source, count));
}
skipWhile(predicate: (element: T, index: number) => boolean): IterableQuery<T> {
return new Itiriri(skipWhile(this.source, predicate));
}
slice(start?: number, end?: number): IterableQuery<T> {
return new Itiriri(slice(this.source, start, end));
}
splice(start: number, deleteCount: number, ...items: T[]): IterableQuery<T> {
return new Itiriri(splice(this.source, start, deleteCount, items));
}
// #endregion
// #region IterableTransformation implementation
map<S>(selector: (element: T, index: number) => S): IterableQuery<S> {
return new Itiriri(map(this.source, selector));
}
flat<S>(selector: (element: T, index: number) => Iterable<S>): IterableQuery<S> {
return new Itiriri(flat<S>(map(this.source, selector)));
}
groupBy<K, S>(
keySelector: (element: T, index: number) => K,
valueSelector: (element: T, index: number) => S = x => <any>x,
): IterableQuery<[K, IterableQuery<S>]> {
const source = this.source;
const groups = iterable(function* () {
yield* toGroups(source, keySelector, valueSelector);
});
const result = map(groups, elem => <[K, IterableQuery<S>]>[elem[0], new Itiriri(elem[1])]);
return new Itiriri(result);
}
// #endregion
// #region IterableSet implementation
distinct<S>(selector: (element: T) => S = element<S>()): IterableQuery<T> {
return new Itiriri(distinct(this.source, selector));
}
exclude<S>(other: Iterable<T>, selector: (element: T) => S = element<S>()): IterableQuery<T> {
return new Itiriri(exclude(this.source, other, selector));
}
intersect<S>(other: Iterable<T>, selector: (element: T) => S = element<S>()): IterableQuery<T> {
return new Itiriri(intersect(this.source, other, selector));
}
union<S>(other: Iterable<T>, selector: (element: T) => S = element<S>()): IterableQuery<T> {
return new Itiriri(distinct(concat(this.source, other), selector));
}
// #endregion
// #region IterableJoin implementation
join<TKey, TRight, TResult>(
other: Iterable<TRight>,
leftKeySelector: (element: T, index: number) => TKey,
rightKeySelector: (element: TRight, index: number) => TKey,
joinSelector: (left: T, right: TRight) => TResult,
): IterableQuery<TResult> {
const iterator = join(
this.source,
other,
leftKeySelector,
rightKeySelector,
joinSelector);
return new Itiriri(iterator);
}
leftJoin<TKey, TRight, TResult>(
other: Iterable<TRight>,
leftKeySelector: (element: T, index: number) => TKey,
rightKeySelector: (element: TRight, index: number) => TKey,
joinSelector: (left: T, right?: TRight) => TResult,
): IterableQuery<TResult> {
const iterator = leftJoin(
this.source,
other,
leftKeySelector,
rightKeySelector,
joinSelector);
return new Itiriri(iterator);
}
rightJoin<TKey, TRight, TResult>(
other: Iterable<TRight>,
rightKeySelector: (element: TRight, index: number) => TKey,
leftKeySelector: (element: T, index: number) => TKey,
joinSelector: (right: TRight, left?: T) => TResult,
): IterableQuery<TResult> {
const iterator = leftJoin(
other,
this.source,
rightKeySelector,
leftKeySelector,
joinSelector,
);
return new Itiriri(iterator);
}
groupJoin<TKey, TRight, TResult>(
other: Iterable<TRight>,
leftKeySelector: (element: T, index: number) => TKey,
rightKeySelector: (element: TRight, index: number) => TKey,
joinSelector: (left: T, right: TRight[]) => TResult,
): IterableQuery<TResult> {
const iterator = groupJoin(
this.source,
other,
leftKeySelector,
rightKeySelector,
joinSelector);
return new Itiriri(iterator);
}
// #endregion
// #region IterableCast implementation
toArray<S = T>(selector?: (element: T, index: number) => S): (T | S)[] {
return selector ? toArray(map(this.source, selector)) :
toArray(this.source);
}
toMap<K, E = T>(
keySelector: (element: T, index: number) => K = element<K>(),
valueSelector: (element: T, index: number) => E = element<E>(),
): Map<K, E | T> {
return toMap(this.source, keySelector, valueSelector);
}
toGroups<K, E = T>(
keySelector: (element: T, index: number) => K = element<K>(),
valueSelector: (element: T, index: number) => E = element<E>(),
): Map<K, (E | T)[]> {
return toGroups(this.source, keySelector, valueSelector);
}
toSet<S>(selector: (element: T, index: number) => S = element<S>()): Set<S> {
return toSet(map(this.source, selector));
}
toString(): string {
return toArray(this.source).toString();
}
// #endregion
}
function element<T>() {
return (e: any) => <T>e;
}
function alwaysTrue() {
return () => true;
}
function comparer<T>() {
return (a: T, b: T) => a === b ? 0 : (a > b ? 1 : -1);
} | the_stack |
import {
codebuildProjectNames,
getCodebuildRoleName,
getSnsAlertTopicName,
getSourcesBucketName,
installerBuildspec,
installerFile,
updaterBuildspec,
updaterFile,
ENVKEY_RELEASES_BUCKET,
getS3CredsSecretName,
} from "./stack-constants";
import { SharedIniFileCredentials, SNS } from "aws-sdk";
import CodeBuild from "aws-sdk/clients/codebuild";
import S3 from "aws-sdk/clients/s3";
import IAM from "aws-sdk/clients/iam";
import { createBucketIfNeeded, putDeployTag } from "./aws-helpers";
import { getReleaseAsset, getLatestReleaseVersion } from "./artifact-helpers";
import { Infra } from "@core/types";
import SecretsManager from "aws-sdk/clients/secretsmanager";
export const bootstrapSelfHostedDeployment = async (
params: Infra.DeploySelfHostedParams & {
deploymentTag: string;
subdomain: string;
updateStatus: (status: string) => void;
}
) => {
if (params.failoverRegion && params.failoverRegion == params.primaryRegion) {
throw new Error("Failover region can't be the same as primary region");
}
const credentials = new SharedIniFileCredentials({
profile: params.profile,
});
const codebuild = new CodeBuild({
region: params.primaryRegion,
credentials,
});
const sns = new SNS({ region: params.primaryRegion, credentials });
const s3 = new S3({
region: params.primaryRegion,
credentials,
});
const secrets = new SecretsManager({
region: params.primaryRegion,
credentials,
});
const iam = new IAM({
credentials,
});
const sourcesBucketName = getSourcesBucketName(params.deploymentTag);
const snsAlertTopicName = getSnsAlertTopicName(params.deploymentTag);
const overrideBucket =
"overrideReleaseBucket" in params && params.overrideReleaseBucket
? params.overrideReleaseBucket
: undefined;
const bucket: string = overrideBucket || ENVKEY_RELEASES_BUCKET;
const creds = "creds" in params ? params.creds : undefined;
params.updateStatus("Determining latest API and Infrastructure versions...");
const apiVersionNumber =
params.apiVersionNumber ??
(await getLatestReleaseVersion({
project: "apienterprise",
creds,
bucket,
}));
const infraVersionNumber =
params.infraVersionNumber ??
(await getLatestReleaseVersion({
project: "infra",
creds,
bucket,
}));
params.updateStatus(
"EnvKey API version: " +
apiVersionNumber +
"\n" +
"EnvKey Infrastructure version: " +
infraVersionNumber
);
await putDeployTag({
profile: params.profile,
primaryRegion: params.primaryRegion,
deploymentTag: params.deploymentTag,
});
let s3CredsSecretArn: string | undefined;
if (creds) {
({ ARN: s3CredsSecretArn } = await secrets
.createSecret({
SecretString: JSON.stringify(creds),
Name: getS3CredsSecretName(params.deploymentTag),
})
.promise());
}
const codebuildPersistCreds = s3CredsSecretArn
? {
// pre-release aws creds are the only one that'd be used for self-hosted, and this
// would indicate a developer is testing a self-hosted version
s3CredsSecretArn,
}
: {};
const extraCodebuildEnvVars = overrideBucket
? [
{
name: "ENVKEY_RELEASES_BUCKET",
value: overrideBucket,
},
]
: [];
const topic = await sns
.createTopic({
Name: snsAlertTopicName,
})
.promise();
await sns
.subscribe({
Endpoint: params.infraAlertsEmail,
Protocol: "email",
TopicArn: topic.TopicArn!,
})
.promise();
params.updateStatus("Setting up an EnvKey build project role...");
const codebuildRole = await createCodebuildRoleIfNeeded({
iam,
deploymentTag: params.deploymentTag,
});
params.updateStatus("Creating source S3 bucket...");
await createBucketIfNeeded(s3)(sourcesBucketName);
params.updateStatus("Copying installer into your source bucket...");
const installerZip = await getReleaseAsset({
releaseTag: `infra-v${infraVersionNumber}`,
assetName: installerFile,
creds,
bucket,
});
await s3
.putObject({
Bucket: sourcesBucketName,
Key: installerFile,
Body: installerZip,
})
.promise();
params.updateStatus("Creating EnvKey build projects...");
const updaterZip = await getReleaseAsset({
releaseTag: `infra-v${infraVersionNumber}`,
assetName: updaterFile,
creds,
bucket,
});
await s3
.putObject({
Bucket: sourcesBucketName,
Key: updaterFile,
Body: updaterZip,
})
.promise();
await Promise.all([
// installer
await createInstallerProject({
codebuild,
domain: params.domain,
primaryRegion: params.primaryRegion,
failoverRegion: params.failoverRegion,
verifiedSenderEmail: params.verifiedSenderEmail,
deploymentTag: params.deploymentTag,
subdomain: params.subdomain,
snsTopicArn: topic.TopicArn!,
apiVersionNumber,
infraVersionNumber,
failoverVersionNumber: params.failoverVersionNumber,
isCustomDomain: params.customDomain ? "1" : "",
notifySmsWhenDone: params.notifySmsWhenDone,
registerAction: params.registerAction,
serviceRole: codebuildRole.Arn,
extraCodebuildEnvVars,
internalMode: params.internalMode,
authorizedAccounts: params.authorizedAccounts,
deployWaf: params.deployWaf,
...codebuildPersistCreds,
}),
// updater
await createUpdaterProject({
codebuild,
deploymentTag: params.deploymentTag,
serviceRole: codebuildRole.Arn,
snsTopicArn: topic.TopicArn!,
extraCodebuildEnvVars,
...codebuildPersistCreds,
}),
]);
params.updateStatus("Kicking off EnvKey install...");
await codebuild
.startBuild({
projectName: codebuildProjectNames.initialInstall(params.deploymentTag),
})
.promise();
};
export const createCodebuildRoleIfNeeded = async (params: {
iam: IAM;
deploymentTag: string;
}): Promise<IAM.Role> => {
const { iam, deploymentTag } = params;
const codebuildRoleName = getCodebuildRoleName(deploymentTag);
try {
const { Role } = await iam
.getRole({ RoleName: codebuildRoleName })
.promise();
if (Role) {
return Role;
}
} catch (ignored) {}
const codebuildRole = await iam
.createRole({
AssumeRolePolicyDocument: JSON.stringify({
Version: "2012-10-17",
Statement: [
{
Effect: "Allow",
Principal: {
Service: ["codebuild.amazonaws.com"],
},
Action: ["sts:AssumeRole"],
},
],
}),
Path: "/",
RoleName: codebuildRoleName,
})
.promise();
// Important: policy takes a few seconds to attach, despite the promise returning!
await iam
.attachRolePolicy({
RoleName: codebuildRoleName,
PolicyArn: "arn:aws:iam::aws:policy/AdministratorAccess",
})
.promise();
return codebuildRole.Role;
};
export const createInstallerProject = async (params: {
codebuild: CodeBuild;
deploymentTag: string;
primaryRegion: string;
failoverRegion?: string;
deployWaf?: boolean;
domain: string;
subdomain: string;
snsTopicArn: string;
verifiedSenderEmail: string;
isCustomDomain: "1" | "";
apiVersionNumber: string;
infraVersionNumber: string;
failoverVersionNumber?: string;
serviceRole: string;
// optionals
extraCodebuildEnvVars?: { name: string; value: string }[];
notifySmsWhenDone?: string;
registerAction?: Record<string, any>;
s3CredsSecretArn?: string;
internalMode?: boolean;
authorizedAccounts?: string[];
}): Promise<void> => {
const { codebuild, deploymentTag, serviceRole } = params;
const sourcesBucketName = getSourcesBucketName(deploymentTag);
const environmentVariables: CodeBuild.EnvironmentVariables = [
{ name: "PRIMARY_REGION", value: params.primaryRegion },
{ name: "DOMAIN", value: params.domain },
{
name: "SENDER_EMAIL",
value: params.verifiedSenderEmail,
},
{ name: "DEPLOYMENT_TAG", value: deploymentTag },
{ name: "SUBDOMAIN", value: params.subdomain },
{ name: "SNS_TOPIC_ARN", value: params.snsTopicArn },
{ name: "API_VERSION_NUMBER", value: params.apiVersionNumber },
{ name: "INFRA_VERSION_NUMBER", value: params.infraVersionNumber },
{
name: "FAILOVER_VERSION_NUMBER",
value: params.failoverVersionNumber || "",
},
{
name: "USE_CUSTOM_DOMAIN",
value: params.isCustomDomain || "",
},
{
name: "FAILOVER_REGION",
value: params.failoverRegion ?? "",
},
{
name: "INTERNAL_MODE",
value: params.internalMode ? "1" : "",
},
{
name: "DEPLOY_WAF",
value: params.deployWaf ? "1" : "",
},
{
name: "AUTHORIZED_ACCOUNTS_JSON",
value: params.internalMode
? JSON.stringify(params.authorizedAccounts)
: "",
},
// optionals
{
name: "NOTIFY_SMS_WHEN_DONE",
value: params.notifySmsWhenDone ?? "",
},
{
name: "REGISTER_ACTION",
value: params.registerAction ? JSON.stringify(params.registerAction) : "",
},
];
if (params.extraCodebuildEnvVars?.length) {
environmentVariables.push(...params.extraCodebuildEnvVars);
}
if ("s3CredsSecretArn" in params && params.s3CredsSecretArn) {
environmentVariables.push({
name: "ENVKEY_RELEASES_S3_CREDS_JSON",
// the docs are confusing for this; it's just the secret arn
value: params.s3CredsSecretArn,
type: "SECRETS_MANAGER",
});
}
await codebuild
.createProject({
name: codebuildProjectNames.initialInstall(deploymentTag),
artifacts: { type: "NO_ARTIFACTS" },
environment: {
privilegedMode: true, // for docker
computeType: "BUILD_GENERAL1_SMALL",
image: "aws/codebuild/standard:4.0",
imagePullCredentialsType: "CODEBUILD",
type: "LINUX_CONTAINER",
environmentVariables,
},
serviceRole,
source: {
type: "S3",
location: `${sourcesBucketName}/${installerFile}`,
buildspec: installerBuildspec,
},
timeoutInMinutes: 90,
})
.promise();
};
export const createUpdaterProject = async (params: {
codebuild: CodeBuild;
deploymentTag: string;
snsTopicArn: string;
serviceRole: string;
extraCodebuildEnvVars?: { name: string; value: string }[];
s3CredsSecretArn?: string;
}): Promise<void> => {
const { codebuild, deploymentTag, snsTopicArn, serviceRole } = params;
const sourcesBucketName = getSourcesBucketName(deploymentTag);
const environmentVariables: CodeBuild.EnvironmentVariables = [
{ name: "DEPLOYMENT_TAG", value: deploymentTag },
{
name: "SNS_TOPIC_ARN",
value: snsTopicArn,
},
// the next three be updated later when an actual api update is needed
{ name: "API_VERSION_NUMBER", value: "" },
{ name: "INFRA_VERSION_NUMBER_TO", value: "" },
// Allows testing deployments or overriding deployments by deploying using a specific version
// of the Infra which is different than its published latest infra-version.txt on main.
{ name: "RUN_FROM_INFRA_VERSION_NUMBER_OVERRIDE", value: "" },
];
if (params.extraCodebuildEnvVars?.length) {
environmentVariables.push(...params.extraCodebuildEnvVars);
}
if ("s3CredsSecretArn" in params && params.s3CredsSecretArn) {
environmentVariables.push({
name: "ENVKEY_RELEASES_S3_CREDS_JSON",
// the docs are confusing for this; it's just the secret arn
value: params.s3CredsSecretArn,
type: "SECRETS_MANAGER",
});
}
await codebuild
.createProject({
name: codebuildProjectNames.updater(deploymentTag),
artifacts: { type: "NO_ARTIFACTS" },
environment: {
privilegedMode: true, // for docker
computeType: "BUILD_GENERAL1_SMALL",
image: "aws/codebuild/standard:4.0",
imagePullCredentialsType: "CODEBUILD",
type: "LINUX_CONTAINER",
environmentVariables,
},
serviceRole,
source: {
type: "S3",
location: `${sourcesBucketName}/${updaterFile}`,
buildspec: updaterBuildspec,
},
timeoutInMinutes: 60,
})
.promise();
}; | the_stack |
const DBFactory = (): IDBFactory => {
const host: any = window
return host.indexedDB
|| host.mozIndexedDB
|| host.webkitIndexedDB
|| host.msIndexedDB
|| host.shimIndexedDB
}
// ---------------------------------------------------------------------------
//
// Semaphore
//
// Asynchronous semaphore used to control concurrent read / write access
// on a Device. This type will only allow for 1 asynchronous operation
// to be run on resource at a given time. Overlapped operations are
// queued and run in sequence.
//
// ---------------------------------------------------------------------------
type SemaphoreFunction<T=any> = () => Promise<T> | T
type Awaiter<T = any> = {
func: SemaphoreFunction<T>,
resolve: (value: T) => void,
reject: (error: Error) => void,
}
class Semaphore {
private awaiters: Array<Awaiter>
private running: boolean
constructor() {
this.awaiters = []
this.running = false
}
/** Schedules this operation to run. */
public run<T=any>(func: SemaphoreFunction<T>): Promise<T> {
return new Promise<T>((resolve, reject) => {
this.awaiters.push({ func, resolve, reject })
this.dispatch()
})
}
/** (async-recursive) Dispatchs operations to the configured concurrency limit. */
private async dispatch(): Promise<any> {
if (this.running || this.awaiters.length === 0) {
return
}
const awaiter = this.awaiters.shift() as Awaiter
this.running = true
try {
awaiter.resolve(await awaiter.func())
setTimeout(() => {
this.running = false
this.dispatch()
}, 0)
} catch (error) {
awaiter.reject(error)
setTimeout(() => {
this.running = false
this.dispatch()
}, 0)
}
}
}
// -------------------------------------------------------------------------
//
// ReaderAsyncIterator
//
// A specialized async iterator implementation specific to the Reader.
// This iterator will iterator so long as the 'next' value given from
// the Reader is not `null`.
//
// -------------------------------------------------------------------------
export class ReaderAsyncIterator<T = any> implements AsyncIterator<Record> {
constructor(private readonly reader: Reader) { }
public async next(): Promise<IteratorResult<Record>> {
const next = await this.reader.read()
if (next === null) {
const done = true
const value: any = null
return { done, value }
}
const done = false
const value = next
return { done, value }
}
}
// -------------------------------------------------------------------------
//
// Reader<T>
//
// A asynchronous reader interface for IndexedDB results. Allows IDB records
// to asynchronously be pushed into the Reader, and provides the mechanary
// to support down stream async iteration.
//
// -------------------------------------------------------------------------
interface Deferred {
resolve(record: Record): void
reject (error: Error): void
}
interface Value {
error?: Error | DOMException
record?: Record
}
export class Reader {
[Symbol.asyncIterator](): ReaderAsyncIterator {
return new ReaderAsyncIterator(this)
}
private deferreds: Deferred[] = []
private values: Value[] = []
private ended: boolean = false
private resolve() {
if(this.values.length > 0 && this.deferreds.length > 0) {
const deferred = this.deferreds.shift()!
const value = this.values.shift()!
if(value !== null && value.record === null) {
this.ended = true
}
return (value.error)
? deferred.reject (value.error!)
: deferred.resolve(value.record!)
}
}
public write(record: any) {
this.values.push({ record })
this.resolve()
}
public error(error: Error) {
this.values.push({ error })
this.resolve()
}
public read(): Promise<Record | null> {
if(this.ended) { return Promise.resolve(null) }
const promise = new Promise<any>((resolve, reject) => {
this.deferreds.push({ resolve, reject })
})
this.resolve()
return promise
}
}
export type DatabaseKey = string
export type StoreKey = string
export type RecordKey = string
export interface Record {
key: RecordKey
[key: string]: any
}
export interface DatabaseOptions {
version?: number
additions: StoreKey[]
removals: StoreKey[]
}
export interface Transact {
inserts: Map<StoreKey, Record[]>
updates: Map<StoreKey, Record[]>
deletes: Map<StoreKey, Record[]>
}
/**
* An IndexedDB database abstraction that provides a promise based read and
* write interface over a IndexedDB database. Provides functionality to open and
* close IDB stores, lookup store names, get and scan over object stores and run
* transactional updates.
*/
export class IDBDriver {
private semaphore: Semaphore
constructor(private database: IDBDatabase) {
this.semaphore = new Semaphore()
}
// #region Version Increments
/** (mutable-database) Adds these stores to this database. Will increment the database on version change. */
public add(storeKeys: StoreKey[]): Promise<void> {
return this.semaphore.run(async () => {
for(const storeKey of storeKeys) {
const name = this.database.name
const version = this.database.version
if(!this.stores().includes(storeKey)) {
this.database.close()
this.database = await IDBDriver.open(name, {
version: version + 1,
additions: [storeKey],
removals: []
})
}
}
})
}
/** (mutable-database) Removes these stores to this database. Will increment the database on version change. */
public remove (storeKeys: StoreKey[]): Promise<void> {
return this.semaphore.run(async () => {
for(const storeKey of storeKeys) {
const name = this.database.name
const version = this.database.version
if(this.stores().includes(storeKey)) {
this.database.close()
this.database = await IDBDriver.open(name, {
version: version + 1,
additions: [],
removals: [storeKey]
})
}
}
})
}
// #region Get, Count and Read
/** Returns the name of this database. */
public name(): string {
return this.database.name
}
/** Returns the version of this database. */
public version(): number {
return this.database.version
}
/** Returns store names for this database. */
public stores(): string[] {
const stores = []
for(let i = 0; i < this.database.objectStoreNames.length; i++) {
stores.push(this.database.objectStoreNames[i])
}
return stores
}
/** Gets a store record with with the given recordKey. */
public get(storeKey: StoreKey, recordKey: RecordKey): Promise<Record | undefined> {
return this.semaphore.run(() => new Promise<Record>((resolve, reject) => {
const transaction = this.database.transaction([storeKey], 'readonly')
const store = transaction.objectStore(storeKey)
const request = store.get(recordKey)
request.addEventListener("success", () => resolve(request.result))
request.addEventListener("error", () => reject(request.error))
}))
}
/** Counts records in the given store. */
public count(storeKey: StoreKey): Promise<number> {
return this.semaphore.run(() => new Promise<number>((resolve, reject) => {
const transaction = this.database.transaction([storeKey], 'readonly')
const store = transaction.objectStore(storeKey)
const request = store.count()
request.addEventListener("success", () => resolve(request.result))
request.addEventListener("error", () => reject (request.error))
}))
}
/** Reads store records. The will read until 'null' as last record. */
public read(storeKey: StoreKey): Reader {
const reader = new Reader()
const transaction = this.database.transaction([storeKey], 'readonly')
transaction.addEventListener("error", () => reader.error(transaction.error))
transaction.addEventListener("complete", () => reader.write(null))
const store = transaction.objectStore(storeKey)
const request = store.openCursor()
request.addEventListener("error", () => reader.error(request.error!))
request.addEventListener("success", (event: any) => {
const cursor = event.target.result as IDBCursorWithValue
if (cursor) {
reader.write(cursor.value)
cursor.continue()
}
})
return reader
}
// #region Transactions
/** Applies an store update against the given transaction. */
private transactUpdateRecordCursors(transaction: IDBTransaction, storeKey: StoreKey, records: Record[]) {
return new Promise<void>((resolve, reject) => {
const store = transaction.objectStore(storeKey)
const request = store.openCursor()
request.addEventListener("error", () => reject(transaction.error))
request.addEventListener("success", (event: any) => {
const cursor = event.target.result as IDBCursorWithValue
if (cursor === null) {
resolve()
return
}
for(const record of records) {
if(record.key === cursor.key) {
cursor.update(record)
cursor.continue()
return
}
}
cursor.continue()
})
})
}
/** Updates records with the given transaction. */
private transactUpdateRecords(transaction: IDBTransaction, updates: Map<StoreKey, Record[]>) {
return Promise.all([...updates.keys()].map(storeKey => {
const records = updates.get(storeKey)!
return this.transactUpdateRecordCursors(
transaction,
storeKey,
records
)
}))
}
/** Inserts the given records with the given transaction. */
private transactInsertRecords(transaction: IDBTransaction, inserts: Map<StoreKey, Record[]>) {
for(const storeKey of inserts.keys()) {
const store = transaction.objectStore(storeKey)
const records = inserts.get(storeKey)!
records.forEach(record => store.add(record))
}
}
/** Deletes the given records with the given transaction. */
private transactDeleteRecords(transaction: IDBTransaction, deletes: Map<StoreKey, Record[]>) {
for(const storeKey of deletes.keys()) {
const store = transaction.objectStore(storeKey)
const records = deletes.get(storeKey)!
records.forEach(record => store.delete(record.key))
}
}
/** Executes inserts | updates and deletes as a single operation. */
public transact(transact: Transact): Promise<void> {
return this.semaphore.run(() => new Promise<void>(async (resolve, reject) => {
// select storeKeys distinct
const storeKeys = [
...transact.inserts.keys(),
...transact.deletes.keys(),
...transact.updates.keys()
].filter((value, index, result) =>
result.indexOf(value) === index)
if(storeKeys.length === 0) {
resolve()
return
}
// execute transaction across storeKeys
const transaction = this.database.transaction(storeKeys, 'readwrite')
transaction.addEventListener("error", (error: any) => reject(error.target.error))
transaction.addEventListener("complete", () => resolve())
if([...transact.inserts.keys()].length > 0) {
this.transactInsertRecords(transaction, transact.inserts)
}
if([...transact.updates.keys()].length > 0) {
await this.transactUpdateRecords(transaction, transact.updates)
}
if([...transact.deletes.keys()].length > 0) {
this.transactDeleteRecords(transaction, transact.deletes)
}
}))
}
/** Closes this database. */
public close() {
this.database.close()
}
// #region Statics
/** Opens this database */
private static open(databaseKey: DatabaseKey, options: DatabaseOptions = {additions: [], removals: []}): Promise<IDBDatabase> {
return new Promise<IDBDatabase>((resolve, reject) => {
const request = DBFactory().open(databaseKey, options.version)
request.addEventListener('error', () => reject(request.error))
request.addEventListener('success', () => resolve(request.result as IDBDatabase))
request.addEventListener("upgradeneeded", () => {
const updated = request.result as IDBDatabase
options.additions.forEach (storeKey => updated.createObjectStore(storeKey, { keyPath: 'key' }))
options.removals.forEach (storeKey => updated.deleteObjectStore(storeKey))
})
})
}
/** Connects to an IDB instance. */
public static async connect(databaseKey: DatabaseKey): Promise<IDBDriver> {
const database = await IDBDriver.open(databaseKey)
return new IDBDriver(database)
}
/** Drops this database. */
public static drop(databaseKey: DatabaseKey): Promise<void> {
return new Promise<void>((resolve, reject) => {
const request = DBFactory().deleteDatabase(databaseKey)
request.addEventListener("error", () => reject(request.error))
request.addEventListener("success", () => resolve())
})
}
} | the_stack |
import { promisify } from 'util'
import { Readable, pipeline as rawPipeline } from 'stream'
import type { Adapter } from '@resolve-js/eventstore-base'
import createAdapter from './create-adapter'
const pipeline = promisify(rawPipeline)
jest.setTimeout(1000 * 60 * 5)
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
void ([array[i], array[j]] = [array[j], array[i]])
}
return array
}
function validateEvents(events) {
const aggregateIdVersionMap = {}
const threadIdCounterMap = {}
const threadIdTimestampMap = {}
let maxTimestamp = -1
const allErrors = []
for (const event of events) {
const errors = []
if (event.threadId == null) {
errors.push(new Error('Incorrect "threadId"'))
}
const expectedAggregateVersion =
(aggregateIdVersionMap[event.aggregateId] == null
? 0
: aggregateIdVersionMap[event.aggregateId]) + 1
if (
event.aggregateVersion == null ||
event.aggregateVersion !== expectedAggregateVersion
) {
// eslint-disable-next-line no-console
console.log('event.aggregateVersion', event.aggregateVersion)
// eslint-disable-next-line no-console
console.log(
'aggregateIdVersionMap[event.aggregateId]',
aggregateIdVersionMap[event.aggregateId]
)
// eslint-disable-next-line no-console
console.log('expectedAggregateVersion', expectedAggregateVersion)
// eslint-disable-next-line no-console
console.log('aggregateId', event.aggregateId)
errors.push(new Error('Incorrect "aggregateVersion"'))
} else {
aggregateIdVersionMap[event.aggregateId] = event.aggregateVersion
}
const expectedThreadCounter =
(threadIdCounterMap[event.threadId] == null
? -1
: threadIdCounterMap[event.threadId]) + 1
if (
event.threadCounter == null ||
event.threadCounter !== expectedThreadCounter
) {
// eslint-disable-next-line no-console
console.log('event.threadCounter', event.threadCounter)
// eslint-disable-next-line no-console
console.log(
'threadIdCounterMap[event.threadId]',
threadIdCounterMap[event.threadId]
)
// eslint-disable-next-line no-console
console.log('expectedThreadCounter', expectedThreadCounter)
// eslint-disable-next-line no-console
console.log('threadId', event.threadId)
errors.push(new Error('Incorrect "threadCounter"'))
} else {
threadIdCounterMap[event.threadId] = event.threadCounter
}
const expectedTimestamp =
threadIdTimestampMap[event.threadId] == null
? 0
: threadIdTimestampMap[event.threadId]
if (event.timestamp == null || event.timestamp < expectedTimestamp) {
// eslint-disable-next-line no-console
console.log('event.timestamp', event.timestamp)
// eslint-disable-next-line no-console
console.log(
'threadIdTimestampMap[event.threadId]',
threadIdTimestampMap[event.threadId]
)
// eslint-disable-next-line no-console
console.log('expectedTimestamp', expectedTimestamp)
// eslint-disable-next-line no-console
console.log('threadId', event.threadId)
errors.push(new Error('Incorrect "timestamp"'))
} else {
threadIdTimestampMap[event.threadId] = event.timestamp
}
if (event.timestamp == null || event.timestamp < maxTimestamp) {
// eslint-disable-next-line no-console
console.log('event.timestamp', event.timestamp)
// eslint-disable-next-line no-console
console.log('maxTimestamp', maxTimestamp)
errors.push(new Error('Incorrect "timestamp"'))
} else {
maxTimestamp = event.timestamp
}
if (errors.length > 0) {
allErrors.push(...errors)
}
}
if (allErrors.length > 0) {
// eslint-disable-next-line no-console
console.log('aggregateIdVersionMap', aggregateIdVersionMap)
// eslint-disable-next-line no-console
console.log('threadIdCounterMap', threadIdCounterMap)
const error = new Error(allErrors.map(({ message }) => message).join('\n'))
error.stack = allErrors.map(({ stack }) => stack).join('\n')
throw error
}
}
let adapter: Adapter
beforeEach(async () => {
adapter = createAdapter()
await adapter.init()
})
afterEach(async () => {
if (adapter != null) {
await adapter.drop()
await adapter.dispose()
adapter = null
}
})
test('incremental import should work correctly', async () => {
const countEvents = 2500 + Math.floor(75 * Math.random())
const events = []
for (let eventIndex = 0; eventIndex < countEvents; eventIndex++) {
events.push({
aggregateId: `aggregateId${eventIndex % 10}`,
type: `EVENT${eventIndex % 3}`,
payload: { eventIndex },
timestamp: Date.now(),
})
}
await adapter.incrementalImport(events)
const resultEvents = (
await adapter.loadEvents({ limit: countEvents + 1, cursor: null })
).events
expect(resultEvents.length).toEqual(countEvents)
validateEvents(resultEvents)
})
test('inject-events should work correctly', async () => {
const countInitialEvents = 250 + Math.floor(75 * Math.random())
const countIncrementalImportEvents = 25000 + Math.floor(75000 * Math.random())
const countAllEvents = countInitialEvents + countIncrementalImportEvents
const initialEvents = []
for (let eventIndex = 0; eventIndex < countInitialEvents; eventIndex++) {
initialEvents.push({
threadId: eventIndex % 256,
threadCounter: Math.floor(eventIndex / 256),
aggregateId: `aggregateId${eventIndex % 10}`,
aggregateVersion: Math.floor(eventIndex / 10) + 1,
type: `EVENT${eventIndex % 3}`,
payload: { eventIndex },
timestamp: Date.now(),
})
}
// const t0 = Date.now()
await pipeline(
Readable.from(
(async function* eventStream() {
for (const event of initialEvents) {
yield Buffer.from(`${JSON.stringify(event)}\n`)
}
})()
),
adapter.importEvents()
)
// const t1 = Date.now()
await new Promise((resolve) => setImmediate(resolve))
// // eslint-disable-next-line no-console
// console.log(
// `Importing initial events ${t1 - t0} ms / Events ${countInitialEvents}`
// )
const tempInitialEvents = (
await adapter.loadEvents({ limit: countInitialEvents + 1, cursor: null })
).events
expect(tempInitialEvents.length).toEqual(initialEvents.length)
expect(tempInitialEvents).toEqual(initialEvents)
await new Promise((resolve) => setTimeout(resolve, 1000))
const incrementalImportTimestamp = Date.now()
let incrementalImportEvents = []
// const t2 = Date.now()
const importId = await adapter.beginIncrementalImport()
const incrementalImportPromises = []
// let incrementalBatchIdx = 0
for (
let eventIndex = 0;
eventIndex < countIncrementalImportEvents;
eventIndex++
) {
incrementalImportEvents.push({
aggregateId: `aggregateId${eventIndex % 10}`,
type: `EVENT${eventIndex % 3}`,
timestamp: incrementalImportTimestamp + eventIndex,
payload: { eventIndex },
})
if (eventIndex % 256 === 0) {
shuffle(incrementalImportEvents)
//const currentBatchIdx = incrementalBatchIdx++
incrementalImportPromises.push(
adapter.pushIncrementalImport(incrementalImportEvents, importId)
// .then(() => {
// // eslint-disable-next-line no-console
// console.log(`Pushing incremental batch ${currentBatchIdx}`)
// })
)
incrementalImportEvents = []
}
}
if (incrementalImportEvents.length > 0) {
// const currentBatchIdx = incrementalBatchIdx++
shuffle(incrementalImportEvents)
incrementalImportPromises.push(
adapter.pushIncrementalImport(incrementalImportEvents, importId)
// .then(() => {
// // eslint-disable-next-line no-console
// console.log(`Pushing incremental batch ${currentBatchIdx}`)
// })
)
}
await Promise.all(incrementalImportPromises)
// const t3 = Date.now()
await new Promise((resolve) => setImmediate(resolve))
// // eslint-disable-next-line no-console
// console.log(
// `Pushing incremental events ${t3 -
// t2} ms / Events ${countIncrementalImportEvents}`
// )
await adapter.commitIncrementalImport(importId, true)
// const t4 = Date.now()
await new Promise((resolve) => setImmediate(resolve))
// // eslint-disable-next-line no-console
// console.log(
// `Commiting incremental events ${t4 -
// t3} ms / Events ${countIncrementalImportEvents}`
// )
const resultEvents = (
await adapter.loadEvents({ limit: countAllEvents + 1, cursor: null })
).events
expect(resultEvents.length).toEqual(countAllEvents)
validateEvents(resultEvents)
})
test('inject-events should work correctly with retries', async () => {
const countInitialEvents = 250 + Math.floor(750 * Math.random())
const initialEvents = []
const incrementalImportEvents = []
for (let eventIndex = 0; eventIndex < countInitialEvents; eventIndex++) {
const timestamp = Date.now()
const type = `EVENT${eventIndex % 3}`
const aggregateId = `aggregateId${eventIndex % 10}`
if (eventIndex < countInitialEvents * 0.66) {
initialEvents.push({
threadId: eventIndex % 256,
threadCounter: Math.floor(eventIndex / 256),
aggregateId,
aggregateVersion: Math.floor(eventIndex / 10) + 1,
type,
payload: { eventIndex },
timestamp,
})
}
if (eventIndex > countInitialEvents * 0.33) {
incrementalImportEvents.push({
threadId: eventIndex % 256,
threadCounter: Math.floor(eventIndex / 256),
aggregateId,
aggregateVersion: Math.floor(eventIndex / 10) + 1,
type,
payload: { eventIndex },
timestamp,
})
}
}
await pipeline(
Readable.from(
(async function* eventStream() {
for (const event of initialEvents) {
yield Buffer.from(`${JSON.stringify(event)}\n`)
}
})()
),
adapter.importEvents()
)
await new Promise((resolve) => setImmediate(resolve))
const tempInitialEvents = (
await adapter.loadEvents({ limit: countInitialEvents + 1, cursor: null })
).events
expect(tempInitialEvents.length).toEqual(initialEvents.length)
expect(tempInitialEvents).toEqual(initialEvents)
await new Promise((resolve) => setTimeout(resolve, 1000))
const importId = await adapter.beginIncrementalImport()
await adapter.pushIncrementalImport(incrementalImportEvents, importId)
await new Promise((resolve) => setImmediate(resolve))
await adapter.commitIncrementalImport(importId, true)
})
test('preserve order of input events with the same timestamp', async () => {
async function orderCheck() {
for (
let aggregateIndex = 0;
aggregateIndex < aggregateCount;
aggregateIndex++
) {
const aggregateId = aggregateIds[aggregateIndex]
const { events } = await adapter.loadEvents({
cursor: null,
limit: 10000,
aggregateIds: [aggregateId],
})
for (let index = 0; index < events.length - 1; index++) {
const nextIndex = index + 1
if (
events[nextIndex].aggregateVersion !==
events[index].aggregateVersion + 1
) {
throw new Error(
`Bad order. aggregateId = ${aggregateId}. ${JSON.stringify(
events,
null,
2
)}`
)
}
}
}
}
const aggregateCount = 5
const timestampCount = 7
const aggregateIds = Array.from(Array(aggregateCount).keys()).map(
(id) => `id_${id}`
)
const aggregateVersions = aggregateIds.reduce((acc, val) => {
acc[val] = 0
return acc
}, {})
const threadCounters = Array.from(Array(256).keys())
.map((_, index) => index)
.reduce((acc, val) => {
acc[val] = 0
return acc
}, {})
const initialEvents = []
let eventIndex = 0
for (
let aggregateIndex = 0;
aggregateIndex < aggregateCount;
aggregateIndex++
) {
for (
let timestampIndex = 0;
timestampIndex < timestampCount;
timestampIndex++
) {
eventIndex++
const aggregateId = aggregateIds[aggregateIndex]
const aggregateVersion = ++aggregateVersions[aggregateId]
const timestamp = eventIndex
const threadId = (eventIndex * aggregateCount * timestampCount) % 256
const threadCounter = threadCounters[threadId]++
initialEvents.push({
threadId,
threadCounter,
aggregateId,
aggregateVersion,
timestamp,
type: 'type',
payload: {},
})
}
}
await pipeline(
Readable.from(
(async function* eventStream() {
for (const event of initialEvents) {
yield Buffer.from(`${JSON.stringify(event)}\n`)
}
})()
),
adapter.importEvents()
)
await orderCheck()
const incrementalEvents = [
{
timestamp: 1626110770000,
aggregateId: aggregateIds[0],
type: 'type',
payload: { idx: 0 },
},
{
timestamp: 1626110770000,
aggregateId: aggregateIds[0],
type: 'type',
payload: { idx: 1 },
},
{
timestamp: 1626132179642,
aggregateId: aggregateIds[0],
type: 'type',
payload: { idx: 2 },
},
{
timestamp: 1626132179642,
aggregateId: aggregateIds[0],
type: 'type',
payload: { idx: 3 },
},
{
timestamp: 1626132179642,
aggregateId: aggregateIds[0],
type: 'type',
payload: { idx: 4 },
},
{
timestamp: 1626132179642,
aggregateId: aggregateIds[0],
type: 'type',
payload: { idx: 5 },
},
]
await adapter.incrementalImport(incrementalEvents)
await orderCheck()
}) | the_stack |
'use strict';
import * as React from 'react';
import { connect } from 'react-redux';
import { makeListKey } from 'chord/platform/utils/common/keys';
import { IStateGlobal } from 'chord/workbench/api/common/state/stateGlobal';
import SongItemView from 'chord/workbench/parts/common/component/songItem';
import ArtistItemView from 'chord/workbench/parts/common/component/artistItem';
import AlbumItemView from 'chord/workbench/parts/common/component/albumItem';
import CollectionItemView from 'chord/workbench/parts/common/component/collectionItem';
import UserProfileItemView from 'chord/workbench/parts/common/component/userProfileItem';
import EpisodeItemView from 'chord/workbench/parts/common/component/episodeItem';
import PodcastItemView from 'chord/workbench/parts/common/component/podcastItem';
import RadioItemView from 'chord/workbench/parts/common/component/radioItem';
import { ViewMorePlusItem } from 'chord/workbench/parts/common/component/viewMoreItem';
import { NavMenu } from 'chord/workbench/parts/common/component/navMenu';
import {
getMoreSongs,
getMoreAlbums,
getMoreArtists,
getMoreCollections,
getMoreUserProfiles,
getMoreEpisodes,
getMorePodcasts,
getMoreRadios,
} from 'chord/workbench/parts/mainView/browser/action/libraryResult';
import { handlePlayLibrarySongs } from 'chord/workbench/parts/player/browser/action/playLibrarySongs';
import { ILibraryResultProps } from 'chord/workbench/parts/mainView/browser/component/library/props/libraryResult';
class LibraryResult extends React.Component<ILibraryResultProps, any> {
static view: string
constructor(props: ILibraryResultProps) {
super(props);
if (!LibraryResult.view) {
LibraryResult.view = this.props.view;
}
this.state = { view: LibraryResult.view };
this.changeLibraryResultView = this.changeLibraryResultView.bind(this);
this._itemWrap = this._itemWrap.bind(this);
this._getSongsView = this._getSongsView.bind(this);
this._getAlbumsView = this._getAlbumsView.bind(this);
this._getArtistsView = this._getArtistsView.bind(this);
this._getCollectionsView = this._getCollectionsView.bind(this);
this._getUserProfilesView = this._getUserProfilesView.bind(this);
this._getEpisodesView = this._getEpisodesView.bind(this);
this._getPodcastsView = this._getPodcastsView.bind(this);
this._getRadiosView = this._getRadiosView.bind(this);
this._getLibraryNavMenu = this._getLibraryNavMenu.bind(this);
this.topResult = this.topResult.bind(this);
this.songsResult = this.songsResult.bind(this);
this.artistsResult = this.artistsResult.bind(this);
this.albumsResult = this.albumsResult.bind(this);
this.collectionsResult = this.collectionsResult.bind(this);
this.userProfilesResult = this.userProfilesResult.bind(this);
}
changeLibraryResultView(view: string) {
LibraryResult.view = view;
this.setState({ view });
}
_getSongsView(size?: number) {
let songsView = this.props.songs.slice(0, size ? size : Infinity).map(
(userSong, index) => (
<SongItemView
key={makeListKey(index, 'song', 'library')}
song={userSong.song}
active={false}
short={false}
thumb={false}
handlePlay={null} />
)
);
return songsView;
}
_itemWrap(item, index, name) {
return (
<div key={makeListKey(index, name, 'library')}
className='col-xs-6 col-sm-4 col-md-3 col-lg-2 col-xl-2'>
{item}
</div>
);
}
_getAlbumsView(size?: number) {
let albumsView = this.props.albums.slice(0, size ? size : Infinity).map(
(userAlbum, index) => (
this._itemWrap(
<AlbumItemView album={userAlbum.album} />, index, 'album')
)
);
return albumsView;
}
_getArtistsView(size?: number) {
let artistsView = this.props.artists.slice(0, size ? size : Infinity).map(
(userArtist, index) => (
this._itemWrap(<ArtistItemView artist={userArtist.artist} />, index, 'artist')
)
);
return artistsView;
}
_getCollectionsView(size?: number) {
let collectionsView = this.props.collections.slice(0, size ? size : Infinity).map(
(userCollection, index) => (
this._itemWrap(<CollectionItemView collection={userCollection.collection} />, index, 'collection')
)
);
return collectionsView;
}
_getUserProfilesView(size?: number) {
let userProfilesView = this.props.userProfiles.slice(0, size ? size : Infinity).map(
(userUserProfile, index) => (
this._itemWrap(<UserProfileItemView userProfile={userUserProfile.userProfile} />, index, 'userProfile')
)
);
return userProfilesView;
}
_getEpisodesView(size?: number) {
let episodesView = this.props.episodes.slice(0, size ? size : Infinity).map(
(userEpisode, index) => (
<EpisodeItemView
key={makeListKey(index, 'episode', 'library')}
episode={userEpisode.episode}
active={false}
short={false}
thumb={false}
handlePlay={null} />
)
);
return episodesView;
}
_getPodcastsView(size?: number) {
let podcastsView = this.props.podcasts.slice(0, size ? size : Infinity).map(
(userPodcast, index) => (
this._itemWrap(
<PodcastItemView podcast={userPodcast.podcast} />, index, 'podcast')
)
);
return podcastsView;
}
_getRadiosView(size?: number) {
let radiosView = this.props.radios.slice(0, size ? size : Infinity).map(
(userRadio, index) => (
this._itemWrap(<RadioItemView radio={userRadio.radio} />, index, 'radio')
)
);
return radiosView;
}
_getLibraryNavMenu() {
let views = [
{ name: 'TOP RESULT', value: 'top' },
{ name: 'SONGS', value: 'songs' },
{ name: 'ARTISTS', value: 'artists' },
{ name: 'ALBUMS', value: 'albums' },
{ name: 'COLLECTIONS', value: 'collections' },
{ name: 'USERS', value: 'userProfiles' },
{ name: 'PODCASTS', value: 'podcasts' },
{ name: 'RADIOS', value: 'radios' },
{ name: 'EPISODES', value: 'episodes' },
];
return <NavMenu
namespace='search-navmenu'
thisView={LibraryResult.view}
views={views}
handleClick={this.changeLibraryResultView} />;
}
topResult() {
let defaultSize = 10;
let songsView = this._getSongsView(defaultSize);
let albumsView = this._getAlbumsView(defaultSize);
let artistsView = this._getArtistsView(defaultSize);
let collectionsView = this._getCollectionsView(defaultSize);
let userProfilesView = this._getUserProfilesView(defaultSize);
let episodesView = this._getEpisodesView(defaultSize);
let podcastsView = this._getPodcastsView(defaultSize);
let radiosView = this._getRadiosView(defaultSize);
let searchNavMenu = this._getLibraryNavMenu();
let makeItemsView = (name, itemsView) => (
<div className='row'>
<h1 className="search-result-title" style={{ textAlign: 'center' }}>
{name}</h1>
<section>
<div className='container-fluid container-fluid--noSpaceAround'>
<div className='align-row-wrap row'>
{itemsView}
</div>
</div>
</section>
</div>
);
return (
<div>
{/* Library Result Nagivation Menu */}
{searchNavMenu}
<div className='contentSpacing'>
<div className='container-fluid container-fluid--noSpaceAround'>
{/* Songs View */}
<div className='row'>
<h1 className="search-result-title" style={{ textAlign: 'center' }}>
Songs</h1>
<button className="btn btn-green btn-small cursor-pointer"
style={{ margin: '0px auto 15px', display: 'block' }}
onClick={this.props.handlePlayLibrarySongs}>
PlAY ALL</button>
<section className='tracklist-container'>
<ol className='tracklist'>
{songsView}
</ol>
</section>
</div>
{/* Artists View */}
{makeItemsView('Artists', artistsView)}
{/* Albums View */}
{makeItemsView('Albums', albumsView)}
{/* Collections View */}
{makeItemsView('Collections', collectionsView)}
{/* UserProfiles View */}
{makeItemsView('Followings', userProfilesView)}
{/* Podcasts View */}
{makeItemsView('Podcasts', podcastsView)}
{/* Radios View */}
{makeItemsView('Radios', radiosView)}
{/* Episodes View */}
<div className='row'>
<h1 className="search-result-title" style={{ textAlign: 'center' }}>
Episodes</h1>
<section className='tracklist-container'>
<ol className='tracklist'>
{episodesView}
</ol>
</section>
</div>
</div>
</div>
</div>
);
}
songsResult() {
let songsView = this._getSongsView();
let searchNavMenu = this._getLibraryNavMenu();
let keyword = this.props.keyword;
let offset = this.props.songsOffset;
let viewMore = offset.more ? (<ViewMorePlusItem handler={(size) => this.props.getMoreSongs(keyword, offset, size)} />) : null;
return (
<div>
{/* Library Result Nagivation Menu */}
{searchNavMenu}
<div className='contentSpacing'>
<div className='container-fluid container-fluid--noSpaceAround'>
{/* Songs View */}
<div className='row'>
<h1 className="search-result-title" style={{ textAlign: 'center' }}>
Songs</h1>
<button className="btn btn-green btn-small cursor-pointer"
style={{ margin: '0px auto 15px', display: 'block' }}
onClick={this.props.handlePlayLibrarySongs}>
PlAY ALL</button>
<section className='tracklist-container'>
<ol className='tracklist'>
{songsView}
</ol>
</section>
</div>
{viewMore}
</div>
</div>
</div>
);
}
_itemsResult(itemsView, viewMore) {
let searchNavMenu = this._getLibraryNavMenu();
return (
<div>
{/* Library Result Nagivation Menu */}
{searchNavMenu}
<div className='contentSpacing'>
<div className='container-fluid container-fluid--noSpaceAround'>
{/* Items View */}
<div className='row'>
<h1 className="search-result-title" style={{ textAlign: 'center' }}>
Artists</h1>
<section>
<div className='container-fluid container-fluid--noSpaceAround'>
<div className='align-row-wrap row'>
{itemsView}
</div>
</div>
</section>
</div>
{viewMore}
</div>
</div>
</div>
);
}
artistsResult() {
let artistsView = this._getArtistsView();
let keyword = this.props.keyword;
let offset = this.props.artistsOffset;
let viewMore = offset.more ? (<ViewMorePlusItem handler={(size) => this.props.getMoreArtists(keyword, offset, size)} />) : null;
return this._itemsResult(artistsView, viewMore);
}
albumsResult() {
let albumsView = this._getAlbumsView();
let keyword = this.props.keyword;
let offset = this.props.albumsOffset;
let viewMore = offset.more ? (<ViewMorePlusItem handler={(size) => this.props.getMoreAlbums(keyword, offset, size)} />) : null;
return this._itemsResult(albumsView, viewMore);
}
collectionsResult() {
let collectionsView = this._getCollectionsView();
let keyword = this.props.keyword;
let offset = this.props.collectionsOffset;
let viewMore = offset.more ? (<ViewMorePlusItem handler={(size) => this.props.getMoreCollections(keyword, offset, size)} />) : null;
return this._itemsResult(collectionsView, viewMore);
}
userProfilesResult() {
let userProfilesView = this._getUserProfilesView();
let keyword = this.props.keyword;
let offset = this.props.userProfilesOffset;
let viewMore = offset.more ? (<ViewMorePlusItem handler={(size) => this.props.getMoreUserProfiles(keyword, offset, size)} />) : null;
return this._itemsResult(userProfilesView, viewMore);
}
episodesResult() {
let episodesView = this._getEpisodesView();
let searchNavMenu = this._getLibraryNavMenu();
let keyword = this.props.keyword;
let offset = this.props.episodesOffset;
let viewMore = offset.more ? (<ViewMorePlusItem handler={(size) => this.props.getMoreEpisodes(keyword, offset, size)} />) : null;
return (
<div>
{/* Library Result Nagivation Menu */}
{searchNavMenu}
<div className='contentSpacing'>
<div className='container-fluid container-fluid--noSpaceAround'>
{/* Episodes View */}
<div className='row'>
<h1 className="search-result-title" style={{ textAlign: 'center' }}>
Episodes</h1>
<section className='tracklist-container'>
<ol className='tracklist'>
{episodesView}
</ol>
</section>
</div>
{viewMore}
</div>
</div>
</div>
);
}
podcastsResult() {
let podcastsView = this._getPodcastsView();
let keyword = this.props.keyword;
let offset = this.props.podcastsOffset;
let viewMore = offset.more ? (<ViewMorePlusItem handler={(size) => this.props.getMorePodcasts(keyword, offset, size)} />) : null;
return this._itemsResult(podcastsView, viewMore);
}
radiosResult() {
let radiosView = this._getRadiosView();
let keyword = this.props.keyword;
let offset = this.props.radiosOffset;
let viewMore = offset.more ? (<ViewMorePlusItem handler={(size) => this.props.getMoreRadios(keyword, offset, size)} />) : null;
return this._itemsResult(radiosView, viewMore);
}
render() {
let view = LibraryResult.view;
switch (view) {
case 'songs':
return this.songsResult();
case 'artists':
return this.artistsResult();
case 'albums':
return this.albumsResult();
case 'collections':
return this.collectionsResult();
case 'userProfiles':
return this.userProfilesResult();
case 'episodes':
return this.episodesResult();
case 'podcasts':
return this.podcastsResult();
case 'radios':
return this.radiosResult();
default: // view == 'top'
return this.topResult();
}
}
}
function mapStateToProps(state: IStateGlobal) {
return {
...state.mainView.libraryView.result,
keyword: state.mainView.libraryView.keyword,
};
}
function mapDispatchToProps(dispatch) {
return {
getMoreSongs: (keyword, offset, size) => dispatch(getMoreSongs(keyword, offset, size)),
getMoreAlbums: (keyword, offset, size) => dispatch(getMoreAlbums(keyword, offset, size)),
getMoreArtists: (keyword, offset, size) => dispatch(getMoreArtists(keyword, offset, size)),
getMoreCollections: (keyword, offset, size) => dispatch(getMoreCollections(keyword, offset, size)),
getMoreUserProfiles: (keyword, offset, size) => dispatch(getMoreUserProfiles(keyword, offset, size)),
getMoreEpisodes: (keyword, offset, size) => dispatch(getMoreEpisodes(keyword, offset, size)),
getMorePodcasts: (keyword, offset, size) => dispatch(getMorePodcasts(keyword, offset, size)),
getMoreRadios: (keyword, offset, size) => dispatch(getMoreRadios(keyword, offset, size)),
handlePlayLibrarySongs: () => handlePlayLibrarySongs().then(act => dispatch(act)),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(LibraryResult); | the_stack |
import { noop } from '@babel/types';
/**
* Various helper functions around paths and file types
*/
export class PathOperations
{
/**
* check if the current file path meets any of the conditions that should cause analysis
* to skip it
* @param filePath the full file path of the file being analyzed
* @param ignoreList the current collection of conditions to ignore (e.g. *.log, node_modules/*)
* @return true if the file should be ignored, false if it should be processed
*/
public static ignoreFile(filePath: string, ignoreList: string[] = []): boolean
{
if (filePath && filePath.length > 1)
{
filePath = filePath.replace(/\\/g,"/");
let XRegExp = require('xregexp');
for(let ignore of ignoreList)
{
//if the string representation of the regex in the array is screwed up, it may
//cause an exception when its used to construct a regex. That shouldn't prohibit
//trying the other patterns
try{
if(XRegExp.exec(filePath, RegExp(ignore, "i")))
{
return true;
}
}
catch(e) {noop();}
}
}
return false;
}
/**
* Clean up the directory path, stripping trailing / or \ and replacing double slashes with single
* even if not cleaned up, it should work with every API that needs a path, but it makes path comparisons suck
* @param directory the directory path to clean up
* @return cleaned up directory path
*/
public normalizeDirectoryPaths(directory : string) : string
{
directory = directory.replace(/\\\\/g,"\\" );
directory = directory.replace(/\/\//g,"/" );
if(directory.slice(-1) == "\\" || directory.slice(-1) == "/" )
{
directory = directory.substring(0,directory.length );
}
// Chop off any initial ./ or .\ substrings
if (directory.slice(0, 2) === './' || directory.slice(0, 2) === '.\\') {
directory = directory.slice(2);
}
return directory;
}
/**
* Figure out the mime type for a source file based on its extension. this is using a precomputed list of
* mime types, so will not succeed for every file type
* @param filePath the path of the file
* @return the mime type of the file if known, otherwise text/plain
*/
public getMimeFromPath(filePath : string) : string
{
let path = require('path');
let extension : string = path.extname(filePath);
switch (extension.toLowerCase())
{
case ".bat":
case ".cmd": return "text/x-c";
case ".clj":
case ".cljs":
case ".cljc":
case ".cljx":
case ".clojure":
case "edn": return "text/plain";
case ".coffee":
case ".cson": return "text/plain";
case ".c": return "text/x-c";
case ".cpp":
case ".cc":
case ".cxx":
case ".c++":
case ".h":
case ".hh":
case ".hxx":
case ".hpp":
case ".h++": return "text/x-c";
case ".cs":
case ".csx":
case ".cake": return "text/plain";
case ".css": return "text/css";
case ".dockerfile": return "text/plain";
case ".fs":
case ".fsi":
case ".fsx":
case ".fsscript": return "text/plain";
case ".go": return "text/plain";
case ".groovy":
case ".gvy":
case ".gradle": return "text/plain";
case ".handlebars":
case ".hbs": return "text/plain";
case ".hlsl":
case ".fx":
case ".fxh":
case ".vsh":
case ".psh":
case ".cfinc":
case ".hlsli": return "text/plain";
case ".html":
case ".htm":
case ".shtml":
case ".xhtml":
case ".mdoc":
case ".jsp":
case ".asp":
case ".aspx":
case ".jshtm":
case ".volt":
case ".ejs":
case ".rhtml": return "text/html";
case ".ini": return "text/plain";
case ".jade":
case ".pug": return "jade";
case ".java":
case ".jav": return "text/plain";
case ".jsx": return "text/javascript";
case ".js":
case ".es6":
case "mjs":
case ".pac": return "text/javascript";
case ".json":
case ".bowerrc":
case ".jshintrc":
case ".jscsrc":
case ".eslintrc":
case ".babelrc":
case ".webmanifest":
case ".code-workspace": return "application/json";
case ".less": return "text/plain";
case ".lua": return "text/plain";
case ".mk": return "text/plain";
case ".md":
case ".mdown":
case ".markdown":
case "markdn": return "text/plain";
case ".m":
case ".mm": return "text/x-c";
case ".php":
case ".php3":
case ".php4":
case ".php5":
case ".phtml":
case ".ph3":
case ".ph4":
case ".ctp": return "text/plain";
case ".pl":
case ".pm":
case ".t":
case "p6":
case "pl6":
case "pm6":
case "nqp":
case ".pod": return "text/x-script.perl";
case ".ps1":
case ".psm1":
case ".psd1":
case ".pssc":
case ".psrc": return "text/plain";
case ".py":
case ".rpy":
case ".pyw":
case ".cpy":
case ".gyp":
case ".gypi": return "text/x-script.python";
case ".r":
case ".rhistory":
case ".rprofile":
case ".rt": return "text/plain";
case ".cshtml": return "text/html";
case ".rb":
case ".rbx":
case ".rjs":
case ".gemspec":
case ".rake":
case ".ru":
case ".erb": return "text/plain";
case ".rs": return "text/plain";
case ".scala":
case ".sc": return "text/plain";
case ".scss": return "text/plain";
case ".shadder": return "text/plain";
case ".sh":
case ".bash":
case ".bashrc":
case ".bash_aliases":
case ".bash_profile":
case ".bash_login":
case ".ebuild":
case ".install":
case ".profile":
case ".bash_logout":
case ".zsh":
case ".zshrc":
case ".zprofile":
case ".zlogin":
case ".zlogout":
case ".zshenv":
case ".zsh-theme": return "text/plain";
case ".sql":
case ".dsql": return "text/plain";
case ".swift": return "text/plain";
case ".ts": return "text/plain";
case ".tsx": return "text/plain";
case ".vb":
case ".vba":
case "brs":
case ".bas":
case ".vbs": return "text/plain";
case ".xml":
case ".xsd":
case ".ascx":
case ".atom":
case ".axml":
case ".bpmn":
case ".config":
case ".cpt":
case ".csl":
case ".csproj":
case ".csproj.user":
case ".dita":
case ".ditamap":
case ".dtd":
case ".dtml":
case ".fsproj":
case ".fxml":
case ".iml":
case ".isml":
case ".jmx":
case ".launch":
case ".menu":
case ".mxml":
case ".nuspec":
case ".opml":
case ".owl":
case ".proj":
case ".props":
case ".pt":
case ".publishsettings":
case ".pubxml":
case ".pubxml.user":
case ".rdf":
case ".rng":
case ".rss":
case ".shproj":
case ".storyboard":
case ".svg":
case ".targets":
case ".tld":
case ".tmx":
case ".vbproj":
case ".vbproj.user":
case ".vcxproj":
case ".vcxproj.filters":
case ".wsdl":
case ".wxi":
case ".wxl":
case ".wxs":
case ".xaml":
case ".xbl":
case ".xib":
case ".xlf":
case ".xliff":
case ".xpdl":
case ".xul":
case ".xoml": return "text/xml";
case ".yaml":
case "eyaml":
case "eyml":
case ".yml": return "text/plain";
}
return "text/plain";
}
/**
* Get the language identifier for a file based on its extension(either VS Code or SARIF depending on param)
* @param filePath the file path for the file being analyzed
* @param sarifConvention (optional) if true, uses SARIF terminology where it deviates, false/default is VS Code identifiers
*/
public getLangFromPath(filePath : string, sarifConvention : boolean = false) : string
{
let path = require('path');
let extension : string = path.extname(filePath);
switch (extension.toLowerCase())
{
case ".bat": return "bat";
case ".cmd": return "cmd";
case ".clj":
case ".cljs":
case ".cljc":
case ".cljx":
case ".clojure":
case "edn": return "clojure";
case ".coffee":
case ".cson": return "coffeescript";
case ".c": return "c";
case ".cpp":
case ".cc":
case ".cxx":
case ".c++":
case ".h":
case ".hh":
case ".hxx":
case ".hpp":
case ".h++": return (sarifConvention) ? "cplusplus" : "cpp";
case ".cs":
case ".csx":
case ".cake": return "csharp";
case ".css": return "css";
case ".dockerfile": return "dockerfile";
case ".fs":
case ".fsi":
case ".fsx":
case ".fsscript": return "fsharp";
case ".go": return "go";
case ".groovy":
case ".gvy":
case ".gradle": return "groovy";
case ".handlebars":
case ".hbs": return "handlebars";
case ".hlsl":
case ".fx":
case ".fxh":
case ".vsh":
case ".psh":
case ".cfinc":
case ".hlsli": return "hlsl";
case ".html":
case ".htm":
case ".shtml":
case ".xhtml":
case ".mdoc":
case ".jsp":
case ".asp":
case ".aspx":
case ".jshtm":
case ".volt":
case ".ejs":
case ".rhtml": return "html";
case ".ini": return "ini";
case ".jade":
case ".pug": return "jade";
case ".java":
case ".jav": return "java";
case ".jsx": return "javascriptreact";
case ".js":
case ".es6":
case "mjs":
case ".pac": return "javascript";
case ".json":
case ".bowerrc":
case ".jshintrc":
case ".jscsrc":
case ".eslintrc":
case ".babelrc":
case ".webmanifest":
case ".code-workspace": return "json";
case ".less": return "less";
case ".lua": return "lua";
case ".mk": return "makefile";
case ".md":
case ".mdown":
case ".markdown":
case "markdn": return "markdown";
case ".m":
case ".mm": return (sarifConvention) ? "objectivec" : "objective-c";
case ".php":
case ".php3":
case ".php4":
case ".php5":
case ".phtml":
case ".ph3":
case ".ph4":
case ".ctp": return "php";
case ".pl":
case ".pm":
case ".t":
case "p6":
case "pl6":
case "pm6":
case "nqp":
case ".pod": return "perl";
case ".ps1":
case ".psm1":
case ".psd1":
case ".pssc":
case ".psrc": return "powershell";
case ".py":
case ".rpy":
case ".pyw":
case ".cpy":
case ".gyp":
case ".gypi": return "python";
case ".r":
case ".rhistory":
case ".rprofile":
case ".rt": return "r";
case ".cshtml": return "razor";
case ".rb":
case ".rbx":
case ".rjs":
case ".gemspec":
case ".rake":
case ".ru":
case ".erb": return "ruby";
case ".rs": return "rust";
case ".scala":
case ".sc": return "scala";
case ".scss": return "scss";
case ".shadder": return "shaderlab";
case ".sh":
case ".bash":
case ".bashrc":
case ".bash_aliases":
case ".bash_profile":
case ".bash_login":
case ".ebuild":
case ".install":
case ".profile":
case ".bash_logout":
case ".zsh":
case ".zshrc":
case ".zprofile":
case ".zlogin":
case ".zlogout":
case ".zshenv":
case ".zsh-theme": return "shellscript";
case ".sql":
case ".dsql": return "sql";
case ".swift": return "swift";
case ".ts": return "typescript";
case ".tsx": return "typescriptreact";
case ".vb":
case ".vba":
case "brs":
case ".bas":
case ".vbs": return (sarifConvention) ? "visualbasic" : "vb";
case ".xml":
case ".xsd":
case ".ascx":
case ".atom":
case ".axml":
case ".bpmn":
case ".config":
case ".cpt":
case ".csl":
case ".csproj":
case ".csproj.user":
case ".dita":
case ".ditamap":
case ".dtd":
case ".dtml":
case ".fsproj":
case ".fxml":
case ".iml":
case ".isml":
case ".jmx":
case ".launch":
case ".menu":
case ".mxml":
case ".nuspec":
case ".opml":
case ".owl":
case ".proj":
case ".props":
case ".pt":
case ".publishsettings":
case ".pubxml":
case ".pubxml.user":
case ".rdf":
case ".rng":
case ".rss":
case ".shproj":
case ".storyboard":
case ".svg":
case ".targets":
case ".tld":
case ".tmx":
case ".vbproj":
case ".vbproj.user":
case ".vcxproj":
case ".vcxproj.filters":
case ".wsdl":
case ".wxi":
case ".wxl":
case ".wxs":
case ".xaml":
case ".xbl":
case ".xib":
case ".xlf":
case ".xliff":
case ".xpdl":
case ".xul":
case ".xoml": return "xml";
case ".yaml":
case "eyaml":
case "eyml":
case ".yml": return "yaml";
}
return "plaintext";
}
/**
* Create a URI from a file path
* @param filePath the filepath a URI should be created from
* @return a URI format for the file based on its provided path
*/
public fileToURI(filePath : string) : string
{
if (typeof filePath !== 'string') {
throw new Error('Expected a string');
}
let path = require('path');
var pathName = path.resolve(filePath).replace(/\\/g, '/');
// Windows drive letter must be prefixed with a slash
if (pathName[0] !== '/') {
pathName = '/' + pathName;
}
return encodeURI('file://' + pathName);
};
} | the_stack |
import * as chai from 'chai';
import chaiHttp = require('chai-http');
import {TestHelper} from '../TestHelper';
import {FixtureUtils} from '../../fixtures/FixtureUtils';
import {Notification} from '../../src/models/Notification';
import {IUser} from '../../../shared/models/IUser';
import {User, IUserModel} from '../../src/models/User';
import {ICourseModel} from '../../src/models/Course';
import {Lecture} from '../../src/models/Lecture';
import {API_NOTIFICATION_TYPE_ALL_CHANGES, API_NOTIFICATION_TYPE_NONE, NotificationSettings} from '../../src/models/NotificationSettings';
import {errorCodes} from '../../src/config/errorCodes';
chai.use(chaiHttp);
const should = chai.should();
const BASE_URL = '/api/notification';
const testHelper = new TestHelper(BASE_URL);
/**
* Common setup function for the notification creation (POST) routes.
*/
async function preparePostSetup() {
const course = await FixtureUtils.getRandomCourse();
const student = course.students[Math.floor(Math.random() * course.students.length)];
const teacher = await FixtureUtils.getRandomTeacherForCourse(course);
return {course, student, teacher};
}
/**
* Common setup function for the notification creation (POST) routes with a changed course.
*/
async function preparePostChangedCourseSetup(active: boolean = true) {
const setup = await preparePostSetup();
const {course} = setup;
course.active = active;
await course.save();
const newNotification = {
targetId: course.id,
targetType: 'course',
text: 'test text'
};
return {...setup, newNotification};
}
/**
* Common setup function for the notification creation (POST) routes with invalid targetId.
*/
async function preparePostNotFoundSetup(targetType: string) {
const setup = await preparePostSetup();
const newNotification = {
targetType,
targetId: '000000000000000000000000',
text: 'test text'
};
return {...setup, newNotification};
}
/**
* Function that is given a student and returns a urlPostfix string for the commonUserPostRequest.
*/
type PostUrlPostfixAssembler = (student: IUser) => string;
/**
* 'should respond with 400 for an invalid targetType'
*/
async function invalidTargetTypePostTest(urlPostfixAssembler: PostUrlPostfixAssembler) {
const {student, teacher, newNotification} = await preparePostChangedCourseSetup();
newNotification.targetType = 'some-invalid-targetType';
const res = await testHelper.commonUserPostRequest(teacher, urlPostfixAssembler(student), newNotification);
res.status.should.be.equal(400);
res.body.message.should.be.equal(errorCodes.notification.invalidTargetType.text);
}
/**
* 'should respond with 404 for an invalid course/lecture/unit id target'
*/
async function notFoundPostTest(targetType: string, urlPostfixAssembler: PostUrlPostfixAssembler) {
const {teacher, student, newNotification} = await preparePostNotFoundSetup(targetType);
const res = await testHelper.commonUserPostRequest(teacher, urlPostfixAssembler(student), newNotification);
res.status.should.be.equal(404);
}
function addCommonPostTests(urlPostfixAssembler: PostUrlPostfixAssembler) {
it('should respond with 404 for an invalid course id target', async () => {
await notFoundPostTest('course', urlPostfixAssembler);
});
it('should respond with 404 for an invalid lecture id target', async () => {
await notFoundPostTest('lecture', urlPostfixAssembler);
});
it('should respond with 404 for an invalid unit id target', async () => {
await notFoundPostTest('unit', urlPostfixAssembler);
});
it('should respond with 400 for an invalid targetType', async () => {
await invalidTargetTypePostTest(urlPostfixAssembler);
});
}
describe('Notifications', async () => {
beforeEach(async () => {
await testHelper.resetForNextTest();
});
describe(`POST ${BASE_URL}`, async () => {
/**
* For the PostNotifications route this can simply return '' without doing anything.
*/
function urlPostfixAssembler() {
return '';
}
it('should fail if text parameter is not given', async () => {
const {course, teacher} = await preparePostSetup();
const newNotification = {
targetId: course.id,
targetType: 'course'
};
const res = await testHelper.commonUserPostRequest(teacher, '', newNotification);
res.status.should.be.equal(400);
res.body.name.should.be.equal('ParamRequiredError');
});
it('should create notifications for students with the corresponding settings', async () => {
const {course, teacher, newNotification} = await preparePostChangedCourseSetup();
const res = await testHelper.commonUserPostRequest(teacher, '', newNotification);
res.status.should.be.equal(200);
should.equal(await Notification.countDocuments({changedCourse: course}), course.students.length, 'Notification count mismatch');
});
it('should not create notifications when the course is inactive', async () => {
const {course, teacher, newNotification} = await preparePostChangedCourseSetup(false);
const res = await testHelper.commonUserPostRequest(teacher, '', newNotification);
res.status.should.be.equal(200);
should.equal(await Notification.countDocuments({changedCourse: course}), 0, 'Notification count mismatch');
});
it('should forbid notification creation for an unauthorized teacher', async () => {
const {course, newNotification} = await preparePostChangedCourseSetup();
const unauthorizedTeacher = await FixtureUtils.getUnauthorizedTeacherForCourse(course);
const res = await testHelper.commonUserPostRequest(unauthorizedTeacher, '', newNotification);
res.status.should.be.equal(403);
});
addCommonPostTests(urlPostfixAssembler);
});
describe(`POST ${BASE_URL} user :id`, async () => {
/**
* For the PostNotification route this will use the given student to return /user/${student._id}.
*/
function urlPostfixAssembler(student: IUser) {
return `/user/${student._id}`;
}
interface IChangedCourseSuccessTest {
course: ICourseModel;
teacher: IUserModel;
student: IUser;
newNotification: any;
}
async function changedCourseSuccessTest ({course, teacher, student, newNotification}: IChangedCourseSuccessTest, expectedCount = 1) {
const res = await testHelper.commonUserPostRequest(teacher, `/user/${student._id}`, newNotification);
res.status.should.be.equal(200);
should.equal(await Notification.countDocuments({changedCourse: course}), expectedCount, 'Notification count mismatch');
}
it('should fail if required parameters are omitted', async () => {
const {teacher} = await preparePostSetup();
const res = await testHelper.commonUserPostRequest(teacher, '/user/507f191e810c19729de860ea', {});
res.status.should.be.equal(400);
res.body.name.should.be.equal('ParamRequiredError');
});
it('should fail if user not given', async () => {
const {course, teacher} = await preparePostSetup();
const newNotification = {
targetId: course.id,
targetType: 'course',
text: 'test text'
};
const res = await testHelper.commonUserPostRequest(teacher, '/user/507f191e810c19729de860ea', newNotification);
res.status.should.be.equal(404);
res.body.message.should.be.equal(errorCodes.notification.targetUserNotFound.text);
});
it('should create notifications for a student, with course-targetType & text', async () => {
await changedCourseSuccessTest(await preparePostChangedCourseSetup());
});
it('should create notifications for a student, with course-targetType & text, setting API_NOTIFICATION_TYPE_ALL_CHANGES', async () => {
const setup = await preparePostChangedCourseSetup();
await new NotificationSettings({
user: setup.student,
course: setup.course,
notificationType: API_NOTIFICATION_TYPE_ALL_CHANGES,
emailNotification: true
}).save();
await changedCourseSuccessTest(setup);
});
it('should create notifications for a student, with lecture-targetType & text', async () => {
const {course, student, teacher} = await preparePostChangedCourseSetup();
const lectureId = (await FixtureUtils.getRandomLectureFromCourse(course))._id;
const lecture = await Lecture.findById(lectureId);
lecture.name = 'New test name';
await lecture.save();
const newNotification = {
targetId: lecture.id,
targetType: 'lecture',
text: 'test text'
};
await changedCourseSuccessTest({course, student, teacher, newNotification});
});
it('should create notifications for a student, with unit-targetType & text', async () => {
const {course, student, teacher} = await preparePostChangedCourseSetup();
const lecture = await FixtureUtils.getRandomLectureFromCourse(course);
const unit = await FixtureUtils.getRandomUnitFromLecture(lecture);
unit.visible = true;
await unit.save();
const newNotification = {
targetId: unit.id,
targetType: 'unit',
text: 'test text'
};
await changedCourseSuccessTest({course, student, teacher, newNotification});
});
it('should create no notifications for a student, with unit-targetType & text, if the unit is invisible', async () => {
const {course, student, teacher} = await preparePostChangedCourseSetup();
const lecture = await FixtureUtils.getRandomLectureFromCourse(course);
const unit = await FixtureUtils.getRandomUnitFromLecture(lecture);
unit.visible = false;
await unit.save();
const newNotification = {
targetId: unit.id,
targetType: 'unit',
text: 'test text'
};
await changedCourseSuccessTest({course, student, teacher, newNotification}, 0);
});
it('should create notifications for a student, with course-targetType & text, setting API_NOTIFICATION_TYPE_NONE', async () => {
const setup = await preparePostChangedCourseSetup();
await new NotificationSettings({
user: setup.student,
course: setup.course,
notificationType: API_NOTIFICATION_TYPE_NONE,
emailNotification: false
}).save();
await changedCourseSuccessTest(setup);
});
it('should create notifications for a student, with text only', async () => {
const {student, teacher} = await preparePostSetup();
const newNotification = {
targetType: 'text',
text: 'test text'
};
const res = await testHelper.commonUserPostRequest(teacher, `/user/${student._id}`, newNotification);
res.status.should.be.equal(200);
should.equal(await Notification.countDocuments({user: student._id}), 1, 'Notification count mismatch');
});
it('should respond with 400 for requesting text only targetType without text', async () => {
const {student, teacher} = await preparePostSetup();
const newNotification = {
targetType: 'text'
};
const res = await testHelper.commonUserPostRequest(teacher, `/user/${student._id}`, newNotification);
res.status.should.be.equal(400);
res.body.message.should.be.equal(errorCodes.notification.textOnlyWithoutText.text);
});
it('should forbid notification creation for an unauthorized teacher', async () => {
const {course, student, newNotification} = await preparePostChangedCourseSetup();
const unauthorizedTeacher = await FixtureUtils.getUnauthorizedTeacherForCourse(course);
const res = await testHelper.commonUserPostRequest(unauthorizedTeacher, `/user/${student._id}`, newNotification);
res.status.should.be.equal(403);
});
addCommonPostTests(urlPostfixAssembler);
});
describe(`GET ${BASE_URL} user :id`, () => {
it('should return all notifications for one user', async () => {
const course = await FixtureUtils.getRandomCourse();
const student = await User.findById(course.students[0]);
await new Notification({
user: student,
changedCourse: course,
text: 'Tritratrulala'
}).save();
const res = await testHelper.commonUserGetRequest(student, '');
res.status.should.be.equal(200);
res.body.forEach((notification: any) => {
notification._id.should.be.a('string');
notification.text.should.be.a('string');
});
});
});
describe(`DELETE ${BASE_URL} :id`, () => {
it('should delete a notification', async () => {
const course = await FixtureUtils.getRandomCourse();
const students = await FixtureUtils.getRandomStudents(2, 5);
course.students = course.students.concat(students);
await course.save();
const newNotification = await new Notification({
user: students[0],
changedCourse: course,
text: 'Tritratrulala'
}).save();
const res = await testHelper.commonUserDeleteRequest(students[0], `/${newNotification._id}`);
res.status.should.be.equal(200);
const deletedNotification = await Notification.findById(newNotification._id);
should.not.exist(deletedNotification, 'Notification does still exist');
});
it('should respond with 404 for a notification id that doesn\'t belong to the user', async () => {
const course = await FixtureUtils.getRandomCourse();
const students = await FixtureUtils.getRandomStudents(2, 5);
const newNotification = await new Notification({
user: students[0],
changedCourse: course,
text: 'Tritratrulala'
}).save();
const res = await testHelper.commonUserDeleteRequest(students[1], `/${newNotification._id}`);
res.status.should.be.equal(404);
});
});
}); | the_stack |
import { URLExt } from '@jupyterlab/coreutils';
import {
Widget
} from "@phosphor/widgets";
import {
Dialog
} from "@jupyterlab/apputils";
import {
IDisposable, DisposableDelegate
} from '@phosphor/disposable';
import {
JupyterLab, JupyterLabPlugin, ILayoutRestorer
} from '@jupyterlab/application';
import {
ToolbarButton
} from '@jupyterlab/apputils';
import {
DocumentRegistry
} from '@jupyterlab/docregistry';
import {
NotebookPanel, INotebookModel
} from '@jupyterlab/notebook';
import {
PageConfig
} from '@jupyterlab/coreutils';
import { ServerConnection } from '@jupyterlab/services';
import { JobsWidget } from './jobs';
/**
* The plugin registration information.
*/
const buttonPlugin: JupyterLabPlugin<void> = {
activate: activateButton,
id: 'nova:button',
autoStart: true,
};
const jobsPlugin: JupyterLabPlugin<void> = {
activate: activateJobs,
id: 'nova:jobs',
autoStart: true,
requires: [ILayoutRestorer],
};
import { style } from 'typestyle'
export const iconStyle = style({
backgroundImage: 'var(--jp-nova-icon-train)',
backgroundRepeat: 'no-repeat',
backgroundSize: '16px'
})
/**
* A notebook widget extension that adds a button to the toolbar.
*/
export
class ButtonExtension implements DocumentRegistry.IWidgetExtension<NotebookPanel, INotebookModel> {
/**
* Create a new extension object.
*/
createNew(panel: NotebookPanel, context: DocumentRegistry.IContext<INotebookModel>): IDisposable {
let callback = () => {
let notebook_path = panel.context.contentsModel.path;
let notebook_path_array = notebook_path.split("/")
let notebook = notebook_path_array[notebook_path_array.length - 1]
let path_to_folder = PageConfig.getOption('serverRoot') + "/" + notebook_path
path_to_folder = path_to_folder.substring(0, path_to_folder.length - notebook.length);
let setting = ServerConnection.makeSettings();
let fullUrl = URLExt.join(setting.baseUrl, "nova");
const dialog = new Dialog({
title: 'Submit notebook',
body: new SubmitJobForm(),
focusNodeSelector: 'input',
buttons: [
Dialog.cancelButton(),
Dialog.okButton({label: 'SUBMIT'})
]
});
const result = dialog.launch();
result.then(result => {
if (typeof result.value != 'undefined' && result.value) {
let fullRequest = {
method: 'POST',
body: JSON.stringify(
{
"home_dir": PageConfig.getOption('serverRoot'),
"dir": path_to_folder,
"notebook": notebook,
"gpu_count": result.value["gpu_count"],
"gpu_type": result.value["gpu_type"],
"instance_type": result.value["instance_type"],
"local": result.value["local"],
"parameter": result.value["parameter"]
}
)
};
ServerConnection.makeRequest(fullUrl, fullRequest, setting);
console.log(result.value);
}
dialog.dispose();
});
};
let button = new ToolbarButton({
className: 'backgroundTraining',
iconClassName: iconStyle + ' jp-Icon jp-Icon-16 jp-ToolbarButtonComponent-icon',
onClick: callback,
tooltip: 'Submit for background training.'
});
panel.toolbar.insertItem(0, 'trainOnBackground', button);
return new DisposableDelegate(() => {
button.dispose();
});
}
}
function activateButton( app: JupyterLab) {
console.log('JupyterLab nova button extension is activated!');
app.docRegistry.addWidgetExtension('Notebook', new ButtonExtension());
}
/**
* Activate the extension.
*/
function activateJobs(
app: JupyterLab,
restorer: ILayoutRestorer
): void {
console.log('JupyterLab nova jobs extension is activated!');
let sidePanel = new JobsWidget();
sidePanel.id = 'jp-nova-jobs'
sidePanel.title.iconClass = 'jp-FolderIcon jp-SideBar-tabIcon';
sidePanel.title.caption = 'Background Jobs';
if (restorer) {
restorer.add(sidePanel, 'background-jobs');
}
app.shell.addToLeftArea(sidePanel, {rank: 453} );
};
class SubmitJobForm extends Widget {
/**
* Create a redirect form.
*/
constructor() {
super({node: SubmitJobForm.createFormNode()});
}
private static createFormNode(): HTMLElement {
const node = document.createElement('div');
const text = document.createElement('span');
const instanceTypeInput = document.createElement('input');
const gpuTypeInput = document.createElement('input');
const gpuCountInput = document.createElement('input');
const parameterInput = document.createElement('input');
const instanceTypeLabel = document.createElement('span');
const gpuTypeLabel = document.createElement('span');
const gpuCountLabel = document.createElement('span');
const trainingTypeLabel = document.createElement('span');
const parameterLabel = document.createElement('span');
gpuTypeLabel.textContent = 'Enter GPU type';
gpuCountLabel.textContent = 'Select GPU count';
instanceTypeLabel.textContent = 'Select instance type';
trainingTypeLabel.textContent = 'Select training target';
parameterLabel.textContent = 'Notebook parameters (optional)'
gpuTypeInput.placeholder = "t4";
gpuTypeInput.setAttribute("id", "gpuTypeInput");
instanceTypeInput.placeholder = "n1-standard-8";
instanceTypeInput.setAttribute("id", "instanceTypeInput");
gpuCountInput.placeholder = "0";
gpuCountInput.setAttribute("id", "gpuCountInput");
parameterInput.placeholder = "";
parameterInput.setAttribute("id", "parameterInput");
var setParameterBox = document.createElement('input');
setParameterBox.type = 'text';
setParameterBox.id = "parameterInput";
var instanceTypes = [
"n1-standard-1",
"n1-standard-2",
"n1-standard-4",
"n1-standard-8",
"n1-standard-16",
"n1-standard-32",
"n1-standard-64",
"n1-standard-96"
];
var selectInstanceTypeList = document.createElement("select");
selectInstanceTypeList.id = "instanceTypeInput";
for (var i = 0; i < instanceTypes.length; i++) {
var option = document.createElement("option");
option.value = instanceTypes[i];
option.text = instanceTypes[i];
selectInstanceTypeList.appendChild(option);
}
selectInstanceTypeList.value = "n1-standard-4";
var selectGpuList = document.createElement("select");
selectGpuList.id = "gpuTypeInput";
var k80_counts = ["1", "2", "4", "8"];
var selectGpuCount = document.createElement("select");
selectGpuCount.id = "gpuCountInput";
for (var i = 0; i < k80_counts.length; i++) {
var option = document.createElement("option");
option.value = k80_counts[i];
option.text = k80_counts[i];
selectGpuCount.appendChild(option);
}
function update_gpu_count() {
let instance_types_per_gpu_type_per_count: {[key: string]: {[key: string]: string[]}} = {
"k80": {
"1": [
"n1-standard-1",
"n1-standard-2",
"n1-standard-4",
"n1-standard-8"],
"2": [
"n1-standard-1",
"n1-standard-2",
"n1-standard-4",
"n1-standard-8",
"n1-standard-16"],
"4": [
"n1-standard-1",
"n1-standard-2",
"n1-standard-4",
"n1-standard-8",
"n1-standard-16",
"n1-standard-32"],
"8": [
"n1-standard-1",
"n1-standard-2",
"n1-standard-4",
"n1-standard-8",
"n1-standard-16",
"n1-standard-32",
"n1-standard-64"]},
"p4": {
"1": [
"n1-standard-1",
"n1-standard-2",
"n1-standard-4",
"n1-standard-8",
"n1-standard-16"],
"2": [
"n1-standard-1",
"n1-standard-2",
"n1-standard-4",
"n1-standard-8",
"n1-standard-16",
"n1-standard-32"],
"4": [
"n1-standard-1",
"n1-standard-2",
"n1-standard-4",
"n1-standard-8",
"n1-standard-16",
"n1-standard-32",
"n1-standard-64",
"n1-standard-96"]},
"t4": {
"1": [
"n1-standard-1",
"n1-standard-2",
"n1-standard-4",
"n1-standard-8",
"n1-standard-16"],
"2": [
"n1-standard-1",
"n1-standard-2",
"n1-standard-4",
"n1-standard-8",
"n1-standard-16",
"n1-standard-32"],
"4": [
"n1-standard-1",
"n1-standard-2",
"n1-standard-4",
"n1-standard-8",
"n1-standard-16",
"n1-standard-32",
"n1-standard-64",
"n1-standard-96"]
},
"p100": {
"1": [
"n1-standard-1",
"n1-standard-2",
"n1-standard-4",
"n1-standard-8",
"n1-standard-16"],
"2": [
"n1-standard-1",
"n1-standard-2",
"n1-standard-4",
"n1-standard-8",
"n1-standard-16",
"n1-standard-32"],
"4": [
"n1-standard-1",
"n1-standard-2",
"n1-standard-4",
"n1-standard-8",
"n1-standard-16",
"n1-standard-32",
"n1-standard-64"]},
"v100": {
"1": [
"n1-standard-1",
"n1-standard-2",
"n1-standard-4",
"n1-standard-8"],
"2": [
"n1-standard-1",
"n1-standard-2",
"n1-standard-4",
"n1-standard-8",
"n1-standard-16"],
"4": [
"n1-standard-1",
"n1-standard-2",
"n1-standard-4",
"n1-standard-8",
"n1-standard-16",
"n1-standard-32"],
"8": [
"n1-standard-1",
"n1-standard-2",
"n1-standard-4",
"n1-standard-8",
"n1-standard-16",
"n1-standard-32",
"n1-standard-64",
"n1-standard-96"]}
}
let gpu_type_to_counts: {[key: string]: string[]} = {
"k80": ["1", "2", "4", "8"],
"p4": ["1", "2", "4"],
"t4": ["1", "2", "4"],
"p100": ["1", "2", "4"],
"v100": ["1", "2", "4", "8"]
}
let gpu_type = selectGpuList.value;
if (gpu_type == "N/A") {
selectGpuCount.hidden = true;
gpuCountLabel.hidden = true;
return;
}
selectGpuCount.hidden = false;
gpuCountLabel.hidden = false;
let gpu_counts = gpu_type_to_counts[gpu_type];
while (selectGpuCount.firstChild) {
selectGpuCount.removeChild(selectGpuCount.firstChild);
}
for (var i = 0; i < gpu_counts.length; i++) {
var option = document.createElement("option");
option.value = gpu_counts[i];
option.text = gpu_counts[i];
selectGpuCount.appendChild(option);
}
function on_gpu_count_change() {
var gpu_cout = selectGpuCount.value;
var instance_types = instance_types_per_gpu_type_per_count[gpu_type][gpu_cout];
var curren_instance_type = selectInstanceTypeList.value;
while (selectInstanceTypeList.firstChild) {
selectInstanceTypeList.removeChild(selectInstanceTypeList.firstChild);
}
for (var i = 0; i < instance_types.length; i++) {
var option = document.createElement("option");
option.value = instance_types[i];
option.text = instance_types[i];
selectInstanceTypeList.appendChild(option);
}
if (instance_types.indexOf(curren_instance_type) > -1) {
selectInstanceTypeList.value = curren_instance_type;
}
}
selectGpuCount.onchange = on_gpu_count_change;
}
selectGpuList.onchange = update_gpu_count;
var trainingTargets = [
"gce",
// "local" - local trainig is not yet supported and should be reanabled as soon as it is working.
]
var trainingTypeInput = document.createElement("select");
trainingTypeInput.id = "trainingTypeInput";
for (var i = 0; i < trainingTargets.length; i++) {
var option = document.createElement("option");
option.value = trainingTargets[i];
option.text = trainingTargets[i];
trainingTypeInput.appendChild(option);
}
function change_training_type() {
var trainingType = trainingTypeInput.value;
if (trainingType == "local") {
selectGpuCount.hidden = true;
gpuCountLabel.hidden = true;
selectGpuList.hidden = true;
gpuTypeLabel.hidden = true;
selectInstanceTypeList.hidden = true;
instanceTypeLabel.hidden = true;
} else {
selectGpuList.hidden = false;
gpuTypeLabel.hidden = false;
selectInstanceTypeList.hidden = false;
instanceTypeLabel.hidden = false;
update_gpu_count();
}
}
trainingTypeInput.onchange = change_training_type;
selectGpuCount.hidden = true;
gpuCountLabel.hidden = true;
selectGpuList.hidden = false;
gpuTypeLabel.hidden = false;
selectInstanceTypeList.hidden = false;
instanceTypeLabel.hidden = false;
parameterLabel.hidden = false;
setParameterBox.hidden = false;
node.className = 'jp-RedirectForm';
text.textContent = 'Enter configuratio for the background training';
node.appendChild(trainingTypeLabel);
node.appendChild(trainingTypeInput);
node.appendChild(instanceTypeLabel);
node.appendChild(selectInstanceTypeList);
node.appendChild(gpuTypeLabel);
node.appendChild(selectGpuList);
node.appendChild(gpuCountLabel);
node.appendChild(selectGpuCount);
node.appendChild(parameterLabel);
node.appendChild(setParameterBox);
let setting = ServerConnection.makeSettings();
let fullUrl = URLExt.join(setting.baseUrl, "nova");
let fullRequest = {
method: 'GET'
};
ServerConnection.makeRequest(fullUrl, fullRequest, setting).then(response => {
response.text().then(function processText(region: string) {
console.info("\"" + region + "\"");
let gpu_type_per_region: {[key: string]: string[]} = {
"asia-east1-a": ["k80"],
"asia-east1-b": ["k80"],
"asia-east1-c": ["v100"],
"asia-northeast1-a": ["t4"],
"asia-south1-b": ["t4"],
"asia-southeast1-b": ["t4", "p4"],
"asia-southeast1-c": ["p4"],
"australia-southeast1-a": ["p4"],
"australia-southeast1-b": ["p4"],
"europe-west1-b": ["k80"],
"europe-west1-d": ["k80"],
"europe-west4-a": ["v100"],
"europe-west4-b": ["t4", "p4", "v100"],
"europe-west4-c": ["t4", "p4", "v100"],
"southamerica-east1-c": ["t4"],
"northamerica-northeast1-a": ["p4"],
"northamerica-northeast1-b": ["p4"],
"northamerica-northeast1-c": ["p4"],
"us-central1-a": ["t4", "p4", "v100", "k80"],
"us-central1-b": ["t4", "v100"],
"us-central1-c": ["p4", "k80"],
"us-central1-f": ["v100"],
"us-east1-c": ["t4", "k80"],
"us-east1-d": ["t4", "k80"],
"us-east4-a": ["p4"],
"us-east4-b": ["p4"],
"us-east4-c": ["p4"],
"us-west1-a": ["t4", "v100", "k80"],
"us-west1-b": ["t4", "v100", "k80"],
"us-west2-b": ["p4"],
"us-west2-c": ["p4"]
};
console.info(gpu_type_per_region);
console.info(gpu_type_per_region[region]);
var gpus = gpu_type_per_region[region];
gpus.push("N/A");
console.info(gpus);
while (selectGpuList.firstChild) {
selectGpuList.removeChild(selectGpuList.firstChild);
}
for (var i = 0; i < gpus.length; i++) {
var option = document.createElement("option");
option.value = gpus[i];
option.text = gpus[i];
selectGpuList.appendChild(option);
}
selectGpuList.value = "N/A";
});
});
return node;
}
getValue(): {gpu_type: string, gpu_count: number, instance_type: string, local:boolean, parameter:string} {
return {
"gpu_type": (<HTMLInputElement>this.node.querySelector('#gpuTypeInput')).value,
"gpu_count": +(<HTMLInputElement>this.node.querySelector('#gpuCountInput')).value,
"instance_type": (<HTMLInputElement>this.node.querySelector('#instanceTypeInput')).value,
"local": (<HTMLInputElement>this.node.querySelector('#trainingTypeInput')).value == "local",
"parameter": (<HTMLInputElement>this.node.querySelector('#parameterInput')).value
};
}
}
/**
* Export the plugin as default.
*/
export default [buttonPlugin, jobsPlugin]; | the_stack |
import { DefinitionProvider, TextDocument, Position, CancellationToken, DefinitionLink, Uri, Range, workspace, WorkspaceConfiguration } from "vscode";
import { objectReferencePatterns, ReferencePattern, Component } from "../entities/component";
import { componentPathToUri, getComponent, searchAllFunctionNames } from "./cachedEntities";
import { Scope, getValidScopesPrefixPattern, getVariableScopePrefixPattern, unscopedPrecedence } from "../entities/scope";
import { UserFunction, UserFunctionSignature, Argument, getLocalVariables, getFunctionFromPrefix } from "../entities/userFunction";
import { Property } from "../entities/property";
import { equalsIgnoreCase } from "../utils/textUtil";
import { Variable, parseVariableAssignments, getApplicationVariables, getServerVariables } from "../entities/variable";
import { DocumentPositionStateContext, getDocumentPositionStateContext } from "../utils/documentUtil";
import { SearchMode } from "../utils/collections";
import { getFunctionSuffixPattern } from "../entities/function";
export default class CFMLDefinitionProvider implements DefinitionProvider {
public async provideDefinition(document: TextDocument, position: Position, _token: CancellationToken): Promise<DefinitionLink[]> {
const cfmlDefinitionSettings: WorkspaceConfiguration = workspace.getConfiguration("cfml.definition", document.uri);
if (!cfmlDefinitionSettings.get<boolean>("enable", true)) {
return null;
}
const documentPositionStateContext: DocumentPositionStateContext = getDocumentPositionStateContext(document, position);
if (documentPositionStateContext.positionInComment) {
return null;
}
const results: DefinitionLink[] = [];
const docIsCfcFile: boolean = documentPositionStateContext.isCfcFile;
const docIsCfmFile: boolean = documentPositionStateContext.isCfmFile;
const documentText: string = documentPositionStateContext.sanitizedDocumentText;
let wordRange: Range = document.getWordRangeAtPosition(position);
const currentWord: string = documentPositionStateContext.currentWord;
const lowerCurrentWord: string = currentWord.toLowerCase();
if (!wordRange) {
wordRange = new Range(position, position);
}
const docPrefix: string = documentPositionStateContext.docPrefix;
// TODO: These references should ideally be in cachedEntities.
let referenceMatch: RegExpExecArray | null;
objectReferencePatterns.forEach((element: ReferencePattern) => {
const pattern: RegExp = element.pattern;
while ((referenceMatch = pattern.exec(documentText))) {
const path: string = referenceMatch[element.refIndex];
const offset: number = referenceMatch.index + referenceMatch[0].lastIndexOf(path);
const pathRange = new Range(
document.positionAt(offset),
document.positionAt(offset + path.length)
);
if (pathRange.contains(position)) {
const componentUri: Uri = componentPathToUri(path, document.uri);
if (componentUri) {
const comp: Component = getComponent(componentUri);
if (comp) {
results.push({
originSelectionRange: pathRange,
targetUri: comp.uri,
targetRange: comp.declarationRange,
targetSelectionRange: comp.declarationRange
});
}
}
}
}
});
if (docIsCfcFile) {
const thisComponent: Component = documentPositionStateContext.component;
if (thisComponent) {
// Extends
if (thisComponent.extendsRange && thisComponent.extendsRange.contains(position)) {
const extendsComp: Component = getComponent(thisComponent.extends);
if (extendsComp) {
results.push({
originSelectionRange: thisComponent.extendsRange,
targetUri: extendsComp.uri,
targetRange: extendsComp.declarationRange,
targetSelectionRange: extendsComp.declarationRange
});
}
}
// Implements
if (thisComponent.implementsRanges) {
thisComponent.implementsRanges.forEach((range: Range, idx: number) => {
if (range && range.contains(position)) {
const implComp: Component = getComponent(thisComponent.implements[idx]);
if (implComp) {
results.push({
originSelectionRange: range,
targetUri: implComp.uri,
targetRange: implComp.declarationRange,
targetSelectionRange: implComp.declarationRange
});
}
}
});
}
// Component functions (related)
thisComponent.functions.forEach((func: UserFunction) => {
// Function return types
if (func.returnTypeUri && func.returnTypeRange && func.returnTypeRange.contains(position)) {
const returnTypeComp: Component = getComponent(func.returnTypeUri);
if (returnTypeComp) {
results.push({
originSelectionRange: func.returnTypeRange,
targetUri: returnTypeComp.uri,
targetRange: returnTypeComp.declarationRange,
targetSelectionRange: returnTypeComp.declarationRange
});
}
}
// Argument types
func.signatures.forEach((signature: UserFunctionSignature) => {
signature.parameters.filter((arg: Argument) => {
return arg.dataTypeComponentUri && arg.dataTypeRange && arg.dataTypeRange.contains(position);
}).forEach((arg: Argument) => {
const argTypeComp: Component = getComponent(arg.dataTypeComponentUri);
if (argTypeComp) {
results.push({
originSelectionRange: arg.dataTypeRange,
targetUri: argTypeComp.uri,
targetRange: argTypeComp.declarationRange,
targetSelectionRange: argTypeComp.declarationRange
});
}
});
});
if (func.bodyRange && func.bodyRange.contains(position)) {
// Local variable uses
const localVariables = getLocalVariables(func, documentPositionStateContext, thisComponent.isScript);
const localVarPrefixPattern = getValidScopesPrefixPattern([Scope.Local], true);
if (localVarPrefixPattern.test(docPrefix)) {
localVariables.filter((localVar: Variable) => {
return position.isAfterOrEqual(localVar.declarationLocation.range.start) && equalsIgnoreCase(localVar.identifier, currentWord);
}).forEach((localVar: Variable) => {
results.push({
targetUri: localVar.declarationLocation.uri,
targetRange: localVar.declarationLocation.range,
targetSelectionRange: localVar.declarationLocation.range
});
});
}
// Argument uses
if (results.length === 0) {
const argumentPrefixPattern = getValidScopesPrefixPattern([Scope.Arguments], true);
if (argumentPrefixPattern.test(docPrefix)) {
func.signatures.forEach((signature: UserFunctionSignature) => {
signature.parameters.filter((arg: Argument) => {
return equalsIgnoreCase(arg.name, currentWord);
}).forEach((arg: Argument) => {
results.push({
targetUri: thisComponent.uri,
targetRange: arg.nameRange,
targetSelectionRange: arg.nameRange
});
});
});
}
}
}
});
// Component properties (declarations)
thisComponent.properties.filter((prop: Property) => {
return prop.dataTypeComponentUri !== undefined && prop.dataTypeRange.contains(position);
}).forEach((prop: Property) => {
const dataTypeComp: Component = getComponent(prop.dataTypeComponentUri);
if (dataTypeComp) {
results.push({
originSelectionRange: prop.dataTypeRange,
targetUri: dataTypeComp.uri,
targetRange: dataTypeComp.declarationRange,
targetSelectionRange: dataTypeComp.declarationRange
});
}
});
// Component variables
const variablesPrefixPattern = getValidScopesPrefixPattern([Scope.Variables], false);
if (variablesPrefixPattern.test(docPrefix)) {
thisComponent.variables.filter((variable: Variable) => {
return equalsIgnoreCase(variable.identifier, currentWord);
}).forEach((variable: Variable) => {
results.push({
targetUri: variable.declarationLocation.uri,
targetRange: variable.declarationLocation.range,
targetSelectionRange: variable.declarationLocation.range
});
});
}
}
} else if (docIsCfmFile) {
const docVariableAssignments: Variable[] = parseVariableAssignments(documentPositionStateContext, false);
const variableScopePrefixPattern: RegExp = getVariableScopePrefixPattern();
const variableScopePrefixMatch: RegExpExecArray = variableScopePrefixPattern.exec(docPrefix);
if (variableScopePrefixMatch) {
const validScope: string = variableScopePrefixMatch[1];
let currentScope: Scope;
if (validScope) {
currentScope = Scope.valueOf(validScope);
}
docVariableAssignments.filter((variable: Variable) => {
if (!equalsIgnoreCase(variable.identifier, currentWord)) {
return false;
}
if (currentScope) {
return (variable.scope === currentScope || (variable.scope === Scope.Unknown && unscopedPrecedence.includes(currentScope)));
}
return (unscopedPrecedence.includes(variable.scope) || variable.scope === Scope.Unknown);
}).forEach((variable: Variable) => {
results.push({
targetUri: variable.declarationLocation.uri,
targetRange: variable.declarationLocation.range,
targetSelectionRange: variable.declarationLocation.range
});
});
}
}
// User function
const userFunc: UserFunction = await getFunctionFromPrefix(documentPositionStateContext, lowerCurrentWord);
if (userFunc) {
results.push({
targetUri: userFunc.location.uri,
targetRange: userFunc.nameRange, // TODO: userFunc.location.range
targetSelectionRange: userFunc.nameRange
});
}
// Application variables
const applicationVariablesPrefixPattern = getValidScopesPrefixPattern([Scope.Application, Scope.Session, Scope.Request], false);
const variableScopePrefixMatch: RegExpExecArray = applicationVariablesPrefixPattern.exec(docPrefix);
if (variableScopePrefixMatch) {
const currentScope: string = Scope.valueOf(variableScopePrefixMatch[1]);
const applicationDocVariables: Variable[] = await getApplicationVariables(document.uri);
applicationDocVariables.filter((variable: Variable) => {
return variable.scope === currentScope && equalsIgnoreCase(variable.identifier, currentWord);
}).forEach((variable: Variable) => {
results.push({
targetUri: variable.declarationLocation.uri,
targetRange: variable.declarationLocation.range,
targetSelectionRange: variable.declarationLocation.range
});
});
}
// Server variables
const serverVariablesPrefixPattern = getValidScopesPrefixPattern([Scope.Server], false);
if (serverVariablesPrefixPattern.test(docPrefix)) {
const serverDocVariables: Variable[] = getServerVariables(document.uri);
serverDocVariables.filter((variable: Variable) => {
return variable.scope === Scope.Server && equalsIgnoreCase(variable.identifier, currentWord);
}).forEach((variable: Variable) => {
results.push({
targetUri: variable.declarationLocation.uri,
targetRange: variable.declarationLocation.range,
targetSelectionRange: variable.declarationLocation.range
});
});
}
// Search for function by name
if (results.length === 0 && documentPositionStateContext.isContinuingExpression && cfmlDefinitionSettings.get<boolean>("userFunctions.search.enable", false)) {
const wordSuffix: string = documentText.slice(document.offsetAt(wordRange.end), documentText.length);
const functionSuffixPattern: RegExp = getFunctionSuffixPattern();
if (functionSuffixPattern.test(wordSuffix)) {
const functionSearchResults = searchAllFunctionNames(lowerCurrentWord, SearchMode.EqualTo);
functionSearchResults.forEach((userFunc: UserFunction) => {
results.push({
targetUri: userFunc.location.uri,
targetRange: userFunc.nameRange, // TODO: userFunc.location.range
targetSelectionRange: userFunc.nameRange
});
});
}
}
return results;
}
} | the_stack |
import { LoggingDebugSession, Logger, logger, InitializedEvent, TerminatedEvent, StoppedEvent, OutputEvent, Thread, StackFrame, Scope, Source, Handles, DebugSession, Breakpoint } from 'vscode-debugadapter';
import { DebugProtocol } from 'vscode-debugprotocol';
import { Variable, Stack, VariableObject, MIError } from './backend/backend';
import { expandValue } from './backend/gdb_expansion';
import { MI2 } from './backend/flowcpp_runtime';
logger.setup(Logger.LogLevel.Verbose, true);
process.on("unhandledRejection", (error) => {
console.error(error); // This prints error with stack included (as for normal errors)
throw error; // Following best practices re-throw error and let the process exit with error code
});
process.on("uncaughtException", (error) => {
console.error(error); // This prints error with stack included (as for normal errors)
throw error; // Following best practices re-throw error and let the process exit with error code
});
export interface LaunchRequestArguments extends DebugProtocol.LaunchRequestArguments {
cwd: string;
target: string;
runner_path: string;
env: any;
debugger_args: string;
arguments: string;
autorun: string[];
print_calls: boolean;
showDevDebugOutput: boolean;
compiler: string;
}
// this is used to for stack handles - IDs for stack frames are within (0, 1000)
const STACK_HANDLES_START = 1000;
// this is used for variables
const VAR_HANDLES_START = 2000;
export class FlowDebugSession extends LoggingDebugSession {
protected variableHandles = new Handles<VariableObject>(VAR_HANDLES_START);
protected variableHandlesReverse: { [id: string]: number } = {};
protected StackFrames: Stack[] = [];
protected useVarObjects: boolean = true;
protected quit: boolean;
protected needContinue: boolean;
protected started: boolean;
protected crashed: boolean;
protected debugReady: boolean;
protected miDebugger: MI2;
protected threadID: number = 1;
protected debug : boolean;
private resetHandleMaps() {
this.variableHandles = new Handles<VariableObject>(VAR_HANDLES_START);
this.variableHandlesReverse = {};
}
public constructor(debuggerLinesStartAt1: boolean, isServer: boolean = false, threadID: number = 1) {
super("flow-debug.txt", debuggerLinesStartAt1, isServer);
this.threadID = threadID;
}
protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void {
response.body.supportsHitConditionalBreakpoints = true;
response.body.supportsConfigurationDoneRequest = true;
response.body.supportsConditionalBreakpoints = true;
response.body.supportsFunctionBreakpoints = true;
response.body.supportsEvaluateForHovers = true;
response.body.supportsDelayedStackTraceLoading = false;
//response.body.supportsSetVariable = true;
this.sendResponse(response);
}
protected initDebugger(debug : boolean) {
this.miDebugger.on("launcherror", this.launchError.bind(this));
this.miDebugger.on("quit", this.quitEvent.bind(this));
this.miDebugger.on("exited-normally", this.quitEvent.bind(this));
this.miDebugger.on("stopped", this.stopEvent.bind(this));
this.miDebugger.on("msg", this.handleMsg.bind(this));
if (debug) {
this.miDebugger.on("breakpoint", this.handleBreakpoint.bind(this));
this.miDebugger.on("step-end", this.handleBreak.bind(this));
this.miDebugger.on("step-out-end", this.handleBreak.bind(this));
this.miDebugger.on("signal-stop", this.handlePause.bind(this));
}
}
protected handleMsg(type: string, msg: string) {
if (type == "target")
type = "stdout";
if (type == "log")
type = "stderr";
this.sendEvent(new OutputEvent(msg, type));
}
protected handleBreakpoint() {
this.sendEvent(new StoppedEvent("breakpoint", this.threadID));
}
protected handleBreak() {
this.sendEvent(new StoppedEvent("step", this.threadID));
}
protected handlePause() {
this.sendEvent(new StoppedEvent("user request", this.threadID));
}
protected stopEvent() {
if (!this.started)
this.crashed = true;
if (!this.quit)
this.sendEvent(new StoppedEvent("exception", this.threadID));
}
protected quitEvent() {
this.quit = true;
this.sendEvent(new TerminatedEvent());
}
private getCompilerSwitch(compiler: string): string {
return "--" + compiler;
}
protected launchRequest(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments): void {
// make sure to 'Stop' the buffered logging if 'trace' is not set
//logger.setup(args.trace ? Logger.LogLevel.Verbose : Logger.LogLevel.Stop, false);
this.debug = !args.noDebug;
// defaults to flowc
let compiler = args.compiler || "flowc";
this.miDebugger = new MI2(args.runner_path || "flowcpp", this.debug,
[this.getCompilerSwitch(compiler)], [args.debugger_args], args.env);
this.initDebugger(this.debug);
this.quit = false;
this.needContinue = false;
this.started = false;
this.crashed = false;
this.debugReady = false;
this.miDebugger.printCalls = !!args.print_calls;
this.miDebugger.debugOutput = !!args.showDevDebugOutput;
this.miDebugger.load(args.cwd, args.target, args.arguments).then(() => {
if (args.autorun)
args.autorun.forEach(command => {
this.miDebugger.sendUserInput(command);
});
this.sendResponse(response);
this.sendEvent(new InitializedEvent());
// start the program in the runtime - in reality wait for configurationDone
this.miDebugger.start();
}, err => {
this.sendErrorResponse(response, 103, `Failed to load MI Debugger: ${err.toString()}`)
});
}
protected launchError(err: any) {
this.handleMsg("stderr", "Could not start debugger process, does the program exist in filesystem?\n");
this.handleMsg("stderr", err.toString() + "\n");
this.quitEvent();
}
protected disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments): void {
this.miDebugger.stop();
this.sendResponse(response);
}
protected async setVariableRequest(response: DebugProtocol.SetVariableResponse, args: DebugProtocol.SetVariableArguments): Promise<void> {
try {
if (this.useVarObjects) {
let name = args.name;
if (args.variablesReference >= VAR_HANDLES_START) {
const parent = this.variableHandles.get(args.variablesReference) as VariableObject;
name = `${parent.name}.${name}`;
}
let res = await this.miDebugger.varAssign(name, args.value);
response.body = {
value: res.result("value")
};
}
else {
await this.miDebugger.changeVariable(args.name, args.value);
response.body = {
value: args.value
};
}
this.sendResponse(response);
}
catch (err) {
this.sendErrorResponse(response, 11, `Could not continue: ${err}`);
};
}
protected setFunctionBreakPointsRequest(response: DebugProtocol.SetFunctionBreakpointsResponse, args: DebugProtocol.SetFunctionBreakpointsArguments): void {
this.debugReady = true;
let all = args.breakpoints.map(brk => this.miDebugger.addBreakPoint({ raw: brk.name, condition: brk.condition, countCondition: brk.hitCondition }));
Promise.all(all).then(brkpoints => {
response.body = {
breakpoints: brkpoints.map(brkp => new Breakpoint(brkp[0], brkp[1].line))
};
this.sendResponse(response);
}, msg => {
this.sendErrorResponse(response, 10, msg.toString());
});
}
protected setBreakPointsRequest(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments): void {
this.debugReady = true;
let running = this.miDebugger.isRunning();
this.miDebugger.clearBreakPoints().then(async () => {
let path = args.source.path;
let all = args.breakpoints.map(brk => this.miDebugger.addBreakPoint({ file: path, line: brk.line, condition: brk.condition, countCondition: brk.hitCondition }));
let brkpoints = await Promise.all(all);
if (running)
await this.miDebugger.continue();
response.body = {
breakpoints: brkpoints.map(brkp =>
new Breakpoint(brkp[0], brkp[0] ? brkp[1].line : undefined))
};
this.sendResponse(response);
}, msg => {
this.sendErrorResponse(response, 9, msg.toString());
});
}
protected threadsRequest(response: DebugProtocol.ThreadsResponse): void {
response.body = {
threads: [
new Thread(this.threadID, "Thread 1")
]
};
this.sendResponse(response);
}
// performs deep compare of two stacks
private compareStacks(s1: Stack[], s2: Stack[]) {
return (null == s1 && null == s2) ||
(s1 && s2 && s1.length == s2.length && s1.reduce(
(acc, s, i) => acc && (s.address == s2[i].address),
true));
}
protected stackTraceRequest(response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments): void {
// ignore requested stack depth and return the entire stack all the time - flowcpp does not have a way to
// give the number of stack frames without actually listing them all
this.miDebugger.getStack(0).then(async stack => {
let ret: StackFrame[] = stack.map(element => {
let file = element.file;
if (file) {
if (process.platform === "win32") {
if (file.startsWith("\\cygdrive\\") || file.startsWith("/cygdrive/")) {
file = file[10] + ":" + file.substr(11); // replaces /cygdrive/c/foo/bar.txt with c:/foo/bar.txt
}
}
return new StackFrame(element.level, element.function + "@" + element.address, new Source(element.fileName, file), element.line, 0);
}
else
return new StackFrame(element.level, element.function + "@" + element.address, null, element.line, 0);
});
// if changing stack frames, reset all var handles
if (!this.compareStacks(this.StackFrames, stack)) {
for (let varName in this.variableHandlesReverse) {
try {
await this.miDebugger.varDelete(varName);
} catch {
// it might crash with variable not existing - this is OK
}
}
this.resetHandleMaps();
}
this.StackFrames = stack;
response.body = {
stackFrames: ret
};
this.sendResponse(response);
}, err => {
this.sendErrorResponse(response, 12, `Failed to get Stack Trace: ${err.toString()}`)
});
}
protected configurationDoneRequest(response: DebugProtocol.ConfigurationDoneResponse, args: DebugProtocol.ConfigurationDoneArguments): void {
if (this.miDebugger)
this.miDebugger.emit("ui-break-done");
this.sendResponse(response);
}
protected scopesRequest(response: DebugProtocol.ScopesResponse, args: DebugProtocol.ScopesArguments): void {
// 2 handles - one for args, one for locals
const stackHandle = STACK_HANDLES_START + (parseInt(args.frameId as any) || 0) * 2;
response.body = {
scopes: [
new Scope("Locals", stackHandle + 1, false),
new Scope("Arguments", stackHandle, false),
]
};
this.sendResponse(response);
}
private createVariable(arg) {
return this.variableHandles.create(arg);
}
private findOrCreateVariable(varObj: VariableObject): number {
let id: number;
if (this.variableHandlesReverse.hasOwnProperty(varObj.name)) {
id = this.variableHandlesReverse[varObj.name];
}
else {
id = this.createVariable(varObj);
this.variableHandlesReverse[varObj.name] = id;
}
return varObj.isCompound() ? id : 0;
};
protected async variablesRequest(response: DebugProtocol.VariablesResponse, args: DebugProtocol.VariablesArguments): Promise<void> {
const variables: DebugProtocol.Variable[] = [];
if (args.variablesReference < VAR_HANDLES_START) {
const id = args.variablesReference - STACK_HANDLES_START;
let stack: Variable[];
try {
const args = id % 2 == 0;
const frameNum = Math.floor(id / 2);
stack = await this.miDebugger.getStackVariables(this.threadID, frameNum, args);
for (const variable of stack) {
if (this.useVarObjects) {
try {
let varObjName = `var_${frameNum}_${variable.name}`;
let varObj: VariableObject;
try {
const changes = await this.miDebugger.varUpdate(varObjName);
const changelist = changes.result("changelist");
changelist.forEach((change) => {
const vId = this.variableHandlesReverse[varObjName];
const v = this.variableHandles.get(vId) as any;
v.applyChanges(change);
});
const varId = this.variableHandlesReverse[varObjName];
varObj = this.variableHandles.get(varId) as any;
}
catch (err) {
if (err instanceof MIError && err.message.startsWith("No such var:")) {
varObj = await this.miDebugger.varCreate(variable.name, frameNum, varObjName);
const varId = this.findOrCreateVariable(varObj);
varObj.exp = variable.name;
varObj.id = varId;
}
else {
throw err;
}
}
variables.push(varObj.toProtocolVariable());
}
catch (err) {
variables.push({
name: variable.name,
value: `<${err}>`,
variablesReference: 0
});
}
}
}
response.body = {
variables: variables
};
this.sendResponse(response);
}
catch (err) {
this.sendErrorResponse(response, 1, `Could not expand variable: ${err}`);
}
}
else {
const varObj = this.variableHandles.get(args.variablesReference);
try {
// Variable members
const children = await this.miDebugger.varListChildren(varObj.name);
const vars = children.map(child => {
const varId = this.findOrCreateVariable(child);
child.id = varId;
return child.toProtocolVariable();
});
response.body = {
variables: vars
}
this.sendResponse(response);
}
catch (err) {
this.sendErrorResponse(response, 1, `Could not expand variable: ${err}`);
}
}
}
protected pauseRequest(response: DebugProtocol.ContinueResponse, args: DebugProtocol.ContinueArguments): void {
this.miDebugger.interrupt().then(() => {
this.sendResponse(response);
}, msg => {
this.sendErrorResponse(response, 3, `Could not pause: ${msg}`);
});
}
protected continueRequest(response: DebugProtocol.ContinueResponse, args: DebugProtocol.ContinueArguments): void {
this.miDebugger.continue().then(() => {
this.sendResponse(response);
}, msg => {
this.sendErrorResponse(response, 2, `Could not continue: ${msg}`);
});
}
protected stepInRequest(response: DebugProtocol.NextResponse, args: DebugProtocol.NextArguments): void {
this.miDebugger.step().then(() => {
this.sendResponse(response);
}, msg => {
this.sendErrorResponse(response, 4, `Could not step in: ${msg}`);
});
}
protected stepOutRequest(response: DebugProtocol.NextResponse, args: DebugProtocol.NextArguments): void {
this.miDebugger.stepOut().then(() => {
this.sendResponse(response);
}, msg => {
this.sendErrorResponse(response, 5, `Could not step out: ${msg}`);
});
}
protected nextRequest(response: DebugProtocol.NextResponse, args: DebugProtocol.NextArguments): void {
this.miDebugger.next().then(() => {
this.sendResponse(response);
}, msg => {
this.sendErrorResponse(response, 6, `Could not step over: ${msg}`);
});
}
protected evaluateRequest(response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments): void {
if (args.context == "watch" || args.context == "hover")
this.miDebugger.evalExpression(args.expression).then((res) => {
response.body = {
variablesReference: 0,
result: res.result("value")
}
this.sendResponse(response);
}, msg => {
this.sendErrorResponse(response, 7, msg.toString());
});
else {
this.miDebugger.sendUserInput(args.expression).then(output => {
if (typeof output == "undefined")
response.body = {
result: "",
variablesReference: 0
};
else
response.body = {
result: JSON.stringify(output),
variablesReference: 0
};
this.sendResponse(response);
}, msg => {
this.sendErrorResponse(response, 8, msg.toString());
});
}
}
}
function prettyStringArray(strings) {
if (typeof strings == "object") {
if (strings.length !== undefined)
return strings.join(", ");
else
return JSON.stringify(strings);
}
else return strings;
}
DebugSession.run(FlowDebugSession); | the_stack |
import {
ComponentSet,
FileProperties,
MetadataApiRetrieve,
RetrieveResult,
SourceComponent
} from '@salesforce/source-deploy-retrieve';
import { RecompositionState } from '@salesforce/source-deploy-retrieve/lib/src/convert/convertContext';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as shell from 'shelljs';
import * as vscode from 'vscode';
import { RetrieveExecutor } from '../commands/baseDeployRetrieve';
import { SfdxPackageDirectories } from '../sfdxProject';
import { getRootWorkspacePath } from '../util';
export interface MetadataContext {
baseDirectory: string;
commonRoot: string;
components: SourceComponent[];
}
export const enum PathType {
Folder = 'folder',
Individual = 'individual',
Manifest = 'manifest',
Unknown = 'unknown'
}
export interface MetadataCacheResult {
selectedPath: string;
selectedType: PathType;
cachePropPath?: string;
cache: MetadataContext;
project: MetadataContext;
properties: FileProperties[];
}
export interface CorrelatedComponent {
cacheComponent: SourceComponent;
projectComponent: SourceComponent;
lastModifiedDate: string;
}
interface RecomposedComponent {
component?: SourceComponent;
children: Map<string, SourceComponent>;
}
export class MetadataCacheService {
private static CACHE_FOLDER = ['.sfdx', 'diff'];
private static PROPERTIES_FOLDER = ['prop'];
private static PROPERTIES_FILE = 'file-props.json';
private username: string;
private cachePath: string;
private componentPath?: string;
private projectPath?: string;
private isManifest: boolean = false;
private sourceComponents: ComponentSet;
public constructor(username: string) {
this.username = username;
this.sourceComponents = new ComponentSet();
this.cachePath = this.makeCachePath(username);
}
/**
* Specify the base project path and a component path that will define the metadata to cache for the project.
*
* @param componentPath A path referring to a project folder or an individual component resource
* @param projectPath The base path of an sfdx project
*/
public initialize(
componentPath: string,
projectPath: string,
isManifest: boolean = false
): void {
this.componentPath = componentPath;
this.projectPath = projectPath;
this.isManifest = isManifest;
}
/**
* Load a metadata cache based on a project path that defines a set of components.
*
* @param componentPath A path referring to a project folder, an individual component resource
* or a manifest file
* @param projectPath The base path of an sfdx project
* @param isManifest Whether the componentPath references a manifest file
* @returns MetadataCacheResult describing the project and cache folders
*/
public async loadCache(
componentPath: string,
projectPath: string,
isManifest: boolean = false
): Promise<MetadataCacheResult | undefined> {
this.initialize(componentPath, projectPath, isManifest);
const components = await this.getSourceComponents();
const operation = await this.createRetrieveOperation(components);
const results = await operation.pollStatus();
return this.processResults(results);
}
public async getSourceComponents(): Promise<ComponentSet> {
if (this.componentPath && this.projectPath) {
const packageDirs = await SfdxPackageDirectories.getPackageDirectoryFullPaths();
this.sourceComponents = this.isManifest
? await ComponentSet.fromManifest({
manifestPath: this.componentPath,
resolveSourcePaths: packageDirs,
forceAddWildcards: true
})
: ComponentSet.fromSource(this.componentPath);
return this.sourceComponents;
}
return new ComponentSet();
}
public async createRetrieveOperation(
comps?: ComponentSet
): Promise<MetadataApiRetrieve> {
const components = comps || (await this.getSourceComponents());
this.clearDirectory(this.cachePath, true);
const operation = components.retrieve({
usernameOrConnection: this.username,
output: this.cachePath,
merge: false
});
return operation;
}
public async processResults(
result: RetrieveResult | undefined
): Promise<MetadataCacheResult | undefined> {
if (!result) {
return;
}
const { components, properties } = this.extractResults(result);
if (components.length > 0 && this.componentPath && this.projectPath) {
const propsFile = this.saveProperties(properties);
const cacheCommon = this.findLongestCommonDir(components, this.cachePath);
const sourceComps = this.sourceComponents.getSourceComponents().toArray();
const projCommon = this.findLongestCommonDir(
sourceComps,
this.projectPath
);
let selectedType = PathType.Unknown;
if (
fs.existsSync(this.componentPath) &&
fs.lstatSync(this.componentPath).isDirectory()
) {
selectedType = PathType.Folder;
} else if (this.isManifest) {
selectedType = PathType.Manifest;
} else {
selectedType = PathType.Individual;
}
return {
selectedPath: this.componentPath,
selectedType,
cache: {
baseDirectory: this.cachePath,
commonRoot: cacheCommon,
components
},
cachePropPath: propsFile,
project: {
baseDirectory: this.projectPath,
commonRoot: projCommon,
components: sourceComps
},
properties
};
}
}
private extractResults(
result: RetrieveResult
): { components: SourceComponent[]; properties: FileProperties[] } {
const properties: FileProperties[] = [];
if (Array.isArray(result.response.fileProperties)) {
properties.push(...result.response.fileProperties);
} else {
properties.push(result.response.fileProperties);
}
const components = result.components.getSourceComponents().toArray();
return { components, properties };
}
private findLongestCommonDir(
comps: SourceComponent[],
baseDir: string
): string {
if (comps.length === 0) {
return '';
}
if (comps.length === 1) {
return this.getRelativePath(comps[0], baseDir);
}
const allPaths = comps.map(c => this.getRelativePath(c, baseDir));
const baseline = allPaths[0];
let shortest = baseline.length;
for (let whichPath = 1; whichPath < allPaths.length; whichPath++) {
const sample = allPaths[whichPath];
shortest = Math.min(shortest, sample.length);
for (let comparePos = 0; comparePos < shortest; comparePos++) {
if (baseline[comparePos] !== sample[comparePos]) {
shortest = comparePos;
break;
}
}
}
const dir = baseline.substring(0, shortest);
return dir.endsWith(path.sep) ? dir.slice(0, -path.sep.length) : dir;
}
private saveProperties(properties: FileProperties[]): string {
const props = {
componentPath: this.componentPath,
fileProperties: properties
};
const propDir = this.getPropsPath();
const propsFile = path.join(propDir, MetadataCacheService.PROPERTIES_FILE);
fs.mkdirSync(propDir);
fs.writeFileSync(propsFile, JSON.stringify(props));
return propsFile;
}
private getRelativePath(comp: SourceComponent, baseDir: string): string {
const compPath = comp.content || comp.xml;
if (compPath) {
const compDir = path.dirname(compPath);
return compDir.substring(baseDir.length + path.sep.length);
}
return '';
}
/**
* Groups the information in a MetadataCacheResult by component.
* Child components are returned as an array entry unless their parent is present.
* @param result A MetadataCacheResult
* @returns An array with one entry per retrieved component, with all corresponding information about the component included
*/
public static correlateResults(result: MetadataCacheResult): CorrelatedComponent[] {
const components: CorrelatedComponent[] = [];
const projectIndex = new Map<string, RecomposedComponent>();
this.pairParentsAndChildren(projectIndex, result.project.components);
const cacheIndex = new Map<string, RecomposedComponent>();
this.pairParentsAndChildren(cacheIndex, result.cache.components);
const fileIndex = new Map<string, FileProperties>();
for (const fileProperty of result.properties) {
fileIndex.set(MetadataCacheService.makeKey(fileProperty.type, fileProperty.fullName), fileProperty);
}
fileIndex.forEach((fileProperties, key) => {
const cacheComponent = cacheIndex.get(key);
const projectComponent = projectIndex.get(key);
if (cacheComponent && projectComponent) {
if (cacheComponent.component && projectComponent.component) {
components.push({
cacheComponent: cacheComponent.component,
projectComponent: projectComponent.component,
lastModifiedDate: fileProperties.lastModifiedDate
});
} else {
cacheComponent.children.forEach((cacheChild, childKey) => {
const projectChild = projectComponent.children.get(childKey);
if (projectChild) {
components.push({
cacheComponent: cacheChild,
projectComponent: projectChild,
lastModifiedDate: fileProperties.lastModifiedDate
});
}
});
}
}
});
return components;
}
/**
* Creates a map in which parent components and their children are stored together
* @param index The map which is mutated by this function
* @param components The parent and/or child components to add to the map
*/
private static pairParentsAndChildren(index: Map<string, RecomposedComponent>, components: SourceComponent[]) {
for (const comp of components) {
const key = MetadataCacheService.makeKey(comp.type.name, comp.fullName);
// If the component has a parent it is assumed to be a child
if (comp.parent) {
const parentKey = MetadataCacheService.makeKey(comp.parent.type.name, comp.parent.fullName);
const parentEntry = index.get(parentKey);
if (parentEntry) {
// Add the child component if we have an entry for the parent
parentEntry.children.set(key, comp);
} else {
// Create a new entry that does not have a parent yet
index.set(parentKey, {
children: new Map<string, SourceComponent>().set(key, comp)
});
}
} else {
const entry = index.get(key);
if (entry) {
// Add this parent to an existing entry without overwriting the children
entry.component = comp;
} else {
// Create a new entry with just the parent
index.set(key, {
component: comp,
children: new Map<string, SourceComponent>()
});
}
}
}
}
private static makeKey(type: string, fullName: string): string {
return `${type}#${fullName}`;
}
public getCachePath(): string {
return this.cachePath;
}
public makeCachePath(cacheKey: string): string {
return path.join(
os.tmpdir(),
...MetadataCacheService.CACHE_FOLDER,
cacheKey
);
}
public getPropsPath(): string {
return path.join(this.cachePath, ...MetadataCacheService.PROPERTIES_FOLDER);
}
public clearCache(throwErrorOnFailure: boolean = false): string {
this.clearDirectory(this.cachePath, throwErrorOnFailure);
return this.cachePath;
}
private clearDirectory(dirToRemove: string, throwErrorOnFailure: boolean) {
try {
shell.rm('-rf', dirToRemove);
} catch (error) {
if (throwErrorOnFailure) {
throw error;
}
}
}
}
export type MetadataCacheCallback = (
username: string,
cache: MetadataCacheResult | undefined
) => Promise<void>;
export class MetadataCacheExecutor extends RetrieveExecutor<string> {
private cacheService: MetadataCacheService;
private callback: MetadataCacheCallback;
private isManifest: boolean = false;
private username: string;
constructor(
username: string,
executionName: string,
logName: string,
callback: MetadataCacheCallback,
isManifest: boolean = false
) {
super(executionName, logName);
this.callback = callback;
this.isManifest = isManifest;
this.username = username;
this.cacheService = new MetadataCacheService(username);
}
protected async getComponents(response: any): Promise<ComponentSet> {
this.cacheService.initialize(
response.data,
getRootWorkspacePath(),
this.isManifest
);
return this.cacheService.getSourceComponents();
}
protected async doOperation(
components: ComponentSet,
token: vscode.CancellationToken
): Promise<RetrieveResult | undefined> {
const operation = await this.cacheService.createRetrieveOperation(
components
);
this.setupCancellation(operation, token);
return operation.pollStatus();
}
protected async postOperation(result: RetrieveResult | undefined) {
const cache:
| MetadataCacheResult
| undefined = await this.cacheService.processResults(result);
await this.callback(this.username, cache);
}
} | the_stack |
import { Nullable } from "../../../../shared/types";
import * as React from "react";
import { Chart, ChartPoint, ChartTooltipItem } from "chart.js";
import "chartjs-plugin-dragdata";
import "chartjs-plugin-zoom";
import "chartjs-plugin-annotation";
import "chartjs-plugin-dragzone";
import { Animation, IAnimatable } from "babylonjs";
import Editor from "../../../editor";
import { SyncType } from "../tools/types";
import { SyncTool } from "../tools/sync-tools";
import { TimeTracker } from "../tools/time-tracker";
import { IVector2Like } from "../tools/augmentations";
import { PointSelection } from "../tools/points-select";
export interface ITimelineEditorProps {
/**
* Defines the reference to the editor.
*/
editor: Editor;
/**
* Defines the synchronization type for animation when playing/moving time tracker.
*/
synchronizationType: SyncType;
/**
* Defines the reference to the selected animatable.
*/
selectedAnimatable: Nullable<IAnimatable>;
/**
* Defines the callback called on a key has been udpated.
*/
onUpdatedKey: () => void;
/**
* Defines the callback called on the current frame value changed.
*/
onFrameChange: (value: number) => void;
}
export interface ITimelineEditorState {
}
export class TimelineEditor extends React.Component<ITimelineEditorProps, ITimelineEditorState> {
/**
* Defines the reference to the chart.
*/
public chart: Nullable<Chart> = null;
/**
* Defines the reference to the time tracker.
*/
public timeTracker: Nullable<TimeTracker> = null;
/**
* Defines the reference to the point selection.
*/
public selection: Nullable<PointSelection> = null;
private _canvas: Nullable<HTMLCanvasElement> = null;
private _refHandler = {
getCanvas: (ref: HTMLCanvasElement) => this._canvas = ref,
};
private _editor: Editor;
private _panDisabled: boolean = false;
private _yValue: number = 0;
private _lastLine: number = -1;
/**
* Construcor.
* @param props defines the compoenent's props.
*/
public constructor(props: ITimelineEditorProps) {
super(props);
this._editor = props.editor;
this.state = {
selectedAnimatable: null,
};
}
/**
* Renders the component.
*/
public render(): React.ReactNode {
return (
<div style={{ position: "absolute", width: "calc(100% - 10px)", height: "calc(100% - 50px)" }}>
<canvas
ref={this._refHandler.getCanvas}
onMouseDown={(ev) => this._handleMouseDown(ev)}
onMouseMove={(ev) => this._handleMouseMove(ev)}
onMouseUp={(ev) => this._handleMouseUp(ev)}
onDoubleClick={(ev) => this._handleDoubleClick(ev)}
></canvas>
</div>
);
}
/**
* Called on the component did mount.
*/
public componentDidMount(): void {
if (!this._canvas) { return; }
this.chart = new Chart(this._canvas.getContext("2d")!, {
type: "line",
data: {
datasets: [],
},
options: {
dragData: true,
dragX: true,
onDragStart: (_, e) => this._handleDragPointStart(e),
onDrag: (e, di, i, v) => this._handleDragPoint(e, di, i, v),
onDragEnd: (e, di, i, v) => this._handleDragPointEnd(e, di, i, v),
showLines: false,
responsive: true,
legend: {
display: false,
},
maintainAspectRatio: false,
animation: {
duration: 0,
},
tooltips: {
caretPadding: 15,
mode: "point",
intersect: true,
callbacks: {
label: (item) => this._handleTooltipLabel(item),
},
},
annotation: {
events: ["mouseenter", "mouseleave"],
annotations: [],
},
plugins: {
zoom: {
pan: {
enabled: true,
rangeMin: { x: -1, y: -1, },
mode: () => (this._panDisabled || this.timeTracker?.panDisabled) ? "" : "xy",
},
zoom: {
enabled: true,
rangeMin: { x: -1, y: -1 },
mode: () => "x",
},
},
},
scales: {
xAxes: [{
type: "linear",
position: "top",
ticks: {
min: -1,
max: 60,
fontSize: 12,
fontStyle: "bold",
fontColor: "#222222",
stepSize: 1,
},
}],
yAxes: [{
type: "linear",
position: "left",
ticks: {
min: -1,
max: 20,
reverse: true,
stepSize: 1,
fontSize: 14,
fontStyle: "bold",
fontColor: "#222222",
beginAtZero: true,
showLabelBackdrop: true,
labelOffset: 15,
},
}],
}
},
});
// Create time tracker
this.timeTracker = new TimeTracker(this.chart, {
onMoved: () => this._handleTimeTrackerChanged(),
});
this.chart.config.options!.annotation.annotations.push(this.timeTracker?.getAnnotationConfiguration());
// Create selection
this.selection = new PointSelection(this.chart, {
onSelectedFrames: () => { },
});
this.selection.configure();
}
/**
* Called on the component will unmount.
*/
public componentWillUnmount(): void {
// Destroy chart
try {
this.chart?.destroy();
} catch (e) {
this._editor.console.logError("[Animation Editor]: failed to destroy chart.");
}
}
/**
* Sets the new animatable to edit.
* @param animatable defines the reference to the animatable.
*/
public setAnimatable(animatable: IAnimatable): void {
if (!this.chart) { return; }
this.chart.data.datasets = [];
this.chart.config.options!.annotation.annotations = [this.chart.config.options!.annotation.annotations[0]];
this.chart.config.options!.scales!.yAxes![0].ticks!.callback = () => "";
if (!animatable.animations) {
this.chart.update(0);
return;
}
animatable.animations.forEach((a, index) => {
const data: ChartPoint[] = [];
const keys = a.getKeys();
keys.forEach((k) => {
data.push({ x: k.frame, y: 0.5 + index, r: 10 } as ChartPoint);
});
this.chart!.data.datasets!.push({
data,
label: a.name,
borderWidth: 1,
backgroundColor: "rgb(189, 80, 105, 1)",
xAxisID: "x-axis-0",
pointRadius: 10,
pointHitRadius: 15,
});
});
this.chart.config.options!.scales!.yAxes![0].ticks!.callback = (index) => {
return animatable.animations![Math.floor(index)]?.name ?? " ";
};
this.chart.update();
}
/**
* Sets the new frame value for the time tracker.
* @param value defines the new value of time (frame).
*/
public setCurrentFrameValue(value: number): void {
this.timeTracker?.setValue(value);
}
/**
* Updates the current object to the current frame on animation.
*/
public updateObjectToCurrentFrame(): void {
if (!this.props.selectedAnimatable?.animations?.length || !this.timeTracker) { return; }
SyncTool.UpdateObjectToFrame(
this.timeTracker.getValue(),
SyncType.Scene,
this.props.selectedAnimatable,
this.props.selectedAnimatable.animations[0],
this._editor.scene!,
);
}
/**
* Called on the panel has been resized.
* @param height the new height of the plugin's panel.
*/
public resize(height: number): void {
if (!this.chart || height <= 0) { return; }
const lineHeight = 40;
const lineCount = (height / lineHeight) >> 0;
this.chart.config.options!.scales!.yAxes![0].ticks!.max = lineCount;
this.chart.update(0);
}
/**
* Called on the user moves the time tracker.
*/
private _handleTimeTrackerChanged(): void {
if (!this.timeTracker) { return; }
this.updateObjectToCurrentFrame();
this.props.onFrameChange(this.timeTracker.getValue());
}
/**
* Called on an element of the chart is starting being dragged.
*/
private _handleDragPointStart(element: any): void {
if (!this.chart?.data?.datasets) { return; }
this._panDisabled = true;
this._yValue = this.chart.data.datasets[element["_datasetIndex"]]!.data![element["_index"]]["y"];
}
/**
* Called on an element of the chart is being dragged.
*/
private _handleDragPoint(_: MouseEvent, datasetIndex: number, index: number, value: IVector2Like): void {
if (!this.chart?.data?.datasets) { return; }
this.chart.data.datasets[datasetIndex]!.data![index]["y"] = this._yValue;
if (index === 0) {
this.chart.data.datasets[datasetIndex]!.data![index]["x"] = 0;
return;
}
if (this.props.selectedAnimatable?.animations) {
const animation = this.props.selectedAnimatable.animations[datasetIndex];
if (animation) {
this._updateKey(animation, index, value.x);
}
}
this.updateObjectToCurrentFrame()
this.props.onUpdatedKey();
}
/**
* Callback called on an element stops being dragged.
*/
private _handleDragPointEnd(_: MouseEvent, datasetIndex: number, index: number, value: IVector2Like): void {
this._panDisabled = false;
if (index === 0) { return; }
// Sort animation
if (this.props.selectedAnimatable?.animations) {
const animation = this.props.selectedAnimatable.animations[datasetIndex];
if (animation) {
this._updateKey(animation, index, value.x);
const keys = animation.getKeys();
keys.sort((a, b) => a.frame - b.frame);
}
}
this.props.onUpdatedKey();
}
/**
* Updates the currently drgged key.
*/
private _updateKey(animation: Animation, keyIndex: number, value: number): void {
const keys = animation.getKeys();
const key = keys[keyIndex];
if (key) {
key.frame = value;
}
}
/**
* Called on the mouse is down on the canvas.
*/
private _handleMouseDown(ev: React.MouseEvent<HTMLCanvasElement, MouseEvent>): void {
this.timeTracker?.mouseDown(ev);
}
/**
* Called on the mouse moves on the canvas.
*/
private _handleMouseMove(ev: React.MouseEvent<HTMLCanvasElement, MouseEvent>): void {
if (!this.chart || !this.timeTracker || !this.props.selectedAnimatable?.animations?.length) { return; }
this.timeTracker.mouseMove(ev);
const y = Math.floor(this.chart["scales"]["y-axis-0"].getValueForPixel(ev.nativeEvent.offsetY));
if (y === this._lastLine || y < 0 || y >= this.props.selectedAnimatable.animations.length) { return; }
this._lastLine = y;
this.chart.config.options!.annotation.annotations = [
this.chart.config.options!.annotation.annotations[0],
{
drawTime: "beforeDatasetsDraw",
id: "highlight" + y,
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
yMin: y,
yMax: y + 1,
backgroundColor: "#666666",
borderColor: "grey",
borderWidth: 1,
},
];
this.chart.update(0);
}
/**
* Called on the mouse is up on the canvas.
*/
private _handleMouseUp(ev: React.MouseEvent<HTMLCanvasElement, MouseEvent>): void {
this.timeTracker?.mouseUp(ev);
}
/**
* Called on the user double clicks on the chart.
*/
private _handleDoubleClick(ev: React.MouseEvent<HTMLCanvasElement, MouseEvent>): void {
if (!this.chart || !this.timeTracker || !this.props.selectedAnimatable?.animations?.length) { return; }
const elements = this.chart.getElementsAtEvent(ev);
if (elements && elements.length > 0) {
const element = elements[this._yValue >> 0];
if (!element) { return; }
const animation = this.props.selectedAnimatable.animations[element["_datasetIndex"]];
if (!animation) { return; }
const key = animation.getKeys()[element["_index"]];
if (!key) { return; }
this.timeTracker?.setValue(key.frame);
} else {
const positionOnChart = this.timeTracker.getPositionOnChart(ev.nativeEvent);
if (positionOnChart) {
this.timeTracker?.setValue(Math.max(positionOnChart.x, 0));
}
}
this.chart.update(0);
this.updateObjectToCurrentFrame();
}
/**
* Called on the label is being drawn in the chart.
*/
private _handleTooltipLabel(item: ChartTooltipItem): string {
if (!this.props.selectedAnimatable?.animations?.length) { return ""; }
const animation = this.props.selectedAnimatable.animations[item.datasetIndex!];
if (!animation) { return ""; }
const key = animation.getKeys()[item.index!];
if (!key) { return ""; }
return `Value: ${key.value}`;
}
} | the_stack |
import * as Path from 'path'
import { readFileSync, writeFileSync, existsSync } from 'fs'
import * as ts from "../../../node_modules/typescript/lib/typescript"
declare function print(msg :any, ...v :any[]) :void
const rootdir = Path.normalize(__dirname + "/../../..")
function main() {
let infile = __dirname + "/ast.ts"
let outfile = Path.resolve(__dirname + "/../nodes.ts")
let f = parse(infile)
f = transform(f)
let output = gencode(f)
print(output.substr(0,100)+"...")
// print(output)
output = (
`// generated from ${Path.relative(Path.dirname(outfile), infile)}` +
` by ${Path.relative(Path.dirname(outfile), Path.dirname(infile))}/run.sh` +
` -- do not edit.\n` +
output
)
print(`write ${outfile}`)
writeFileSync(outfile, output, "utf8")
}
function parse(filename :string) :ts.SourceFile {
let src = readFileSync(filename, "utf8")
let f :ts.SourceFile = ts.createSourceFile(
filename,
src,
ts.ScriptTarget.ESNext,
/*setParentNodes*/ false, // add "parent" property to nodes
ts.ScriptKind.TS
)
let diagnostics = (f as any).parseDiagnostics as ts.DiagnosticWithLocation[]|null
if (diagnostics) {
if (printDiagnostics(diagnostics, filename) > 0) {
process.exit(1)
}
}
// print(f)
return f
}
function gencode(f :ts.SourceFile) :string {
let p = ts.createPrinter({
removeComments: false,
newLine: ts.NewLineKind.LineFeed,
omitTrailingSemicolon: true,
noEmitHelpers: true,
})
// return p.printNode(ts.EmitHint.SourceFile, f, f)
return p.printFile(f)
}
class NodeInfo {
name :string
n :ts.ClassDeclaration
members :ts.ClassElement[]
fields :FieldInfo[]
parentName :string = ""
parent :NodeInfo|null = null
unusedParentFields = new Set<string>()
constructor(name :string, n :ts.ClassDeclaration) {
this.name = name
this.n = n
this.members = n!.members as any as ts.ClassElement[]
}
addMember(n :ts.ClassElement) {
if (n.name && ts.isIdentifier(n.name)) {
let name = n.name.escapedText.toString()
if (this.hasMember(name)) {
throw new Error(`duplicate class member ${this.name}.${name}`)
}
}
this.members.push(n)
}
hasMember(name :string) :boolean {
for (let m of this.members) {
if (m.name && ts.isIdentifier(m.name) && m.name.escapedText.toString() == name) {
return true
}
}
return false
}
hasParent(name :string) :boolean {
if (this.parent) {
if (this.parent.name == name) {
return true
}
return this.parent.hasParent(name)
}
return false
}
heritageChain() :NodeInfo[] {
let v = this.parent ? this.parent.heritageChain() : []
v.push(this)
return v
}
// allFields returns all fields for the node in order without duplicates
//
allFields() :Map<string,FieldInfo> {
let m = new Map<string,FieldInfo>()
this.collectFields(m, null)
return m
}
collectFields(m :Map<string,FieldInfo>, skip :Set<string>|null) {
if (this.parent) {
this.parent.collectFields(m, this.unusedParentFields)
}
for (let f of this.fields) {
if (skip && skip.has(f.name)) {
m.delete(f.name)
} else {
m.set(f.name, f)
}
}
}
// allFields1() :FieldInfo[] {
// if (!this.parent) {
// return this.fields
// }
// let fields :FieldInfo[] = []
// let names = new Set<string>(this.fields.map(f => f.name))
// for (let p of this.parent.heritageChain()) {
// for (let f of p.fields) {
// if (!names.has(f.name) && !this.unusedParentFields.has(f.name)) {
// names.add(f.name)
// fields.push(f)
// }
// }
// }
// return fields.length > 0 ? fields.concat(this.fields) : this.fields
// }
getField(name :string) :FieldInfo|null {
for (let f of this.fields) {
if (f.name == name) {
return f
}
}
return null
}
}
class ArrayNode {
// represents an array node type, e.g. Expr[]
constructor(
public n :ArrayNode|NodeInfo,
) {}
}
class FieldInfo {
nodeType :NodeInfo|ArrayNode|null = null // non-null if type is a AST node
constructor(
public name :string,
public type :ts.TypeNode|null,
public init :ts.Expression|null,
public isNullable :boolean,
public definedBy :NodeInfo,
){}
}
const reprMethodName = "repr"
// name of primitive types that skip careful string repr
const directToStringTypenames = new Set<string>(`
int number float bool boolean
Pos Num Int64 SInt64 UInt64
`.trim().split(/[\s\r\n]+/))
class Transformer<T extends ts.Node> {
context :ts.TransformationContext
classToFields = new Map<string,ts.ParameterDeclaration[]>()
nodeInfo = new Map<string,NodeInfo>() // classname => info
baseNode :NodeInfo|null = null
constructor(context: ts.TransformationContext) {
this.context = context
}
createMethod(name :string, params :ts.ParameterDeclaration[], t :ts.TypeNode|null, ...body :ts.Statement[]) {
return ts.createMethod(
undefined, // decorators
undefined, // modifiers
undefined, // asteriskToken
name,
undefined, // questionToken
undefined, // typeParameters
params,
t || undefined,
body ? ts.createBlock(body, /*multiline*/body.length > 1) : undefined
)
}
createMethod0(name :string, t :ts.TypeNode|null, ...body :ts.Statement[]) {
return this.createMethod(name, [], t, ...body)
}
generateTypeTestMethod(methodName :string, classname :string) :ts.MethodDeclaration {
// isTYPE() :this is TYPE { return this instanceof classname }
let t = ts.createTypePredicateNode(
ts.createThisTypeNode(),
ts.createTypeReferenceNode(classname, undefined)
)
return this.createMethod0(
methodName,
t, // type
ts.createReturn(
ts.createBinary(
ts.createThis(),
ts.SyntaxKind.InstanceOfKeyword,
ts.createIdentifier(classname)
)
)
)
}
// generateToStringMethod(c :NodeInfo) :ts.MethodDeclaration {
// return this.createMethod0(
// "toString",
// ts.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
// ts.createReturn(ts.createStringLiteral(c.name)),
// )
// }
generateReprMethod(c :NodeInfo) :ts.MethodDeclaration {
// all public field names
let fields = c.allFields()
for (let name of Array.from(fields.keys())) {
// hide "pos" field as it is very noisy and rarely helpful in repr
if (name[0] == "_" || name == "pos") {
fields.delete(name)
}
}
// if (c.name == "RestType") {
// // info.unusedParentFields
// print({ fields, unusedParentFields: c.unusedParentFields })
// }
const sepArgName = "sep"
const makeMethod = (body :ts.Statement[]) => this.createMethod(
reprMethodName,
[
ts.createParameter(
undefined,
undefined,
undefined,
sepArgName,
undefined,
ts.createTypeReferenceNode("string", undefined),
ts.createStringLiteral("\n ")
)
],
ts.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
...body,
)
if (fields.size == 0) {
return makeMethod([
ts.createReturn(ts.createStringLiteral(`(${c.name})`))
])
}
let fieldnames = Array.from(fields.keys())
let body :ts.Statement[] = []
let ret :ts.Expression
let sepArgName2 = sepArgName + "2"
let addedSep2 = false
const setNeedsSep2 = () => {
if (addedSep2) { return }
addedSep2 = true
// var sep2 = ln.charCodeAt(0) == 0xA ? sep + " " : sep
body.unshift(
ts.createVariableStatement(
undefined,
[ts.createVariableDeclaration(
sepArgName2,
undefined,
ts.createConditional(
ts.createBinary(
ts.createCall(
ts.createPropertyAccess(ts.createIdentifier(sepArgName), "charCodeAt"),
undefined,
[ts.createNumericLiteral("0")]
),
ts.createToken(ts.SyntaxKind.EqualsEqualsToken),
ts.createNumericLiteral("10", ts.TokenFlags.HexSpecifier)
),
ts.createBinary(
ts.createIdentifier(sepArgName),
ts.createToken(ts.SyntaxKind.PlusToken),
ts.createStringLiteral(" ")
),
ts.createIdentifier(sepArgName)
)
)]
)
)
}
// fieldReprExpr generates an expression that produces the most suitable
// "representation" of the field's value.
const fieldReprExpr = (f :FieldInfo) => {
assert(f)
let prop = ts.createPropertyAccess(ts.createThis(), f.name)
if (f.nodeType) {
setNeedsSep2()
if (f.nodeType instanceof ArrayNode) {
return ts.createCall(
ts.createIdentifier("reprNodeArray"),
undefined,
[ ts.createIdentifier(sepArgName2), prop ]
)
}
return ts.createCall(
ts.createPropertyAccess(prop, reprMethodName),
undefined,
[ ts.createIdentifier(sepArgName2) ]
)
}
if (f.type && ts.isTypeReferenceNode(f.type) && ts.isIdentifier(f.type.typeName)) {
let typename = f.type.typeName.escapedText.toString()
if (directToStringTypenames.has(typename)) {
// simple implicit string conversion
return prop
}
}
setNeedsSep2()
return ts.createCall(
ts.createIdentifier("reprAny"),
undefined,
[ ts.createIdentifier(sepArgName2), prop ]
)
}
// find longest span of fields that are non-nullable
let firstNullableField :FieldInfo|null = null // non-null if we encountered one
let lastNonNullableFieldIndex = -1
for (let f of fields.values()) {
if (f.isNullable) {
firstNullableField = f
break
}
lastNonNullableFieldIndex++
}
// initial string with node name and non-null fields
let sinit :ts.Expression
if (lastNonNullableFieldIndex > -1) {
let head = ts.createTemplateHead(`(${c.name}`)
let spans :ts.TemplateSpan[] = []
spans.push(ts.createTemplateSpan(
ts.createIdentifier(sepArgName),
ts.createTemplateMiddle(`(${fieldnames[0]} `)
))
let i = 0
for (; i < lastNonNullableFieldIndex; i++) {
let left = fieldnames[i]
let right = fieldnames[i + 1]
spans.push(ts.createTemplateSpan(
fieldReprExpr(fields.get(left)!),
ts.createTemplateMiddle(`)`)
))
spans.push(ts.createTemplateSpan(
ts.createIdentifier(sepArgName),
ts.createTemplateMiddle(`(${right} `)
))
}
spans.push(ts.createTemplateSpan(
fieldReprExpr(fields.get(fieldnames[i])!),
ts.createTemplateTail(firstNullableField ? ")" : "))")
))
sinit = ts.createTemplateExpression(head, spans)
} else {
sinit = ts.createStringLiteral(`(${c.name}`)
}
// var s = <sinit>
body.push(
ts.createVariableStatement(
undefined,
[ts.createVariableDeclaration(
"s",
undefined,
sinit
)]
)
)
// conditionally add nullable fields
if (firstNullableField) {
let foundCont = false
for (let f of fields.values()) {
if (!foundCont) {
if (f === firstNullableField) {
foundCont = true
} else {
continue
}
}
// v.push(this.field)
let reprExpr = ts.createExpressionStatement(
ts.createBinary(
ts.createIdentifier("s"),
ts.SyntaxKind.PlusEqualsToken,
ts.createBinary(
ts.createBinary(
ts.createBinary(
ts.createIdentifier("sep"),
ts.SyntaxKind.PlusToken,
ts.createStringLiteral(`(${f.name} `)
),
ts.SyntaxKind.PlusToken,
fieldReprExpr(f)
),
ts.SyntaxKind.PlusToken,
ts.createStringLiteral(`)`)
)
)
)
if (f.isNullable) {
body.push(
// if (this.field) v.push(this.field)
ts.createIf(ts.createPropertyAccess(ts.createThis(), f.name), reprExpr)
)
} else {
body.push(reprExpr)
}
}
}
// finally,
if (firstNullableField) {
ret = ts.createBinary(
ts.createIdentifier("s"),
ts.SyntaxKind.PlusToken,
ts.createStringLiteral(")")
)
} else {
ret = ts.createIdentifier("s")
}
body.push(ts.createReturn(ret))
return makeMethod(body)
}
generateVisitMethod(c :NodeInfo) :ts.MethodDeclaration {
// all public field names
let fields = c.allFields()
for (let name of Array.from(fields.keys())) {
// hide "pos" field as it is very noisy and rarely helpful in repr
if (name[0] == "_" || name == "pos") {
fields.delete(name)
}
}
let body :ts.Statement[] = []
for (let f of fields.values()) {
let prop :ts.Expression = ts.createPropertyAccess(ts.createThis(), f.name)
let visitFun = "visitField" // TODO: based on field type
let visitArgs :ts.Expression[] = [] // extra args
if (f.nodeType) {
if (f.nodeType instanceof ArrayNode) {
visitFun = "visitFieldNA"
} else {
visitFun = "visitFieldN"
}
} else if (f.type) {
if (ts.isArrayTypeNode(f.type)) {
let t = f.type.elementType
if (ts.isParenthesizedTypeNode(t)) {
// unwrap "(A|B)" => "A|B"
t = t.type
}
if (ts.isUnionTypeNode(t)) {
let allAreNodeTypes = true
for (let t2 of t.types) {
if (
!ts.isTypeReferenceNode(t2) ||
!ts.isIdentifier(t2.typeName) ||
!this.nodeInfo.has(t2.typeName.escapedText.toString())
) {
allAreNodeTypes = false
break
}
}
if (allAreNodeTypes) {
visitFun = "visitFieldNA"
} else {
visitFun = "visitFieldA"
}
} else {
visitFun = "visitFieldA"
}
} else if (ts.isTypeReferenceNode(f.type) && ts.isIdentifier(f.type.typeName)) {
let typename = f.type.typeName.escapedText.toString()
if (typename == "Storage" || typename == "token") {
// TODO: automatically understand that "Storage" is an enum
visitFun = "visitFieldE"
// prop = ts.createElementAccess(
// ts.createIdentifier(typename),
// prop
// )
visitArgs.push(ts.createIdentifier(typename))
}
}
}
let stmt :ts.Statement = ts.createExpressionStatement(
ts.createCall(
ts.createPropertyAccess(ts.createIdentifier("v"), ts.createIdentifier(visitFun)),
undefined,
[ ts.createStringLiteral(f.name), prop ].concat(visitArgs)
)
)
if (f.isNullable) {
if (f.nodeType) {
stmt = ts.createIf(prop, stmt)
} else {
stmt = ts.createIf(
ts.createBinary(
ts.createBinary(
prop,
ts.SyntaxKind.ExclamationEqualsEqualsToken,
ts.createNull()
),
ts.SyntaxKind.AmpersandAmpersandToken,
ts.createBinary(
prop,
ts.SyntaxKind.ExclamationEqualsEqualsToken,
ts.createIdentifier("undefined")
),
),
stmt
)
}
}
body.push(stmt)
}
return this.createMethod(
"visit",
// ts.createParameter(U, [publicKeyword], U, f.name, U, f.type)
[
ts.createParameter(
undefined,
[],
undefined,
"v",
undefined,
ts.createTypeReferenceNode("NodeVisitor", [])
),
],
null,
...body
)
}
// main transformer function
transform :ts.Transformer<T> = node => {
let n = ts.visitNode(node, this.visit)
if (!this.baseNode) {
throw new Error("did not find \"Node\" class")
}
// link up parents
for (let [classname, c] of this.nodeInfo) {
if (c.parentName) {
c.parent = this.nodeInfo.get(c.parentName)!
if (!c.parent) {
throw new Error(`can not find parent "${c.parentName}" of "${c.name}"`)
}
}
}
// enrich field types
for (let [classname, c] of this.nodeInfo) {
for (let f of c.fields) {
if (!f.type) {
let p = c.parent
while (p) {
let pf = p.getField(f.name)
if (pf && pf.type) {
f.type = pf.type
break
}
p = p.parent
}
}
if (f.type) {
if (ts.isUnionTypeNode(f.type)) {
// make sure we pick up on null types in unions and set FieldInfo.isNullable
for (let t of f.type.types) {
if (
t.kind == ts.SyntaxKind.NullKeyword ||
t.kind == ts.SyntaxKind.UndefinedKeyword
) {
f.isNullable = true
break
}
}
}
if (!f.nodeType) {
let t :ts.TypeNode = f.type
// unwrap array
let arrayDepth :int[] = []
const unwrapArray = (t :ts.TypeNode) :ts.TypeNode => {
let d = 0
while (ts.isArrayTypeNode(t)) {
d++
t = t.elementType
}
arrayDepth.push(d)
return t
}
const wrapArray = (depth :int|undefined, f :FieldInfo) => {
if (depth && f.nodeType) {
// restore array type
while (depth--) {
f.nodeType = new ArrayNode(f.nodeType)
}
}
}
t = unwrapArray(t)
if (ts.isTypeReferenceNode(t) && ts.isIdentifier(t.typeName)) {
// look up & link up AST node type
let typename = t.typeName.escapedText.toString()
f.nodeType = this.nodeInfo.get(typename) || null
} else if (ts.isUnionTypeNode(t)) {
// in this case, the field is optional and was converted
let typename = ""
let hasMultipleTypes = false
let typeInArrayOfDepth = 0
for (let t2 of t.types) {
t2 = unwrapArray(t2)
if (ts.isTypeReferenceNode(t2) && ts.isIdentifier(t2.typeName)) {
if (typename) {
// we don't handle multiple AST Node field types (yet)
hasMultipleTypes = true
} else {
typename = t2.typeName.escapedText.toString()
typeInArrayOfDepth = arrayDepth.pop() || 0
continue
}
}
arrayDepth.pop()
}
if (!hasMultipleTypes && typename) {
f.nodeType = this.nodeInfo.get(typename) || null
wrapArray(typeInArrayOfDepth, f)
}
}
wrapArray(arrayDepth.pop(), f)
} // if (!f.nodeType)
} // if (f.type)
}
}
// generate members for Node class
for (let [classname, c] of this.nodeInfo) {
if (!c.hasMember("visit")) {
c.addMember(this.generateVisitMethod(c))
}
// if (!c.hasMember(reprMethodName) && !c.hasParent("PrimType")) {
// c.addMember(this.generateReprMethod(c))
// }
// if (!c.hasMember("toString")) {
// c.addMember(this.generateToStringMethod(c))
// }
if (c !== this.baseNode) {
// isTYPE() :this is TYPE
let methodName = "is" + classname
if (!this.baseNode.hasMember(methodName)) {
this.baseNode.addMember(
this.generateTypeTestMethod(methodName, classname)
)
}
}
}
return n
}
visit = (n :ts.Node) :ts.Node => {
// print(`visit ${ts.SyntaxKind[n.kind]} ${ts.isIdentifier(n) ? n.escapedText : ""}`)
if (ts.isClassDeclaration(n)) {
return this.visitClass(n)
}
if (ts.isImportDeclaration(n)) {
return this.visitImport(n)
}
// if (ts.isFunctionDeclaration(n)) {
// print((n as any).body.statements[0].declarationList.declarations[0])
// }
return ts.visitEachChild(n, this.visit, this.context)
}
visitImport(n :ts.ImportDeclaration) :ts.ImportDeclaration {
if (ts.isStringLiteral(n.moduleSpecifier)) {
// rewrite relative paths since output file is written to parent dir
let path = n.moduleSpecifier.text
if (path[0] == ".") {
// "../foo/bar" => "./foo/bar"
// "../../bar" => "../bar"
path = Path.relative("..", path)
if (!path.startsWith("../")) {
path = "./" + path
}
n.moduleSpecifier = ts.createStringLiteral(path)
}
}
return n
}
visitClass(n :ts.ClassDeclaration) :ts.ClassDeclaration {
// name of class
let classname = n.name ? String(n.name.escapedText) : "_"
// node info
let info = new NodeInfo(classname, n)
this.nodeInfo.set(classname, info)
if (classname[0] != "_") {
// make sure class has "export" modifier
n.modifiers = ts.createNodeArray([ts.createModifier(ts.SyntaxKind.ExportKeyword)])
// reference to base node
if (classname == "Node") {
this.baseNode = info
}
}
// name of parent classes
let parentClassname = ""
if (n.heritageClauses) for (let h of n.heritageClauses) {
if (h.token == ts.SyntaxKind.ExtendsKeyword) for (let t of h.types) {
let e = t.expression
if (ts.isIdentifier(e)) {
parentClassname = e.escapedText.toString()
info.parentName = parentClassname
// note: TS does not support multiple inheritance
break
}
}
}
// parent fields
let parentFields = this.classToFields.get(parentClassname) || [] as ts.ParameterDeclaration[]
let parentFieldNames = new Set<string>(parentFields.map(p =>
(p.name as ts.Identifier).escapedText.toString()
))
let parentFieldValues = new Map<string,ts.Expression>()
// find fields
info.fields = []
let initBody :ts.Statement[] = []
let hasCustomConstructor = false
let mvMembers = new Set<ts.Node>()
let numMovedDefaultValues = 0
for (let i = 0; i < n.members.length; i++) {
let m = n.members[i]
if (ts.isConstructorDeclaration(m)) {
hasCustomConstructor = true
// print('cons', ts.SyntaxKind[m.parameters[0].kind], m.parameters[0])
let paramsForSubclasses :ts.ParameterDeclaration[] = []
for (let p of m.parameters) {
paramsForSubclasses.push(ts.createParameter(
p.decorators,
undefined, // skip "public"
p.dotDotDotToken,
p.name,
undefined, // no questionToken,
p.type,
// no initializer
))
}
this.classToFields.set(classname, paramsForSubclasses)
break
}
// init() { ... } -- move ... to constructor
if (
!hasCustomConstructor &&
ts.isMethodDeclaration(m) &&
m.body &&
ts.isIdentifier(m.name) &&
m.name.escapedText.toString() == "init"
) {
if (m.parameters.length > 0) {
throw new Error(`unexpected init() method with parameters in class ${classname}`)
}
initBody = m.body.statements.slice()
mvMembers.add(m)
continue
}
// // debug/print an existing method on a class.
// // useful for reverse-engineering TS AST<->code.
// if (
// ts.isMethodDeclaration(m) &&
// m.body &&
// ts.isIdentifier(m.name) &&
// m.name.escapedText.toString() == "foofoo"
// ) {
// print(
// repr(
// (m as any).body.statements[0], //.declarationList.declarations[0],
// // (m as any).body.statements[2],
// 4
// )
// )
// }
if (!ts.isPropertyDeclaration(m)) {
continue
}
if (!ts.isIdentifier(m.name)) {
continue
}
let name = m.name.escapedText.toString()
let isNullable = false
// if (classname == "Type") {
// print("parentFieldNames", parentFieldNames, {name})
// }
if (!m.type) {
if (m.initializer) {
// e.g. "foo = initval"
if (parentFieldNames.has(name)) {
parentFieldValues.set(name, m.initializer)
mvMembers.add(m)
info.unusedParentFields.add(name)
numMovedDefaultValues++
continue
}
} else {
print(`missing type for field ${classname}.${name}`)
continue
}
} else if (m.questionToken) {
if (
m.initializer &&
ts.isIdentifier(m.initializer) &&
m.initializer.originalKeywordKind == ts.SyntaxKind.UndefinedKeyword
) {
// e.g. "x? :Foo = undefined" -> "x? :Foo"
m.initializer = undefined
continue
}
// convert "foo? :Type" -> "foo :Type|null|undefined"
m.questionToken = undefined
isNullable = true
m.type = ts.createUnionTypeNode([
ts.createKeywordTypeNode(ts.SyntaxKind.NullKeyword),
// ts.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword),
m.type,
])
}
info.fields.push(new FieldInfo(
name,
m.type || null,
m.initializer || null,
isNullable,
info
))
if (m.type && !m.initializer) {
// move field to constructor
mvMembers.add(m)
}
} // for (let i = 0; i < n.members.length; i++)
// typecast class members to mutable array
let classMembers = n.members as any as ts.ClassElement[]
// remove members that will move into constructor
if (!hasCustomConstructor) {
for (let i = 0; i < n.members.length; i++) {
if (mvMembers.has(n.members[i])) {
classMembers.splice(i, 1)
i--
}
}
}
// add constructor
if (!hasCustomConstructor) {
let publicKeyword = ts.createToken(ts.SyntaxKind.PublicKeyword)
let params = new Map<string,ts.ParameterDeclaration>()
let body :ts.Statement[] = []
if (parentFields.length > 0 && parentFields.length >= parentFieldValues.size) {
let superVals = new Array<ts.Expression>(parentFields.length)
for (let i = 0; i < parentFields.length; i++) {
let f = parentFields[i]
let name = (f.name as ts.Identifier).escapedText.toString()
let val = parentFieldValues.get(name)
superVals[i] = val || ts.createIdentifier(name)
if (!val) {
params.set(name, f)
}
}
// super(param0, param1, ...)
body = [
ts.createExpressionStatement(
ts.createCall(ts.createSuper(), undefined, superVals)
)
]
}
let paramsForSubclasses = new Map<string,ts.ParameterDeclaration>(params)
let localParamCount = 0
const U = undefined
for (let f of info.fields) {
if (f.type && !f.init) {
localParamCount++
params.set(f.name, ts.createParameter(U, [publicKeyword], U, f.name, U, f.type))
paramsForSubclasses.set(f.name, ts.createParameter(U, [], U, f.name, U, f.type))
}
}
// add constructor if the class has any local fields
if (localParamCount > 0 || numMovedDefaultValues > 0 || initBody.length > 0) {
if (initBody.length > 0) {
body = body.concat(initBody)
}
let cons = ts.createConstructor(
undefined,
undefined,
Array.from(params.values()),
ts.createBlock(body, /*multiline*/false),
)
classMembers.unshift(cons)
}
this.classToFields.set(classname, Array.from(paramsForSubclasses.values()))
}
// print({classname, parentClassname, hasCustomConstructor, fields})
return ts.visitEachChild(n, this.visit, this.context)
// return n
}
}
function transform<T extends ts.Node>(f :T) :T {
let transformers :ts.TransformerFactory<T>[] = [
(context: ts.TransformationContext) :ts.Transformer<T> =>
new Transformer<T>(context).transform
]
let compilerOptions :ts.CompilerOptions = {
module: ts.ModuleKind.ESNext,
target: ts.ScriptTarget.ESNext,
}
let r = ts.transform<T>(f, transformers, compilerOptions)
if (r.diagnostics) {
let file = ts.isSourceFile(f) ? f.fileName : "<input>"
if (printDiagnostics(r.diagnostics, file) > 0) {
process.exit(1)
}
}
return r.transformed[0]!
}
const IGNORE = -1
, INFO = ts.DiagnosticCategory.Message
, WARN = ts.DiagnosticCategory.Warning
, ERR = ts.DiagnosticCategory.Error
, SUGGESTION = ts.DiagnosticCategory.Suggestion
, OK = IGNORE
// rules maps TS diagnostics codes to severity levels.
// The special value IGNORE can be used to completely silence a diagnostic.
// For diagnostic codes not listed, the default DiagnosticCategory for a
// certain diagnostic is used.
const diagrules = {
6031: IGNORE, // starting compilation
6194: IGNORE, // Found N errors. Watching for file changes.
6133: WARN, // unused variable, parameter or import
}
// returns number of errors
function printDiagnostics(diagnostics :ts.DiagnosticWithLocation[], file :string) :number {
let errcount = 0
file = Path.relative(rootdir, file)
for (let d of diagnostics) {
let {line, character} = ts.getLineAndCharacterOfPosition(d.file, d.start)
let level = diagrules[d.code] !== undefined ? diagrules[d.code] : d.category
let levelstr = "W"
if (level == ERR) {
levelstr = "E"
errcount++
}
console.error(
`${file}:${line+1}:${character+1}: ${levelstr} ` +
ts.flattenDiagnosticMessageText(d.messageText, "\n") +
` [TS${d.code}]`
)
}
return errcount
}
try {
main()
} catch (e) {
console.error(e.stack || ""+e)
process.exit(1)
} | the_stack |
import { service, inject } from 'spryly';
import { Server } from '@hapi/hapi';
import { ConfigService } from './config';
import { LoggingService } from './logging';
import {
ModuleInfoFieldIds,
ModuleState,
PipelineState,
AIModelProvider,
IoTCentralService
} from './iotCentral';
import { HealthState } from './health';
import * as _get from 'lodash.get';
import * as _random from 'lodash.random';
import * as request from 'request';
import * as fse from 'fs-extra';
import {
resolve as pathResolve,
parse as pathParse
} from 'path';
import { promisify } from 'util';
import { exec } from 'child_process';
import { bind } from '../utils';
const defaultStorageFolderPath: string = '/data/misc/storage';
const defaultResNetConfigFolderPath: string = '/data/misc/storage/ResNetSetup/configs';
const defaultONNXModelFolderPath: string = '/data/misc/storage/ONNXSetup/detector';
const defaultONNXConfigFolderPath: string = '/data/misc/storage/ONNXSetup/configs';
const defaultUnzipCommand: string = 'unzip -d ###UNZIPDIR ###TARGET';
const DSConfigInputMap = {
wpVideoStreamInput1: 'SOURCE0',
wpVideoStreamInput2: 'SOURCE1',
wpVideoStreamInput3: 'SOURCE2',
wpVideoStreamInput4: 'SOURCE3'
};
const MsgConvConfigMap = {
wpVideoStreamInput1: 'SENSOR0',
wpVideoStreamInput2: 'SENSOR1',
wpVideoStreamInput3: 'SENSOR2',
wpVideoStreamInput4: 'SENSOR3'
};
const defaultRowMap = '1:1:1:2:2:4:4:4:4';
const defaultColumnMap = '1:1:2:2:2:2:2:2:2';
const defaultBatchSizeMap = '1:1:2:4:4:8:8:8:8';
const defaultDisplayWidthMap = '1280:1280:1280:1280:1280:1280:1280:1280:1280';
const defaultDisplayHeightMap = '720:720:720:720:720:720:720:720:720';
@service('module')
export class ModuleService {
@inject('$server')
private server: Server;
@inject('config')
private config: ConfigService;
@inject('logger')
private logger: LoggingService;
@inject('iotCentral')
private iotCentral: IoTCentralService;
private displayRowMap = defaultRowMap;
private displayColumnMap = defaultColumnMap;
private batchSizeMap = defaultBatchSizeMap;
private displayWidthMap = defaultDisplayWidthMap;
private displayHeightMap = defaultDisplayHeightMap;
private storageFolderPath: string = defaultStorageFolderPath;
private resNetConfigFolderPath = defaultResNetConfigFolderPath;
private onnxModelFolderPath = defaultONNXModelFolderPath;
private onnxConfigFolderPath = defaultONNXConfigFolderPath;
private unzipCommand: string = defaultUnzipCommand;
public async init(): Promise<void> {
this.logger.log(['ModuleService', 'info'], 'initialize');
this.server.method({ name: 'module.startService', method: this.startService });
this.server.method({ name: 'module.updateDSConfiguration', method: this.updateDSConfiguration });
this.displayRowMap = (this.config.get('DisplayRowMap') || defaultRowMap).split(':');
this.displayColumnMap = (this.config.get('DisplayColumnMap') || defaultColumnMap).split(':');
this.batchSizeMap = (this.config.get('BatchSizeMap') || defaultBatchSizeMap).split(':');
this.displayWidthMap = (this.config.get('DisplayWidthMap') || defaultDisplayWidthMap).split(':');
this.displayHeightMap = (this.config.get('DisplayHeightMap') || defaultDisplayHeightMap).split(':');
this.storageFolderPath = (this.server.settings.app as any).storageRootDirectory;
this.resNetConfigFolderPath = pathResolve(this.storageFolderPath, 'ResNetSetup', 'configs');
this.onnxModelFolderPath = pathResolve(this.storageFolderPath, 'ONNXSetup', 'detector');
this.onnxConfigFolderPath = pathResolve(this.storageFolderPath, 'ONNXSetup', 'configs');
this.unzipCommand = this.config.get('unzipCommand') || defaultUnzipCommand;
}
// @ts-ignore (testparam)
public async sample1(testparam: any): Promise<void> {
return;
}
@bind
public async startService(): Promise<void> {
this.logger.log(['ModuleService', 'info'], `Starting module service...`);
await this.iotCentral.sendMeasurement({
[ModuleInfoFieldIds.State.ModuleState]: ModuleState.Active,
[ModuleInfoFieldIds.Event.VideoStreamProcessingStarted]: 'NVIDIA DeepStream'
});
}
public async getHealth(): Promise<number> {
const iotCentralHealth = await this.iotCentral.getHealth();
if (iotCentralHealth < HealthState.Good) {
this.logger.log(['ModuleService', 'info'], `Health check iot:${iotCentralHealth}`);
return HealthState.Critical;
}
await this.iotCentral.sendMeasurement({
[ModuleInfoFieldIds.Telemetry.SystemHeartbeat]: iotCentralHealth
});
return HealthState.Good;
}
public async saveUrlModelPackage(videoModelUrl: string): Promise<string> {
let result = '';
try {
const fileParse = pathParse(videoModelUrl);
const fileName = (_get(fileParse, 'base') || '').split('?')[0];
let receivedBytes = 0;
let progressChunk = 0;
let progressTotal = 0;
if (!fileName) {
return '';
}
this.logger.log(['ModuleService', 'info'], `Downloading model package: ${fileName}`);
result = await new Promise((resolve, reject) => {
request
.get(videoModelUrl)
.on('error', (error) => {
this.logger.log(['ModuleService', 'error'], `Error downloading model package: ${error.message}`);
return reject(error);
})
.on('response', (data) => {
const totalBytes = parseInt(data.headers['content-length'], 10) || 1;
progressChunk = Math.floor(totalBytes / 10);
this.logger.log(['ModuleService', 'info'], `Downloading model package - total bytes: ${totalBytes}`);
})
.on('data', (chunk) => {
receivedBytes += chunk.length;
if (receivedBytes > (progressTotal + progressChunk)) {
progressTotal += progressChunk;
this.logger.log(['ModuleService', 'info'], `Downloading video model package - received bytes: ${receivedBytes}`);
}
})
.on('end', () => {
this.logger.log(['ModuleService', 'info'], `Finished downloading video model package: ${fileName}`);
return resolve(fileName);
})
.pipe(fse.createWriteStream(pathResolve(this.storageFolderPath, fileName)))
.on('error', (error) => {
return reject(error);
})
.on('close', () => {
return resolve(fileName);
});
});
}
catch (ex) {
this.logger.log(['ModuleService', 'error'], `Error downloading model package: ${ex.message}`);
result = '';
}
return result;
}
@bind
public async updateDSConfiguration() {
await this.iotCentral.sendMeasurement({
[ModuleInfoFieldIds.State.ModuleState]: ModuleState.Inactive
});
this.logger.log(['ModuleService', 'info'], `updateDSConfiguration:\n${JSON.stringify(this.iotCentral.detectionSettings, null, 4)}`);
if (this.iotCentral.detectionSettings.wpDemoMode === true) {
await this.saveDSResNetDemoConfiguration();
}
else if (this.iotCentral.detectionSettings.wpAIModelProvider === AIModelProvider.DeepStream) {
await this.saveDSResNetConfiguration();
}
else if (this.iotCentral.detectionSettings.wpAIModelProvider === AIModelProvider.CustomVision) {
await this.saveCustomVisionConfiguration();
}
else {
this.logger.log(['ModuleService', 'warning'], `Updating DS configuration: nothing to set so skipping...`);
}
await this.iotCentral.sendMeasurement({
[ModuleInfoFieldIds.State.ModuleState]: ModuleState.Active
});
}
private async changeVideoModel(videoModelUrl: string): Promise<boolean> {
let status = true;
this.logger.log(['ModuleService', 'info'], `Changing video model...`);
try {
const fileName = await this.saveUrlModelPackage(videoModelUrl);
if (fileName) {
status = await this.extractAndVerifyModelFiles(fileName);
if (status === true) {
status = await this.switchVisionModel(fileName);
}
}
}
catch (ex) {
this.logger.log(['ModuleService', 'info'], `Error while changing video model: ${ex.message}`);
status = false;
}
return status;
}
private async extractAndVerifyModelFiles(fileName: string): Promise<boolean> {
const sourceFileName = fileName;
const destFileName = sourceFileName;
const destFilePath = pathResolve(this.storageFolderPath, destFileName);
const destUnzipDir = destFilePath.slice(0, -4);
try {
if (fse.statSync(destFilePath).size <= 0) {
this.logger.log(['ModuleService', 'error'], `Empty video model package detected - skipping`);
return false;
}
this.logger.log(['ModuleService', 'info'], `Removing any existing target unzip dir: ${destUnzipDir}`);
await promisify(exec)(`rm -rf ${destUnzipDir}`);
const unzipCommand = this.unzipCommand.replace('###UNZIPDIR', destUnzipDir).replace('###TARGET', destFilePath);
const { stdout } = await promisify(exec)(unzipCommand);
this.logger.log(['ModuleService', 'info'], `Extracted files: ${stdout}`);
this.logger.log(['ModuleService', 'info'], `Removing zip package: ${destFilePath}`);
await promisify(exec)(`rm -f ${destFilePath}`);
this.logger.log(['ModuleService', 'info'], `Done extracting in: ${destUnzipDir}`);
return this.ensureModelFilesExist(destUnzipDir);
}
catch (ex) {
this.logger.log(['ModuleService', 'error'], `Error extracting files: ${ex.message}`);
}
return false;
}
private async ensureModelFilesExist(modelFolder: string): Promise<boolean> {
this.logger.log(['ModuleService', 'info'], `Ensure model files exist in: ${modelFolder}`);
try {
const modelFiles = await fse.readdir(modelFolder);
if (modelFiles
&& modelFiles.find(file => file === 'model.onnx')
&& modelFiles.find(file => file === 'labels.txt')) {
return true;
}
}
catch (ex) {
this.logger.log(['ModuleService', 'error'], `Error enumerating model files: ${ex.message}`);
}
return false;
}
private async switchVisionModel(fileName: any): Promise<boolean> {
const sourceFileName = fileName;
const destFileName = sourceFileName;
const destFilePath = pathResolve(this.storageFolderPath, destFileName);
const destUnzipDir = destFilePath.slice(0, -4);
try {
this.logger.log(['ModuleService', 'info'], `Copying new model files from: ${destUnzipDir}`);
await promisify(exec)(`rm -f ${this.onnxModelFolderPath}/*.engine`);
await promisify(exec)(`cp ${pathResolve(destUnzipDir, 'model.onnx')} ${this.onnxModelFolderPath}`);
await promisify(exec)(`cp ${pathResolve(destUnzipDir, 'labels.txt')} ${this.onnxModelFolderPath}`);
this.logger.log(['ModuleService', 'info'], `Removing unzipped model folder: ${destUnzipDir}`);
await promisify(exec)(`rm -rf ${destUnzipDir}`);
return true;
}
catch (ex) {
this.logger.log(['ModuleService', 'error'], `Error extracting files: ${ex.message}`);
}
return false;
}
private async saveDSResNetDemoConfiguration() {
this.logger.log(['ModuleService', 'info'], `Setting carsDemo configuration`);
await promisify(exec)(`cp ${pathResolve(this.resNetConfigFolderPath, 'carsConfig.txt')} ${pathResolve(this.storageFolderPath, 'DSConfig.txt')}`);
await this.iotCentral.setPipelineState(PipelineState.Active);
}
private getActiveStreams(): number {
let activeStreams: number = 0;
for (const key in this.iotCentral.videoStreamInputSettings) {
if (!this.iotCentral.videoStreamInputSettings.hasOwnProperty(key)) {
continue;
}
const input = this.iotCentral.videoStreamInputSettings[key];
if (_get(input, 'cameraId') && _get(input, 'videoStreamUrl')) {
activeStreams++;
}
}
return activeStreams;
}
private computeDSConfiguration(activeStreams: number): string[] {
const rows = this.displayRowMap[activeStreams];
const columns = this.displayColumnMap[activeStreams];
const sedCommands = [`sed "`];
sedCommands.push(`s/###DISPLAY_ROWS/${rows}/g;`);
sedCommands.push(`s/###DISPLAY_COLUMNS/${columns}/g;`);
sedCommands.push(`s/###DISPLAY_WIDTH/${this.displayWidthMap[activeStreams]}/g;`);
sedCommands.push(`s/###DISPLAY_HEIGHT/${this.displayHeightMap[activeStreams]}/g;`);
for (const key in this.iotCentral.videoStreamInputSettings) {
if (!this.iotCentral.videoStreamInputSettings.hasOwnProperty(key)) {
continue;
}
const configSource = DSConfigInputMap[key];
const input = this.iotCentral.videoStreamInputSettings[key];
const active = (_get(input, 'cameraId') && _get(input, 'videoStreamUrl')) ? '1' : '0';
const videoStreamUrl = (_get(input, 'videoStreamUrl') || '').replace(/\//g, '\\/');
const videoStreamType = videoStreamUrl.startsWith('rtsp') ? '4' : '3';
sedCommands.push(`s/###${configSource}_ENABLE/${active}/g;`);
sedCommands.push(`s/###${configSource}_TYPE/${videoStreamType}/g;`);
sedCommands.push(`s/###${configSource}_VIDEOSTREAM/${videoStreamUrl}/g;`);
}
return sedCommands;
}
private async saveDSResNetConfiguration(): Promise<boolean> {
let status = false;
try {
const activeStreams = this.getActiveStreams();
const sedCommands = this.computeDSConfiguration(activeStreams);
sedCommands.push(`s/###BATCH_SIZE/${this.batchSizeMap[activeStreams]}/g;`);
sedCommands.push(`" ${pathResolve(this.resNetConfigFolderPath, 'DSConfig_Template.txt')} > ${pathResolve(this.storageFolderPath, 'DSConfig.txt')}`);
this.logger.log(['ModuleService', 'info'], `Executing sed command: ${sedCommands.join('')}`);
await promisify(exec)(sedCommands.join(''));
await this.iotCentral.setPipelineState(activeStreams > 0 ? PipelineState.Active : PipelineState.Inactive);
await this.saveDSMsgConvConfiguration(this.resNetConfigFolderPath);
status = true;
}
catch (ex) {
this.logger.log(['ModuleService', 'error'], `Exception while updating DSConfig.txt: ${ex.message}`);
}
return status;
}
private async saveCustomVisionConfiguration(): Promise<boolean> {
let status = false;
try {
const customVisionModelUrl = this.iotCentral.detectionSettings.wpCustomVisionModelUrl;
if (!customVisionModelUrl) {
this.logger.log(['ModuleService', 'warning'], `No Custom Vision model url - skipping...`);
return false;
}
await this.iotCentral.sendMeasurement({
[ModuleInfoFieldIds.Event.ChangeVideoModel]: customVisionModelUrl
});
await this.changeVideoModel(customVisionModelUrl);
// TODO:
// Rewrite the labels.txt file because it can be packaged with Windows-style line endings ('/r/n')
// from the Custom Vision service. DeepStream interprets these explicitly and the detection class
// names include a '/r' on the end.
const labelData = (fse.readFileSync(pathResolve(this.onnxModelFolderPath, 'labels.txt'), 'utf8') || '').replace(/\r\n|\r|\n/g, '\n');
fse.writeFileSync(pathResolve(this.onnxModelFolderPath, 'labels.txt'), labelData);
const numClasses = labelData.split('\n').length;
this.logger.log(['ModuleService', 'info'], `Number of class labels detected: ${numClasses}`);
const sedConfigInferCommands = [`sed "`];
sedConfigInferCommands.push(`s/###CLASSES_COUNT/${numClasses}/g;`);
sedConfigInferCommands.push(`" ${pathResolve(this.onnxConfigFolderPath, 'config_infer_onnx_template.txt')} > ${pathResolve(this.onnxConfigFolderPath, 'config_infer_onnx.txt')}`);
this.logger.log(['ModuleService', 'info'], `Executing sed command: ${sedConfigInferCommands.join('')}`);
await promisify(exec)(sedConfigInferCommands.join(''));
const activeStreams = this.getActiveStreams();
const sedCommands = this.computeDSConfiguration(activeStreams);
sedCommands.push(`" ${pathResolve(this.onnxConfigFolderPath, 'onnxConfig_template.txt')} > ${pathResolve(this.storageFolderPath, 'DSConfig.txt')}`);
this.logger.log(['ModuleService', 'info'], `Executing sed command: ${sedCommands.join('')}`);
await promisify(exec)(sedCommands.join(''));
await this.iotCentral.setPipelineState(activeStreams > 0 ? PipelineState.Active : PipelineState.Inactive);
await this.saveDSMsgConvConfiguration(this.onnxConfigFolderPath);
status = true;
}
catch (ex) {
this.logger.log(['ModuleService', 'error'], `Exception while updating DSConfig.txt: ${ex.message}`);
}
return status;
}
private async saveDSMsgConvConfiguration(configFilePath: string): Promise<boolean> {
let status = false;
try {
const sedCommands = [`sed "`];
for (const key in this.iotCentral.videoStreamInputSettings) {
if (!this.iotCentral.videoStreamInputSettings.hasOwnProperty(key)) {
continue;
}
const input = this.iotCentral.videoStreamInputSettings[key];
const cameraId = (_get(input, 'cameraId') || 'NOT_SET').replace(/\ /g, '_');
sedCommands.push(`s/###${MsgConvConfigMap[key]}_ID/${cameraId}/g;`);
}
sedCommands.push(`" ${pathResolve(configFilePath, 'msgconv_config_template.txt')} > ${pathResolve(configFilePath, 'msgconv_config.txt')}`);
this.logger.log(['ModuleService', 'info'], `Executing sed command: '${sedCommands.join('')}'`);
await promisify(exec)(sedCommands.join(''));
status = true;
}
catch (ex) {
this.logger.log(['ModuleService', 'error'], `Exception while updating msgconv_config.txt: ${ex.message}`);
}
return status;
}
} | the_stack |
import {
ShaderLayout,
BindingLayout,
UniformBinding,
UniformBlockBinding,
ProgramBindings,
AttributeBinding,
VaryingBinding,
AttributeLayout,
AccessorObject
} from '@luma.gl/api';
import GL from '@luma.gl/constants';
import {isWebGL2} from '../../context/context/webgl-checks';
import Accessor from '../../classic/accessor'; // TODO - should NOT depend on classic API
import {decodeUniformType, decodeAttributeType} from './uniforms';
import {getVertexFormat} from '../converters/vertex-formats';
import {isSamplerUniform} from './uniforms';
/**
* Extract metadata describing binding information for a program's shaders
* Note: `linkProgram()` needs to have been called
* (although linking does not need to have been successful).
*/
export function getShaderLayout(gl: WebGLRenderingContext, program: WebGLProgram): ShaderLayout {
const programBindings = getProgramBindings(gl, program);
const shaderLayout: ShaderLayout = {
attributes: [],
bindings: []
};
for (const attribute of programBindings.attributes) {
const format =
// attribute.accessor.format ||
getVertexFormat(attribute.accessor.type || GL.FLOAT, attribute.accessor.size);
shaderLayout.attributes.push({
name: attribute.name,
location: attribute.location,
format,
stepMode: attribute.accessor.divisor === 1 ? 'instance' : 'vertex'
});
}
// Uniform blocks
for (const uniformBlock of programBindings.uniformBlocks) {
const uniforms = uniformBlock.uniforms.map((uniform) => ({
name: uniform.name,
format: uniform.format,
byteOffset: uniform.byteOffset,
byteStride: uniform.byteStride,
arrayLength: uniform.arrayLength
}));
shaderLayout.bindings.push({
type: 'uniform',
name: uniformBlock.name,
location: uniformBlock.location,
visibility: (uniformBlock.vertex ? 0x1 : 0) & (uniformBlock.fragment ? 0x2 : 0),
minBindingSize: uniformBlock.byteLength,
uniforms
});
}
let textureUnit = 0;
for (const uniform of programBindings.uniforms) {
if (isSamplerUniform(uniform.type)) {
const {viewDimension, sampleType} = getSamplerInfo(uniform.type);
shaderLayout.bindings.push({
type: 'texture',
name: uniform.name,
location: textureUnit,
viewDimension,
sampleType
});
// @ts-expect-error
uniform.textureUnit = textureUnit;
textureUnit += 1;
}
}
const uniforms = programBindings.uniforms?.filter((uniform) => uniform.location !== null) || [];
if (uniforms.length) {
shaderLayout.uniforms = uniforms;
}
if (programBindings.varyings?.length) {
shaderLayout.varyings = programBindings.varyings;
}
return shaderLayout;
}
/**
* Extract metadata describing binding information for a program's shaders
* Note: `linkProgram()` needs to have been called
* (although linking does not need to have been successful).
*/
export function getProgramBindings(
gl: WebGLRenderingContext,
program: WebGLProgram
): ProgramBindings {
const config: ProgramBindings = {
attributes: readAttributeBindings(gl, program),
uniforms: readUniformBindings(gl, program),
uniformBlocks: readUniformBlocks(gl, program),
varyings: readVaryings(gl, program)
};
Object.seal(config);
return config;
// generateWebGPUStyleBindings(bindings);
}
/**
* Extract info about all transform feedback varyings
*
* linkProgram needs to have been called, although linking does not need to have been successful
*/
function readAttributeBindings(
gl: WebGLRenderingContext,
program: WebGLProgram
): AttributeBinding[] {
const attributes: AttributeBinding[] = [];
const count = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
for (let index = 0; index < count; index++) {
const {name, type: compositeType, size} = gl.getActiveAttrib(program, index);
const location = gl.getAttribLocation(program, name);
// Add only user provided attributes, for built-in attributes like
// `gl_InstanceID` locaiton will be < 0
if (location >= 0) {
const {glType, components} = decodeAttributeType(compositeType);
const accessor: AccessorObject = {type: glType, size: size * components};
// Any attribute name containing the word "instance" will be assumed to be instanced
if (/instance/i.test(name)) {
accessor.divisor = 1;
}
const attributeInfo = {location, name, accessor: new Accessor(accessor)}; // Base values
attributes.push(attributeInfo);
}
}
attributes.sort((a: AttributeBinding, b: AttributeBinding) => a.location - b.location);
return attributes;
}
/**
* Extract info about all transform feedback varyings
*
* linkProgram needs to have been called, although linking does not need to have been successful
*/
function readVaryings(gl: WebGLRenderingContext, program: WebGLProgram): VaryingBinding[] {
if (!isWebGL2(gl)) {
return [];
}
const gl2 = gl as WebGL2RenderingContext;
const varyings: VaryingBinding[] = [];
const count = gl.getProgramParameter(program, GL.TRANSFORM_FEEDBACK_VARYINGS);
for (let location = 0; location < count; location++) {
const {name, type: compositeType, size} = gl2.getTransformFeedbackVarying(program, location);
const {glType, components} = decodeUniformType(compositeType);
const accessor = new Accessor({type: glType, size: size * components});
const varying = {location, name, accessor}; // Base values
varyings.push(varying);
}
varyings.sort((a, b) => a.location - b.location);
return varyings;
}
/**
* Extract info about all uniforms
*
* Query uniform locations and build name to setter map.
*/
function readUniformBindings(gl: WebGLRenderingContext, program: WebGLProgram): UniformBinding[] {
const uniforms: UniformBinding[] = [];
const uniformCount = gl.getProgramParameter(program, GL.ACTIVE_UNIFORMS);
for (let i = 0; i < uniformCount; i++) {
const {name: rawName, size, type} = gl.getActiveUniform(program, i);
const {name, isArray} = parseUniformName(rawName);
let webglLocation = gl.getUniformLocation(program, name);
const uniformInfo = {
// WebGL locations are uniquely typed but just numbers
location: webglLocation as number,
name,
size,
type,
isArray
};
uniforms.push(uniformInfo);
// Array (e.g. matrix) uniforms can occupy several 4x4 byte banks
if (uniformInfo.size > 1) {
for (let j = 0; j < uniformInfo.size; j++) {
const elementName = `${name}[${j}]`;
webglLocation = gl.getUniformLocation(program, elementName);
const arrayElementUniformInfo = {
...uniformInfo,
name: elementName,
location: webglLocation as number
};
uniforms.push(arrayElementUniformInfo);
}
}
}
return uniforms;
}
/**
* Extract info about all "active" uniform blocks
*
* ("Active" just means that unused (aka inactive) blocks may have been
* optimized away during linking)
*/
function readUniformBlocks(
gl: WebGLRenderingContext,
program: WebGLProgram
): UniformBlockBinding[] {
if (!isWebGL2(gl)) {
return [];
}
const gl2 = gl as WebGL2RenderingContext;
const getBlockParameter = (blockIndex: number, pname: GL): any =>
gl2.getActiveUniformBlockParameter(program, blockIndex, pname);
const uniformBlocks: UniformBlockBinding[] = [];
const blockCount = gl2.getProgramParameter(program, GL.ACTIVE_UNIFORM_BLOCKS);
for (let blockIndex = 0; blockIndex < blockCount; blockIndex++) {
const blockInfo = {
name: gl2.getActiveUniformBlockName(program, blockIndex),
location: getBlockParameter(blockIndex, GL.UNIFORM_BLOCK_BINDING),
byteLength: getBlockParameter(blockIndex, GL.UNIFORM_BLOCK_DATA_SIZE),
vertex: getBlockParameter(blockIndex, GL.UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER),
fragment: getBlockParameter(blockIndex, GL.UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER),
uniformCount: getBlockParameter(blockIndex, GL.UNIFORM_BLOCK_ACTIVE_UNIFORMS),
uniforms: [] as any[]
};
const uniformIndices = getBlockParameter(blockIndex, GL.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES);
const uniformType = gl2.getActiveUniforms(program, uniformIndices, GL.UNIFORM_TYPE); // Array of GLenum indicating the types of the uniforms.
const uniformArrayLength = gl2.getActiveUniforms(program, uniformIndices, GL.UNIFORM_SIZE); // Array of GLuint indicating the sizes of the uniforms.
const uniformBlockIndex = gl2.getActiveUniforms(
program,
uniformIndices,
GL.UNIFORM_BLOCK_INDEX
); // Array of GLint indicating the block indices of the uniforms.
const uniformOffset = gl2.getActiveUniforms(program, uniformIndices, GL.UNIFORM_OFFSET); // Array of GLint indicating the uniform buffer offsets.
const uniformStride = gl2.getActiveUniforms(program, uniformIndices, GL.UNIFORM_ARRAY_STRIDE); // Array of GLint indicating the strides between the elements.
const uniformMatrixStride = gl2.getActiveUniforms(
program,
uniformIndices,
GL.UNIFORM_MATRIX_STRIDE
); // Array of GLint indicating the strides between columns of a column-major matrix or a row-major matrix.
const uniformRowMajor = gl2.getActiveUniforms(program, uniformIndices, GL.UNIFORM_IS_ROW_MAJOR);
for (let i = 0; i < blockInfo.uniformCount; ++i) {
blockInfo.uniforms.push({
name: gl2.getActiveUniform(program, uniformIndices[i]).name,
format: decodeUniformType(uniformType[i]).format,
type: uniformType[i],
arrayLength: uniformArrayLength[i],
byteOffset: uniformOffset[i],
byteStride: uniformStride[i],
matrixStride: uniformStride[i],
rowMajor: uniformRowMajor[i]
});
}
uniformBlocks.push(blockInfo);
}
uniformBlocks.sort((a, b) => a.location - b.location);
return uniformBlocks;
}
const SAMPLER_UNIFORMS_GL_TO_GPU: Record<
number,
[
'1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d',
'float' | 'unfilterable-float' | 'depth' | 'sint' | 'uint'
]
> = {
[GL.SAMPLER_2D]: ['2d', 'float'],
[GL.SAMPLER_CUBE]: ['cube', 'float'],
[GL.SAMPLER_3D]: ['3d', 'float'],
[GL.SAMPLER_2D_SHADOW]: ['3d', 'depth'],
[GL.SAMPLER_2D_ARRAY]: ['2d-array', 'float'],
[GL.SAMPLER_2D_ARRAY_SHADOW]: ['2d-array', 'depth'],
[GL.SAMPLER_CUBE_SHADOW]: ['cube', 'float'],
[GL.INT_SAMPLER_2D]: ['2d', 'sint'],
[GL.INT_SAMPLER_3D]: ['3d', 'sint'],
[GL.INT_SAMPLER_CUBE]: ['cube', 'sint'],
[GL.INT_SAMPLER_2D_ARRAY]: ['2d-array', 'uint'],
[GL.UNSIGNED_INT_SAMPLER_2D]: ['2d', 'uint'],
[GL.UNSIGNED_INT_SAMPLER_3D]: ['3d', 'uint'],
[GL.UNSIGNED_INT_SAMPLER_CUBE]: ['cube', 'uint'],
[GL.UNSIGNED_INT_SAMPLER_2D_ARRAY]: ['2d-array', 'uint']
};
function getSamplerInfo(type: GL):
| {
viewDimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d';
sampleType: 'float' | 'unfilterable-float' | 'depth' | 'sint' | 'uint';
}
| undefined {
let sampler = SAMPLER_UNIFORMS_GL_TO_GPU[type];
if (sampler) {
const [viewDimension, sampleType] = sampler;
return {viewDimension, sampleType};
}
return null;
}
// HELPERS
function parseUniformName(name: string): {name: string; length: number; isArray: boolean} {
// Shortcut to avoid redundant or bad matches
if (name[name.length - 1] !== ']') {
return {
name,
length: 1,
isArray: false
};
}
// if array name then clean the array brackets
const UNIFORM_NAME_REGEXP = /([^[]*)(\[[0-9]+\])?/;
const matches = name.match(UNIFORM_NAME_REGEXP);
if (!matches || matches.length < 2) {
throw new Error(`Failed to parse GLSL uniform name ${name}`);
}
return {
name: matches[1],
length: matches[2] ? 1 : 0,
isArray: Boolean(matches[2])
};
}
/**
* TODO - verify this is a copy of above and delete
* import type {TextureFormat} from '@luma.gl/api';
* Extract info about all "active" uniform blocks
* ("Active" just means that unused (inactive) blocks may have been optimized away during linking)
*
function getUniformBlockBindings(gl, program): Binding[] {
if (!isWebGL2(gl)) {
return;
}
const bindings: Binding[] = [];
const count = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS);
for (let blockIndex = 0; blockIndex < count; blockIndex++) {
const vertex = gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER),
const fragment = gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER),
const visibility = (vertex) + (fragment);
const binding: BufferBinding = {
location: gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_BINDING),
// name: gl.getActiveUniformBlockName(program, blockIndex),
type: 'uniform',
visibility,
minBindingSize: gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_DATA_SIZE),
// uniformCount: gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_ACTIVE_UNIFORMS),
// uniformIndices: gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES),
}
bindings.push(binding);
}
return bindings;
}
function setBindings(gl2: WebGL2RenderingContext, program: WebGLProgram, bindings: Binding[][]): void {
for (const bindGroup of bindings) {
for (const binding of bindGroup) {
}
}
// Set up indirection table
// this.gl2.uniformBlockBinding(this.handle, blockIndex, blockBinding);
}
*/ | the_stack |
import 'mocha'
import * as admin from 'firebase-admin'
import fs from 'fs'
import { expect } from 'chai'
import * as sinon from 'sinon'
import 'sinon-chai'
import { to } from '../utils/async'
import { encrypt } from '../utils/encryption'
import functionsTestLib from 'firebase-functions-test'
const functionsTest = functionsTestLib()
const responsePath = 'responses/actionRunner/1'
const createdAt = 'timestamp'
const existingProjectId = 'existing'
describe('actionRunner RTDB Cloud Function (RTDB:onCreate)', function () {
(this as any).timeout(20000)
let actionRunner
let adminInitStub
let databaseStub
let setStub
let refStub
let docStub
let collectionStub
let parentStorageStub
let parentFirestoreStub
before(() => {
parentStorageStub = sinon.stub().returns({
bucket: sinon.stub().returns({
file: sinon.stub().returns({
delete: sinon.stub().returns(Promise.resolve({})),
// Mock download method with invalid JSON file data
download: sinon.spy(({ destination }) => {
fs.writeFileSync(
destination,
JSON.stringify({ asdf: 'asdf' }, null, 2)
)
return Promise.resolve({ asdf: 'asdf' })
})
}),
upload: sinon.stub().returns(Promise.resolve({}))
})
})
// Stub Firebase's admin.initializeApp()
parentFirestoreStub = sinon.stub().returns({
collection: sinon.stub().returns({
doc: sinon.stub().returns({
get: sinon.stub().returns(Promise.resolve({ data: () => ({}) })),
set: sinon.stub().returns(Promise.resolve(null)),
path: 'projects/my-project'
}),
path: 'projects',
firestore: {
batch: sinon.stub().returns({
commit: sinon.stub().returns(Promise.resolve()),
set: sinon.stub().returns({})
}),
doc: sinon.stub().returns({
get: sinon.stub().returns(
Promise.resolve({
data: () => ({ some: 'value' }),
exists: true
})
)
})
},
get: sinon.stub().returns(
Promise.resolve({
data: () => ({ some: 'value' }),
exists: true
})
)
}),
doc: sinon.stub().returns({
firestore: {
batch: sinon.stub().returns({
commit: sinon.stub().returns(Promise.resolve()),
set: sinon.stub().returns({})
}),
doc: sinon.stub().returns({
get: sinon.stub().returns(
Promise.resolve({
data: () => ({ some: 'value' }),
exists: true
})
)
})
},
update: sinon.stub().returns(Promise.resolve()),
get: sinon
.stub()
.returns(
Promise.resolve({ data: () => ({ some: 'value' }), exists: true, get: () => 'token' })
),
})
})
parentFirestoreStub.batch = sinon.stub().returns({
set: sinon.stub().returns(Promise.resolve()),
commit: sinon.stub().returns(Promise.resolve())
})
adminInitStub = sinon.stub(admin, 'initializeApp').returns(({
firestore: parentFirestoreStub,
database: sinon.stub().returns({
ref: sinon.stub().returns({
once: sinon.stub().returns(Promise.resolve({ val: () => ({}) })),
update: sinon.stub().returns(Promise.resolve())
})
}),
storage: parentStorageStub
} as any))
sinon.stub(admin.credential, 'cert')
})
after(() => {
// Restore firebase-admin stub to the original
adminInitStub.restore()
})
beforeEach(() => {
// Stub Firebase's functions.config() (default in test/setup)
functionsTest.mockConfig({
firebase: {
databaseURL: 'https://some-project.firebaseio.com'
},
encryption: {
password: 'asdf'
},
algolia: {
app_id: 'asdf',
api_key: 'asdf'
},
})
// Stubs for Firestore methods
docStub = sinon.stub().returns({
set: sinon.stub().returns(Promise.resolve({})),
get: sinon.stub().returns(Promise.resolve({ get: () => {} })),
collection: sinon.stub().returns({
add: sinon.stub().returns(Promise.resolve({})),
doc: docStub
})
})
docStub
.withArgs(`projects/${existingProjectId}/environments/asdf`)
.returns({
get: sinon.stub().returns(
Promise.resolve({
data: () => ({ serviceAccount: { credential: 'asdf' } }),
exists: true
})
)
})
collectionStub = sinon.stub().returns({
add: sinon.stub().returns(Promise.resolve({})),
doc: docStub
})
// Create Firestore stub out of stubbed methods
const firestoreStub = sinon
.stub()
.returns({ doc: docStub, collection: collectionStub })
// Apply stubs as admin.firestore()
sinon.stub(admin, 'firestore').get(() => firestoreStub)
admin.firestore.FieldValue = ({ serverTimestamp: sinon.stub(() => createdAt) } as any)
// Stubs for RTDB methods
setStub = sinon.stub().returns(Promise.resolve({ ref: 'new_ref' }))
refStub = sinon.stub().returns({
set: setStub,
update: setStub,
push: sinon.stub().returns(Promise.resolve({}))
})
databaseStub = sinon.stub().returns({ ref: refStub })
databaseStub.ServerValue = { TIMESTAMP: 'test' }
// Apply stubs as admin.database()
sinon.stub(admin, 'database').get(() => databaseStub)
// Load wrapped version of Cloud Function
actionRunner = functionsTest.wrap(
require(`${__dirname}/../../src/actionRunner`).default
)
/* eslint-enable global-require */
})
afterEach(() => {
// Restoring our test-level stubs to the original methods
functionsTest.cleanup()
})
describe('Invalid Action Template', () => {
it('Throws and updates error if projectId is undefined', async () => {
const snap = {
val: () => ({})
}
const fakeContext = {
params: { pushId: 1 }
}
// Invoke with fake event object
const [err] = await to(actionRunner(snap, fakeContext))
// Confir error thrown with correct message
expect(err).to.have.property('message', 'projectId parameter is required')
// Ref for response is correct path
expect(refStub).to.have.been.calledWith(responsePath)
// Error object written to response
expect(setStub).to.have.been.calledOnce
})
it('Throws if action template is not included', async () => {
const snap = {
val: () => ({ projectId: 'test' }),
ref: refStub()
}
const fakeContext = {
params: { pushId: 1 }
}
// Invoke with fake event object
const [err] = await to(actionRunner(snap, fakeContext))
// Response marked as started
expect(setStub).to.have.been.calledWith({
startedAt: 'test',
status: 'started'
})
// Confir error thrown with correct message
expect(err).to.have.property(
'message',
'Valid Action Template is required to run steps'
)
// Ref for response is correct path
expect(refStub).to.have.been.calledWith(responsePath)
// Error object written to response
expect(setStub).to.have.been.calledWith({
completed: true,
completedAt: 'test',
error: 'Valid Action Template is required to run steps',
status: 'error'
})
})
it('Throws if action template is not an object', async () => {
const snap = {
val: () => ({ projectId: 'test', template: 'asdf' }),
ref: refStub()
}
const fakeContext = {
params: { pushId: 1 }
}
// Invoke with fake event object
const [err] = await to(actionRunner(snap, fakeContext))
// Response marked as started
expect(setStub).to.have.been.calledWith({
startedAt: 'test',
status: 'started'
})
// Confir error thrown with correct message
expect(err).to.have.property(
'message',
'Valid Action Template is required to run steps'
)
// Ref for response is correct path
expect(refStub).to.have.been.calledWith(responsePath)
// Error object written to response
expect(setStub).to.have.been.calledWith({
completed: true,
completedAt: 'test',
error: 'Valid Action Template is required to run steps',
status: 'error'
})
})
it('Throws if action template does not contain steps', async () => {
const snap = {
val: () => ({ projectId: 'test', template: { asdf: 'asdf' } }),
ref: refStub()
}
const fakeContext = {
params: { pushId: 1 }
}
// Invoke with fake event object
const [err] = await to(actionRunner(snap, fakeContext))
// Response marked as started
expect(setStub).to.have.been.calledWith({
startedAt: 'test',
status: 'started'
})
// Confir error thrown with correct message
expect(err).to.have.property(
'message',
'Valid Action Template is required to run steps'
)
// Ref for response is correct path
expect(refStub).to.have.been.calledWith(responsePath)
// Error object written to response
expect(setStub).to.have.been.calledWith({
completed: true,
completedAt: 'test',
error: 'Valid Action Template is required to run steps',
status: 'error'
})
})
it('Throws if action template does not contain inputs', async () => {
const snap = {
val: () => ({ projectId: 'test', template: { steps: [] } }),
ref: refStub()
}
const fakeContext = {
params: { pushId: 1 }
}
// Invoke with fake event object
const [err] = await to(actionRunner(snap, fakeContext))
// Response marked as started
expect(setStub).to.have.been.calledWith({
startedAt: 'test',
status: 'started'
})
// Confir error thrown with correct message
expect(err).to.have.property(
'message',
'Inputs array was not provided to action request'
)
// Ref for response is correct path
expect(refStub).to.have.been.calledWith(responsePath)
// Error object written to response
expect(setStub).to.have.been.calledWith({
completed: true,
completedAt: 'test',
error: 'Inputs array was not provided to action request',
status: 'error'
})
})
it('Throws if action template does not contain inputValues', async () => {
const snap = {
val: () => ({ projectId: 'test', template: { steps: [], inputs: [] } }),
ref: refStub()
}
const fakeContext = {
params: { pushId: 1 }
}
// Invoke with fake event object
const [err] = await to(actionRunner(snap, fakeContext))
// Response marked as started
expect(setStub).to.have.been.calledWith({
startedAt: 'test',
status: 'started'
})
// Confir error thrown with correct message
expect(err).to.have.property(
'message',
'Input values array was not provided to action request'
)
// Ref for response is correct path
expect(refStub).to.have.been.calledWith(responsePath)
// Error object written to response
expect(setStub).to.have.been.calledWith({
completed: true,
completedAt: 'test',
error: 'Input values array was not provided to action request',
status: 'error'
})
})
it('Throws if inputValues are not passed', async () => {
const snap = {
val: () => ({
projectId: 'test',
template: { steps: [], inputs: [] }
}),
ref: refStub()
}
const fakeContext = {
params: { pushId: 1 }
}
// Invoke with fake event object
const [err] = await to(actionRunner(snap, fakeContext))
// Response marked as started
expect(setStub).to.have.been.calledWith({
startedAt: 'test',
status: 'started'
})
// Confir error thrown with correct message
expect(err).to.have.property(
'message',
'Input values array was not provided to action request'
)
// Ref for response is correct path
expect(refStub).to.have.been.calledWith(responsePath)
// Error object written to response
expect(setStub).to.have.been.calledWith({
completed: true,
completedAt: 'test',
error: 'Input values array was not provided to action request',
status: 'error'
})
})
it('Throws if environment does not have databaseURL', async () => {
const snap = {
val: () => ({
projectId: 'test',
inputValues: [],
environments: [{ type: 'test' }],
template: { steps: [], inputs: [] }
}),
ref: refStub()
}
const fakeContext = {
params: { pushId: 1 }
}
// Invoke with fake event object
const [err] = await to(actionRunner(snap, fakeContext))
// Response marked as started
expect(setStub).to.have.been.calledWith({
startedAt: 'test',
status: 'started'
})
// Confir error thrown with correct message
expect(err).to.have.property(
'message',
'databaseURL is required for action to authenticate through serviceAccount'
)
// Ref for response is correct path
expect(refStub).to.have.been.calledWith(responsePath)
// Error object written to response
expect(setStub).to.have.been.calledWith({
completed: true,
completedAt: 'test',
error:
'databaseURL is required for action to authenticate through serviceAccount',
status: 'error'
})
})
it('Throws if environment does not an environment key or id', async () => {
const snap = {
val: () => ({
projectId: 'test',
inputValues: [],
environments: [
{ databaseURL: 'https://some-project.firebaseio.com' }
],
template: { steps: [], inputs: [] }
}),
ref: refStub()
}
const fakeContext = {
params: { pushId: 1 }
}
// Invoke with fake event object
const [err] = await to(actionRunner(snap, fakeContext))
// Response marked as started
expect(setStub).to.have.been.calledWith({
startedAt: 'test',
status: 'started'
})
// Confir error thrown with correct message
expect(err).to.have.property(
'message',
'environmentKey or id is required for action to authenticate through serviceAccount'
)
// Ref for response is correct path
expect(refStub).to.have.been.calledWith(responsePath)
// Error object written to response
expect(setStub).to.have.been.calledWith({
completed: true,
completedAt: 'test',
error:
'environmentKey or id is required for action to authenticate through serviceAccount',
status: 'error'
})
})
it('Throws if project does not contain serviceAccount', async () => {
const id = 'asdf'
const projectId = 'another'
const snap = {
val: () => ({
projectId,
inputValues: [],
environments: [
{ databaseURL: 'https://some-project.firebaseio.com', id }
],
template: { steps: [], inputs: [] }
}),
ref: refStub()
}
const fakeContext = {
params: { pushId: 1 }
}
// Invoke with fake event object
const [err] = await to(actionRunner(snap, fakeContext))
// Response marked as started
expect(setStub).to.have.been.calledWith({
startedAt: 'test',
status: 'started'
})
// Confir error thrown with correct message
expect(err).to.have.property(
'message',
`Project containing service account not at path: projects/${projectId}/environments/${id}`
)
// Ref for response is correct path
expect(refStub).to.have.been.calledWith(responsePath)
// Error object written to response
expect(setStub).to.have.been.calledWith({
completed: true,
completedAt: 'test',
error: `Project containing service account not at path: projects/${projectId}/environments/${id}`,
status: 'error'
})
})
it('Throws if provided an invalid service account object (i.e. a string that is not an encrypted object)', async () => {
const snap = {
val: () => ({
projectId: existingProjectId,
inputValues: [],
environments: [
{ databaseURL: 'https://some-project.firebaseio.com', id: 'asdf' }
],
template: { steps: [], inputs: [] }
}),
ref: refStub()
}
const fakeContext = {
params: { pushId: 1 }
}
// Invoke with fake event object
const [err] = await to(actionRunner(snap, fakeContext))
// Response marked as started
expect(setStub).to.have.been.calledWith({
startedAt: 'test',
status: 'started'
})
// Confir error thrown with correct message
expect(err).to.have.property(
'message',
'Service account not a valid object'
)
// Ref for response is correct path
expect(refStub).to.have.been.calledWith(responsePath)
// Error object written to response
expect(setStub).to.have.been.calledWith({
completed: true,
completedAt: 'test',
error: 'Service account not a valid object',
status: 'error'
})
})
it('Throws if template contains invalid steps', async () => {
const validProjectId = 'aosidjfoaisjdfoi'
docStub.withArgs(`projects/${validProjectId}/environments/asdf`).returns({
get: sinon.stub().returns(
Promise.resolve({
data: () => ({
serviceAccount: {
credential: encrypt(({
type: 'service_account',
project_id: 'asdf',
private_key_id: 'asdf',
private_key: 'asdf',
client_email: 'asdf',
client_id: 'sadf',
auth_uri: 'https://accounts.google.com/o/oauth2/auth',
token_uri: 'https://accounts.google.com/o/oauth2/token',
auth_provider_x509_cert_url:
'https://www.googleapis.com/oauth2/v1/certs',
client_x509_cert_url: 'asdf'
} as any))
}
}),
exists: true
})
)
})
const snap = {
val: () => ({
projectId: validProjectId,
inputValues: ['projects'],
environments: [
{
databaseURL: 'https://some-project.firebaseio.com',
id: 'asdf'
}
],
template: {
steps: [
{
type: 'copy'
}
],
inputs: []
}
}),
ref: refStub()
}
const fakeContext = {
params: { pushId: 1 }
}
// Invoke with fake event object
const [err] = await to(actionRunner(snap, fakeContext))
// Response marked as started
expect(setStub).to.have.been.calledWith({
startedAt: 'test',
status: 'started'
})
// Confirm res
expect(err).to.have.property(
'message',
'Error running step: 0 : src, dest and src.resource are required to run step'
)
// Ref for response is correct path
expect(refStub).to.have.been.calledWith(responsePath)
// Success object written to response
expect(setStub).to.have.been.calledWith({
completed: true,
completedAt: 'test',
error:
'Error running step: 0 : src, dest and src.resource are required to run step',
status: 'error'
})
})
})
describe('Action template with type "copy"', () => {
/**
* @param opts
*/
function createValidActionRunnerStubs(opts?: any) {
const {
projectId = 'asdfasdf1',
srcResource = 'rtdb',
destResource = 'rtdb',
inputValues = ['projects']
} = opts || {}
// Environment Doc Stub (subcollection of project document)
const environmentDocStub = docStub
.withArgs(`projects/${projectId}/environments/asdf`)
.returns({
get: sinon.stub().returns(
Promise.resolve({
data: () => ({
serviceAccount: {
credential: encrypt(({
type: 'service_account',
project_id: 'asdf',
private_key_id: 'asdf',
private_key: 'asdf',
client_email: 'asdf',
client_id: 'sadf',
auth_uri: 'https://accounts.google.com/o/oauth2/auth',
token_uri: 'https://accounts.google.com/o/oauth2/token',
auth_provider_x509_cert_url:
'https://www.googleapis.com/oauth2/v1/certs',
client_x509_cert_url: 'asdf'
} as any))
}
}),
exists: true
})
)
})
// Event DataSnapshot stub
const snapStub = {
val: () => ({
projectId,
inputValues,
environments: [
{
databaseURL: 'https://some-project.firebaseio.com',
id: 'asdf'
},
{
databaseURL: 'https://some-project.firebaseio.com',
id: 'asdf'
}
],
template: {
steps: [
{
type: 'copy',
dest: { pathType: 'input', path: 0, resource: destResource },
src: { pathType: 'input', path: 0, resource: srcResource }
}
],
inputs: [{ type: 'userInput' }]
}
}),
ref: refStub()
}
return {
snapStub,
environmentDocStub
}
}
describe('with src: "firestore" and dest: "firestore"', () => {
it('successfully copies a single document between Firestore instances', async () => {
const { snapStub } = createValidActionRunnerStubs({
srcResource: 'firestore',
destResource: 'firestore',
inputValues: ['projects/my-project']
})
const fakeContext = {
params: { pushId: 1 }
}
// Invoke with fake event object
const res = await actionRunner(snapStub, fakeContext)
// Response marked as started
expect(setStub).to.have.been.calledWith({
startedAt: 'test',
status: 'started'
})
// Confirm res
expect(res).to.be.null
// Ref for response is correct path
expect(refStub).to.have.been.calledWith(responsePath)
// Success object written to response
expect(setStub).to.have.been.calledWith({
completed: true,
completedAt: 'test',
status: 'success'
})
})
it('successfully copies multiple documents between Firestore instances', async function () {
// this.retries(3) // retry to avoid file already exists error for serviceAccount
const { snapStub } = createValidActionRunnerStubs({
srcResource: 'firestore',
destResource: 'firestore'
})
const fakeContext = {
params: { pushId: 1 }
}
// Invoke with fake event object
const res = await actionRunner(snapStub, fakeContext)
// Response marked as started
expect(setStub).to.have.been.calledWith({
startedAt: 'test',
status: 'started'
})
// Confirm res
expect(res).to.be.null
// Ref for response is correct path
expect(refStub).to.have.been.calledWith(responsePath)
// Success object written to response
expect(setStub).to.have.been.calledWith({
completed: true,
completedAt: 'test',
status: 'success'
})
})
})
describe('with src: "firestore" and dest: "rtdb"', () => {
it('successfully copies from Firestore to Real Time Database', async () => {
const { snapStub } = createValidActionRunnerStubs({
srcResource: 'firestore',
destResource: 'rtdb'
})
const fakeContext = {
params: { pushId: 1 }
}
// Invoke with fake event object
const res = await actionRunner(snapStub, fakeContext)
// Response marked as started
expect(setStub).to.have.been.calledWith({
startedAt: 'test',
status: 'started'
})
// Confirm res
expect(res).to.be.null
// Ref for response is correct path
expect(refStub).to.have.been.calledWith(responsePath)
// Success object written to response
expect(setStub).to.have.been.calledWith({
completed: true,
completedAt: 'test',
status: 'success'
})
})
})
describe('with src "rtdb" and dest: "rtdb"', () => {
it('successfully copies between RTDB instances', async () => {
const { snapStub } = createValidActionRunnerStubs()
const fakeContext = {
params: { pushId: 1 }
}
// Invoke with fake event object
const res = await actionRunner(snapStub, fakeContext)
// Response marked as started
expect(setStub).to.have.been.calledWith({
startedAt: 'test',
status: 'started'
})
// Confirm res
expect(res).to.be.null
// Ref for response is correct path
expect(refStub).to.have.been.calledWith(responsePath)
// Success object written to response
expect(setStub).to.have.been.calledWith({
completed: true,
completedAt: 'test',
status: 'success'
})
})
})
describe('with src: "rtdb" and dest: "firestore"', () => {
it('successfully copies from RTDB to Firestore', async () => {
const { snapStub } = createValidActionRunnerStubs({
srcResource: 'rtdb',
destResource: 'firestore'
})
const fakeContext = {
params: { pushId: 1 }
}
// Invoke with fake event object
const res = await actionRunner(snapStub, fakeContext)
// Response marked as started
expect(setStub).to.have.been.calledWith({
startedAt: 'test',
status: 'started'
})
// Confirm res
expect(res).to.be.null
// Ref for response is correct path
expect(refStub).to.have.been.calledWith(responsePath)
// Success object written to response
expect(setStub).to.have.been.calledWith({
completed: true,
completedAt: 'test',
status: 'success'
})
})
})
describe('with src: "rtdb" and dest: "storage"', () => {
// Skipped due to "Error running step: 0 : ENOENT: no such file or directory, open"
it.skip('successfully copies from RTDB to Cloud Storage', async () => {
const { snapStub } = createValidActionRunnerStubs({
srcResource: 'rtdb',
destResource: 'storage'
})
const fakeContext = {
params: { pushId: 1 }
}
// Invoke with fake event object
const res = await actionRunner(snapStub, fakeContext)
// Response marked as started
expect(setStub).to.have.been.calledWith({
startedAt: 'test',
status: 'started'
})
// Confirm res
expect(res).to.be.null
// Ref for response is correct path
expect(refStub).to.have.been.calledWith(responsePath)
// Success object written to response
expect(setStub).to.have.been.calledWith({
completed: true,
completedAt: 'test',
status: 'success'
})
})
})
describe('with src: "storage" and dest: "rtdb"', () => {
it('successfully copies from Cloud Storage to RTDB', async () => {
const { snapStub } = createValidActionRunnerStubs({
srcResource: 'storage',
destResource: 'rtdb'
})
const fakeContext = {
params: { pushId: 1 }
}
// Invoke with fake event object
const res = await actionRunner(snapStub, fakeContext)
// Response marked as started
expect(setStub).to.have.been.calledWith({
startedAt: 'test',
status: 'started'
})
// Confirm res
expect(res).to.be.null
// Ref for response is correct path
expect(refStub).to.have.been.calledWith(responsePath)
// Success object written to response
expect(setStub).to.have.been.calledWith({
completed: true,
completedAt: 'test',
status: 'success'
})
})
})
})
describe('Action template with backups', () => {
it('Calls backups before running steps', async () => {
const snap = {
val: () => ({
projectId: 'test',
inputValues: [],
template: { steps: [], inputs: [], backups: [] }
}),
ref: refStub()
}
const fakeContext = {
params: { pushId: 1 }
}
// Invoke with fake event object
const res = await actionRunner(snap, fakeContext)
// Response marked as started
expect(setStub).to.have.been.calledWith({
startedAt: 'test',
status: 'started'
})
// Confirm res
expect(res).to.be.null
// Ref for response is correct path
expect(refStub).to.have.been.calledWith(responsePath)
// Success object written to response
expect(setStub).to.have.been.calledWith({
completed: true,
completedAt: 'test',
status: 'success'
})
})
})
}) | the_stack |
import {useState, useEffect, createRef} from 'react';
import axios from 'axios';
import {Grid, Card, CardActions, CardContent, Button, Typography, List, ListItem, TextField, Box} from '@material-ui/core';
// Icons
import ReplayIcon from '@material-ui/icons/Replay';
import SmsIcon from '@material-ui/icons/Sms';
import SendIcon from '@material-ui/icons/Send';
import CancelIcon from '@material-ui/icons/Cancel';
import SystemUpdateIcon from '@material-ui/icons/SystemUpdate';
import ForwardIcon from '@material-ui/icons/Forward';
// Config
import { BACKEND_ENDPOINT } from '../../config';
// Context
import { useFeatures, useSnackbar, useInstances } from '../../context';
// Components
import { CustomModal, CustomDropzone, CustomTerminal } from '../../components';
// Types
import { IDeviceInfo, IFeatures, IModalData } from '../../types';
const Toolbox = () => {
const { instances, currentInstance } = useInstances();
const availableFeatures: IFeatures = useFeatures();
const { closeSnackbar, setSnackbarData } = useSnackbar();
const [deviceInfo, setDeviceInfo] = useState<IDeviceInfo | null>();
const [modalData, setModalData] = useState<IModalData>({open: false, title: "", body: <></>, closeModal: () => null});
const [fileData, setFileData] = useState<any>(null);
//SMS Function Refs
const phoneNumber = createRef<any>();
const smsBody = createRef<any>();
//Port Forward Function Refs
const portNumber = createRef<any>();
//Custom Terminal State
const [cwd, setCwd] = useState('/');
useEffect(() => {
async function getDeviceInfo(){
if(!instances || currentInstance === null || !instances[currentInstance]){
return;
}
try{
const deviceInfo = await axios.get(`${BACKEND_ENDPOINT.CORE_PREFIX}${instances[currentInstance].address}:${instances[currentInstance].core_port}${BACKEND_ENDPOINT.PATH_DEVICE}`);
setDeviceInfo(deviceInfo.data);
}
catch (err){
setSnackbarData({open: true, msg: "Error retrieving device info", severity: "error", closeSnackbar: closeSnackbar});
}
}
async function getCwd(){
if(!instances || currentInstance === null || !instances[currentInstance]){
return;
}
try{
const nextCwd = await axios.get(`${BACKEND_ENDPOINT.CORE_PREFIX}${instances[currentInstance].address}:${instances[currentInstance].core_port}${BACKEND_ENDPOINT.PATH_CWD}`);
setCwd(nextCwd.data);
}
catch (err){
setSnackbarData({open: true, msg: "Error retrieving current working directory", severity: "error", closeSnackbar: closeSnackbar});
}
}
if(currentInstance !== null){
getCwd();
if(availableFeatures.DEVICEINFO || !deviceInfo){
getDeviceInfo();
}
}
}, [currentInstance]);
const closeModal = () => {
setModalData(Object.assign({},modalData, {'open': false}));
}
const rebootDevice = async () => {
if(!instances || currentInstance === null || !instances[currentInstance]){
return;
}
if(!availableFeatures.REBOOT){
setSnackbarData({open: true, msg: "This feature is disabled", severity: "error", closeSnackbar: closeSnackbar});
return;
}
try{
await axios.get(`${BACKEND_ENDPOINT.CORE_PREFIX}${instances[currentInstance].address}:${instances[currentInstance].core_port}${BACKEND_ENDPOINT.PATH_REBOOT}`);
setSnackbarData({open: true, msg: "Device rebooting...", severity: "success", closeSnackbar: closeSnackbar});
}
catch (err){
setSnackbarData({open: true, msg: "Error rebooting device", severity: "error", closeSnackbar: closeSnackbar});
}
}
const openSMSModal = () => {
const modalBody = (
<form>
<TextField id="phone-number" label="Phone Number" variant="outlined" className="full-width mb-3" inputRef={phoneNumber}/>
<TextField
id="sms"
label="SMS body"
multiline
rows={4}
variant="outlined"
className="full-width mb-3"
inputRef={smsBody}
/>
<div className="modal-prompt">
<Button variant="contained" color="primary" onClick={sendSMS} startIcon={<SendIcon />}>Send</Button>
<Button variant="contained" color="primary" onClick={closeModal} startIcon={<CancelIcon />}>Cancel</Button>
</div>
</form>
)
const nextModalData = {
'open': true,
'title': "SMS Info",
'body': modalBody,
'closeModal': closeModal
}
setModalData(nextModalData);
}
const sendSMS = async () => {
if(!instances || currentInstance === null || !instances[currentInstance]){
return;
}
if(!availableFeatures.SMS){
setSnackbarData({open: true, msg: "This feature is disabled", severity: "error", closeSnackbar: closeSnackbar});
return;
}
if(!phoneNumber.current || !smsBody.current){
setSnackbarData({open: true, msg: "Phone number or SMS body are wrong", severity: "error", closeSnackbar: closeSnackbar});
return;
}
const smsParams = {
'phoneNumber': phoneNumber.current?.value,
'message': smsBody.current?.value,
}
try{
await axios.post(`${BACKEND_ENDPOINT.CORE_PREFIX}${instances[currentInstance].address}:${instances[currentInstance].core_port}${BACKEND_ENDPOINT.PATH_SMS}`, smsParams);
setSnackbarData({open: true, msg: "SMS sent", severity: "success", closeSnackbar: closeSnackbar});
}
catch (err){
setSnackbarData({open: true, msg: "Error in sending SMS", severity: "error", closeSnackbar: closeSnackbar});
}
closeModal();
}
const installAPK = async () => {
if(!instances || currentInstance === null || !instances[currentInstance]){
return;
}
if(!availableFeatures.APK){
setSnackbarData({open: true, msg: "This feature is disabled", severity: "error", closeSnackbar: closeSnackbar});
return;
}
const formData = new FormData();
formData.append('file', fileData); // appending file
try{
await axios.post(`${BACKEND_ENDPOINT.CORE_PREFIX}${instances[currentInstance].address}:${instances[currentInstance].core_port}${BACKEND_ENDPOINT.PATH_APK}`, formData);
setSnackbarData({open: true, msg: "APK installed", severity: "success", closeSnackbar: closeSnackbar});
}
catch (err){
setSnackbarData({open: true, msg: "Error in installing APK", severity: "error", closeSnackbar: closeSnackbar});
}
}
const openPortForwardModal = () => {
const modalBody = (
<form>
<TextField id="port-number" label="Port Number" variant="outlined" className="full-width mb-3" inputRef={portNumber}/>
<div className="modal-prompt">
<Button variant="contained" color="primary" onClick={portForward} startIcon={<ForwardIcon />}>Forward</Button>
<Button variant="contained" color="primary" onClick={closeModal} startIcon={<CancelIcon />}>Cancel</Button>
</div>
</form>
)
const nextModalData = {
'open': true,
'title': "Port forward",
'body': modalBody,
'closeModal': closeModal
}
setModalData(nextModalData);
}
const portForward = async () => {
if(!instances || currentInstance === null || !instances[currentInstance]){
return;
}
if(!availableFeatures.FORWARD){
setSnackbarData({open: true, msg: "This feature is disabled", severity: "error", closeSnackbar: closeSnackbar});
return;
}
try{
const forwardParams = {
'portNumber': portNumber.current.value ?? "0",
}
await axios.post(`${BACKEND_ENDPOINT.CORE_PREFIX}${instances[currentInstance].address}:${instances[currentInstance].core_port}${BACKEND_ENDPOINT.PATH_FORWARD}`, forwardParams);
setSnackbarData({open: true, msg: "Port Forwarded", severity: "success", closeSnackbar: closeSnackbar});
}
catch (err){
setSnackbarData({open: true, msg: "Error in forwarding port", severity: "error", closeSnackbar: closeSnackbar});
}
closeModal();
}
const DeviceInfo = (
<>
<Typography variant="h5" component="h2">
Device Info
</Typography>
<List>
<ListItem disableGutters={true}><b>Type: </b> {deviceInfo?.type ?? ""}</ListItem>
<ListItem disableGutters={true}><b>Android version: </b> {deviceInfo?.androidVersion ?? ""}</ListItem>
<ListItem disableGutters={true}><b>Processor: </b> {deviceInfo?.processor ?? ""}</ListItem>
<ListItem disableGutters={true}><b>Device: </b> {deviceInfo?.device ?? ""}</ListItem>
</List>
</>
)
const InstallAPKContent = (
<>
<Typography variant="h5" component="h2">
Install APK
</Typography>
<CustomDropzone setFileData={setFileData} />
<Button variant="contained" color="primary" className="full-width" onClick={installAPK} startIcon={<SystemUpdateIcon />}>Install APK</Button>
</>
)
return (
<>
{/* Custom Modal for SMS */}
<CustomModal {...modalData} />
<Grid container justify="center" alignItems="stretch" spacing={3}>
<Grid item xs={6} className="flex">
<Card className="full-width">
<CardContent>
{DeviceInfo}
</CardContent>
<CardActions>
<Button disabled={!availableFeatures.REBOOT} variant="contained" color="primary" className="full-width" onClick={rebootDevice} startIcon={<ReplayIcon />}>Reboot</Button>
<Button disabled={!availableFeatures.SMS} variant="contained" color="primary" className="full-width" onClick={openSMSModal} startIcon={<SmsIcon />}>SMS</Button>
</CardActions>
<CardActions>
<Button disabled={!availableFeatures.FORWARD} variant="contained" color="primary" className="full-width" onClick={openPortForwardModal} startIcon={<ForwardIcon />}>Forward Port</Button>
</CardActions>
</Card>
</Grid>
<Grid item xs={6} className="flex">
<Card className="full-width relative">
<CardContent className={`${!availableFeatures.APK && 'disabledFeatureOverlay'}`}>
{InstallAPKContent}
</CardContent>
</Card>
</Grid>
</Grid>
<Card className="mt-4 flex grow relative">
<CardContent className={`flex grow column ${!availableFeatures.TERMINAL && 'disabledFeatureOverlay'}`}>
<CustomTerminal cwd={cwd} onCwdChange={setCwd} key={cwd}/>
</CardContent>
</Card>
</>
)
}
export default Toolbox; | the_stack |
* @module OrbitGT
*/
//package orbitgt.pointcloud.render;
type int8 = number;
type int16 = number;
type int32 = number;
type float32 = number;
type float64 = number;
import { Bounds } from "../../spatial/geom/Bounds";
import { AList } from "../../system/collection/AList";
import { Message } from "../../system/runtime/Message";
import { BlockIndex } from "../model/BlockIndex";
import { GridIndex } from "../model/GridIndex";
import { PointData } from "../model/PointData";
import { TileIndex } from "../model/TileIndex";
import { AViewRequest } from "./AViewRequest";
import { Block } from "./Block";
import { DataManager } from "./DataManager";
import { Level } from "./Level";
/**
* Class TileSpatialIndex manages a spatial index of levels, blocks and tiles in pointcloud. The index does not store data, only block and tile indexes.
*
* @version 1.0 November 2015
*/
/** @internal */
export class ViewTree {
/** The name of this module */
private static readonly MODULE: string = "ViewTree";
/** Debug mode? */
private static readonly DEBUG: boolean = false;
/** The data manager */
private _dataManager: DataManager;
/** The levels */
private _levels: Array<Level>;
/** The data bounds */
private _dataBounds: Bounds;
/** The root blocks */
private _rootBlocks: AList<Block>;
/**
* Create a new tree.
* @param levels the levels.
* @param dataBounds the data bounds.
*/
public constructor(dataManager: DataManager, levels: Array<Level>, dataBounds: Bounds) {
/* Store the parameters */
this._dataManager = dataManager;
this._levels = levels;
this._dataBounds = dataBounds;
/* Find the root blocks */
this._rootBlocks = this.findRootBlocks();
}
/**
* Find all root blocks (dropping of single-point tiles during pyramid creation can lead to missing branches).
* @return all root blocks.
*/
private findRootBlocks(): AList<Block> {
/* Check some levels below the top */
let startLevel: int32 = (this._levels.length - 6);
if (startLevel < 0) startLevel = 0;
Message.print(ViewTree.MODULE, "Finding root blocks starting at level index " + startLevel + " of " + this._levels.length);
/* Check the levels */
let rootBlocks: AList<Block> = new AList<Block>();
let nextLevelIndex: GridIndex = new GridIndex(0, 0, 0);
for (let i: number = startLevel; i < this._levels.length - 1; i++) {
/* Check all blocks in the level */
let level: Level = this._levels[i];
for (let block of level.getBlocks()) {
/* Non-top level? */
let isRoot: boolean = true;
if (i < this._levels.length - 2) {
/* Do we have a parent block in the next level? */
block.getBlockIndex().gridIndex.getNextLevelIndex(nextLevelIndex);
isRoot = (this._levels[i + 1].findBlockGridIndex(nextLevelIndex) == null);
if (isRoot) Message.print(ViewTree.MODULE, "Block L" + i + " " + block.getBlockIndex().gridIndex + " is non-top root");
}
/* Add to the list? */
if (isRoot) rootBlocks.add(block);
}
}
/* Return the roots */
Message.print(ViewTree.MODULE, "Found " + rootBlocks.size() + " root blocks");
return rootBlocks;
}
/**
* Get the number of levels.
* @return the number of levels.
*/
public getLevelCount(): int32 {
return this._levels.length;
}
/**
* Get a level.
* @param index the index of the level.
* @return the level.
*/
public getLevel(index: int32): Level {
return this._levels[index];
}
/**
* Get the data bounds.
* @return the data bounds.
*/
public getDataBounds(): Bounds {
return this._dataBounds;
}
/**
* Set the blocks for a level (after a data load operation).
* @param level the level.
* @param blockIndexes the indexes of the blocks in the level.
*/
public setLevelBlocks(level: Level, blockIndexes: Array<BlockIndex>): void {
if (blockIndexes == null) return;
let blockList: Array<Block> = new Array<Block>(blockIndexes.length);
for (let i: number = 0; i < blockIndexes.length; i++) blockList[i] = new Block(blockIndexes[i]);
level.setBlockList(blockList);
Message.print(ViewTree.MODULE, "Loaded " + blockIndexes.length + " blocks for level " + level.getIndex());
}
/**
* Set the tiles for a block (after a data load operation).
* @param blockIndex the index of the block.
* @param tileIndexes the indexes of the tiles in the block.
*/
public setBlockTiles(blockIndex: BlockIndex, tileIndexes: Array<TileIndex>): void {
let level: Level = this._levels[blockIndex.level];
let block: Block = level.findBlock(blockIndex);
block.setTiles(tileIndexes);
}
/**
* Split a tile into lower-level tiles.
* @param level the level of the tile to split.
* @param tile the tile to split.
* @param childLevel the lower level of the tile.
* @param children the list of children to split into.
* @param levelsToLoad the list of levels to load.
* @param blocksToLoad the list of blocks to load.
* @return true if the list of children is complete.
*/
private splitTile(level: Level, tile: TileIndex, childLevel: Level, children: AList<TileIndex>, levelsToLoad: AList<Level>, blocksToLoad: AList<BlockIndex>): boolean {
/* Clear the result */
children.clear();
/* Already calculated? */
let childList: Array<TileIndex> = tile.children;
if (childList != null) {
/* Return */
for (let child of childList) children.add(child);
return true;
}
/* Assume we have a complete list of children */
let complete: boolean = true;
/* Unloaded level? */
if (childLevel.getBlockCount() == 0) {
/* No need to continue, we need the level block list */
if (levelsToLoad.contains(childLevel) == false) levelsToLoad.add(childLevel);
return false;
}
/* Check the 8 possible child tiles */
let index: GridIndex = tile.gridIndex;
let childIndex: GridIndex = new GridIndex(0, 0, 0);
for (let z: number = 0; z < 2; z++) for (let y: number = 0; y < 2; y++) for (let x: number = 0; x < 2; x++) {
/* Get the index of the child */
childIndex.x = (2 * index.x + x);
childIndex.y = (2 * index.y + y);
childIndex.z = (2 * index.z + z);
/* Find the block */
let block: Block = childLevel.findBlockForTile(childIndex);
if (block == null) {
/* This should not happen */
Message.printWarning(ViewTree.MODULE, "Unable to find tile block " + childIndex + " in child level " + childLevel.getIndex() + " (" + childLevel.getBlockCount() + " blocks)");
complete = false;
continue;
}
/* No tile info in the block? */
if (block.hasTiles() == false) {
/* Load the block data */
if (blocksToLoad.contains(block.getBlockIndex()) == false) blocksToLoad.add(block.getBlockIndex());
complete = false;
}
else {
/* Find the child */
let child: TileIndex = block.findTile(childIndex);
if (child != null) children.add(child);
}
}
/* Store the result if complete */
if (complete) {
/* Store */
let tileChildren: Array<TileIndex> = new Array<TileIndex>(children.size());
for (let i: number = 0; i < tileChildren.length; i++) tileChildren[i] = children.get(i);
tile.children = tileChildren;
}
/* Do we have all children? */
return complete;
}
/**
* Is all tile data available for rendering?
* @param viewRequest the view request.
* @param tiles a list of tiles to check.
* @param missingTiles the list of tiles whose data is missing.
*/
private checkDataAvailable(viewRequest: AViewRequest, tiles: AList<TileIndex>, missingTiles: AList<TileIndex>): void {
/* Check all tiles */
missingTiles.clear();
for (let i: number = 0; i < tiles.size(); i++) {
/* Get the next tile */
let tile: TileIndex = tiles.get(i);
/* Not available? */
if (this._dataManager.isTileLoaded(tile) == null) {
/* Request to load the block */
missingTiles.add(tile);
}
else {
/* Touch the block */
tile.accessTime = viewRequest.getFrameTime();
}
}
}
/**
* Is all tile data available for rendering?
* @param viewRequest the view request.
* @param tiles a list of tiles to check.
* @return true if the tile data is available.
*/
private isDataAvailable(viewRequest: AViewRequest, tiles: Array<TileIndex>): boolean {
/* Check all tiles */
for (let i: number = 0; i < tiles.length; i++) {
/* Get the next tile */
let tile: TileIndex = tiles[i];
/* Not available? */
if (this._dataManager.isTileLoaded(tile) == null) return false;
}
/* Available */
return true;
}
/**
* Add visible tiles to the view.
* @param viewRequest the view request.
* @param level the level of the tiles.
* @param tiles the tiles to check.
* @param visibleTiles the list of visible tiles to add to.
*/
private addTilesToView(viewRequest: AViewRequest, level: Level, tiles: Array<TileIndex>, levelsToLoad: AList<Level>, blocksToLoad: AList<BlockIndex>, tilesToLoad: AList<TileIndex>, tilesToRender: AList<PointData>): void {
/* No tiles? */
if (tiles == null) return;
/* Make the lists */
let childTiles: AList<TileIndex> = new AList<TileIndex>();
let missingChildTiles: AList<TileIndex> = new AList<TileIndex>();
/* Check all tiles */
for (let i: number = 0; i < tiles.length; i++) {
/* Get the next tile */
let tile: TileIndex = tiles[i];
if (ViewTree.DEBUG) Message.print(ViewTree.MODULE, "Checking tile L" + tile.level + " (" + tile.gridIndex.x + "," + tile.gridIndex.y + "," + tile.gridIndex.z + ")");
/* Visible? */
let tileBounds: Bounds = level.getTileGrid().getCellBounds(tile.gridIndex).getIntersection(this._dataBounds);
if (ViewTree.DEBUG) Message.print(ViewTree.MODULE, "> level " + tile.level);
if (viewRequest.isVisibleBox(tileBounds)) {
/* Has the tile been loaded? */
let tileData: PointData = this._dataManager.isTileLoaded(tile);
let tileAvailable: boolean = (tileData != null);
tile.accessTime = viewRequest.getFrameTime();
if (ViewTree.DEBUG) Message.print(ViewTree.MODULE, " > available? " + tileAvailable);
/* We load all intermediate tiles to avoid holes in the coverage */
if (tileAvailable == false) tilesToLoad.add(tile);
/* Split the tile? */
let shouldSplit: boolean = (level.getIndex() > 0) && viewRequest.shouldSplit(level, tile);
if (shouldSplit) {
if (ViewTree.DEBUG) Message.print(ViewTree.MODULE, " > visible, but needs splitting");
/* Find the children at the lower level */
let childLevel: Level = this._levels[level.getIndex() - 1];
let completeChildList: boolean = this.splitTile(level, tile, childLevel, childTiles, levelsToLoad, blocksToLoad);
if (completeChildList == false) {
if (ViewTree.DEBUG) Message.print(ViewTree.MODULE, " > loading child indexes");
/* Display the tile while we wait for the block-tiles to load */
if (tileAvailable) tilesToRender.add(tileData);
}
else {
/* Are all children available with their data? */
this.checkDataAvailable(viewRequest, childTiles, missingChildTiles);
if (missingChildTiles.size() == 0) {
if (ViewTree.DEBUG) Message.print(ViewTree.MODULE, " > rendering children");
/* Add the children */
let childTiles2: Array<TileIndex> = new Array<TileIndex>(childTiles.size());
for (let j: number = 0; j < childTiles2.length; j++) childTiles2[j] = childTiles.get(j);
this.addTilesToView(viewRequest, childLevel, childTiles2, levelsToLoad, blocksToLoad, tilesToLoad, tilesToRender);
}
else {
if (ViewTree.DEBUG) Message.print(ViewTree.MODULE, " > loading children");
/* Request for the missing children to be loaded */
for (let j: number = 0; j < missingChildTiles.size(); j++) tilesToLoad.add(missingChildTiles.get(j));
/* Display the tile while we wait for the child tiles to load */
if (tileAvailable) tilesToRender.add(tileData);
}
}
}
else {
/* Display the tile */
if (ViewTree.DEBUG) Message.print(ViewTree.MODULE, " > visible");
if (tileAvailable) tilesToRender.add(tileData);
}
}
else {
/* Log */
if (ViewTree.DEBUG) Message.print(ViewTree.MODULE, " > not visible");
}
}
}
/**
* Find tile indexes for a 3D view.
* @param viewRequest the request parameters.
* @param visibleTiles the list of visible tiles to add to.
* @param availableTiles the set of available tiles.
* @param visibleAvailableTiles the list if visible and available tiles to add to.
*/
public renderView3D(viewRequest: AViewRequest, levelsToLoad: AList<Level>, blocksToLoad: AList<BlockIndex>, tilesToLoad: AList<TileIndex>, tilesToRender: AList<PointData>): void {
/* Log? */
if (ViewTree.DEBUG) Message.print(ViewTree.MODULE, "Finding pointcloud tiles to render");
if (ViewTree.DEBUG) Message.print(ViewTree.MODULE, " > dataBounds: " + this._dataBounds);
//if (DEBUG) Message.print(MODULE," > view: "+viewRequest.getViewProjection());
//if (DEBUG) Message.print(MODULE," > distance: "+viewRequest.getDistanceRange());
//if (DEBUG) Message.print(MODULE," > model-transform: "+viewRequest.getModelTransform());
/* Check all blocks */
tilesToRender.clear();
if (ViewTree.DEBUG) Message.print(ViewTree.MODULE, "Checking " + this._rootBlocks.size() + " root blocks");
for (let i: number = 0; i < this._rootBlocks.size(); i++) // start from the root tiles
{
/* Visible? */
let block: Block = this._rootBlocks.get(i);
let blockIndex: BlockIndex = block.getBlockIndex();
let level: Level = this._levels[blockIndex.level];
/* Visible? */
if (ViewTree.DEBUG) Message.print(ViewTree.MODULE, "Checking top-level block L" + blockIndex.level + " (" + blockIndex.gridIndex.x + "," + blockIndex.gridIndex.y + "," + blockIndex.gridIndex.z + ")");
let blockBounds: Bounds = block.getBlockBounds(level).getIntersection(this._dataBounds);
if (ViewTree.DEBUG) Message.print(ViewTree.MODULE, " > blockBounds: " + blockBounds);
if (viewRequest.isVisibleBox(blockBounds)) {
/* Add the tiles */
if (ViewTree.DEBUG) Message.print(ViewTree.MODULE, " > visible");
this.addTilesToView(viewRequest, level, block.getTiles(blocksToLoad), levelsToLoad, blocksToLoad, tilesToLoad, tilesToRender);
}
}
}
} | the_stack |
import escapeStringRegexp from 'escape-string-regexp';
import {
assertGet,
command,
CommandFunction,
CreateExtensionPlugin,
cx,
DispatchFunction,
extension,
findMatches,
FromToProps,
getSelectedWord,
Handler,
isEmptyArray,
isNumber,
isSelectionEmpty,
isString,
keyBinding,
KeyBindingCommandFunction,
KeyBindingProps,
NamedShortcut,
PlainExtension,
ProsemirrorNode,
Static,
Transaction,
} from '@remirror/core';
import { Decoration, DecorationSet } from '@remirror/pm/view';
export interface SearchOptions {
/**
* @default false
*/
autoSelectNext?: boolean;
/**
* @default 'search'
*/
searchClass?: Static<string>;
/**
* The class to apply to the currently highlighted index.
*
* @default 'highlighted-search'
*/
highlightedClass?: Static<string>;
/**
* @default false
*/
searching?: boolean;
/**
* @default false
*/
caseSensitive?: boolean;
/**
* @default true
*/
disableRegex?: boolean;
/**
* @default false
*/
alwaysSearch?: boolean;
/**
* Whether to clear the search when the `Escape` key is pressed.
*
* @default true
*/
clearOnEscape?: boolean;
/**
* Search handler
*/
onSearch: Handler<(selectedText: string, direction: SearchDirection) => void>;
}
export type SearchDirection = 'next' | 'previous';
/**
* This extension add search functionality to your editor.
*/
@extension<SearchOptions>({
defaultOptions: {
autoSelectNext: true,
searchClass: 'search',
highlightedClass: 'highlighted-search',
searching: false,
caseSensitive: false,
disableRegex: true,
alwaysSearch: false,
clearOnEscape: true,
},
handlerKeys: ['onSearch'],
staticKeys: ['searchClass', 'highlightedClass'],
})
export class SearchExtension extends PlainExtension<SearchOptions> {
get name() {
return 'search' as const;
}
private _updating = false;
private _searchTerm?: string;
private _results: FromToProps[] = [];
private _activeIndex = 0;
/**
* This plugin is responsible for adding something decorations to the
*/
createPlugin(): CreateExtensionPlugin {
return {
state: {
init() {
return DecorationSet.empty;
},
apply: (tr, old) => {
if (
this._updating ||
this.options.searching ||
(tr.docChanged && this.options.alwaysSearch)
) {
return this.createDecoration(tr.doc);
}
if (tr.docChanged) {
return old.map(tr.mapping, tr.doc);
}
return old;
},
},
props: {
decorations: (state) => {
return this.getPluginState(state);
},
},
};
}
/**
* Find a search term in the editor. If no search term is provided it
* defaults to the currently selected text.
*/
@command()
search(searchTerm?: string, direction?: SearchDirection): CommandFunction {
return this.find(searchTerm, direction);
}
/**
* Find the next occurrence of the search term.
*/
@command()
searchNext(): CommandFunction {
return this.find(this._searchTerm, 'next');
}
/**
* Find the previous occurrence of the search term.
*/
@command()
searchPrevious(): CommandFunction {
return this.find(this._searchTerm, 'previous');
}
/**
* Replace the provided
*/
@command()
replaceSearchResult(replacement: string, index?: number): CommandFunction {
return this.replace(replacement, index);
}
/**
* Replaces all search results with the replacement text.
*/
@command()
replaceAllSearchResults(replacement: string): CommandFunction {
return this.replaceAll(replacement);
}
/**
* Clears the current search.
*/
@command()
clearSearch(): CommandFunction {
return this.clear();
}
@keyBinding<SearchExtension>({ shortcut: NamedShortcut.Find })
searchForwardShortcut(props: KeyBindingProps): boolean {
return this.createSearchKeyBinding('next')(props);
}
@keyBinding<SearchExtension>({ shortcut: NamedShortcut.FindBackwards })
searchBackwardShortcut(props: KeyBindingProps): boolean {
return this.createSearchKeyBinding('previous')(props);
}
@keyBinding<SearchExtension>({ shortcut: 'Escape', isActive: (options) => options.clearOnEscape })
escapeShortcut(_: KeyBindingProps): boolean {
if (!isString(this._searchTerm)) {
return false;
}
this.clearSearch();
return true;
}
private createSearchKeyBinding(direction: SearchDirection): KeyBindingCommandFunction {
return ({ state }) => {
let searchTerm: string | undefined;
if (isSelectionEmpty(state)) {
if (!this._searchTerm) {
return false;
}
searchTerm = this._searchTerm;
}
this.find(searchTerm, direction);
return true;
};
}
private findRegExp() {
return new RegExp(this._searchTerm ?? '', !this.options.caseSensitive ? 'gui' : 'gu');
}
private getDecorations() {
return this._results.map((deco, index) =>
Decoration.inline(deco.from, deco.to, {
class: cx(
this.options.searchClass,
index === this._activeIndex && this.options.highlightedClass,
),
}),
);
}
private gatherSearchResults(doc: ProsemirrorNode) {
interface MergedTextNode {
text: string;
pos: number;
}
this._results = [];
const mergedTextNodes: MergedTextNode[] = [];
let index = 0;
if (!this._searchTerm) {
return;
}
doc.descendants((node, pos) => {
const mergedTextNode = mergedTextNodes[index];
if (!node.isText && mergedTextNode) {
index += 1;
return;
}
if (mergedTextNode) {
mergedTextNodes[index] = {
text: `${mergedTextNode.text}${node.text ?? ''}`,
pos: mergedTextNode.pos + (index === 0 ? 1 : 0),
};
return;
}
mergedTextNodes[index] = {
text: node.text ?? '',
pos,
};
});
for (const { text, pos } of mergedTextNodes) {
const search = this.findRegExp();
findMatches(text, search).forEach((match) => {
this._results.push({
from: pos + match.index,
to: pos + match.index + assertGet(match, 0).length,
});
});
}
}
private replace(replacement: string, index?: number): CommandFunction {
return (props) => {
const { tr, dispatch } = props;
const result = this._results[isNumber(index) ? index : this._activeIndex];
if (!result) {
return false;
}
if (!dispatch) {
return true;
}
tr.insertText(replacement, result.from, result.to);
return this.searchNext()(props);
};
}
private rebaseNextResult({ replacement, index, lastOffset = 0 }: RebaseNextResultProps) {
const nextIndex = index + 1;
if (!this._results[nextIndex]) {
return;
}
const current = assertGet(this._results, index);
const offset = current.to - current.from - replacement.length + lastOffset;
const next = assertGet(this._results, nextIndex);
this._results[nextIndex] = {
to: next.to - offset,
from: next.from - offset,
};
return offset;
}
private replaceAll(replacement: string): CommandFunction {
return (props) => {
const { tr, dispatch } = props;
let offset: number | undefined;
if (isEmptyArray(this._results)) {
return false;
}
if (!dispatch) {
return true;
}
this._results.forEach(({ from, to }, index) => {
tr.insertText(replacement, from, to);
offset = this.rebaseNextResult({ replacement, index, lastOffset: offset });
});
return this.find(this._searchTerm)(props);
};
}
private find(searchTerm?: string, direction?: SearchDirection): CommandFunction {
return ({ tr, dispatch }) => {
const range = isSelectionEmpty(tr) ? getSelectedWord(tr) : tr.selection;
let actualSearch = '';
if (searchTerm) {
actualSearch = searchTerm;
} else if (range) {
const { from, to } = range;
actualSearch = tr.doc.textBetween(from, to);
}
this._searchTerm = this.options.disableRegex
? escapeStringRegexp(actualSearch)
: actualSearch;
this._activeIndex = !direction
? 0
: rotateHighlightedIndex({
direction,
previousIndex: this._activeIndex,
resultsLength: this._results.length,
});
return this.updateView(tr, dispatch);
};
}
private clear(): CommandFunction {
return ({ tr, dispatch }) => {
this._searchTerm = undefined;
this._activeIndex = 0;
return this.updateView(tr, dispatch);
};
}
/**
* Dispatch an empty transaction to trigger an update of the decoration.
*/
private updateView(tr: Transaction, dispatch?: DispatchFunction): boolean {
this._updating = true;
if (dispatch) {
dispatch(tr);
}
this._updating = false;
return true;
}
private createDecoration(doc: ProsemirrorNode) {
this.gatherSearchResults(doc);
const decorations = this.getDecorations();
return decorations ? DecorationSet.create(doc, decorations) : [];
}
}
interface RebaseNextResultProps {
replacement: string;
index: number;
lastOffset?: number;
}
interface RotateHighlightedIndexProps {
/**
* Whether the search is moving forward or backward.
*/
direction: SearchDirection;
/**
* The total number of matches
*/
resultsLength: number;
/**
* The previously matched index
*/
previousIndex: number;
}
export const rotateHighlightedIndex = (props: RotateHighlightedIndexProps): number => {
const { direction, resultsLength, previousIndex } = props;
if (direction === 'next') {
return previousIndex + 1 > resultsLength - 1 ? 0 : previousIndex + 1;
}
return previousIndex - 1 < 0 ? resultsLength - 1 : previousIndex - 1;
};
declare global {
namespace Remirror {
interface AllExtensions {
search: SearchExtension;
}
}
} | the_stack |
import '../jest-extensions';
import {
predicate, DataFrame, RecordBatch
} from 'apache-arrow';
import { test_data } from './table-tests';
import { jest } from '@jest/globals';
const { col, lit, custom, and, or, And, Or } = predicate;
const F32 = 0, I32 = 1, DICT = 2;
describe(`DataFrame`, () => {
for (let datum of test_data) {
describe(datum.name, () => {
describe(`scan()`, () => {
test(`yields all values`, () => {
const df = new DataFrame(datum.table());
let expected_idx = 0;
df.scan((idx, batch) => {
const columns = batch.schema.fields.map((_, i) => batch.getChildAt(i)!);
expect(columns.map((c) => c.get(idx))).toEqual(values[expected_idx++]);
});
});
test(`calls bind function with every batch`, () => {
const df = new DataFrame(datum.table());
let bind = jest.fn();
df.scan(() => { }, bind);
for (let batch of df.chunks) {
expect(bind).toHaveBeenCalledWith(batch);
}
});
});
describe(`scanReverse()`, () => {
test(`yields all values`, () => {
const df = new DataFrame(datum.table());
let expected_idx = values.length;
df.scanReverse((idx, batch) => {
const columns = batch.schema.fields.map((_, i) => batch.getChildAt(i)!);
expect(columns.map((c) => c.get(idx))).toEqual(values[--expected_idx]);
});
});
test(`calls bind function with every batch`, () => {
const df = new DataFrame(datum.table());
let bind = jest.fn();
df.scanReverse(() => { }, bind);
for (let batch of df.chunks) {
expect(bind).toHaveBeenCalledWith(batch);
}
});
});
test(`count() returns the correct length`, () => {
const df = new DataFrame(datum.table());
const values = datum.values();
expect(df.count()).toEqual(values.length);
});
test(`getColumnIndex`, () => {
const df = new DataFrame(datum.table());
expect(df.getColumnIndex('i32')).toEqual(I32);
expect(df.getColumnIndex('f32')).toEqual(F32);
expect(df.getColumnIndex('dictionary')).toEqual(DICT);
});
const df = new DataFrame(datum.table());
const values = datum.values();
let get_i32: (idx: number) => number, get_f32: (idx: number) => number;
const filter_tests = [
{
name: `filter on f32 >= 0`,
filtered: df.filter(col('f32').ge(0)),
expected: values.filter((row) => row[F32] >= 0)
}, {
name: `filter on 0 <= f32`,
filtered: df.filter(lit(0).le(col('f32'))),
expected: values.filter((row) => 0 <= row[F32])
}, {
name: `filter on i32 <= 0`,
filtered: df.filter(col('i32').le(0)),
expected: values.filter((row) => row[I32] <= 0)
}, {
name: `filter on 0 >= i32`,
filtered: df.filter(lit(0).ge(col('i32'))),
expected: values.filter((row) => 0 >= row[I32])
}, {
name: `filter on f32 < 0`,
filtered: df.filter(col('f32').lt(0)),
expected: values.filter((row) => row[F32] < 0)
}, {
name: `filter on i32 > 1 (empty)`,
filtered: df.filter(col('i32').gt(0)),
expected: values.filter((row) => row[I32] > 0)
}, {
name: `filter on f32 <= -.25 || f3 >= .25`,
filtered: df.filter(col('f32').le(-.25).or(col('f32').ge(.25))),
expected: values.filter((row) => row[F32] <= -.25 || row[F32] >= .25)
}, {
name: `filter on !(f32 <= -.25 || f3 >= .25) (not)`,
filtered: df.filter(col('f32').le(-.25).or(col('f32').ge(.25)).not()),
expected: values.filter((row) => !(row[F32] <= -.25 || row[F32] >= .25))
}, {
name: `filter method combines predicates (f32 >= 0 && i32 <= 0)`,
filtered: df.filter(col('i32').le(0)).filter(col('f32').ge(0)),
expected: values.filter((row) => row[I32] <= 0 && row[F32] >= 0)
}, {
name: `filter on dictionary == 'a'`,
filtered: df.filter(col('dictionary').eq('a')),
expected: values.filter((row) => row[DICT] === 'a')
}, {
name: `filter on 'a' == dictionary (commutativity)`,
filtered: df.filter(lit('a').eq(col('dictionary'))),
expected: values.filter((row) => row[DICT] === 'a')
}, {
name: `filter on dictionary != 'b'`,
filtered: df.filter(col('dictionary').ne('b')),
expected: values.filter((row) => row[DICT] !== 'b')
}, {
name: `filter on f32 >= i32`,
filtered: df.filter(col('f32').ge(col('i32'))),
expected: values.filter((row) => row[F32] >= row[I32])
}, {
name: `filter on f32 <= i32`,
filtered: df.filter(col('f32').le(col('i32'))),
expected: values.filter((row) => row[F32] <= row[I32])
}, {
name: `filter on f32*i32 > 0 (custom predicate)`,
filtered: df.filter(custom(
(idx: number) => (get_f32(idx) * get_i32(idx) > 0),
(batch: RecordBatch) => {
get_f32 = col('f32').bind(batch);
get_i32 = col('i32').bind(batch);
})),
expected: values.filter((row) => (row[F32] as number) * (row[I32] as number) > 0)
}, {
name: `filter out all records`,
filtered: df.filter(lit(1).eq(0)),
expected: []
}
];
for (let this_test of filter_tests) {
const { name, filtered, expected } = this_test;
describe(name, () => {
test(`count() returns the correct length`, () => {
expect(filtered.count()).toEqual(expected.length);
});
describe(`scan()`, () => {
test(`iterates over expected values`, () => {
let expected_idx = 0;
filtered.scan((idx, batch) => {
const columns = batch.schema.fields.map((_, i) => batch.getChildAt(i)!);
expect(columns.map((c) => c.get(idx))).toEqual(expected[expected_idx++]);
});
});
test(`calls bind function lazily`, () => {
let bind = jest.fn();
filtered.scan(() => { }, bind);
if (expected.length) {
expect(bind).toHaveBeenCalled();
} else {
expect(bind).not.toHaveBeenCalled();
}
});
});
describe(`scanReverse()`, () => {
test(`iterates over expected values in reverse`, () => {
let expected_idx = expected.length;
filtered.scanReverse((idx, batch) => {
const columns = batch.schema.fields.map((_, i) => batch.getChildAt(i)!);
expect(columns.map((c) => c.get(idx))).toEqual(expected[--expected_idx]);
});
});
test(`calls bind function lazily`, () => {
let bind = jest.fn();
filtered.scanReverse(() => { }, bind);
if (expected.length) {
expect(bind).toHaveBeenCalled();
} else {
expect(bind).not.toHaveBeenCalled();
}
});
});
});
}
test(`countBy on dictionary returns the correct counts`, () => {
// Make sure countBy works both with and without the Col wrapper
// class
let expected: { [key: string]: number } = { 'a': 0, 'b': 0, 'c': 0 };
for (let row of values) {
expected[row[DICT]] += 1;
}
expect(df.countBy(col('dictionary')).toJSON()).toEqual(expected);
expect(df.countBy('dictionary').toJSON()).toEqual(expected);
});
test(`countBy on dictionary with filter returns the correct counts`, () => {
let expected: { [key: string]: number } = { 'a': 0, 'b': 0, 'c': 0 };
for (let row of values) {
if (row[I32] === 1) { expected[row[DICT]] += 1; }
}
expect(df.filter(col('i32').eq(1)).countBy('dictionary').toJSON()).toEqual(expected);
});
test(`countBy on non dictionary column throws error`, () => {
expect(() => { df.countBy('i32'); }).toThrow();
expect(() => { df.filter(col('dict').eq('a')).countBy('i32'); }).toThrow();
});
test(`countBy on non-existent column throws error`, () => {
expect(() => { df.countBy('FAKE' as any); }).toThrow();
});
test(`table.select() basic tests`, () => {
let selected = df.select('f32', 'dictionary');
expect(selected.schema.fields).toHaveLength(2);
expect(selected.schema.fields[0]).toEqual(df.schema.fields[0]);
expect(selected.schema.fields[1]).toEqual(df.schema.fields[2]);
expect(selected).toHaveLength(values.length);
let idx = 0, expected_row;
for (let row of selected) {
expected_row = values[idx++];
expect(row.f32).toEqual(expected_row[F32]);
expect(row.dictionary).toEqual(expected_row[DICT]);
}
});
test(`table.filter(..).count() on always false predicates returns 0`, () => {
expect(df.filter(col('i32').ge(100)).count()).toEqual(0);
expect(df.filter(col('dictionary').eq('z')).count()).toEqual(0);
});
describe(`lit-lit comparison`, () => {
test(`always-false count() returns 0`, () => {
expect(df.filter(lit('abc').eq('def')).count()).toEqual(0);
expect(df.filter(lit(0).ge(1)).count()).toEqual(0);
});
test(`always-true count() returns length`, () => {
expect(df.filter(lit('abc').eq('abc')).count()).toEqual(df.length);
expect(df.filter(lit(-100).le(0)).count()).toEqual(df.length);
});
});
describe(`col-col comparison`, () => {
test(`always-false count() returns 0`, () => {
expect(df.filter(col('dictionary').eq(col('i32'))).count()).toEqual(0);
});
test(`always-true count() returns length`, () => {
expect(df.filter(col('dictionary').eq(col('dictionary'))).count()).toEqual(df.length);
});
});
});
}
});
describe(`Predicate`, () => {
const p1 = col('a').gt(100);
const p2 = col('a').lt(1000);
const p3 = col('b').eq('foo');
const p4 = col('c').eq('bar');
const expected = [p1, p2, p3, p4];
test(`and flattens children`, () => {
expect(and(p1, p2, p3, p4).children).toEqual(expected);
expect(and(p1.and(p2), new And(p3, p4)).children).toEqual(expected);
expect(and(p1.and(p2, p3, p4)).children).toEqual(expected);
});
test(`or flattens children`, () => {
expect(or(p1, p2, p3, p4).children).toEqual(expected);
expect(or(p1.or(p2), new Or(p3, p4)).children).toEqual(expected);
expect(or(p1.or(p2, p3, p4)).children).toEqual(expected);
});
}); | the_stack |
import { ContractAddresses } from '@0x/contract-addresses';
import { artifacts as erc20Artifacts, DummyERC20TokenContract } from '@0x/contracts-erc20';
import { IExchangeContract } from '@0x/contracts-exchange';
import { blockchainTests, constants, expect, getRandomPortion, verifyEventsFromLogs } from '@0x/contracts-test-utils';
import {
artifacts as exchangeProxyArtifacts,
IZeroExContract,
LogMetadataTransformerContract,
signCallData,
} from '@0x/contracts-zero-ex';
import { migrateOnceAsync } from '@0x/migrations';
import {
assetDataUtils,
encodeFillQuoteTransformerData,
encodePayTakerTransformerData,
ETH_TOKEN_ADDRESS,
FillQuoteTransformerSide,
findTransformerNonce,
signatureUtils,
SignedExchangeProxyMetaTransaction,
} from '@0x/order-utils';
import { AssetProxyId, Order, SignedOrder } from '@0x/types';
import { BigNumber, hexUtils, ZeroExRevertErrors } from '@0x/utils';
import * as ethjs from 'ethereumjs-util';
const { MAX_UINT256, NULL_ADDRESS, NULL_BYTES, NULL_BYTES32, ZERO_AMOUNT } = constants;
blockchainTests.resets('exchange proxy - meta-transactions', env => {
const quoteSignerKey = hexUtils.random();
const quoteSigner = hexUtils.toHex(ethjs.privateToAddress(ethjs.toBuffer(quoteSignerKey)));
let owner: string;
let relayer: string;
let maker: string;
let taker: string;
let flashWalletAddress: string;
let zeroEx: IZeroExContract;
let exchange: IExchangeContract;
let inputToken: DummyERC20TokenContract;
let outputToken: DummyERC20TokenContract;
let feeToken: DummyERC20TokenContract;
let addresses: ContractAddresses;
let protocolFee: BigNumber;
let metadataTransformer: LogMetadataTransformerContract;
const GAS_PRICE = new BigNumber('1e9');
const MAKER_BALANCE = new BigNumber('100e18');
const TAKER_BALANCE = new BigNumber('100e18');
const TAKER_FEE_BALANCE = new BigNumber('100e18');
before(async () => {
[, relayer, maker, taker] = await env.getAccountAddressesAsync();
addresses = await migrateOnceAsync(env.provider);
zeroEx = new IZeroExContract(addresses.exchangeProxy, env.provider, env.txDefaults, {
LogMetadataTransformer: LogMetadataTransformerContract.ABI(),
DummyERC20Token: DummyERC20TokenContract.ABI(),
});
exchange = new IExchangeContract(addresses.exchange, env.provider, env.txDefaults);
[inputToken, outputToken, feeToken] = await Promise.all(
[...new Array(3)].map(i =>
DummyERC20TokenContract.deployFrom0xArtifactAsync(
erc20Artifacts.DummyERC20Token,
env.provider,
env.txDefaults,
{},
`DummyToken-${i}`,
`TOK${i}`,
new BigNumber(18),
BigNumber.max(MAKER_BALANCE, TAKER_BALANCE),
),
),
);
// LogMetadataTransformer is not deployed in migrations.
metadataTransformer = await LogMetadataTransformerContract.deployFrom0xArtifactAsync(
exchangeProxyArtifacts.LogMetadataTransformer,
env.provider,
{
...env.txDefaults,
from: addresses.exchangeProxyTransformerDeployer,
},
{},
);
owner = await zeroEx.owner().callAsync();
protocolFee = await exchange.protocolFeeMultiplier().callAsync();
flashWalletAddress = await zeroEx.getTransformWallet().callAsync();
const erc20Proxy = await exchange.getAssetProxy(AssetProxyId.ERC20).callAsync();
const allowanceTarget = await zeroEx.getAllowanceTarget().callAsync();
await outputToken.mint(MAKER_BALANCE).awaitTransactionSuccessAsync({ from: maker });
await inputToken.mint(TAKER_BALANCE).awaitTransactionSuccessAsync({ from: taker });
await feeToken.mint(TAKER_FEE_BALANCE).awaitTransactionSuccessAsync({ from: taker });
await outputToken.approve(erc20Proxy, MAX_UINT256).awaitTransactionSuccessAsync({ from: maker });
await inputToken.approve(allowanceTarget, MAX_UINT256).awaitTransactionSuccessAsync({ from: taker });
await feeToken.approve(allowanceTarget, MAX_UINT256).awaitTransactionSuccessAsync({ from: taker });
await zeroEx.setQuoteSigner(quoteSigner).awaitTransactionSuccessAsync({ from: owner });
});
interface Transformation {
deploymentNonce: number;
data: string;
}
interface SwapInfo {
inputTokenAddress: string;
outputTokenAddress: string;
inputTokenAmount: BigNumber;
minOutputTokenAmount: BigNumber;
transformations: Transformation[];
orders: SignedOrder[];
}
async function generateSwapAsync(orderFields: Partial<Order> = {}, isRfqt: boolean = false): Promise<SwapInfo> {
const order = await signatureUtils.ecSignTypedDataOrderAsync(
env.provider,
{
chainId: 1337,
exchangeAddress: exchange.address,
expirationTimeSeconds: new BigNumber(Date.now()),
salt: new BigNumber(hexUtils.random()),
feeRecipientAddress: NULL_ADDRESS,
senderAddress: NULL_ADDRESS,
takerAddress: isRfqt ? flashWalletAddress : NULL_ADDRESS,
makerAddress: maker,
makerAssetData: assetDataUtils.encodeERC20AssetData(outputToken.address),
takerAssetData: assetDataUtils.encodeERC20AssetData(inputToken.address),
makerFeeAssetData: NULL_BYTES,
takerFeeAssetData: NULL_BYTES,
takerAssetAmount: getRandomPortion(TAKER_BALANCE),
makerAssetAmount: getRandomPortion(MAKER_BALANCE),
makerFee: ZERO_AMOUNT,
takerFee: ZERO_AMOUNT,
...orderFields,
},
maker,
);
const transformations = [
{
deploymentNonce: findTransformerNonce(
addresses.transformers.fillQuoteTransformer,
addresses.exchangeProxyTransformerDeployer,
),
data: encodeFillQuoteTransformerData({
orders: [order],
signatures: [order.signature],
buyToken: outputToken.address,
sellToken: inputToken.address,
fillAmount: order.takerAssetAmount,
maxOrderFillAmounts: [],
refundReceiver: hexUtils.leftPad(2, 20), // Send refund to sender.
rfqtTakerAddress: isRfqt ? taker : NULL_ADDRESS,
side: FillQuoteTransformerSide.Sell,
}),
},
{
deploymentNonce: findTransformerNonce(
addresses.transformers.payTakerTransformer,
addresses.exchangeProxyTransformerDeployer,
),
data: encodePayTakerTransformerData({
tokens: [inputToken.address, outputToken.address, ETH_TOKEN_ADDRESS],
amounts: [MAX_UINT256, MAX_UINT256, MAX_UINT256],
}),
},
{
deploymentNonce: findTransformerNonce(
metadataTransformer.address,
addresses.exchangeProxyTransformerDeployer,
),
data: NULL_BYTES,
},
];
return {
transformations,
orders: [order],
inputTokenAddress: inputToken.address,
outputTokenAddress: outputToken.address,
inputTokenAmount: order.takerAssetAmount,
minOutputTokenAmount: order.makerAssetAmount,
};
}
function getSwapData(swap: SwapInfo): string {
return zeroEx
.transformERC20(
swap.inputTokenAddress,
swap.outputTokenAddress,
swap.inputTokenAmount,
swap.minOutputTokenAmount,
swap.transformations,
)
.getABIEncodedTransactionData();
}
function getSignedSwapData(swap: SwapInfo, signerKey?: string): string {
return signCallData(
zeroEx
.transformERC20(
swap.inputTokenAddress,
swap.outputTokenAddress,
swap.inputTokenAmount,
swap.minOutputTokenAmount,
swap.transformations,
)
.getABIEncodedTransactionData(),
signerKey ? signerKey : quoteSignerKey,
);
}
async function createMetaTransactionAsync(
data: string,
value: BigNumber,
fee?: BigNumber | number,
): Promise<SignedExchangeProxyMetaTransaction> {
return signatureUtils.ecSignTypedDataExchangeProxyMetaTransactionAsync(
env.provider,
{
value,
signer: taker,
sender: relayer,
minGasPrice: GAS_PRICE,
maxGasPrice: GAS_PRICE,
expirationTimeSeconds: new BigNumber(Math.floor(Date.now() / 1000) + 60),
salt: new BigNumber(hexUtils.random()),
callData: data,
feeToken: feeToken.address,
feeAmount: fee !== undefined ? new BigNumber(fee) : getRandomPortion(TAKER_FEE_BALANCE),
domain: {
chainId: 1,
name: 'ZeroEx',
version: '1.0.0',
verifyingContract: zeroEx.address,
},
},
taker,
);
}
it('can call `transformERC20()` with signed calldata and no relayer fee', async () => {
const swap = await generateSwapAsync();
const callDataHash = hexUtils.hash(getSwapData(swap));
const signedSwapData = getSignedSwapData(swap);
const _protocolFee = protocolFee.times(GAS_PRICE).times(swap.orders.length + 1); // Pay a little more fee than needed.
const mtx = await createMetaTransactionAsync(signedSwapData, _protocolFee, 0);
const relayerEthBalanceBefore = await env.web3Wrapper.getBalanceInWeiAsync(relayer);
const receipt = await zeroEx
.executeMetaTransaction(mtx, mtx.signature)
.awaitTransactionSuccessAsync({ from: relayer, value: mtx.value, gasPrice: GAS_PRICE });
const relayerEthRefund = relayerEthBalanceBefore
.minus(await env.web3Wrapper.getBalanceInWeiAsync(relayer))
.minus(GAS_PRICE.times(receipt.gasUsed));
// Ensure the relayer got back the unused protocol fees.
expect(relayerEthRefund).to.bignumber.eq(protocolFee.times(GAS_PRICE));
// Ensure the relayer got paid no mtx fees.
expect(await feeToken.balanceOf(relayer).callAsync()).to.bignumber.eq(0);
// Ensure the taker got output tokens.
expect(await outputToken.balanceOf(taker).callAsync()).to.bignumber.eq(swap.minOutputTokenAmount);
// Ensure the maker got input tokens.
expect(await inputToken.balanceOf(maker).callAsync()).to.bignumber.eq(swap.inputTokenAmount);
// Check events.
verifyEventsFromLogs(
receipt.logs,
[
{
taker,
callDataHash,
sender: zeroEx.address,
data: NULL_BYTES,
},
],
'TransformerMetadata',
);
});
it('can call `transformERC20()` with signed calldata and a relayer fee', async () => {
const swap = await generateSwapAsync();
const callDataHash = hexUtils.hash(getSwapData(swap));
const signedSwapData = getSignedSwapData(swap);
const _protocolFee = protocolFee.times(GAS_PRICE).times(swap.orders.length + 1); // Pay a little more fee than needed.
const mtx = await createMetaTransactionAsync(signedSwapData, _protocolFee);
const relayerEthBalanceBefore = await env.web3Wrapper.getBalanceInWeiAsync(relayer);
const receipt = await zeroEx
.executeMetaTransaction(mtx, mtx.signature)
.awaitTransactionSuccessAsync({ from: relayer, value: mtx.value, gasPrice: GAS_PRICE });
const relayerEthRefund = relayerEthBalanceBefore
.minus(await env.web3Wrapper.getBalanceInWeiAsync(relayer))
.minus(GAS_PRICE.times(receipt.gasUsed));
// Ensure the relayer got back the unused protocol fees.
expect(relayerEthRefund).to.bignumber.eq(protocolFee.times(GAS_PRICE));
// Ensure the relayer got paid mtx fees.
expect(await feeToken.balanceOf(relayer).callAsync()).to.bignumber.eq(mtx.feeAmount);
// Ensure the taker got output tokens.
expect(await outputToken.balanceOf(taker).callAsync()).to.bignumber.eq(swap.minOutputTokenAmount);
// Ensure the maker got input tokens.
expect(await inputToken.balanceOf(maker).callAsync()).to.bignumber.eq(swap.inputTokenAmount);
// Check events.
verifyEventsFromLogs(
receipt.logs,
[
{
taker,
callDataHash,
sender: zeroEx.address,
data: NULL_BYTES,
},
],
'TransformerMetadata',
);
});
it('can call `transformERC20()` with wrongly signed calldata and a relayer fee', async () => {
const swap = await generateSwapAsync();
const signedSwapData = getSignedSwapData(swap, hexUtils.random());
const _protocolFee = protocolFee.times(GAS_PRICE).times(swap.orders.length + 1); // Pay a little more fee than needed.
const mtx = await createMetaTransactionAsync(signedSwapData, _protocolFee);
const relayerEthBalanceBefore = await env.web3Wrapper.getBalanceInWeiAsync(relayer);
const receipt = await zeroEx
.executeMetaTransaction(mtx, mtx.signature)
.awaitTransactionSuccessAsync({ from: relayer, value: mtx.value, gasPrice: GAS_PRICE });
const relayerEthRefund = relayerEthBalanceBefore
.minus(await env.web3Wrapper.getBalanceInWeiAsync(relayer))
.minus(GAS_PRICE.times(receipt.gasUsed));
// Ensure the relayer got back the unused protocol fees.
expect(relayerEthRefund).to.bignumber.eq(protocolFee.times(GAS_PRICE));
// Ensure the relayer got paid mtx fees.
expect(await feeToken.balanceOf(relayer).callAsync()).to.bignumber.eq(mtx.feeAmount);
// Ensure the taker got output tokens.
expect(await outputToken.balanceOf(taker).callAsync()).to.bignumber.eq(swap.minOutputTokenAmount);
// Ensure the maker got input tokens.
expect(await inputToken.balanceOf(maker).callAsync()).to.bignumber.eq(swap.inputTokenAmount);
// Check events.
verifyEventsFromLogs(
receipt.logs,
[
{
taker,
// Only signed calldata should have a nonzero hash.
callDataHash: NULL_BYTES32,
sender: zeroEx.address,
data: NULL_BYTES,
},
],
'TransformerMetadata',
);
});
it('`transformERC20()` can fill RFQT order if calldata is signed', async () => {
const swap = await generateSwapAsync({}, true);
const callDataHash = hexUtils.hash(getSwapData(swap));
const signedSwapData = getSignedSwapData(swap);
const _protocolFee = protocolFee.times(GAS_PRICE).times(swap.orders.length + 1); // Pay a little more fee than needed.
const mtx = await createMetaTransactionAsync(signedSwapData, _protocolFee, 0);
const relayerEthBalanceBefore = await env.web3Wrapper.getBalanceInWeiAsync(relayer);
const receipt = await zeroEx
.executeMetaTransaction(mtx, mtx.signature)
.awaitTransactionSuccessAsync({ from: relayer, value: mtx.value, gasPrice: GAS_PRICE });
const relayerEthRefund = relayerEthBalanceBefore
.minus(await env.web3Wrapper.getBalanceInWeiAsync(relayer))
.minus(GAS_PRICE.times(receipt.gasUsed));
// Ensure the relayer got back the unused protocol fees.
expect(relayerEthRefund).to.bignumber.eq(protocolFee.times(GAS_PRICE));
// Ensure the relayer got paid no mtx fees.
expect(await feeToken.balanceOf(relayer).callAsync()).to.bignumber.eq(0);
// Ensure the taker got output tokens.
expect(await outputToken.balanceOf(taker).callAsync()).to.bignumber.eq(swap.minOutputTokenAmount);
// Ensure the maker got input tokens.
expect(await inputToken.balanceOf(maker).callAsync()).to.bignumber.eq(swap.inputTokenAmount);
// Check events.
verifyEventsFromLogs(
receipt.logs,
[
{
taker,
callDataHash,
sender: zeroEx.address,
data: NULL_BYTES,
},
],
'TransformerMetadata',
);
});
it('`transformERC20()` can fill RFQT order if calldata is not signed but no quote signer configured', async () => {
const swap = await generateSwapAsync({}, true);
const callData = getSwapData(swap);
const callDataHash = hexUtils.hash(callData);
const _protocolFee = protocolFee.times(GAS_PRICE).times(swap.orders.length + 1); // Pay a little more fee than needed.
const mtx = await createMetaTransactionAsync(callData, _protocolFee, 0);
const relayerEthBalanceBefore = await env.web3Wrapper.getBalanceInWeiAsync(relayer);
await zeroEx.setQuoteSigner(NULL_ADDRESS).awaitTransactionSuccessAsync({ from: owner });
const receipt = await zeroEx
.executeMetaTransaction(mtx, mtx.signature)
.awaitTransactionSuccessAsync({ from: relayer, value: mtx.value, gasPrice: GAS_PRICE });
const relayerEthRefund = relayerEthBalanceBefore
.minus(await env.web3Wrapper.getBalanceInWeiAsync(relayer))
.minus(GAS_PRICE.times(receipt.gasUsed));
// Ensure the relayer got back the unused protocol fees.
expect(relayerEthRefund).to.bignumber.eq(protocolFee.times(GAS_PRICE));
// Ensure the relayer got paid no mtx fees.
expect(await feeToken.balanceOf(relayer).callAsync()).to.bignumber.eq(0);
// Ensure the taker got output tokens.
expect(await outputToken.balanceOf(taker).callAsync()).to.bignumber.eq(swap.minOutputTokenAmount);
// Ensure the maker got input tokens.
expect(await inputToken.balanceOf(maker).callAsync()).to.bignumber.eq(swap.inputTokenAmount);
// Check events.
verifyEventsFromLogs(
receipt.logs,
[
{
taker,
callDataHash,
sender: zeroEx.address,
data: NULL_BYTES,
},
],
'TransformerMetadata',
);
});
it('`transformERC20()` cannot fill RFQT order if calldata is not signed', async () => {
const swap = await generateSwapAsync({}, true);
const callData = getSwapData(swap);
const _protocolFee = protocolFee.times(GAS_PRICE).times(swap.orders.length + 1); // Pay a little more fee than needed.
const mtx = await createMetaTransactionAsync(callData, _protocolFee, 0);
const tx = zeroEx
.executeMetaTransaction(mtx, mtx.signature)
.awaitTransactionSuccessAsync({ from: relayer, value: mtx.value, gasPrice: GAS_PRICE });
return expect(tx).to.revertWith(new ZeroExRevertErrors.MetaTransactions.MetaTransactionCallFailedError());
});
}); | the_stack |
/*
* Copyright(c) 2017 Microsoft Corporation. All rights reserved.
*
* This code is licensed under the MIT License (MIT).
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/********************************************
* Draggable Shapes Manager
* Author: Ricky Brundritt
* License: MIT
*********************************************/
/// <reference path="../../Common/typings/MicrosoftMaps/Microsoft.Maps.d.ts"/>
/**
* An enumeration which defines how a shape is dragged on the map.
*/
enum DragMethod {
/** Shapes are dragged such that they maintain their Pixel dimensions. */
pixel,
/** Shapes are dragged using geospatial accurate projections. The shape may become distorted when moved towards the poles. */
geo
}
interface DraggableShape extends Microsoft.Maps.IPrimitive {
_dragevents: Microsoft.Maps.IHandlerId[];
}
/**
* A class that makes it easy to make any shape draggable.
*/
class DraggableShapesManager {
/**********************
* Private Properties
***********************/
private _currentLocation: Microsoft.Maps.Location;
private _currentShape: Microsoft.Maps.IPrimitive;
private _currentPoint: Microsoft.Maps.Point;
private _map: Microsoft.Maps.Map;
private _dragMethod: DragMethod = DragMethod.pixel;
private _mapMoveEventId: Microsoft.Maps.IHandlerId;
private _shapes: Microsoft.Maps.IPrimitive[] = [];
/**********************
* Constructor
***********************/
/**
* @constructor
* @param map The map to add the DraggableShapesManager to.
* @param dragMethod The drag method to use.
*/
constructor(map, dragMethod?: DragMethod) {
this._map = map;
if (typeof dragMethod != 'undefined') {
this._dragMethod = dragMethod;
}
var self = this;
//Update the shape as the mouse moves on the map.
this._mapMoveEventId = Microsoft.Maps.Events.addHandler(this._map, 'mousemove', (e) => { self._updateShape(<Microsoft.Maps.IMouseEventArgs>e); });
}
/**********************
* Public Functions
***********************/
/**
* Disposes the DraggableShapesManager and releases it's resources.
*/
public dispose(): void {
Microsoft.Maps.Events.removeHandler(this._mapMoveEventId);
this._currentLocation = null;
this._currentShape = null;
this._currentPoint = null;
this._map = null;
this._dragMethod = null;
for (var i = 0; i < this._shapes.length; i++){
this.disableDraggable(this._shapes[i]);
}
this._shapes = null;
}
/**
* Adds draggable functionality to a shape.
* @param shape The shape to add draggable functionality to.
*/
public makeDraggable(shape: Microsoft.Maps.IPrimitive): void {
if (this._shapes.indexOf(shape) === -1) {
if (shape instanceof Microsoft.Maps.Pushpin) {
//Pushpins already support dragging.
shape.setOptions({ draggable: true });
} else {
var s = <DraggableShape>shape;
if (!s._dragevents) {
s._dragevents = [];
}
var self = this;
s._dragevents.push(Microsoft.Maps.Events.addHandler(s, 'mousedown', (e) => {
//Lock map so it doesn't move when dragging.
self._map.setOptions({ disablePanning: true });
//Set the current draggable shape.
self._currentShape = e.target;
//Capture the mouse start location and pixel point.
self._currentLocation = e.location;
self._currentPoint = e.point;
}));
s._dragevents.push(Microsoft.Maps.Events.addHandler(s, 'mouseup', (e) => {
//Unlock map panning.
self._map.setOptions({ disablePanning: false });
//Set current shape to null, so that no updates will happen will mouse is up.
self._currentShape = null;
}));
}
}
}
/**
* Removes the draggable functionality of a shape.
* @param shape The shape to remove the draggable functionality from.
*/
public disableDraggable(shape: Microsoft.Maps.IPrimitive): void {
if (this._shapes.indexOf(shape) !== -1) {
if (shape instanceof Microsoft.Maps.Pushpin) {
//Pushpins already support dragging.
shape.setOptions({ draggable: false });
} else {
var s = <DraggableShape>shape;
if (s._dragevents) {
this._clearShapeEvents(s._dragevents);
s._dragevents = null;
}
}
this._shapes.splice(this._shapes.indexOf(shape), 1);
}
}
/**
* Gets the drag method currently used by the DraggabeShapesManager.
* @returns The drag method currently used by the DraggabeShapesManager.
*/
public getDragMethod(): DragMethod {
return this._dragMethod;
}
/**
* Sets the drag method used by the DraggabeShapesManager.
* @param dragMethod The drag method used by the DraggabeShapesManager.
*/
public setDragMethod(dragMethod: DragMethod): void {
if (typeof dragMethod !== 'undefined') {
this._dragMethod = dragMethod;
}
}
/**********************
* Private Functions
***********************/
/**
* Removes an array of event handler ID's to remove.
* @param events An array of event handler ID's to remove.
*/
private _clearShapeEvents(events: Microsoft.Maps.IHandlerId[]): void {
for (var i = 0; i < events.length; i++) {
Microsoft.Maps.Events.removeHandler(events[i]);
}
}
/**
* Updates a shapes position as it is being dragged.
* @param e The mouse event argument.
*/
private _updateShape(e: Microsoft.Maps.IMouseEventArgs): void {
if (this._currentShape) {
//As an optimization, only update the shape if the mouse has moved atleast 5 pixels.
//This will significantly reduce the number of recalculations and provide much better performance.
var dx = this._currentPoint.x - e.point.x;
var dy = this._currentPoint.y - e.point.y;
if (dx * dx + dy * dy <= 25) {
return;
}
if (this._dragMethod === DragMethod.pixel) {
this._pixelAccurateUpdate(e);
} else {
this._geoAccurateUpdate(e);
}
}
}
/**
* Updates the position of a shape as it dragged using a geospatially accurate shift.
* @param e The mouse event argument.
*/
private _geoAccurateUpdate(e: Microsoft.Maps.IMouseEventArgs): void {
var newLoc = e.location;
var currentLocation = <Microsoft.Maps.Location>this._currentLocation;
//Calculate the distance and heading from the last mouse location used to update the shape to the new location.
var distance = Microsoft.Maps.SpatialMath.getDistanceTo(currentLocation, newLoc);
var heading = Microsoft.Maps.SpatialMath.getHeading(currentLocation, newLoc);
if (this._currentShape instanceof Microsoft.Maps.Polygon) {
var polygon = <Microsoft.Maps.Polygon>this._currentShape;
var rings = polygon.getRings();
for (var i = 0, len = rings.length; i < len; i++) {
rings[i] = this._shiftLocations(rings[i], heading, distance);
}
//Update the in rings ina polygon.
polygon.setRings(rings);
} else if (this._currentShape instanceof Microsoft.Maps.Polyline) {
var line = <Microsoft.Maps.Polyline>this._currentShape;
var locs = line.getLocations();
//Update the locations of a polyline.
line.setLocations(this._shiftLocations(locs, heading, distance));
} else if (this._currentShape instanceof Microsoft.Maps.Pushpin) {
//Although not needed, for completeness, this supports dragging of pushpins.
var pin = <Microsoft.Maps.Pushpin>this._currentShape;
var locs = this._shiftLocations([pin.getLocation()], heading, distance);
pin.setLocation(locs[0]);
}
//Store the new mouse location and point that was used to update the shape.
this._currentLocation = newLoc;
this._currentPoint = e.point;
}
/**
* Updates the position of a shape as it dragged using a pixel accurate shift.
* @param e The mouse event argument.
*/
private _pixelAccurateUpdate(e: Microsoft.Maps.IMouseEventArgs): void {
//Shift the shape based on pixel offset.
var newPoint = Microsoft.Maps.SpatialMath.Tiles.locationToGlobalPixel(e.location, 19);
var point = Microsoft.Maps.SpatialMath.Tiles.locationToGlobalPixel(this._currentLocation, 19);
var dx = point.x - newPoint.x;
var dy = point.y - newPoint.y;
if (this._currentShape instanceof Microsoft.Maps.Polygon) {
var polygon = <Microsoft.Maps.Polygon>this._currentShape;
var rings = polygon.getRings();
for (var i = 0, len = rings.length; i < len; i++) {
rings[i] = this._pixelShiftLocations(rings[i], dx, dy);
}
//Update the in rings ina polygon.
polygon.setRings(rings);
} else if (this._currentShape instanceof Microsoft.Maps.Polyline) {
var line = <Microsoft.Maps.Polyline>this._currentShape;
var locs = line.getLocations();
//Update the locations of a polyline.
line.setLocations(this._pixelShiftLocations(locs, dx, dy));
} else if (this._currentShape instanceof Microsoft.Maps.Pushpin) {
//Although not needed, for completeness, this supports dragging of pushpins.
var pin = <Microsoft.Maps.Pushpin>this._currentShape;
var locs = this._pixelShiftLocations([pin.getLocation()], dx, dy);
pin.setLocation(locs[0]);
}
//Store the new mouse location and point that was used to update the shape.
this._currentLocation = e.location;
this._currentPoint = e.point;
}
/**
* Takes an array of locations and shifts them a specified distancein a specified direction.
* @param locs The locations to shift.
* @param heading The direction to shift the locations.
* @param distance The distance to shift the locations.
* @returns An array of shifted locations.
*/
private _shiftLocations(locs: Microsoft.Maps.Location[], heading: number, distance: number): Microsoft.Maps.Location[] {
//Based on the distance and heading, shift all locations in the array accordingly.
var loc;
for (var i = 0, len = locs.length; i < len; i++) {
locs[i] = Microsoft.Maps.SpatialMath.getDestination(locs[i], heading, distance);
}
return locs;
}
/**
* Takes an rray of locations and shifts them a specified distance in pixels at zoom level 19.
* @param locs The locations to shift.
* @param dx Horizontal offset distance to shift the locations in pixels at zoom level 19.
* @param dy Vertical offset distance to shift the locations in pixels at zoom level 19.
* @returns An array of shifted locations.
*/
private _pixelShiftLocations(locs: Microsoft.Maps.Location[], dx: number, dy: number): Microsoft.Maps.Location[] {
var mapWidth19 = Math.pow(2, 19) * 256;
//Based on the distance and heading, shift all locations in the array accordingly.
for (var i = 0, len = locs.length; i < len; i++) {
var p = Microsoft.Maps.SpatialMath.Tiles.locationToGlobalPixel(locs[i], 19);
p.x -= dx;
p.y -= dy;
if (p.x < 0) {
p.x += mapWidth19;
} else if (p.x > mapWidth19) {
p.x -= mapWidth19;
}
locs[i] = Microsoft.Maps.SpatialMath.Tiles.globalPixelToLocation(p, 19);
}
return locs;
}
}
//Load SpatialMath module dependancy.
Microsoft.Maps.loadModule('Microsoft.Maps.SpatialMath', function () {
Microsoft.Maps.moduleLoaded('DraggableShapesModule');
}); | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { PollerLike, PollOperationState } from "@azure/core-lro";
import {
AnalysisServicesServer,
ServersListByResourceGroupOptionalParams,
ServersListOptionalParams,
ServersGetDetailsOptionalParams,
ServersGetDetailsResponse,
ServersCreateOptionalParams,
ServersCreateResponse,
ServersDeleteOptionalParams,
AnalysisServicesServerUpdateParameters,
ServersUpdateOptionalParams,
ServersUpdateResponse,
ServersSuspendOptionalParams,
ServersResumeOptionalParams,
ServersListSkusForNewOptionalParams,
ServersListSkusForNewResponse,
ServersListSkusForExistingOptionalParams,
ServersListSkusForExistingResponse,
ServersListGatewayStatusOptionalParams,
ServersListGatewayStatusResponse,
ServersDissociateGatewayOptionalParams,
CheckServerNameAvailabilityParameters,
ServersCheckNameAvailabilityOptionalParams,
ServersCheckNameAvailabilityResponse,
ServersListOperationResultsOptionalParams,
ServersListOperationStatusesOptionalParams,
ServersListOperationStatusesResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Interface representing a Servers. */
export interface Servers {
/**
* Gets all the Analysis Services servers for the given resource group.
* @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services
* server is part. This name must be at least 1 character in length, and no more than 90.
* @param options The options parameters.
*/
listByResourceGroup(
resourceGroupName: string,
options?: ServersListByResourceGroupOptionalParams
): PagedAsyncIterableIterator<AnalysisServicesServer>;
/**
* Lists all the Analysis Services servers for the given subscription.
* @param options The options parameters.
*/
list(
options?: ServersListOptionalParams
): PagedAsyncIterableIterator<AnalysisServicesServer>;
/**
* Gets details about the specified Analysis Services server.
* @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services
* server is part. This name must be at least 1 character in length, and no more than 90.
* @param serverName The name of the Analysis Services server. It must be a minimum of 3 characters,
* and a maximum of 63.
* @param options The options parameters.
*/
getDetails(
resourceGroupName: string,
serverName: string,
options?: ServersGetDetailsOptionalParams
): Promise<ServersGetDetailsResponse>;
/**
* Provisions the specified Analysis Services server based on the configuration specified in the
* request.
* @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services
* server is part. This name must be at least 1 character in length, and no more than 90.
* @param serverName The name of the Analysis Services server. It must be a minimum of 3 characters,
* and a maximum of 63.
* @param serverParameters Contains the information used to provision the Analysis Services server.
* @param options The options parameters.
*/
beginCreate(
resourceGroupName: string,
serverName: string,
serverParameters: AnalysisServicesServer,
options?: ServersCreateOptionalParams
): Promise<
PollerLike<PollOperationState<ServersCreateResponse>, ServersCreateResponse>
>;
/**
* Provisions the specified Analysis Services server based on the configuration specified in the
* request.
* @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services
* server is part. This name must be at least 1 character in length, and no more than 90.
* @param serverName The name of the Analysis Services server. It must be a minimum of 3 characters,
* and a maximum of 63.
* @param serverParameters Contains the information used to provision the Analysis Services server.
* @param options The options parameters.
*/
beginCreateAndWait(
resourceGroupName: string,
serverName: string,
serverParameters: AnalysisServicesServer,
options?: ServersCreateOptionalParams
): Promise<ServersCreateResponse>;
/**
* Deletes the specified Analysis Services server.
* @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services
* server is part. This name must be at least 1 character in length, and no more than 90.
* @param serverName The name of the Analysis Services server. It must be at least 3 characters in
* length, and no more than 63.
* @param options The options parameters.
*/
beginDelete(
resourceGroupName: string,
serverName: string,
options?: ServersDeleteOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Deletes the specified Analysis Services server.
* @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services
* server is part. This name must be at least 1 character in length, and no more than 90.
* @param serverName The name of the Analysis Services server. It must be at least 3 characters in
* length, and no more than 63.
* @param options The options parameters.
*/
beginDeleteAndWait(
resourceGroupName: string,
serverName: string,
options?: ServersDeleteOptionalParams
): Promise<void>;
/**
* Updates the current state of the specified Analysis Services server.
* @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services
* server is part. This name must be at least 1 character in length, and no more than 90.
* @param serverName The name of the Analysis Services server. It must be at least 3 characters in
* length, and no more than 63.
* @param serverUpdateParameters Request object that contains the updated information for the server.
* @param options The options parameters.
*/
beginUpdate(
resourceGroupName: string,
serverName: string,
serverUpdateParameters: AnalysisServicesServerUpdateParameters,
options?: ServersUpdateOptionalParams
): Promise<
PollerLike<PollOperationState<ServersUpdateResponse>, ServersUpdateResponse>
>;
/**
* Updates the current state of the specified Analysis Services server.
* @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services
* server is part. This name must be at least 1 character in length, and no more than 90.
* @param serverName The name of the Analysis Services server. It must be at least 3 characters in
* length, and no more than 63.
* @param serverUpdateParameters Request object that contains the updated information for the server.
* @param options The options parameters.
*/
beginUpdateAndWait(
resourceGroupName: string,
serverName: string,
serverUpdateParameters: AnalysisServicesServerUpdateParameters,
options?: ServersUpdateOptionalParams
): Promise<ServersUpdateResponse>;
/**
* Suspends operation of the specified Analysis Services server instance.
* @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services
* server is part. This name must be at least 1 character in length, and no more than 90.
* @param serverName The name of the Analysis Services server. It must be at least 3 characters in
* length, and no more than 63.
* @param options The options parameters.
*/
beginSuspend(
resourceGroupName: string,
serverName: string,
options?: ServersSuspendOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Suspends operation of the specified Analysis Services server instance.
* @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services
* server is part. This name must be at least 1 character in length, and no more than 90.
* @param serverName The name of the Analysis Services server. It must be at least 3 characters in
* length, and no more than 63.
* @param options The options parameters.
*/
beginSuspendAndWait(
resourceGroupName: string,
serverName: string,
options?: ServersSuspendOptionalParams
): Promise<void>;
/**
* Resumes operation of the specified Analysis Services server instance.
* @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services
* server is part. This name must be at least 1 character in length, and no more than 90.
* @param serverName The name of the Analysis Services server. It must be at least 3 characters in
* length, and no more than 63.
* @param options The options parameters.
*/
beginResume(
resourceGroupName: string,
serverName: string,
options?: ServersResumeOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Resumes operation of the specified Analysis Services server instance.
* @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services
* server is part. This name must be at least 1 character in length, and no more than 90.
* @param serverName The name of the Analysis Services server. It must be at least 3 characters in
* length, and no more than 63.
* @param options The options parameters.
*/
beginResumeAndWait(
resourceGroupName: string,
serverName: string,
options?: ServersResumeOptionalParams
): Promise<void>;
/**
* Lists eligible SKUs for Analysis Services resource provider.
* @param options The options parameters.
*/
listSkusForNew(
options?: ServersListSkusForNewOptionalParams
): Promise<ServersListSkusForNewResponse>;
/**
* Lists eligible SKUs for an Analysis Services resource.
* @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services
* server is part. This name must be at least 1 character in length, and no more than 90.
* @param serverName The name of the Analysis Services server. It must be at least 3 characters in
* length, and no more than 63.
* @param options The options parameters.
*/
listSkusForExisting(
resourceGroupName: string,
serverName: string,
options?: ServersListSkusForExistingOptionalParams
): Promise<ServersListSkusForExistingResponse>;
/**
* Return the gateway status of the specified Analysis Services server instance.
* @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services
* server is part. This name must be at least 1 character in length, and no more than 90.
* @param serverName The name of the Analysis Services server.
* @param options The options parameters.
*/
listGatewayStatus(
resourceGroupName: string,
serverName: string,
options?: ServersListGatewayStatusOptionalParams
): Promise<ServersListGatewayStatusResponse>;
/**
* Dissociates a Unified Gateway associated with the server.
* @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services
* server is part. This name must be at least 1 character in length, and no more than 90.
* @param serverName The name of the Analysis Services server. It must be at least 3 characters in
* length, and no more than 63.
* @param options The options parameters.
*/
dissociateGateway(
resourceGroupName: string,
serverName: string,
options?: ServersDissociateGatewayOptionalParams
): Promise<void>;
/**
* Check the name availability in the target location.
* @param location The region name which the operation will lookup into.
* @param serverParameters Contains the information used to provision the Analysis Services server.
* @param options The options parameters.
*/
checkNameAvailability(
location: string,
serverParameters: CheckServerNameAvailabilityParameters,
options?: ServersCheckNameAvailabilityOptionalParams
): Promise<ServersCheckNameAvailabilityResponse>;
/**
* List the result of the specified operation.
* @param location The region name which the operation will lookup into.
* @param operationId The target operation Id.
* @param options The options parameters.
*/
listOperationResults(
location: string,
operationId: string,
options?: ServersListOperationResultsOptionalParams
): Promise<void>;
/**
* List the status of operation.
* @param location The region name which the operation will lookup into.
* @param operationId The target operation Id.
* @param options The options parameters.
*/
listOperationStatuses(
location: string,
operationId: string,
options?: ServersListOperationStatusesOptionalParams
): Promise<ServersListOperationStatusesResponse>;
} | the_stack |
import CodeGenerator, { findTagById, convertToTreeData, updateChildrenText, copyObject } from 'lib/constructor';
import { TProtypoElement } from 'ibax/protypo';
import { TConstructorTreeElement, IFindTagResult } from 'ibax/editor';
test('Constructor module', () => {
const jsonData: TProtypoElement[] = [
{
tag: 'p',
attr: {
'class': 'text-danger text-center'
},
children: [
{
tag: 'strong',
id: 'tag_34954216',
attr: {
className: null
},
children: [
{
tag: 'text',
text: 'Bold text',
id: 'tag_88634399'
}
],
childrenText: 'Bold text'
},
{
tag: 'span',
id: 'tag_65961696',
attr: {
className: null
},
children: [
{
tag: 'text',
text: ' and ',
id: 'tag_19360500'
}
],
childrenText: ' and '
},
{
tag: 'em',
id: 'tag_34004593',
attr: {
className: null
},
children: [
{
tag: 'text',
text: 'italic',
id: 'tag_77362545'
}
],
childrenText: 'italic'
}
],
id: 'tag_88596132',
childrenText: '<b>Bold text</b><span> and </span><i>italic</i>'
},
{
tag: 'div',
attr: {
'class': 'classname'
},
sysAttr: {
canDropPosition: 'inside'
},
children: [
{
tag: 'input',
id: 'tag_27384336',
attr: {
name: 'sample input',
'class': 'form-control'
}
},
{
tag: 'button',
id: 'tag_14345510',
children: [
{
tag: 'text',
text: 'Button',
id: 'tag_66000647'
}
],
childrenText: 'Button'
}
],
id: 'tag_42524123',
childrenText: null
}
];
const jsonDataNoChildrenText: TProtypoElement[] = [
{
tag: 'p',
attr: {
'class': 'text-danger text-center'
},
children: [
{
tag: 'strong',
id: 'tag_34954216',
attr: {
className: null
},
children: [
{
tag: 'text',
text: 'Bold text',
id: 'tag_88634399'
}
]
},
{
tag: 'span',
id: 'tag_65961696',
attr: {
className: null
},
children: [
{
tag: 'text',
text: ' and ',
id: 'tag_19360500'
}
]
},
{
tag: 'em',
id: 'tag_34004593',
attr: {
className: null
},
children: [
{
tag: 'text',
text: 'italic',
id: 'tag_77362545'
}
]
}
],
id: 'tag_88596132'
},
{
tag: 'div',
attr: {
'class': 'classname'
},
sysAttr: {
canDropPosition: 'inside'
},
children: [
{
tag: 'input',
id: 'tag_27384336',
attr: {
name: 'sample input',
'class': 'form-control'
}
},
{
tag: 'button',
id: 'tag_14345510',
children: [
{
tag: 'text',
text: 'Button',
id: 'tag_66000647'
}
]
}
],
id: 'tag_42524123'
}
];
const selectedTag: TProtypoElement = {
tag: 'input',
id: 'tag_27384336',
attr: {
name: 'sample input',
'class': 'form-control'
}
};
const foundTag: IFindTagResult = {
el: {
attr: {
class: 'form-control',
name: 'sample input'
},
id: 'tag_27384336',
tag: 'input'
},
parent: {
attr: {
class: 'classname'
},
sysAttr: {
canDropPosition: 'inside'
},
children: [
{
attr: {
class: 'form-control',
name: 'sample input'
},
id: 'tag_27384336',
tag: 'input'
},
{
children: [
{
id: 'tag_66000647',
tag: 'text',
text: 'Button'
}
],
childrenText: 'Button',
id: 'tag_14345510',
tag: 'button'
},
],
childrenText: null,
id: 'tag_42524123',
tag: 'div'
},
parentPosition: 0,
tail: false
};
const treeData: TConstructorTreeElement[] = [
{
title: 'p',
children: [
{
title: 'strong: Bold text',
children: null,
expanded: true,
id: 'tag_34954216',
selected: false,
logic: false,
canMove: true,
canDrop: true,
tag: {
tag: 'strong',
id: 'tag_34954216',
attr: {
className: null
},
children: [
{
tag: 'text',
text: 'Bold text',
id: 'tag_88634399'
}
],
childrenText: 'Bold text'
}
},
{
title: 'span: and ',
children: null,
expanded: true,
id: 'tag_65961696',
selected: false,
logic: false,
canMove: true,
canDrop: true,
tag: {
tag: 'span',
id: 'tag_65961696',
attr: {
className: null
},
children: [
{
tag: 'text',
text: ' and ',
id: 'tag_19360500'
}
],
childrenText: ' and '
}
},
{
title: 'em: italic',
children: null,
expanded: true,
id: 'tag_34004593',
selected: false,
logic: false,
canMove: true,
canDrop: true,
tag: {
tag: 'em',
id: 'tag_34004593',
attr: {
className: null
},
children: [
{
tag: 'text',
text: 'italic',
id: 'tag_77362545'
}
],
childrenText: 'italic'
}
}
],
expanded: true,
id: 'tag_88596132',
selected: false,
logic: false,
canMove: true,
canDrop: true,
tag: {
tag: 'p',
attr: {
'class': 'text-danger text-center'
},
children: [
{
tag: 'strong',
id: 'tag_34954216',
attr: {
className: null
},
children: [
{
tag: 'text',
text: 'Bold text',
id: 'tag_88634399'
}
],
childrenText: 'Bold text'
},
{
tag: 'span',
id: 'tag_65961696',
attr: {
className: null
},
children: [
{
tag: 'text',
text: ' and ',
id: 'tag_19360500'
}
],
childrenText: ' and '
},
{
tag: 'em',
id: 'tag_34004593',
attr: {
className: null
},
children: [
{
tag: 'text',
text: 'italic',
id: 'tag_77362545'
}
],
childrenText: 'italic'
}
],
id: 'tag_88596132',
childrenText: '<b>Bold text</b><span> and </span><i>italic</i>'
}
},
{
title: 'div',
children: [
{
title: 'input',
children: null,
expanded: true,
id: 'tag_27384336',
selected: true,
logic: false,
canMove: true,
canDrop: false,
tag: {
tag: 'input',
id: 'tag_27384336',
attr: {
name: 'sample input',
'class': 'form-control'
}
}
},
{
title: 'button: Button',
children: null,
expanded: true,
id: 'tag_14345510',
selected: false,
logic: false,
canMove: true,
canDrop: true,
tag: {
tag: 'button',
id: 'tag_14345510',
children: [
{
tag: 'text',
text: 'Button',
id: 'tag_66000647'
}
],
childrenText: 'Button'
}
}
],
expanded: true,
id: 'tag_42524123',
selected: false,
logic: false,
canMove: true,
canDrop: true,
tag: {
tag: 'div',
attr: {
'class': 'classname'
},
sysAttr: {
canDropPosition: 'inside'
},
children: [
{
tag: 'input',
id: 'tag_27384336',
attr: {
name: 'sample input',
'class': 'form-control'
}
},
{
tag: 'button',
id: 'tag_14345510',
children: [
{
tag: 'text',
text: 'Button',
id: 'tag_66000647'
}
],
childrenText: 'Button'
}
],
id: 'tag_42524123',
childrenText: null
}
}
];
const pageTemplate = 'P(Class: text-danger text-center){\n Strong(Body: Bold text)\n Span(Body: and )\n Em(Body: italic)\n}\nDiv(Class: classname){\n Input(Name: sample input, Class: form-control)\n Button(Body: Button)\n}';
const codeGenerator = new CodeGenerator(jsonData);
expect(foundTag).toEqual(findTagById(jsonData, 'tag_27384336'));
expect(treeData).toEqual(convertToTreeData(jsonData, selectedTag));
expect(pageTemplate).toEqual(codeGenerator.render());
expect(jsonData).toEqual(updateChildrenText(jsonDataNoChildrenText));
expect(jsonData).toEqual(copyObject(jsonData));
}); | the_stack |
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
import * as url from "url";
import * as portableFetch from "portable-fetch";
import { Configuration } from "./configuration";
const BASE_PATH = "https://petstore.swagger.io/v2".replace(/\/+$/, "");
/**
*
* @export
*/
export const COLLECTION_FORMATS = {
csv: ",",
ssv: " ",
tsv: "\t",
pipes: "|",
};
/**
*
* @export
* @interface FetchAPI
*/
export interface FetchAPI {
(url: string, init?: any): Promise<Response>;
}
/**
*
* @export
* @interface FetchArgs
*/
export interface FetchArgs {
url: string;
options: any;
}
/**
*
* @export
* @class BaseAPI
*/
export class BaseAPI {
protected configuration: Configuration;
constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected fetch: FetchAPI = portableFetch) {
if (configuration) {
this.configuration = configuration;
this.basePath = configuration.basePath || this.basePath;
}
}
};
/**
*
* @export
* @class RequiredError
* @extends {Error}
*/
export class RequiredError extends Error {
name: "RequiredError"
constructor(public field: string, msg?: string) {
super(msg);
}
}
/**
* some description
* @export
* @interface Amount
*/
export interface Amount {
/**
* some description
* @type {number}
* @memberof Amount
*/
value: number;
/**
*
* @type {Currency}
* @memberof Amount
*/
currency: Currency;
}
/**
* Describes the result of uploading an image resource
* @export
* @interface ApiResponse
*/
export interface ApiResponse {
/**
*
* @type {number}
* @memberof ApiResponse
*/
code?: number;
/**
*
* @type {string}
* @memberof ApiResponse
*/
type?: string;
/**
*
* @type {string}
* @memberof ApiResponse
*/
message?: string;
}
/**
* A category for a pet
* @export
* @interface Category
*/
export interface Category {
/**
*
* @type {number}
* @memberof Category
*/
id?: number;
/**
*
* @type {string}
* @memberof Category
*/
name?: string;
}
/**
* some description
* @export
* @interface Currency
*/
export interface Currency {
}
/**
* An order for a pets from the pet store
* @export
* @interface Order
*/
export interface Order {
/**
*
* @type {number}
* @memberof Order
*/
id?: number;
/**
*
* @type {number}
* @memberof Order
*/
petId?: number;
/**
*
* @type {number}
* @memberof Order
*/
quantity?: number;
/**
*
* @type {Date}
* @memberof Order
*/
shipDate?: Date;
/**
* Order Status
* @type {string}
* @memberof Order
*/
status?: Order.StatusEnum;
/**
*
* @type {boolean}
* @memberof Order
*/
complete?: boolean;
}
/**
* @export
* @namespace Order
*/
export namespace Order {
/**
* @export
* @enum {string}
*/
export enum StatusEnum {
Placed = <any> 'placed',
Approved = <any> 'approved',
Delivered = <any> 'delivered'
}
}
/**
* A pet for sale in the pet store
* @export
* @interface Pet
*/
export interface Pet {
/**
*
* @type {number}
* @memberof Pet
*/
id?: number;
/**
*
* @type {Category}
* @memberof Pet
*/
category?: Category;
/**
*
* @type {string}
* @memberof Pet
*/
name: string;
/**
*
* @type {Array<string>}
* @memberof Pet
*/
photoUrls: Array<string>;
/**
*
* @type {Array<Tag>}
* @memberof Pet
*/
tags?: Array<Tag>;
/**
* pet status in the store
* @type {string}
* @memberof Pet
*/
status?: Pet.StatusEnum;
}
/**
* @export
* @namespace Pet
*/
export namespace Pet {
/**
* @export
* @enum {string}
*/
export enum StatusEnum {
Available = <any> 'available',
Pending = <any> 'pending',
Sold = <any> 'sold'
}
}
/**
* A tag for a pet
* @export
* @interface Tag
*/
export interface Tag {
/**
*
* @type {number}
* @memberof Tag
*/
id?: number;
/**
*
* @type {string}
* @memberof Tag
*/
name?: string;
}
/**
* A User who is purchasing from the pet store
* @export
* @interface User
*/
export interface User {
/**
*
* @type {number}
* @memberof User
*/
id?: number;
/**
*
* @type {string}
* @memberof User
*/
username?: string;
/**
*
* @type {string}
* @memberof User
*/
firstName?: string;
/**
*
* @type {string}
* @memberof User
*/
lastName?: string;
/**
*
* @type {string}
* @memberof User
*/
email?: string;
/**
*
* @type {string}
* @memberof User
*/
password?: string;
/**
*
* @type {string}
* @memberof User
*/
phone?: string;
/**
* User Status
* @type {number}
* @memberof User
*/
userStatus?: number;
}
/**
* PetApi - fetch parameter creator
* @export
*/
export const PetApiFetchParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @summary Add a new pet to the store
* @param {Pet} body Pet object that needs to be added to the store
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
addPet(body: Pet, options: any = {}): FetchArgs {
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('body','Required parameter body was null or undefined when calling addPet.');
}
const localVarPath = `/pet`;
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions = Object.assign({ method: 'POST' }, options);
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication petstore_auth required
// oauth required
if (configuration && configuration.accessToken) {
const localVarAccessTokenValue = typeof configuration.accessToken === 'function'
? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"])
: configuration.accessToken;
localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue;
}
localVarHeaderParameter['Content-Type'] = 'application/json';
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
const needsSerialization = (<any>"Pet" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json';
localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || "");
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Deletes a pet
* @param {number} petId Pet id to delete
* @param {string} [apiKey]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deletePet(petId: number, apiKey?: string, options: any = {}): FetchArgs {
// verify required parameter 'petId' is not null or undefined
if (petId === null || petId === undefined) {
throw new RequiredError('petId','Required parameter petId was null or undefined when calling deletePet.');
}
const localVarPath = `/pet/{petId}`
.replace(`{${"petId"}}`, encodeURIComponent(String(petId)));
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions = Object.assign({ method: 'DELETE' }, options);
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication petstore_auth required
// oauth required
if (configuration && configuration.accessToken) {
const localVarAccessTokenValue = typeof configuration.accessToken === 'function'
? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"])
: configuration.accessToken;
localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue;
}
if (apiKey !== undefined && apiKey !== null) {
localVarHeaderParameter['api_key'] = String(apiKey);
}
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Multiple status values can be provided with comma separated strings
* @summary Finds Pets by status
* @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options: any = {}): FetchArgs {
// verify required parameter 'status' is not null or undefined
if (status === null || status === undefined) {
throw new RequiredError('status','Required parameter status was null or undefined when calling findPetsByStatus.');
}
const localVarPath = `/pet/findByStatus`;
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions = Object.assign({ method: 'GET' }, options);
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication petstore_auth required
// oauth required
if (configuration && configuration.accessToken) {
const localVarAccessTokenValue = typeof configuration.accessToken === 'function'
? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"])
: configuration.accessToken;
localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue;
}
if (status) {
localVarQueryParameter['status'] = status.join(COLLECTION_FORMATS["csv"]);
}
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* @summary Finds Pets by tags
* @param {Array<string>} tags Tags to filter by
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
findPetsByTags(tags: Array<string>, options: any = {}): FetchArgs {
// verify required parameter 'tags' is not null or undefined
if (tags === null || tags === undefined) {
throw new RequiredError('tags','Required parameter tags was null or undefined when calling findPetsByTags.');
}
const localVarPath = `/pet/findByTags`;
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions = Object.assign({ method: 'GET' }, options);
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication petstore_auth required
// oauth required
if (configuration && configuration.accessToken) {
const localVarAccessTokenValue = typeof configuration.accessToken === 'function'
? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"])
: configuration.accessToken;
localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue;
}
if (tags) {
localVarQueryParameter['tags'] = tags.join(COLLECTION_FORMATS["csv"]);
}
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Returns a single pet
* @summary Find pet by ID
* @param {number} petId ID of pet to return
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getPetById(petId: number, options: any = {}): FetchArgs {
// verify required parameter 'petId' is not null or undefined
if (petId === null || petId === undefined) {
throw new RequiredError('petId','Required parameter petId was null or undefined when calling getPetById.');
}
const localVarPath = `/pet/{petId}`
.replace(`{${"petId"}}`, encodeURIComponent(String(petId)));
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions = Object.assign({ method: 'GET' }, options);
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication api_key required
if (configuration && configuration.apiKey) {
const localVarApiKeyValue = typeof configuration.apiKey === 'function'
? configuration.apiKey("api_key")
: configuration.apiKey;
localVarHeaderParameter["api_key"] = localVarApiKeyValue;
}
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Update an existing pet
* @param {Pet} body Pet object that needs to be added to the store
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updatePet(body: Pet, options: any = {}): FetchArgs {
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('body','Required parameter body was null or undefined when calling updatePet.');
}
const localVarPath = `/pet`;
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions = Object.assign({ method: 'PUT' }, options);
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication petstore_auth required
// oauth required
if (configuration && configuration.accessToken) {
const localVarAccessTokenValue = typeof configuration.accessToken === 'function'
? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"])
: configuration.accessToken;
localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue;
}
localVarHeaderParameter['Content-Type'] = 'application/json';
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
const needsSerialization = (<any>"Pet" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json';
localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || "");
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Updates a pet in the store with form data
* @param {number} petId ID of pet that needs to be updated
* @param {string} [name] Updated name of the pet
* @param {string} [status] Updated status of the pet
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updatePetWithForm(petId: number, name?: string, status?: string, options: any = {}): FetchArgs {
// verify required parameter 'petId' is not null or undefined
if (petId === null || petId === undefined) {
throw new RequiredError('petId','Required parameter petId was null or undefined when calling updatePetWithForm.');
}
const localVarPath = `/pet/{petId}`
.replace(`{${"petId"}}`, encodeURIComponent(String(petId)));
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions = Object.assign({ method: 'POST' }, options);
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
const localVarFormParams = new url.URLSearchParams();
// authentication petstore_auth required
// oauth required
if (configuration && configuration.accessToken) {
const localVarAccessTokenValue = typeof configuration.accessToken === 'function'
? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"])
: configuration.accessToken;
localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue;
}
if (name !== undefined) {
localVarFormParams.set('name', name as any);
}
if (status !== undefined) {
localVarFormParams.set('status', status as any);
}
localVarHeaderParameter['Content-Type'] = 'application/x-www-form-urlencoded';
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
localVarRequestOptions.body = localVarFormParams.toString();
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary uploads an image
* @param {number} petId ID of pet to update
* @param {string} [additionalMetadata] Additional data to pass to server
* @param {any} [file] file to upload
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
uploadFile(petId: number, additionalMetadata?: string, file?: any, options: any = {}): FetchArgs {
// verify required parameter 'petId' is not null or undefined
if (petId === null || petId === undefined) {
throw new RequiredError('petId','Required parameter petId was null or undefined when calling uploadFile.');
}
const localVarPath = `/pet/{petId}/uploadImage`
.replace(`{${"petId"}}`, encodeURIComponent(String(petId)));
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions = Object.assign({ method: 'POST' }, options);
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
const localVarFormParams = new url.URLSearchParams();
// authentication petstore_auth required
// oauth required
if (configuration && configuration.accessToken) {
const localVarAccessTokenValue = typeof configuration.accessToken === 'function'
? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"])
: configuration.accessToken;
localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue;
}
if (additionalMetadata !== undefined) {
localVarFormParams.set('additionalMetadata', additionalMetadata as any);
}
if (file !== undefined) {
localVarFormParams.set('file', file as any);
}
localVarHeaderParameter['Content-Type'] = 'application/x-www-form-urlencoded';
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
localVarRequestOptions.body = localVarFormParams.toString();
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* PetApi - functional programming interface
* @export
*/
export const PetApiFp = function(configuration?: Configuration) {
return {
/**
*
* @summary Add a new pet to the store
* @param {Pet} body Pet object that needs to be added to the store
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
addPet(body: Pet, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<Response> {
const localVarFetchArgs = PetApiFetchParamCreator(configuration).addPet(body, options);
return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => {
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
};
},
/**
*
* @summary Deletes a pet
* @param {number} petId Pet id to delete
* @param {string} [apiKey]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deletePet(petId: number, apiKey?: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<Response> {
const localVarFetchArgs = PetApiFetchParamCreator(configuration).deletePet(petId, apiKey, options);
return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => {
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
};
},
/**
* Multiple status values can be provided with comma separated strings
* @summary Finds Pets by status
* @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<Array<Pet>> {
const localVarFetchArgs = PetApiFetchParamCreator(configuration).findPetsByStatus(status, options);
return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => {
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
};
},
/**
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* @summary Finds Pets by tags
* @param {Array<string>} tags Tags to filter by
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
findPetsByTags(tags: Array<string>, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<Array<Pet>> {
const localVarFetchArgs = PetApiFetchParamCreator(configuration).findPetsByTags(tags, options);
return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => {
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
};
},
/**
* Returns a single pet
* @summary Find pet by ID
* @param {number} petId ID of pet to return
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getPetById(petId: number, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<Pet> {
const localVarFetchArgs = PetApiFetchParamCreator(configuration).getPetById(petId, options);
return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => {
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
};
},
/**
*
* @summary Update an existing pet
* @param {Pet} body Pet object that needs to be added to the store
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updatePet(body: Pet, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<Response> {
const localVarFetchArgs = PetApiFetchParamCreator(configuration).updatePet(body, options);
return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => {
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
};
},
/**
*
* @summary Updates a pet in the store with form data
* @param {number} petId ID of pet that needs to be updated
* @param {string} [name] Updated name of the pet
* @param {string} [status] Updated status of the pet
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updatePetWithForm(petId: number, name?: string, status?: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<Response> {
const localVarFetchArgs = PetApiFetchParamCreator(configuration).updatePetWithForm(petId, name, status, options);
return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => {
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
};
},
/**
*
* @summary uploads an image
* @param {number} petId ID of pet to update
* @param {string} [additionalMetadata] Additional data to pass to server
* @param {any} [file] file to upload
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<ApiResponse> {
const localVarFetchArgs = PetApiFetchParamCreator(configuration).uploadFile(petId, additionalMetadata, file, options);
return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => {
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
};
},
}
};
/**
* PetApi - factory interface
* @export
*/
export const PetApiFactory = function (configuration?: Configuration, fetch?: FetchAPI, basePath?: string) {
return {
/**
*
* @summary Add a new pet to the store
* @param {Pet} body Pet object that needs to be added to the store
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
addPet(body: Pet, options?: any) {
return PetApiFp(configuration).addPet(body, options)(fetch, basePath);
},
/**
*
* @summary Deletes a pet
* @param {number} petId Pet id to delete
* @param {string} [apiKey]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deletePet(petId: number, apiKey?: string, options?: any) {
return PetApiFp(configuration).deletePet(petId, apiKey, options)(fetch, basePath);
},
/**
* Multiple status values can be provided with comma separated strings
* @summary Finds Pets by status
* @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: any) {
return PetApiFp(configuration).findPetsByStatus(status, options)(fetch, basePath);
},
/**
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* @summary Finds Pets by tags
* @param {Array<string>} tags Tags to filter by
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
findPetsByTags(tags: Array<string>, options?: any) {
return PetApiFp(configuration).findPetsByTags(tags, options)(fetch, basePath);
},
/**
* Returns a single pet
* @summary Find pet by ID
* @param {number} petId ID of pet to return
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getPetById(petId: number, options?: any) {
return PetApiFp(configuration).getPetById(petId, options)(fetch, basePath);
},
/**
*
* @summary Update an existing pet
* @param {Pet} body Pet object that needs to be added to the store
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updatePet(body: Pet, options?: any) {
return PetApiFp(configuration).updatePet(body, options)(fetch, basePath);
},
/**
*
* @summary Updates a pet in the store with form data
* @param {number} petId ID of pet that needs to be updated
* @param {string} [name] Updated name of the pet
* @param {string} [status] Updated status of the pet
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updatePetWithForm(petId: number, name?: string, status?: string, options?: any) {
return PetApiFp(configuration).updatePetWithForm(petId, name, status, options)(fetch, basePath);
},
/**
*
* @summary uploads an image
* @param {number} petId ID of pet to update
* @param {string} [additionalMetadata] Additional data to pass to server
* @param {any} [file] file to upload
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any) {
return PetApiFp(configuration).uploadFile(petId, additionalMetadata, file, options)(fetch, basePath);
},
};
};
/**
* PetApi - interface
* @export
* @interface PetApi
*/
export interface PetApiInterface {
/**
*
* @summary Add a new pet to the store
* @param {Pet} body Pet object that needs to be added to the store
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApiInterface
*/
addPet(body: Pet, options?: any): Promise<{}>;
/**
*
* @summary Deletes a pet
* @param {number} petId Pet id to delete
* @param {string} [apiKey]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApiInterface
*/
deletePet(petId: number, apiKey?: string, options?: any): Promise<{}>;
/**
* Multiple status values can be provided with comma separated strings
* @summary Finds Pets by status
* @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApiInterface
*/
findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: any): Promise<Array<Pet>>;
/**
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* @summary Finds Pets by tags
* @param {Array<string>} tags Tags to filter by
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApiInterface
*/
findPetsByTags(tags: Array<string>, options?: any): Promise<Array<Pet>>;
/**
* Returns a single pet
* @summary Find pet by ID
* @param {number} petId ID of pet to return
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApiInterface
*/
getPetById(petId: number, options?: any): Promise<Pet>;
/**
*
* @summary Update an existing pet
* @param {Pet} body Pet object that needs to be added to the store
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApiInterface
*/
updatePet(body: Pet, options?: any): Promise<{}>;
/**
*
* @summary Updates a pet in the store with form data
* @param {number} petId ID of pet that needs to be updated
* @param {string} [name] Updated name of the pet
* @param {string} [status] Updated status of the pet
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApiInterface
*/
updatePetWithForm(petId: number, name?: string, status?: string, options?: any): Promise<{}>;
/**
*
* @summary uploads an image
* @param {number} petId ID of pet to update
* @param {string} [additionalMetadata] Additional data to pass to server
* @param {any} [file] file to upload
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApiInterface
*/
uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any): Promise<ApiResponse>;
}
/**
* PetApi - object-oriented interface
* @export
* @class PetApi
* @extends {BaseAPI}
*/
export class PetApi extends BaseAPI implements PetApiInterface {
/**
*
* @summary Add a new pet to the store
* @param {Pet} body Pet object that needs to be added to the store
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApi
*/
public addPet(body: Pet, options?: any) {
return PetApiFp(this.configuration).addPet(body, options)(this.fetch, this.basePath);
}
/**
*
* @summary Deletes a pet
* @param {number} petId Pet id to delete
* @param {string} [apiKey]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApi
*/
public deletePet(petId: number, apiKey?: string, options?: any) {
return PetApiFp(this.configuration).deletePet(petId, apiKey, options)(this.fetch, this.basePath);
}
/**
* Multiple status values can be provided with comma separated strings
* @summary Finds Pets by status
* @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApi
*/
public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: any) {
return PetApiFp(this.configuration).findPetsByStatus(status, options)(this.fetch, this.basePath);
}
/**
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* @summary Finds Pets by tags
* @param {Array<string>} tags Tags to filter by
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApi
*/
public findPetsByTags(tags: Array<string>, options?: any) {
return PetApiFp(this.configuration).findPetsByTags(tags, options)(this.fetch, this.basePath);
}
/**
* Returns a single pet
* @summary Find pet by ID
* @param {number} petId ID of pet to return
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApi
*/
public getPetById(petId: number, options?: any) {
return PetApiFp(this.configuration).getPetById(petId, options)(this.fetch, this.basePath);
}
/**
*
* @summary Update an existing pet
* @param {Pet} body Pet object that needs to be added to the store
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApi
*/
public updatePet(body: Pet, options?: any) {
return PetApiFp(this.configuration).updatePet(body, options)(this.fetch, this.basePath);
}
/**
*
* @summary Updates a pet in the store with form data
* @param {number} petId ID of pet that needs to be updated
* @param {string} [name] Updated name of the pet
* @param {string} [status] Updated status of the pet
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApi
*/
public updatePetWithForm(petId: number, name?: string, status?: string, options?: any) {
return PetApiFp(this.configuration).updatePetWithForm(petId, name, status, options)(this.fetch, this.basePath);
}
/**
*
* @summary uploads an image
* @param {number} petId ID of pet to update
* @param {string} [additionalMetadata] Additional data to pass to server
* @param {any} [file] file to upload
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApi
*/
public uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any) {
return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options)(this.fetch, this.basePath);
}
}
/**
* StoreApi - fetch parameter creator
* @export
*/
export const StoreApiFetchParamCreator = function (configuration?: Configuration) {
return {
/**
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* @summary Delete purchase order by ID
* @param {string} orderId ID of the order that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteOrder(orderId: string, options: any = {}): FetchArgs {
// verify required parameter 'orderId' is not null or undefined
if (orderId === null || orderId === undefined) {
throw new RequiredError('orderId','Required parameter orderId was null or undefined when calling deleteOrder.');
}
const localVarPath = `/store/order/{orderId}`
.replace(`{${"orderId"}}`, encodeURIComponent(String(orderId)));
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions = Object.assign({ method: 'DELETE' }, options);
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Returns a map of status codes to quantities
* @summary Returns pet inventories by status
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getInventory(options: any = {}): FetchArgs {
const localVarPath = `/store/inventory`;
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions = Object.assign({ method: 'GET' }, options);
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication api_key required
if (configuration && configuration.apiKey) {
const localVarApiKeyValue = typeof configuration.apiKey === 'function'
? configuration.apiKey("api_key")
: configuration.apiKey;
localVarHeaderParameter["api_key"] = localVarApiKeyValue;
}
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* @summary Find purchase order by ID
* @param {number} orderId ID of pet that needs to be fetched
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getOrderById(orderId: number, options: any = {}): FetchArgs {
// verify required parameter 'orderId' is not null or undefined
if (orderId === null || orderId === undefined) {
throw new RequiredError('orderId','Required parameter orderId was null or undefined when calling getOrderById.');
}
const localVarPath = `/store/order/{orderId}`
.replace(`{${"orderId"}}`, encodeURIComponent(String(orderId)));
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions = Object.assign({ method: 'GET' }, options);
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Place an order for a pet
* @param {Order} body order placed for purchasing the pet
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
placeOrder(body: Order, options: any = {}): FetchArgs {
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('body','Required parameter body was null or undefined when calling placeOrder.');
}
const localVarPath = `/store/order`;
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions = Object.assign({ method: 'POST' }, options);
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
const needsSerialization = (<any>"Order" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json';
localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || "");
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* StoreApi - functional programming interface
* @export
*/
export const StoreApiFp = function(configuration?: Configuration) {
return {
/**
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* @summary Delete purchase order by ID
* @param {string} orderId ID of the order that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteOrder(orderId: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<Response> {
const localVarFetchArgs = StoreApiFetchParamCreator(configuration).deleteOrder(orderId, options);
return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => {
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
};
},
/**
* Returns a map of status codes to quantities
* @summary Returns pet inventories by status
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getInventory(options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> {
const localVarFetchArgs = StoreApiFetchParamCreator(configuration).getInventory(options);
return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => {
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
};
},
/**
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* @summary Find purchase order by ID
* @param {number} orderId ID of pet that needs to be fetched
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getOrderById(orderId: number, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<Order> {
const localVarFetchArgs = StoreApiFetchParamCreator(configuration).getOrderById(orderId, options);
return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => {
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
};
},
/**
*
* @summary Place an order for a pet
* @param {Order} body order placed for purchasing the pet
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
placeOrder(body: Order, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<Order> {
const localVarFetchArgs = StoreApiFetchParamCreator(configuration).placeOrder(body, options);
return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => {
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
};
},
}
};
/**
* StoreApi - factory interface
* @export
*/
export const StoreApiFactory = function (configuration?: Configuration, fetch?: FetchAPI, basePath?: string) {
return {
/**
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* @summary Delete purchase order by ID
* @param {string} orderId ID of the order that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteOrder(orderId: string, options?: any) {
return StoreApiFp(configuration).deleteOrder(orderId, options)(fetch, basePath);
},
/**
* Returns a map of status codes to quantities
* @summary Returns pet inventories by status
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getInventory(options?: any) {
return StoreApiFp(configuration).getInventory(options)(fetch, basePath);
},
/**
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* @summary Find purchase order by ID
* @param {number} orderId ID of pet that needs to be fetched
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getOrderById(orderId: number, options?: any) {
return StoreApiFp(configuration).getOrderById(orderId, options)(fetch, basePath);
},
/**
*
* @summary Place an order for a pet
* @param {Order} body order placed for purchasing the pet
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
placeOrder(body: Order, options?: any) {
return StoreApiFp(configuration).placeOrder(body, options)(fetch, basePath);
},
};
};
/**
* StoreApi - interface
* @export
* @interface StoreApi
*/
export interface StoreApiInterface {
/**
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* @summary Delete purchase order by ID
* @param {string} orderId ID of the order that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof StoreApiInterface
*/
deleteOrder(orderId: string, options?: any): Promise<{}>;
/**
* Returns a map of status codes to quantities
* @summary Returns pet inventories by status
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof StoreApiInterface
*/
getInventory(options?: any): Promise<{ [key: string]: number; }>;
/**
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* @summary Find purchase order by ID
* @param {number} orderId ID of pet that needs to be fetched
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof StoreApiInterface
*/
getOrderById(orderId: number, options?: any): Promise<Order>;
/**
*
* @summary Place an order for a pet
* @param {Order} body order placed for purchasing the pet
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof StoreApiInterface
*/
placeOrder(body: Order, options?: any): Promise<Order>;
}
/**
* StoreApi - object-oriented interface
* @export
* @class StoreApi
* @extends {BaseAPI}
*/
export class StoreApi extends BaseAPI implements StoreApiInterface {
/**
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* @summary Delete purchase order by ID
* @param {string} orderId ID of the order that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof StoreApi
*/
public deleteOrder(orderId: string, options?: any) {
return StoreApiFp(this.configuration).deleteOrder(orderId, options)(this.fetch, this.basePath);
}
/**
* Returns a map of status codes to quantities
* @summary Returns pet inventories by status
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof StoreApi
*/
public getInventory(options?: any) {
return StoreApiFp(this.configuration).getInventory(options)(this.fetch, this.basePath);
}
/**
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* @summary Find purchase order by ID
* @param {number} orderId ID of pet that needs to be fetched
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof StoreApi
*/
public getOrderById(orderId: number, options?: any) {
return StoreApiFp(this.configuration).getOrderById(orderId, options)(this.fetch, this.basePath);
}
/**
*
* @summary Place an order for a pet
* @param {Order} body order placed for purchasing the pet
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof StoreApi
*/
public placeOrder(body: Order, options?: any) {
return StoreApiFp(this.configuration).placeOrder(body, options)(this.fetch, this.basePath);
}
}
/**
* UserApi - fetch parameter creator
* @export
*/
export const UserApiFetchParamCreator = function (configuration?: Configuration) {
return {
/**
* This can only be done by the logged in user.
* @summary Create user
* @param {User} body Created user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUser(body: User, options: any = {}): FetchArgs {
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('body','Required parameter body was null or undefined when calling createUser.');
}
const localVarPath = `/user`;
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions = Object.assign({ method: 'POST' }, options);
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
const needsSerialization = (<any>"User" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json';
localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || "");
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} body List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUsersWithArrayInput(body: Array<User>, options: any = {}): FetchArgs {
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('body','Required parameter body was null or undefined when calling createUsersWithArrayInput.');
}
const localVarPath = `/user/createWithArray`;
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions = Object.assign({ method: 'POST' }, options);
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
const needsSerialization = (<any>"Array<User>" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json';
localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || "");
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} body List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUsersWithListInput(body: Array<User>, options: any = {}): FetchArgs {
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('body','Required parameter body was null or undefined when calling createUsersWithListInput.');
}
const localVarPath = `/user/createWithList`;
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions = Object.assign({ method: 'POST' }, options);
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
const needsSerialization = (<any>"Array<User>" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json';
localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || "");
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* This can only be done by the logged in user.
* @summary Delete user
* @param {string} username The name that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteUser(username: string, options: any = {}): FetchArgs {
// verify required parameter 'username' is not null or undefined
if (username === null || username === undefined) {
throw new RequiredError('username','Required parameter username was null or undefined when calling deleteUser.');
}
const localVarPath = `/user/{username}`
.replace(`{${"username"}}`, encodeURIComponent(String(username)));
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions = Object.assign({ method: 'DELETE' }, options);
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Get user by user name
* @param {string} username The name that needs to be fetched. Use user1 for testing.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getUserByName(username: string, options: any = {}): FetchArgs {
// verify required parameter 'username' is not null or undefined
if (username === null || username === undefined) {
throw new RequiredError('username','Required parameter username was null or undefined when calling getUserByName.');
}
const localVarPath = `/user/{username}`
.replace(`{${"username"}}`, encodeURIComponent(String(username)));
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions = Object.assign({ method: 'GET' }, options);
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Logs user into the system
* @param {string} username The user name for login
* @param {string} password The password for login in clear text
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
loginUser(username: string, password: string, options: any = {}): FetchArgs {
// verify required parameter 'username' is not null or undefined
if (username === null || username === undefined) {
throw new RequiredError('username','Required parameter username was null or undefined when calling loginUser.');
}
// verify required parameter 'password' is not null or undefined
if (password === null || password === undefined) {
throw new RequiredError('password','Required parameter password was null or undefined when calling loginUser.');
}
const localVarPath = `/user/login`;
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions = Object.assign({ method: 'GET' }, options);
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
if (username !== undefined) {
localVarQueryParameter['username'] = username;
}
if (password !== undefined) {
localVarQueryParameter['password'] = password;
}
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Logs out current logged in user session
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
logoutUser(options: any = {}): FetchArgs {
const localVarPath = `/user/logout`;
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions = Object.assign({ method: 'GET' }, options);
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* This can only be done by the logged in user.
* @summary Updated user
* @param {string} username name that need to be deleted
* @param {User} body Updated user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateUser(username: string, body: User, options: any = {}): FetchArgs {
// verify required parameter 'username' is not null or undefined
if (username === null || username === undefined) {
throw new RequiredError('username','Required parameter username was null or undefined when calling updateUser.');
}
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('body','Required parameter body was null or undefined when calling updateUser.');
}
const localVarPath = `/user/{username}`
.replace(`{${"username"}}`, encodeURIComponent(String(username)));
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions = Object.assign({ method: 'PUT' }, options);
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
const needsSerialization = (<any>"User" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json';
localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || "");
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* UserApi - functional programming interface
* @export
*/
export const UserApiFp = function(configuration?: Configuration) {
return {
/**
* This can only be done by the logged in user.
* @summary Create user
* @param {User} body Created user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUser(body: User, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<Response> {
const localVarFetchArgs = UserApiFetchParamCreator(configuration).createUser(body, options);
return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => {
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
};
},
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} body List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUsersWithArrayInput(body: Array<User>, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<Response> {
const localVarFetchArgs = UserApiFetchParamCreator(configuration).createUsersWithArrayInput(body, options);
return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => {
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
};
},
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} body List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUsersWithListInput(body: Array<User>, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<Response> {
const localVarFetchArgs = UserApiFetchParamCreator(configuration).createUsersWithListInput(body, options);
return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => {
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
};
},
/**
* This can only be done by the logged in user.
* @summary Delete user
* @param {string} username The name that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteUser(username: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<Response> {
const localVarFetchArgs = UserApiFetchParamCreator(configuration).deleteUser(username, options);
return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => {
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
};
},
/**
*
* @summary Get user by user name
* @param {string} username The name that needs to be fetched. Use user1 for testing.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getUserByName(username: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<User> {
const localVarFetchArgs = UserApiFetchParamCreator(configuration).getUserByName(username, options);
return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => {
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
};
},
/**
*
* @summary Logs user into the system
* @param {string} username The user name for login
* @param {string} password The password for login in clear text
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
loginUser(username: string, password: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<string> {
const localVarFetchArgs = UserApiFetchParamCreator(configuration).loginUser(username, password, options);
return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => {
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
};
},
/**
*
* @summary Logs out current logged in user session
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
logoutUser(options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<Response> {
const localVarFetchArgs = UserApiFetchParamCreator(configuration).logoutUser(options);
return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => {
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
};
},
/**
* This can only be done by the logged in user.
* @summary Updated user
* @param {string} username name that need to be deleted
* @param {User} body Updated user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateUser(username: string, body: User, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<Response> {
const localVarFetchArgs = UserApiFetchParamCreator(configuration).updateUser(username, body, options);
return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => {
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
};
},
}
};
/**
* UserApi - factory interface
* @export
*/
export const UserApiFactory = function (configuration?: Configuration, fetch?: FetchAPI, basePath?: string) {
return {
/**
* This can only be done by the logged in user.
* @summary Create user
* @param {User} body Created user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUser(body: User, options?: any) {
return UserApiFp(configuration).createUser(body, options)(fetch, basePath);
},
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} body List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUsersWithArrayInput(body: Array<User>, options?: any) {
return UserApiFp(configuration).createUsersWithArrayInput(body, options)(fetch, basePath);
},
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} body List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUsersWithListInput(body: Array<User>, options?: any) {
return UserApiFp(configuration).createUsersWithListInput(body, options)(fetch, basePath);
},
/**
* This can only be done by the logged in user.
* @summary Delete user
* @param {string} username The name that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteUser(username: string, options?: any) {
return UserApiFp(configuration).deleteUser(username, options)(fetch, basePath);
},
/**
*
* @summary Get user by user name
* @param {string} username The name that needs to be fetched. Use user1 for testing.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getUserByName(username: string, options?: any) {
return UserApiFp(configuration).getUserByName(username, options)(fetch, basePath);
},
/**
*
* @summary Logs user into the system
* @param {string} username The user name for login
* @param {string} password The password for login in clear text
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
loginUser(username: string, password: string, options?: any) {
return UserApiFp(configuration).loginUser(username, password, options)(fetch, basePath);
},
/**
*
* @summary Logs out current logged in user session
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
logoutUser(options?: any) {
return UserApiFp(configuration).logoutUser(options)(fetch, basePath);
},
/**
* This can only be done by the logged in user.
* @summary Updated user
* @param {string} username name that need to be deleted
* @param {User} body Updated user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateUser(username: string, body: User, options?: any) {
return UserApiFp(configuration).updateUser(username, body, options)(fetch, basePath);
},
};
};
/**
* UserApi - interface
* @export
* @interface UserApi
*/
export interface UserApiInterface {
/**
* This can only be done by the logged in user.
* @summary Create user
* @param {User} body Created user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApiInterface
*/
createUser(body: User, options?: any): Promise<{}>;
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} body List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApiInterface
*/
createUsersWithArrayInput(body: Array<User>, options?: any): Promise<{}>;
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} body List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApiInterface
*/
createUsersWithListInput(body: Array<User>, options?: any): Promise<{}>;
/**
* This can only be done by the logged in user.
* @summary Delete user
* @param {string} username The name that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApiInterface
*/
deleteUser(username: string, options?: any): Promise<{}>;
/**
*
* @summary Get user by user name
* @param {string} username The name that needs to be fetched. Use user1 for testing.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApiInterface
*/
getUserByName(username: string, options?: any): Promise<User>;
/**
*
* @summary Logs user into the system
* @param {string} username The user name for login
* @param {string} password The password for login in clear text
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApiInterface
*/
loginUser(username: string, password: string, options?: any): Promise<string>;
/**
*
* @summary Logs out current logged in user session
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApiInterface
*/
logoutUser(options?: any): Promise<{}>;
/**
* This can only be done by the logged in user.
* @summary Updated user
* @param {string} username name that need to be deleted
* @param {User} body Updated user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApiInterface
*/
updateUser(username: string, body: User, options?: any): Promise<{}>;
}
/**
* UserApi - object-oriented interface
* @export
* @class UserApi
* @extends {BaseAPI}
*/
export class UserApi extends BaseAPI implements UserApiInterface {
/**
* This can only be done by the logged in user.
* @summary Create user
* @param {User} body Created user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public createUser(body: User, options?: any) {
return UserApiFp(this.configuration).createUser(body, options)(this.fetch, this.basePath);
}
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} body List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public createUsersWithArrayInput(body: Array<User>, options?: any) {
return UserApiFp(this.configuration).createUsersWithArrayInput(body, options)(this.fetch, this.basePath);
}
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} body List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public createUsersWithListInput(body: Array<User>, options?: any) {
return UserApiFp(this.configuration).createUsersWithListInput(body, options)(this.fetch, this.basePath);
}
/**
* This can only be done by the logged in user.
* @summary Delete user
* @param {string} username The name that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public deleteUser(username: string, options?: any) {
return UserApiFp(this.configuration).deleteUser(username, options)(this.fetch, this.basePath);
}
/**
*
* @summary Get user by user name
* @param {string} username The name that needs to be fetched. Use user1 for testing.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public getUserByName(username: string, options?: any) {
return UserApiFp(this.configuration).getUserByName(username, options)(this.fetch, this.basePath);
}
/**
*
* @summary Logs user into the system
* @param {string} username The user name for login
* @param {string} password The password for login in clear text
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public loginUser(username: string, password: string, options?: any) {
return UserApiFp(this.configuration).loginUser(username, password, options)(this.fetch, this.basePath);
}
/**
*
* @summary Logs out current logged in user session
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public logoutUser(options?: any) {
return UserApiFp(this.configuration).logoutUser(options)(this.fetch, this.basePath);
}
/**
* This can only be done by the logged in user.
* @summary Updated user
* @param {string} username name that need to be deleted
* @param {User} body Updated user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public updateUser(username: string, body: User, options?: any) {
return UserApiFp(this.configuration).updateUser(username, body, options)(this.fetch, this.basePath);
}
} | the_stack |
import React, { useState, useRef, useCallback } from 'react';
import PropTypes from 'prop-types';
import pick from 'lodash/pick';
import omit from 'lodash/omit';
import isFunction from 'lodash/isFunction';
import isNil from 'lodash/isNil';
import DropdownMenu from './DropdownMenu';
import Checkbox from '../Checkbox';
import { useCascadeValue, useColumnData, useFlattenData, isSomeChildChecked } from './utils';
import { getNodeParents, findNodeOfTree } from '../utils/treeUtils';
import { getColumnsAndPaths } from '../Cascader/utils';
import { PickerLocale } from '../locales';
import {
createChainedFunction,
mergeRefs,
getSafeRegExpString,
useClassNames,
useCustom,
useUpdateEffect
} from '../utils';
import {
PickerToggle,
PickerOverlay,
SearchBar,
SelectedElement,
PickerToggleTrigger,
usePickerClassName,
usePublicMethods,
useToggleKeyDownEvent,
useFocusItemValue,
pickTriggerPropKeys,
omitTriggerPropKeys,
OverlayTriggerInstance,
PositionChildProps,
listPickerPropTypes,
PickerComponent
} from '../Picker';
import { FormControlPickerProps, ItemDataType } from '../@types/common';
export type ValueType = (number | string)[];
export interface MultiCascaderProps<T = ValueType>
extends FormControlPickerProps<T, PickerLocale, ItemDataType> {
cascade?: boolean;
/** A picker that can be counted */
countable?: boolean;
/** Sets the width of the menu */
menuWidth?: number;
/** Sets the height of the menu */
menuHeight?: number | string;
/** Set the option value for the check box not to be rendered */
uncheckableItemValues?: T;
/** Whether dispaly search input box */
searchable?: boolean;
/** The menu is displayed directly when the component is initialized */
inline?: boolean;
/** Custom render menu */
renderMenu?: (
items: ItemDataType[],
menu: React.ReactNode,
parentNode?: any,
layer?: number
) => React.ReactNode;
/** Custom render menu items */
renderMenuItem?: (itemLabel: React.ReactNode, item: any) => React.ReactNode;
/** Custom render selected items */
renderValue?: (
value: T,
selectedItems: ItemDataType[],
selectedElement: React.ReactNode
) => React.ReactNode;
/** Called when the option is selected */
onSelect?: (
node: ItemDataType,
cascadePaths: ItemDataType[],
event: React.SyntheticEvent
) => void;
/** Called after the checkbox state changes */
onCheck?: (
value: ValueType,
node: ItemDataType,
checked: boolean,
event: React.SyntheticEvent
) => void;
/** Called when clean */
onClean?: (event: React.SyntheticEvent) => void;
/** Called when searching */
onSearch?: (searchKeyword: string, event: React.SyntheticEvent) => void;
/** Asynchronously load the children of the tree node. */
getChildren?: (node: ItemDataType) => ItemDataType[] | Promise<ItemDataType[]>;
}
const emptyArray = [];
const MultiCascader: PickerComponent<MultiCascaderProps> = React.forwardRef(
(props: MultiCascaderProps, ref) => {
const {
as: Component = 'div',
data = emptyArray,
classPrefix = 'picker',
defaultValue,
value: valueProp,
valueKey = 'value',
labelKey = 'label',
childrenKey = 'children',
disabled,
disabledItemValues = emptyArray,
cleanable = true,
locale: overrideLocale,
toggleAs,
style,
countable = true,
cascade = true,
inline,
placeholder,
placement = 'bottomStart',
appearance = 'default',
menuWidth,
menuHeight,
menuClassName,
menuStyle,
searchable = true,
uncheckableItemValues = emptyArray,
id,
getChildren,
renderValue,
renderMenu,
renderMenuItem,
renderExtraFooter,
onEnter,
onExit,
onExited,
onClean,
onSearch,
onSelect,
onChange,
onOpen,
onClose,
onCheck,
...rest
} = props;
const itemKeys = { childrenKey, labelKey, valueKey };
const [active, setActive] = useState(false);
const { flattenData, addFlattenData } = useFlattenData(data, itemKeys);
const { value, setValue, splitValue } = useCascadeValue(
{
...itemKeys,
uncheckableItemValues,
cascade,
value: valueProp || defaultValue
},
flattenData
);
// The columns displayed in the cascading panel.
const { columnData, setColumnData, addColumn, enforceUpdateColumnData } =
useColumnData(flattenData);
useUpdateEffect(() => {
enforceUpdateColumnData(data);
}, [data]);
// The path after cascading data selection.
const [selectedPaths, setSelectedPaths] = useState<ItemDataType[]>();
const triggerRef = useRef<OverlayTriggerInstance>(null);
const overlayRef = useRef<HTMLDivElement>(null);
const targetRef = useRef<HTMLDivElement>(null);
const searchInputRef = useRef<HTMLInputElement>(null);
usePublicMethods(ref, { triggerRef, overlayRef, targetRef });
const { locale, rtl } = useCustom<PickerLocale>('Picker', overrideLocale);
const selectedItems = flattenData.filter(item => value.some(v => v === item[valueKey])) || [];
// Used to hover the focuse item when trigger `onKeydown`
const {
focusItemValue,
setLayer,
setKeys,
onKeyDown: onFocusItem
} = useFocusItemValue(selectedPaths?.[selectedPaths.length - 1]?.[valueKey], {
rtl,
data: flattenData,
valueKey,
defaultLayer: selectedPaths?.length ? selectedPaths.length - 1 : 0,
target: () => overlayRef.current,
callback: useCallback(
value => {
const { columns, paths } = getColumnsAndPaths(data, value, {
valueKey,
childrenKey,
isAttachChildren: true
});
setColumnData(columns);
setSelectedPaths(paths);
},
[childrenKey, data, setColumnData, valueKey]
)
});
/**
* 1.Have a value and the value is valid.
* 2.Regardless of whether the value is valid, as long as renderValue is set, it is judged to have a value.
*/
let hasValue =
selectedItems.length > 0 || (Number(valueProp?.length) > 0 && isFunction(renderValue));
const { prefix, merge } = useClassNames(classPrefix);
const [searchKeyword, setSearchKeyword] = useState('');
const handleEntered = useCallback(() => {
onOpen?.();
setActive(true);
}, [onOpen]);
const handleExited = useCallback(() => {
setActive(false);
setSearchKeyword('');
}, []);
const handleSelect = useCallback(
(node: ItemDataType, cascadePaths: ItemDataType[], event: React.SyntheticEvent) => {
setSelectedPaths(cascadePaths);
onSelect?.(node, cascadePaths, event);
// Lazy load node's children
if (typeof getChildren === 'function' && node[childrenKey]?.length === 0) {
node.loading = true;
const children = getChildren(node);
if (children instanceof Promise) {
children.then((data: ItemDataType[]) => {
node.loading = false;
node[childrenKey] = data;
addFlattenData(data, node);
addColumn(data, cascadePaths.length);
});
} else {
node.loading = false;
node[childrenKey] = children;
addFlattenData(children, node);
addColumn(children, cascadePaths.length);
}
} else if (node[childrenKey]?.length) {
addColumn(node[childrenKey], cascadePaths.length);
}
triggerRef.current?.updatePosition?.();
},
[onSelect, getChildren, childrenKey, addColumn, addFlattenData]
);
const handleCheck = useCallback(
(node: ItemDataType, event: React.SyntheticEvent, checked: boolean) => {
const nodeValue = node[valueKey];
let nextValue: ValueType = [];
if (cascade) {
nextValue = splitValue(node, checked, value).value;
} else {
nextValue = [...value];
if (checked) {
nextValue.push(nodeValue);
} else {
nextValue = nextValue.filter(n => n !== nodeValue);
}
}
setValue(nextValue);
onChange?.(nextValue, event);
onCheck?.(nextValue, node, checked, event);
},
[cascade, onChange, onCheck, setValue, splitValue, value, valueKey]
);
const handleClean = useCallback(
(event: React.SyntheticEvent) => {
if (disabled) {
return;
}
setSelectedPaths([]);
setValue([]);
setColumnData([data]);
onChange?.([], event);
},
[data, disabled, onChange, setColumnData, setValue]
);
const handleMenuPressEnter = useCallback(
(event: React.SyntheticEvent) => {
const focusItem = findNodeOfTree(data, item => item[valueKey] === focusItemValue);
const checkbox = overlayRef.current?.querySelector(
`[data-key="${focusItemValue}"] [type="checkbox"]`
);
if (checkbox) {
handleCheck(focusItem, event, checkbox?.getAttribute('aria-checked') !== 'true');
}
},
[data, focusItemValue, handleCheck, valueKey]
);
const onPickerKeyDown = useToggleKeyDownEvent({
toggle: !focusItemValue || !active,
triggerRef,
targetRef,
overlayRef,
searchInputRef,
active,
onExit: handleClean,
onMenuKeyDown: onFocusItem,
onMenuPressEnter: handleMenuPressEnter,
...rest
});
const handleSearch = useCallback(
(value: string, event: React.SyntheticEvent) => {
setSearchKeyword(value);
onSearch?.(value, event);
if (value) {
setLayer(0);
} else if (selectedPaths?.length) {
setLayer(selectedPaths.length - 1);
}
setKeys([]);
},
[onSearch, selectedPaths, setKeys, setLayer]
);
const getSearchResult = useCallback(() => {
const items: ItemDataType[] = [];
const result = flattenData.filter(item => {
if (uncheckableItemValues.some(value => item[valueKey] === value)) {
return false;
}
if (item[labelKey].match(new RegExp(getSafeRegExpString(searchKeyword), 'i'))) {
return true;
}
return false;
});
for (let i = 0; i < result.length; i++) {
items.push(result[i]);
// A maximum of 100 search results are returned.
if (i === 99) {
return items;
}
}
return items;
}, [flattenData, labelKey, searchKeyword, uncheckableItemValues, valueKey]);
const renderSearchRow = (item: ItemDataType, key: number) => {
const nodes = getNodeParents(item);
const regx = new RegExp(getSafeRegExpString(searchKeyword), 'ig');
const labelElements: React.ReactNode[] = [];
const a = item[labelKey].split(regx);
const b = item[labelKey].match(regx);
for (let i = 0; i < a.length; i++) {
labelElements.push(a[i]);
if (b[i]) {
labelElements.push(
<span key={i} className={prefix('cascader-search-match')}>
{b[i]}
</span>
);
}
}
nodes.push({ ...item, [labelKey]: labelElements });
const active = value.some(value => {
if (cascade) {
return nodes.some(node => node[valueKey] === value);
}
return item[valueKey] === value;
});
const disabled = disabledItemValues.some(value =>
nodes.some(node => node[valueKey] === value)
);
const itemClasses = prefix('cascader-row', {
'cascader-row-disabled': disabled,
'cascader-row-focus': item[valueKey] === focusItemValue
});
return (
<div key={key} className={itemClasses} aria-disabled={disabled} data-key={item[valueKey]}>
<Checkbox
disabled={disabled}
checked={active}
value={item[valueKey]}
indeterminate={
cascade && !active && isSomeChildChecked(item, value, { valueKey, childrenKey })
}
onChange={(_value, checked, event) => {
handleCheck(item, event, checked);
}}
>
<span className={prefix('cascader-cols')}>
{nodes.map((node, index) => (
<span key={`col-${index}`} className={prefix('cascader-col')}>
{node[labelKey]}
</span>
))}
</span>
</Checkbox>
</div>
);
};
const renderSearchResultPanel = () => {
if (searchKeyword === '') {
return null;
}
const items = getSearchResult();
return (
<div className={prefix('cascader-search-panel')} data-layer={0}>
{items.length ? (
items.map(renderSearchRow)
) : (
<div className={prefix('none')}>{locale.noResultsText}</div>
)}
</div>
);
};
const renderDropdownMenu = (positionProps?: PositionChildProps, speakerRef?) => {
const { left, top, className } = positionProps || {};
const styles = { ...menuStyle, left, top };
const classes = merge(
className,
menuClassName,
prefix('cascader-menu', 'multi-cascader-menu', { inline })
);
return (
<PickerOverlay
ref={mergeRefs(overlayRef, speakerRef)}
className={classes}
style={styles}
target={triggerRef}
onKeyDown={onPickerKeyDown}
>
{searchable && (
<SearchBar
placeholder={locale?.searchPlaceholder}
onChange={handleSearch}
value={searchKeyword}
inputRef={searchInputRef}
/>
)}
{renderSearchResultPanel()}
{searchKeyword === '' && (
<DropdownMenu
id={id ? `${id}-listbox` : undefined}
cascade={cascade}
menuWidth={menuWidth}
menuHeight={menuHeight}
uncheckableItemValues={uncheckableItemValues}
disabledItemValues={disabledItemValues}
valueKey={valueKey}
labelKey={labelKey}
childrenKey={childrenKey}
classPrefix={'picker-cascader-menu'}
cascadeData={columnData}
cascadePaths={selectedPaths}
value={value}
onSelect={handleSelect}
onCheck={handleCheck}
renderMenu={renderMenu}
renderMenuItem={renderMenuItem}
/>
)}
{renderExtraFooter?.()}
</PickerOverlay>
);
};
let selectedElement: React.ReactNode = placeholder;
if (selectedItems.length > 0) {
selectedElement = (
<SelectedElement
selectedItems={selectedItems}
countable={countable}
valueKey={valueKey}
labelKey={labelKey}
childrenKey={childrenKey}
prefix={prefix}
cascade={cascade}
locale={locale}
/>
);
}
if (hasValue && isFunction(renderValue)) {
selectedElement = renderValue(
value.length ? value : valueProp ?? [],
selectedItems,
selectedElement
);
// If renderValue returns null or undefined, hasValue is false.
if (isNil(selectedElement)) {
hasValue = false;
}
}
const [classes, usedClassNamePropKeys] = usePickerClassName({
...props,
classPrefix,
hasValue,
name: 'cascader',
appearance,
cleanable
});
if (inline) {
return renderDropdownMenu();
}
return (
<PickerToggleTrigger
pickerProps={pick(props, pickTriggerPropKeys)}
ref={triggerRef}
placement={placement}
onEnter={createChainedFunction(handleEntered, onEnter)}
onExited={createChainedFunction(handleExited, onExited)}
onExit={createChainedFunction(onClose, onExit)}
speaker={renderDropdownMenu}
>
<Component className={classes} style={style}>
<PickerToggle
{...omit(rest, [...omitTriggerPropKeys, ...usedClassNamePropKeys])}
id={id}
as={toggleAs}
appearance={appearance}
disabled={disabled}
ref={targetRef}
onClean={createChainedFunction(handleClean, onClean)}
onKeyDown={onPickerKeyDown}
cleanable={cleanable && !disabled}
hasValue={hasValue}
active={active}
placement={placement}
inputValue={value}
>
{selectedElement || locale.placeholder}
</PickerToggle>
</Component>
</PickerToggleTrigger>
);
}
);
MultiCascader.displayName = 'MultiCascader';
MultiCascader.propTypes = {
...listPickerPropTypes,
value: PropTypes.array,
disabledItemValues: PropTypes.array,
locale: PropTypes.any,
appearance: PropTypes.oneOf(['default', 'subtle']),
cascade: PropTypes.bool,
inline: PropTypes.bool,
countable: PropTypes.bool,
menuWidth: PropTypes.number,
menuHeight: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
uncheckableItemValues: PropTypes.array,
searchable: PropTypes.bool,
renderMenuItem: PropTypes.func,
renderMenu: PropTypes.func,
onSearch: PropTypes.func,
onSelect: PropTypes.func,
onCheck: PropTypes.func
};
export default MultiCascader; | the_stack |
import {
selectDisplay,
makeSelectCurrentLayersOperationInfo,
makeSelectLayersBySlide,
makeSelectLayerIdsBySlide,
makeSelectCurrentLayerList,
selectCurrentLayers,
makeSelectCurrentLayerIds,
makeSelectSlideLayerContextValue,
makeSelectCurrentLayersMaxIndex,
makeSelectCurrentSelectedLayerList,
makeSelectCurrentEditLayerOperationInfo,
makeSelectCurrentSelectedLayerIds,
makeSelectCurrentOperatingLayerList,
makeSelectCurrentOtherLayerList,
makeSelectCurrentOperateItemParams,
makeSelectCurrentDisplayWidgets,
makeSelectClipboardLayers,
makeSelectCurrentDisplayShareToken,
makeSelectCurrentDisplayPasswordShareToken,
makeSelectCurrentDisplayPasswordSharePassword,
makeSelectCurrentDisplayAuthorizedShareToken,
makeSelectSharePanel,
makeSelectDisplayLoading,
makeSelectEditorBaselines
} from 'app/containers/Display/selectors'
import { displayInitialState } from 'app/containers/Display/reducer'
import {
mockGraphLayerId,
mockSlideId,
mockEditing,
mockDisplayState,
mockGraphLayerFormed,
mockGraphLayerInfo
} from './fixtures'
describe('displaySelector', () => {
let state
beforeEach(() => {
state = {
display: displayInitialState
}
})
describe('selectDisplay', () => {
it('should select the display state', () => {
expect(selectDisplay(state)).toEqual(state.display)
})
})
describe('makeSelectCurrentLayersOperationInfo', () => {
let selectCurrentLayersOperationInfo = makeSelectCurrentLayersOperationInfo()
it('should select the current layer operation info', () => {
expect(selectCurrentLayersOperationInfo(mockDisplayState)).toEqual(
mockDisplayState.display.slideLayersOperationInfo[
mockDisplayState.display.currentSlideId
]
)
})
})
describe('makeSelectLayersBySlide', () => {
let selectLayersBySlide
beforeEach(() => {
selectLayersBySlide = makeSelectLayersBySlide()
selectLayersBySlide.resetRecomputations()
})
test('should return bizTable state', () => {
expect(selectLayersBySlide(state, mockSlideId)).toEqual(
state.display.slideLayers[mockSlideId]
)
})
})
describe('makeSelectLayerIdsBySlide', () => {
let selectLayerIdsBySlide
beforeEach(() => {
selectLayerIdsBySlide = makeSelectLayerIdsBySlide()
selectLayerIdsBySlide.resetRecomputations()
})
test('should return select layer ids by slide', () => {
expect(selectLayerIdsBySlide(mockDisplayState, mockSlideId)).toEqual(
Object.keys(mockDisplayState.display.slideLayers[mockSlideId]).map(
(id) => +id
)
)
})
})
describe('makeSelectCurrentLayerList', () => {
const selectCurrentLayerList = makeSelectCurrentLayerList()
test('should return select current layer list', () => {
expect(selectCurrentLayerList(mockDisplayState)).toEqual(
Object.values(
mockDisplayState.display.slideLayers[
mockDisplayState.display.currentSlideId
]
).sort((l1, l2) => l2.index - l1.index)
)
})
})
describe('makeSelectCurrentLayerIds', () => {
const selectCurrentLayerIds = makeSelectCurrentLayerIds()
test('should return select current layer ids', () => {
expect(selectCurrentLayerIds(mockDisplayState)).toEqual(
Object.keys(
mockDisplayState.display.slideLayers[
mockDisplayState.display.currentSlideId
]
).map((id) => +id)
)
})
})
describe('makeSelectSlideLayerContextValue', () => {
const selectSlideLayerContextValue = makeSelectSlideLayerContextValue()
test('should return select slide layer context value', () => {
expect(
selectSlideLayerContextValue(
mockDisplayState,
mockSlideId,
mockGraphLayerId,
mockEditing
)
).toEqual({
layer: mockGraphLayerFormed,
layerInfo: mockGraphLayerInfo
})
})
})
describe('makeSelectCurrentLayersMaxIndex', () => {
const selectCurrentLayersMaxIndex = makeSelectCurrentLayersMaxIndex()
const currentLayers =
mockDisplayState.display.slideLayers[
mockDisplayState.display.currentSlideId
]
const currentLayerList = Object.values(currentLayers).sort(
(l1, l2) => l2.index - l1.index
)
test('should return select current layer max index', () => {
expect(selectCurrentLayersMaxIndex(mockDisplayState)).toEqual(
currentLayerList[currentLayerList.length - 1].index
)
})
})
describe('makeSelectCurrentSelectedLayerList', () => {
const selectCurrentSelectedLayerList = makeSelectCurrentSelectedLayerList()
const currentLayers =
mockDisplayState.display.slideLayers[
mockDisplayState.display.currentSlideId
]
const currentLayerList = Object.values(currentLayers).sort(
(l1, l2) => l2.index - l1.index
)
const currentLayersOperationInfo =
mockDisplayState.display.slideLayersOperationInfo[
mockDisplayState.display.currentSlideId
]
test('should return select current select layer list', () => {
expect(selectCurrentSelectedLayerList(mockDisplayState)).toEqual(
currentLayerList.filter(
({ id }) => currentLayersOperationInfo[id].selected
)
)
})
})
describe('makeSelectCurrentEditLayerOperationInfo', () => {
const selectCurrentEditLayerOperationInfo = makeSelectCurrentEditLayerOperationInfo()
const currentEditOperationInfo =
mockDisplayState.display.slideLayersOperationInfo[
mockDisplayState.display.currentSlideId
]
test('should return select current edit layer operation info', () => {
expect(selectCurrentEditLayerOperationInfo(mockDisplayState)).toEqual(
Object.values(currentEditOperationInfo).filter(
(layerInfo) => layerInfo.editing
)
)
})
})
describe('makeSelectCurrentSelectedLayerIds', () => {
const selectCurrentSelectedLayerIds = makeSelectCurrentSelectedLayerIds()
const currentLayersOperationInfo =
mockDisplayState.display.slideLayersOperationInfo[
mockDisplayState.display.currentSlideId
]
test('should return select current select layer ids', () => {
expect(selectCurrentSelectedLayerIds(mockDisplayState)).toEqual(
Object.keys(currentLayersOperationInfo)
.filter((id) => currentLayersOperationInfo[+id].selected)
.map((id) => +id)
)
})
})
describe('makeSelectCurrentOperatingLayerList', () => {
const selectCurrentOperatingLayerList = makeSelectCurrentOperatingLayerList()
const currentLayers =
mockDisplayState.display.slideLayers[
mockDisplayState.display.currentSlideId
]
test('should return select current operating layer list', () => {
expect(
selectCurrentOperatingLayerList(mockDisplayState, mockGraphLayerId)
).toEqual([currentLayers[mockGraphLayerId]])
})
})
describe('makeSelectCurrentOtherLayerList', () => {
const selectCurrentOtherLayerList = makeSelectCurrentOtherLayerList()
const currentLayers =
mockDisplayState.display.slideLayers[
mockDisplayState.display.currentSlideId
]
test('should return select current other layer list', () => {
expect(
selectCurrentOtherLayerList(mockDisplayState, mockGraphLayerId)
).toEqual([currentLayers[mockGraphLayerId]])
})
})
describe('makeSelectCurrentOperateItemParams', () => {
const selectCurrentOperateItemParams = makeSelectCurrentOperateItemParams()
test('should return select current operate item params', () => {
expect(selectCurrentOperateItemParams(state)).toEqual(
state.display.operateItemParams
)
})
})
describe('makeSelectCurrentDisplayWidgets', () => {
const selectCurrentDisplayWidgets = makeSelectCurrentDisplayWidgets()
test('should return select current display widgets', () => {
expect(selectCurrentDisplayWidgets(state)).toEqual(
state.display.currentDisplayWidgets
)
})
})
describe('makeSelectClipboardLayers', () => {
const selectClipboardLayers = makeSelectClipboardLayers()
test('should return select clipboard layer list', () => {
expect(selectClipboardLayers(state)).toEqual(
state.display.clipboardLayers
)
})
})
describe('makeSelectCurrentDisplayShareToken', () => {
const selectCurrentDisplayShareToken = makeSelectCurrentDisplayShareToken()
test('should return select current display share token', () => {
expect(selectCurrentDisplayShareToken(state)).toEqual(
state.display.currentDisplayShareToken
)
})
})
describe('makeSelectCurrentDisplayPasswordShareToken', () => {
const selectCurrentDisplayPasswordShareToken = makeSelectCurrentDisplayPasswordShareToken()
test('should return select current display password share token', () => {
expect(selectCurrentDisplayPasswordShareToken(state)).toEqual(
state.display.currentDisplayPasswordShareToken
)
})
})
describe('makeSelectCurrentDisplayPasswordSharePassword', () => {
const selectCurrentDisplayPasswordSharePassword = makeSelectCurrentDisplayPasswordSharePassword()
test('should return select current display password share password', () => {
expect(selectCurrentDisplayPasswordSharePassword(state)).toEqual(
state.display.currentDisplayPasswordPassword
)
})
})
describe('makeSelectCurrentDisplayAuthorizedShareToken', () => {
const selectCurrentDisplayAuthorizedShareToken = makeSelectCurrentDisplayAuthorizedShareToken()
test('should return select current display authorized share token', () => {
expect(selectCurrentDisplayAuthorizedShareToken(state)).toEqual(
state.display.currentDisplayAuthorizedShareToken
)
})
})
describe('makeSelectSharePanel', () => {
const selectSharePanel = makeSelectSharePanel()
test('should return select share panel', () => {
expect(selectSharePanel(state)).toEqual(state.display.sharePanel)
})
})
describe('makeSelectDisplayLoading', () => {
const selectDisplayLoading = makeSelectDisplayLoading()
test('should return select display loading', () => {
expect(selectDisplayLoading(state)).toEqual(state.display.loading)
})
})
describe('makeSelectEditorBaselines', () => {
const selectEditorBaselines = makeSelectEditorBaselines()
test('should return select editor baselines', () => {
expect(selectEditorBaselines(state)).toEqual(
state.display.editorBaselines
)
})
})
describe('selectCurrentLayers', () => {
test('should return select current layers', () => {
expect(selectCurrentLayers(mockDisplayState)).toEqual(
mockDisplayState.display.slideLayers[
mockDisplayState.display.currentSlideId
]
)
})
})
}) | the_stack |
import Base64Provider = require('js-base64')
import Docker = require('dockerode')
import { v4 as uuid } from 'uuid'
import DockerService from '../models/DockerService'
import {
IDockerApiPort,
IDockerContainerResource,
PreDeployFunction,
VolumesTypes,
} from '../models/OtherTypes'
import BuildLog from '../user/BuildLog'
import CaptainConstants from '../utils/CaptainConstants'
import EnvVars from '../utils/EnvVars'
import Logger from '../utils/Logger'
import Utils from '../utils/Utils'
import Dockerode = require('dockerode')
// @ts-ignore
import dockerodeUtils = require('dockerode/lib/util')
const Base64 = Base64Provider.Base64
function safeParseChunk(chunk: string): {
stream?: string
error?: any
errorDetail?: any
}[] {
chunk = `${chunk}`.trim()
try {
// See https://github.com/caprover/caprover/issues/570
// This appears to be bug either in Docker or dockerone:
// Sometimes chunk appears as two JSON objects, like
// ```
// {"stream":"something......"}
// {"stream":"another line of things"}
// ```
const chunks = chunk.split('\n')
const returnVal = [] as any[]
chunks.forEach((chk) => {
returnVal.push(JSON.parse(chk))
})
return returnVal
} catch (ignore) {
return [
{
stream: `Cannot parse ${chunk}`,
},
]
}
}
export abstract class IDockerUpdateOrders {
public static readonly AUTO = 'auto'
public static readonly STOP_FIRST = 'stopFirst'
public static readonly START_FIRST = 'startFirst'
}
export type IDockerUpdateOrder = 'auto' | 'stopFirst' | 'startFirst'
class DockerApi {
private dockerode: Docker
constructor(connectionParams: Docker.DockerOptions) {
this.dockerode = new Docker(connectionParams)
}
static get() {
return dockerApiInstance
}
initSwarm(ip: string, portNumber?: number) {
const self = this
portNumber = portNumber || 2377
const port = `${portNumber}`
const advertiseAddr = `${ip}:${port}`
const swarmOptions = {
ListenAddr: `0.0.0.0:${port}`,
AdvertiseAddr: advertiseAddr,
ForceNewCluster: false,
}
Logger.d(`Starting swarm at ${advertiseAddr}`)
return self.dockerode.swarmInit(swarmOptions)
}
swarmLeave(forced: boolean) {
const self = this
return self.dockerode.swarmLeave({
force: !!forced,
})
}
getNodeIdByServiceName(
serviceName: string,
retryCount: number
): Promise<string> {
const self = this
retryCount = retryCount || 0
return self.dockerode
.listTasks({
filters: {
service: [serviceName],
'desired-state': ['running'],
},
})
.then(function (data) {
if (data.length > 0) {
return Promise.resolve(data[0].NodeID)
} else {
if (retryCount < 10) {
return new Promise<void>(function (resolve) {
setTimeout(function () {
resolve()
}, 3000)
}).then(function () {
Logger.d(
`Retrying to get NodeID for ${serviceName} retry count:${retryCount}`
)
return self.getNodeIdByServiceName(
serviceName,
retryCount + 1
)
})
}
throw new Error(
`There must be only one instance (not ${data.length}) of the service running to find node id. ${serviceName}`
)
}
})
}
getLeaderNodeId() {
const self = this
return Promise.resolve()
.then(function () {
return self.dockerode.listNodes()
})
.then(function (nodes) {
for (let idx = 0; idx < nodes.length; idx++) {
const node = nodes[idx]
if (node.ManagerStatus && node.ManagerStatus.Leader) {
return node.ID
}
}
})
}
getAllServices() {
const self = this
return Promise.resolve()
.then(function () {
return self.dockerode.listServices()
})
.then(function (services) {
return (services || []) as unknown as DockerService[]
})
}
createJoinCommand(
captainIpAddress: string,
token: string,
workerIp: string
) {
return `docker swarm join --token ${token} ${captainIpAddress}:2377 --advertise-addr ${workerIp}:2377`
}
getNodesInfo() {
const self = this
return Promise.resolve()
.then(function () {
return self.dockerode.listNodes()
})
.then(function (nodes) {
const ret: ServerDockerInfo[] = []
if (!nodes || !nodes.length) {
return ret
}
for (let i = 0; i < nodes.length; i++) {
const n = nodes[i]
ret.push({
nodeId: n.ID,
type: n.Spec.Role,
isLeader:
n.Spec.Role === 'manager' &&
n.ManagerStatus &&
n.ManagerStatus.Leader === true,
hostname: n.Description.Hostname,
architecture: n.Description.Platform.Architecture,
operatingSystem: n.Description.Platform.OS,
nanoCpu: n.Description.Resources.NanoCPUs,
memoryBytes: n.Description.Resources.MemoryBytes,
dockerEngineVersion: n.Description.Engine.EngineVersion,
ip: n.Status.Addr,
state: n.Status.State, // whether down or ready (this means the machine is down)
status: n.Spec.Availability, // whether active, drain or pause (this is the expected behavior)
})
}
return ret
})
}
getJoinToken(isManager: boolean) {
const self = this
return Promise.resolve()
.then(function () {
return self.dockerode.swarmInspect()
})
.then(function (inspectData) {
if (!inspectData || !inspectData.JoinTokens) {
throw new Error('Inspect data does not contain tokens!!')
}
const token = isManager
? inspectData.JoinTokens.Manager
: inspectData.JoinTokens.Worker
if (!token) {
throw new Error(
'Inspect data does not contain the required token!!'
)
}
return token
})
}
buildImageFromDockerFile(
imageName: string,
newVersionNumber: number,
tarballFilePath: string,
buildLogs: BuildLog,
envVars: IAppEnvVar[],
registryConfig: DockerRegistryConfig
) {
const self = this
const newVersion = `${newVersionNumber}`
Logger.d('Building docker image. This might take a few minutes...')
return Promise.resolve()
.then(function () {
const buildargs: IHashMapGeneric<string> = {}
envVars.forEach((env) => {
buildargs[env.key] = env.value
})
if (envVars.length > 0) {
buildLogs.log(
'Ignore warnings for unconsumed build-args if there is any'
)
}
const optionsForBuild: Dockerode.ImageBuildOptions = {
t: imageName,
buildargs: buildargs,
}
if (Object.keys(registryConfig).length > 0) {
// https://github.com/apocas/dockerode/blob/ed6ef39e0fc81963fedf208c7e0854d8a44cb9a8/lib/docker.js#L271-L274
// https://github.com/apocas/docker-modem/blob/master/lib/modem.js#L160-L163
// "X-Registry-Config" in docker API
optionsForBuild['registryconfig'] = registryConfig
}
return self.dockerode.buildImage(
tarballFilePath,
optionsForBuild
)
})
.then(function (stream) {
return new Promise<void>(function (resolve, reject) {
let errorMessage = ''
stream.setEncoding('utf8')
// THIS BLOCK HAS TO BE HERE. "end" EVENT WON'T GET CALLED OTHERWISE.
stream.on('data', function (chunkRaw) {
Logger.dev(`stream data ${chunkRaw}`)
safeParseChunk(chunkRaw).forEach((chunk) => {
const chuckStream = chunk.stream
if (chuckStream) {
// Logger.dev('stream data ' + chuckStream);
buildLogs.log(chuckStream)
}
if (chunk.error) {
Logger.e(chunk.error)
const errorDetails = JSON.stringify(
chunk.errorDetail
)
Logger.e(errorDetails)
buildLogs.log(errorDetails)
buildLogs.log(chunk.error)
errorMessage += '\n'
errorMessage += errorDetails
errorMessage += '\n'
errorMessage += chunk.error
}
})
})
// stream.pipe(process.stdout, {end: true});
// IncomingMessage
// https://nodejs.org/api/stream.html#stream_event_end
stream.on('end', function () {
if (errorMessage) {
reject(errorMessage)
return
}
resolve()
})
stream.on('error', function (chunk) {
errorMessage += chunk
})
})
})
.then(function () {
return self.dockerode.getImage(imageName).tag({
tag: newVersion,
repo: imageName,
})
})
}
pullImage(
imageNameIncludingTag: string,
authObj: DockerAuthObj | undefined
) {
const self = this
const parsedTag = dockerodeUtils.parseRepositoryTag(
imageNameIncludingTag
)
const repository = parsedTag.repository
const tag = parsedTag.tag || 'latest'
return Promise.resolve()
.then(function () {
return self.dockerode.createImage({
fromImage: repository,
tag: tag,
authconfig: authObj,
})
})
.then(function (stream) {
return new Promise<void>(function (resolve, reject) {
let errorMessage = ''
const logsBeforeError: string[] = []
for (let i = 0; i < 20; i++) {
logsBeforeError.push('')
}
stream.setEncoding('utf8')
// THIS BLOCK HAS TO BE HERE. "end" EVENT WON'T GET CALLED OTHERWISE.
stream.on('data', function (chunkRaw) {
Logger.dev(`stream data ${chunkRaw}`)
safeParseChunk(chunkRaw).forEach((chunk) => {
const chuckStream = chunk.stream
if (chuckStream) {
// Logger.dev('stream data ' + chuckStream);
logsBeforeError.shift()
logsBeforeError.push(chuckStream)
}
if (chunk.error) {
Logger.e(chunk.error)
Logger.e(JSON.stringify(chunk.errorDetail))
errorMessage += '\n [truncated] \n'
errorMessage += logsBeforeError.join('')
errorMessage += '\n'
errorMessage += chunk.error
}
})
})
// stream.pipe(process.stdout, {end: true});
// IncomingMessage
// https://nodejs.org/api/stream.html#stream_event_end
stream.on('end', function () {
if (errorMessage) {
reject(errorMessage)
return
}
resolve()
})
stream.on('error', function (chunk) {
errorMessage += chunk
})
})
})
}
/**
* This method container a lot of hacks to workaround some Docker issues.
* See https://github.com/githubsaturn/captainduckduck/issues/176
*
* @param nameOrId
* @param networkIdOrName
* @returns {Promise<void>}
*/
ensureContainerStoppedAndRemoved(
nameOrId: string,
networkIdOrName: string
) {
const self = this
Logger.d(`Ensuring Stopped & Removed Container: ${nameOrId}`)
return Promise.resolve()
.then(function () {
Logger.d(`Stopping ${nameOrId}`)
return self.dockerode.getContainer(nameOrId).stop({
t: 2,
})
})
.then(function () {
Logger.d(`Waiting to stop ${nameOrId}`)
return Promise.race([
self.dockerode.getContainer(nameOrId).wait(),
new Promise<void>(function (resolve, reject) {
setTimeout(function () {
resolve()
}, 7000)
}),
])
})
.catch(function (error) {
if (error && error.statusCode === 304) {
Logger.w(`Container already stopped: ${nameOrId}`)
return false
}
throw error
})
.then(function () {
Logger.d(`Removing ${nameOrId}`)
return self.dockerode.getContainer(nameOrId).remove({
force: true,
})
})
.then(function () {
return self.pruneContainers()
})
.then(function () {
Logger.d(`Disconnecting from network: ${nameOrId}`)
return self.dockerode.getNetwork(networkIdOrName).disconnect({
Force: true,
Container: nameOrId,
})
})
.catch(function (error) {
if (error && error.statusCode === 404) {
Logger.w(`Container not found: ${nameOrId}`)
return false
}
throw error
})
}
/**
* Creates a volume thar restarts unless stopped
* @param containerName
* @param imageName
* @param volumes an array, hostPath & containerPath, mode
* @param arrayOfEnvKeyAndValue:
* [
* {
* key: 'somekey'
* value: 'some value'
* }
* ]
* @param network
* @param addedCapabilities
* @returns {Promise.<>}
*/
createStickyContainer(
containerName: string,
imageName: string,
volumes: IAppVolume[],
network: string,
arrayOfEnvKeyAndValue: IAppEnvVar[],
addedCapabilities: string[],
addedSecOptions: string[],
authObj: DockerAuthObj | undefined
) {
const self = this
Logger.d(`Creating Sticky Container: ${imageName}`)
const volumesMapped: string[] = []
volumes = volumes || []
for (let i = 0; i < volumes.length; i++) {
const v = volumes[i]
volumesMapped.push(
`${v.hostPath}:${v.containerPath}${v.mode ? `:${v.mode}` : ''}`
)
}
const envs: string[] = []
arrayOfEnvKeyAndValue = arrayOfEnvKeyAndValue || []
for (let i = 0; i < arrayOfEnvKeyAndValue.length; i++) {
const e = arrayOfEnvKeyAndValue[i]
envs.push(`${e.key}=${e.value}`)
}
return Promise.resolve()
.then(function () {
return self.pullImage(imageName, authObj)
})
.then(function () {
return self.dockerode.createContainer({
name: containerName,
Image: imageName,
Env: envs,
HostConfig: {
Binds: volumesMapped,
CapAdd: addedCapabilities,
SecurityOpt: addedSecOptions,
NetworkMode: network,
LogConfig: {
Type: 'json-file',
Config: {
'max-size':
CaptainConstants.configs.defaultMaxLogSize,
},
},
RestartPolicy: {
Name: 'always',
},
},
})
})
.then(function (data) {
return data.start()
})
}
retag(currentName: string, targetName: string) {
const self = this
return Promise.resolve().then(function () {
const currentSplit = currentName.split(':')
const targetSplit = targetName.split(':')
if (targetSplit.length < 2 || targetSplit.length < 2) {
throw new Error(
'This method only support image tags with version'
)
}
if (currentSplit[currentSplit.length - 1].indexOf('/') > 0) {
throw new Error(
'This method only support image tags with version - current image.'
)
}
const targetVersion = targetSplit[targetSplit.length - 1]
if (targetVersion.indexOf('/') > 0) {
throw new Error(
'This method only support image tags with version - target image.'
)
}
return self.dockerode.getImage(currentName).tag({
tag: targetVersion,
repo: targetSplit.slice(0, targetSplit.length - 1).join(':'),
})
})
}
pushImage(imageName: string, authObj: DockerAuthObj, buildLogs: BuildLog) {
const self = this
buildLogs.log(`Pushing to remote: ${imageName}`)
buildLogs.log(`Server: ${authObj ? authObj.serveraddress : 'N/A'}`)
buildLogs.log('This might take a few minutes...')
return Promise.resolve()
.then(function () {
return self.dockerode.getImage(imageName).push({
authconfig: authObj,
})
})
.then(function (stream) {
return new Promise<void>(function (resolve, reject) {
let errorMessage = ''
stream.setEncoding('utf8')
// THIS BLOCK HAS TO BE HERE. "end" EVENT WON'T GET CALLED OTHERWISE.
stream.on('data', function (chunkRaw) {
Logger.dev(`stream data ${chunkRaw}`)
safeParseChunk(chunkRaw).forEach((chunk) => {
const chuckStream = chunk.stream
if (chuckStream) {
// Logger.dev('stream data ' + chuckStream);
buildLogs.log(chuckStream)
}
if (chunk.error) {
Logger.e(chunk.error)
const errorDetails = JSON.stringify(
chunk.errorDetail
)
Logger.e(errorDetails)
buildLogs.log(errorDetails)
buildLogs.log(chunk.error)
errorMessage += '\n'
errorMessage += errorDetails
errorMessage += chunk.error
}
})
})
// stream.pipe(process.stdout, {end: true});
// IncomingMessage
// https://nodejs.org/api/stream.html#stream_event_end
stream.on('end', function () {
if (errorMessage) {
buildLogs.log('Push failed...')
reject(errorMessage)
return
}
buildLogs.log('Push succeeded...')
resolve()
})
stream.on('error', function (chunk) {
errorMessage += chunk
})
})
})
}
/**
* Creates a new service
*
* @param imageName REQUIRED
* @param serviceName REQUIRED
* @param portsToMap an array, containerPort & hostPort
* @param nodeId node ID on which we lock down the service
* @param volumeToMount an array, hostPath & containerPath
* @param arrayOfEnvKeyAndValue:
* [
* {
* key: 'somekey'
* value: 'some value'
* }
* ]
* @param resourcesObject:
* [
* {
* Limits: { NanoCPUs , MemoryBytes}
* Reservation: { NanoCPUs , MemoryBytes}
*
* ]
*/
createServiceOnNodeId(
imageName: string,
serviceName: string,
portsToMap: IAppPort[] | undefined,
nodeId: string | undefined,
volumeToMount: IAppVolume[] | undefined,
arrayOfEnvKeyAndValue: IAppEnvVar[] | undefined,
resourcesObject?: IDockerContainerResource
) {
const self = this
const ports: IDockerApiPort[] = []
if (portsToMap) {
for (let i = 0; i < portsToMap.length; i++) {
const publishMode = portsToMap[i].publishMode
const protocol = portsToMap[i].protocol
const containerPort = portsToMap[i].containerPort
const hostPort = portsToMap[i].hostPort
if (protocol) {
const item: IDockerApiPort = {
Protocol: protocol,
TargetPort: containerPort,
PublishedPort: hostPort,
}
if (publishMode) {
item.PublishMode = publishMode
}
ports.push(item)
} else {
const tcpItem: IDockerApiPort = {
Protocol: 'tcp',
TargetPort: containerPort,
PublishedPort: hostPort,
}
const udpItem: IDockerApiPort = {
Protocol: 'udp',
TargetPort: containerPort,
PublishedPort: hostPort,
}
if (publishMode) {
tcpItem.PublishMode = publishMode
udpItem.PublishMode = publishMode
}
ports.push(tcpItem)
ports.push(udpItem)
}
}
}
const dataToCreate: any = {
name: serviceName,
TaskTemplate: {
ContainerSpec: {
Image: imageName,
},
Resources: resourcesObject,
Placement: {
Constraints: nodeId ? [`node.id == ${nodeId}`] : [],
},
LogDriver: {
Name: 'json-file',
Options: {
'max-size': CaptainConstants.configs.defaultMaxLogSize,
},
},
},
EndpointSpec: {
Ports: ports,
},
}
if (volumeToMount) {
const mts = []
for (let idx = 0; idx < volumeToMount.length; idx++) {
const v = volumeToMount[idx]
if (!v.containerPath) {
throw new Error(
'Service Create currently only supports bind volumes.'
)
}
mts.push({
Source: v.hostPath,
Target: v.containerPath,
Type: VolumesTypes.BIND,
ReadOnly: false,
Consistency: 'default',
})
}
dataToCreate.TaskTemplate.ContainerSpec.Mounts = mts
}
if (arrayOfEnvKeyAndValue) {
dataToCreate.TaskTemplate.ContainerSpec.Env = []
for (let i = 0; i < arrayOfEnvKeyAndValue.length; i++) {
const keyVal = arrayOfEnvKeyAndValue[i]
const newSet = `${keyVal.key}=${keyVal.value}`
dataToCreate.TaskTemplate.ContainerSpec.Env.push(newSet)
}
}
return self.dockerode.createService(dataToCreate)
}
removeServiceByName(serviceName: string) {
const self = this
return self.dockerode.getService(serviceName).remove()
}
deleteVols(vols: string[]) {
const self = this
const promises: (() => Promise<void>)[] = []
const failedVols: string[] = []
vols.forEach((v) => {
promises.push(function () {
return self.dockerode
.getVolume(v) //
.remove() // { force: true }
.catch((err) => {
Logger.d(err)
failedVols.push(v)
})
})
})
return Utils.runPromises(promises) //
.then(function () {
return failedVols
})
}
isServiceRunningByName(serviceName: string) {
return this.dockerode
.getService(serviceName)
.inspect()
.then(function () {
return true
})
.catch(function (error) {
if (error && error.statusCode === 404) {
return false
}
throw error
})
}
getContainerIdByServiceName(
serviceName: string,
retryCountMaybe?: number
): Promise<string> {
const self = this
const retryCount: number = retryCountMaybe || 0
return self.dockerode
.listTasks({
filters: {
service: [serviceName],
'desired-state': ['running'],
},
})
.then(function (data) {
if (data.length >= 2) {
throw new Error(
`There must be only one instance (not ${data.length}) of the service running for sendSingleContainerKillHUP. ${serviceName}`
)
}
if (data.length === 1 && !!data[0].Status.ContainerStatus) {
return Promise.resolve(
data[0].Status.ContainerStatus.ContainerID
)
}
if (retryCount < 10) {
return new Promise<void>(function (resolve) {
setTimeout(function () {
resolve()
}, 3000)
}).then(function () {
Logger.d(
`Retrying to get containerId for ${serviceName} retry count:${retryCount}`
)
return self.getContainerIdByServiceName(
serviceName,
retryCount + 1
)
})
}
throw new Error('No containerId is found')
})
}
executeCommand(serviceName: string, cmd: string[]) {
const self = this
return self
.getContainerIdByServiceName(serviceName)
.then(function (containerIdFound) {
const cmdForLogging = (cmd || []).join(' ')
Logger.d(
`executeCommand Container: ${serviceName} ${cmdForLogging} `
)
if (!Array.isArray(cmd)) {
throw new Error(
'Command should be an array. e.g, ["echo", "--help"] '
)
}
return self.dockerode
.getContainer(containerIdFound)
.exec({
AttachStdin: false,
AttachStdout: true,
AttachStderr: true,
Tty: true,
Cmd: cmd,
})
.then(function (execInstance) {
return execInstance.start({
Detach: false,
Tty: true,
})
})
.then(function (execStream) {
if (!execStream) {
throw new Error(
`No output from service: ${serviceName} running ${cmd}`
)
}
return new Promise<string>(function (resolve) {
let finished = false
let outputBody = ''
// output is a readable stream
// https://nodejs.org/api/stream.html#stream_event_end
execStream.setEncoding('utf8')
execStream.on('data', function (chunk: string) {
outputBody += chunk
})
execStream.on('end', function () {
if (finished) {
return
}
finished = true
resolve(outputBody)
})
execStream.on('close', function () {
if (finished) {
return
}
finished = true
resolve(outputBody)
})
})
})
})
}
sendSingleContainerKillHUP(serviceName: string) {
const self = this
return self
.getContainerIdByServiceName(serviceName)
.then(function (containerIdFound) {
Logger.d(`Kill HUP Container: ${containerIdFound}`)
return self.dockerode.getContainer(containerIdFound).kill({
signal: 'HUP',
})
})
}
/**
* Adds secret to service if it does not already have it.
* @param serviceName
* @param secretName
* @returns {Promise.<>} FALSE if the secret is JUST added, TRUE if secret existed before
*/
ensureSecretOnService(serviceName: string, secretName: string) {
const self = this
let secretToExpose: Docker.Secret
return self.dockerode
.listSecrets({
name: secretName,
})
.then(function (secrets) {
// the filter returns all secrets whose name includes the provided secretKey. e.g., if you ask for
// captain-me, it also returns captain-me1 and etc if exist
for (let i = 0; i < secrets.length; i++) {
const specs = secrets[i].Spec
if (specs && specs.Name === secretName) {
secretToExpose = secrets[i]
break
}
}
if (!secretToExpose) {
throw new Error(`Cannot find secret: ${secretName}`)
}
return self.checkIfServiceHasSecret(
serviceName,
secretToExpose.ID
)
})
.then(function (hasSecret) {
if (hasSecret) {
Logger.d(
`${serviceName} (service) has already been connected to secret: ${secretName}`
)
return true
}
Logger.d(
`Adding ${secretToExpose.ID} Name:${secretName} to service: ${serviceName}`
)
// we only want to update the service is it doesn't have the secret. Otherwise, it keeps restarting!
return self
.updateService(
serviceName,
undefined,
undefined,
undefined,
undefined,
[
{
secretName: secretName,
secretId: secretToExpose.ID,
},
],
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined
)
.then(function () {
return false
})
})
}
checkIfServiceHasSecret(serviceName: string, secretId: string) {
const self = this
return self.dockerode
.getService(serviceName)
.inspect()
.then(function (data) {
const secrets = data.Spec.TaskTemplate.ContainerSpec.Secrets
if (secrets) {
for (let i = 0; i < secrets.length; i++) {
if (secrets[i].SecretID === secretId) {
return true
}
}
}
return false
})
}
ensureSecret(secretKey: string, valueIfNotExist: string) {
const self = this
return this.checkIfSecretExist(secretKey).then(function (secretExists) {
if (secretExists) {
return
} else {
return self.dockerode
.createSecret({
Name: secretKey,
Labels: {},
Data: Base64.encode(valueIfNotExist),
})
.then(function () {
return
})
}
})
}
checkIfSecretExist(secretKey: string) {
const self = this
return self.dockerode
.listSecrets({
name: secretKey,
})
.then(function (secrets) {
// the filter returns all secrets whose name includes the provided secretKey. e.g., if you ask for
// captain-me, it also returns captain-me1 and etc if exist
let secretExists = false
for (let i = 0; i < secrets.length; i++) {
const spec = secrets[i].Spec
if (spec && spec.Name === secretKey) {
secretExists = true
break
}
}
return secretExists
})
}
ensureServiceConnectedToNetwork(serviceName: string, networkName: string) {
const self = this
let networkId: string
return self.dockerode
.getNetwork(networkName)
.inspect()
.then(function (data) {
networkId = data.Id
return self.dockerode.getService(serviceName).inspect()
})
.then(function (serviceData) {
let availableNetworks = serviceData.Spec.TaskTemplate.Networks
const allNetworks = []
availableNetworks = availableNetworks || []
for (let i = 0; i < availableNetworks.length; i++) {
allNetworks.push(availableNetworks[i].Target)
if (availableNetworks[i].Target === networkId) {
Logger.d(
`Network ${networkName} is already attached to service: ${serviceName}`
)
return
}
}
allNetworks.push(networkId)
Logger.d(
`Attaching network ${networkName} to service: ${serviceName}`
)
return self.updateService(
serviceName,
undefined,
undefined,
allNetworks,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined
)
})
}
ensureOverlayNetwork(networkName: string) {
const self = this
return self.dockerode
.getNetwork(networkName)
.inspect()
.then(function (data) {
// Network exists!
return true
})
.catch(function (error) {
if (error && error.statusCode === 404) {
return self.dockerode.createNetwork({
Name: networkName,
CheckDuplicate: true,
Driver: 'overlay',
Attachable: true,
})
}
return new Promise<any>(function (resolve, reject) {
reject(error)
})
})
}
/**
* @param serviceName
* @param imageName
* @param volumes
* [
* {
* containerPath: 'some value' [REQUIRED]
* hostPath: 'somekey' [REQUIRED for bind type]
* volumeName: 'my-volume-name' [REQUIRED for type:volume]
* type: <defaults to bind>, can be volume or tmpfs (not supported yet through captain)
* }
* ]
* @param networks
* @param arrayOfEnvKeyAndValue:
* [
* {
* key: 'somekey'
* value: 'some value'
* }
* ]
* @param secrets:
* [
* {
* secretName: 'somekey'
* secretId: 'some value'
* }
* ]
* @param authObject:
* [
* {
* username: 'someuser
* password: 'password'
* serveraddress: 'registry.captain.com:996'
* }
* ]
* @param instanceCount: String '12' or null
* @param nodeId: nodeId of the node this service will be locked to or null
* @param namespace: String 'captain' or null
* @returns {Promise.<>}
*/
updateService(
serviceName: string,
imageName: string | undefined,
volumes: IAppVolume[] | undefined,
networks: string[] | undefined,
arrayOfEnvKeyAndValue: IAppEnvVar[] | undefined,
secrets: DockerSecret[] | undefined,
authObject: DockerAuthObj | undefined,
instanceCount: number | undefined,
nodeId: string | undefined,
namespace: string | undefined,
ports: IAppPort[] | undefined,
appObject: IAppDef | undefined,
updateOrder: IDockerUpdateOrder | undefined,
serviceUpdateOverride: any | undefined,
preDeployFunction: PreDeployFunction | undefined
) {
const self = this
return self.dockerode
.getService(serviceName)
.inspect()
.then(function (readData) {
const data = JSON.parse(JSON.stringify(readData))
const updatedData = data.Spec
updatedData.version = parseInt(data.Version.Index)
if (imageName) {
updatedData.TaskTemplate.ContainerSpec.Image = imageName
}
if (nodeId) {
updatedData.TaskTemplate.Placement =
updatedData.TaskTemplate.Placement || {}
updatedData.TaskTemplate.Placement.Constraints =
updatedData.TaskTemplate.Placement.Constraints || []
const newConstraints = []
for (
let i = 0;
i <
updatedData.TaskTemplate.Placement.Constraints.length;
i++
) {
const c =
updatedData.TaskTemplate.Placement.Constraints[i]
if (c.indexOf('node.id') < 0) {
newConstraints.push(c)
}
}
newConstraints.push(`node.id == ${nodeId}`)
updatedData.TaskTemplate.Placement.Constraints =
newConstraints
}
if (arrayOfEnvKeyAndValue) {
updatedData.TaskTemplate.ContainerSpec.Env = []
for (let i = 0; i < arrayOfEnvKeyAndValue.length; i++) {
const keyVal = arrayOfEnvKeyAndValue[i]
const newSet = `${keyVal.key}=${keyVal.value}`
updatedData.TaskTemplate.ContainerSpec.Env.push(newSet)
}
}
if (ports) {
updatedData.EndpointSpec = updatedData.EndpointSpec || {}
updatedData.EndpointSpec.Ports = []
for (let i = 0; i < ports.length; i++) {
const p = ports[i]
if (p.protocol) {
updatedData.EndpointSpec.Ports.push({
Protocol: p.protocol,
TargetPort: p.containerPort,
PublishedPort: p.hostPort,
})
} else {
updatedData.EndpointSpec.Ports.push({
Protocol: 'tcp',
TargetPort: p.containerPort,
PublishedPort: p.hostPort,
})
updatedData.EndpointSpec.Ports.push({
Protocol: 'udp',
TargetPort: p.containerPort,
PublishedPort: p.hostPort,
})
}
}
}
if (volumes) {
const mts = []
for (let idx = 0; idx < volumes.length; idx++) {
const v = volumes[idx]
if (v.hostPath) {
mts.push({
Source: v.hostPath,
Target: v.containerPath,
Type: VolumesTypes.BIND,
ReadOnly: false,
Consistency: 'default',
})
} else if (v.volumeName) {
// named volumes are created here:
// /var/lib/docker/volumes/YOUR_VOLUME_NAME/_data
mts.push({
Source:
(namespace ? namespace + '--' : '') +
v.volumeName,
Target: v.containerPath,
Type: VolumesTypes.VOLUME,
ReadOnly: false,
})
} else {
throw new Error('Unknown volume type!!')
}
}
updatedData.TaskTemplate.ContainerSpec.Mounts = mts
}
if (networks) {
updatedData.TaskTemplate.Networks = []
for (let i = 0; i < networks.length; i++) {
updatedData.TaskTemplate.Networks.push({
Target: networks[i],
})
}
}
if (secrets) {
updatedData.TaskTemplate.ContainerSpec.Secrets =
updatedData.TaskTemplate.ContainerSpec.Secrets || []
for (let i = 0; i < secrets.length; i++) {
const obj = secrets[i]
let foundIndexSecret = -1
for (
let idx = 0;
idx <
updatedData.TaskTemplate.ContainerSpec.Secrets
.length;
idx++
) {
if (
updatedData.TaskTemplate.ContainerSpec.Secrets[
idx
].secretId === obj.secretId
) {
foundIndexSecret = idx
}
}
const objToAdd = {
File: {
Name: obj.secretName,
UID: '0',
GID: '0',
Mode: 292, // TODO << what is this! I just added a secret and this is how it came out with... But I don't know what it means
},
SecretID: obj.secretId,
SecretName: obj.secretName,
}
if (foundIndexSecret >= 0) {
updatedData.TaskTemplate.ContainerSpec.Secrets[
foundIndexSecret
] = objToAdd
} else {
updatedData.TaskTemplate.ContainerSpec.Secrets.push(
objToAdd
)
}
}
}
if (updateOrder) {
updatedData.UpdateConfig = updatedData.UpdateConfig || {}
switch (updateOrder) {
case IDockerUpdateOrders.AUTO:
const existingVols =
updatedData.TaskTemplate.ContainerSpec.Mounts ||
[]
updatedData.UpdateConfig.Order =
existingVols.length > 0
? 'stop-first'
: 'start-first'
break
case IDockerUpdateOrders.START_FIRST:
updatedData.UpdateConfig.Order = 'start-first'
break
case IDockerUpdateOrders.STOP_FIRST:
updatedData.UpdateConfig.Order = 'stop-first'
break
default:
const neverHappens: never = updateOrder
throw new Error(
`Unknown update order! ${updateOrder}${neverHappens}`
)
}
}
// docker seems to be trying to smart and update if necessary!
// but sometimes, it fails to update! no so smart, eh?
// Using this random flag, we'll make it to update!
// The main reason for this is NGINX. For some reason, when it sets the volume, it caches the initial
// data from the volume and the container does not pick up changes in the host mounted volume.
// All it takes is a restart of the container to start picking up changes. Note that it only requires
// to restart once. Once rebooted, all changes start showing up.
updatedData.TaskTemplate.ContainerSpec.Labels =
updatedData.TaskTemplate.ContainerSpec.Labels || {}
updatedData.TaskTemplate.ContainerSpec.Labels.randomLabelForceUpdate =
uuid()
updatedData.authconfig = authObject
// TODO
// This stupid hack is necessary. Otherwise, the following scenario will fail
// Service is deployed (or updated) with an image from a private registry
// Then the service is updated with a public image like nginx or something.
// Without this hack, the update fails!!!
// To replicate the bug:
// - Remove this
// - Create a manager and a worker
// - Create a app and have it locked to the worker node
// - Deploy a few sample apps, it works fine.
// - Then try to deploy a simple imageName such as "nginx:1". This will fail!
// - Even with "docker service update srv-captain--name --image nginx:1 --force" it will still fail
// - The only way that you can make it work is by passing --wit-registry-auth flag to CLI.
// I did some reverse engineering to see what happens under the hood, and it appears that docker uses empty user/pass
// So I did that below, and things started working!
// See https://github.com/docker/cli/blob/b9f150b17eea7ea8f92e3a961f666bc599bb4fdf/cli/command/service/update.go#L209
// and
// https://github.com/docker/cli/blob/0c444c521ff43f4341fcb2e673f93e364e8f2fcf/cli/command/registry.go#L176
// and
// https://github.com/docker/cli/blob/0c444c521ff43f4341fcb2e673f93e364e8f2fcf/cli/command/registry.go#L61
if (!updatedData.authconfig) {
updatedData.authconfig = {
username: '',
password: '',
serveraddress: 'docker.io/v1',
}
}
// updatedData.registryAuthFrom = 'previous-spec'
instanceCount = Number(instanceCount)
if (
(instanceCount && instanceCount > 0) ||
instanceCount === 0
) {
if (!updatedData.Mode.Replicated) {
throw new Error(
'Non replicated services cannot be associated with instance count'
)
}
updatedData.Mode.Replicated.Replicas = instanceCount
}
return Utils.mergeObjects(updatedData, serviceUpdateOverride)
})
.then(function (updatedData) {
if (preDeployFunction) {
Logger.d('Running preDeployFunction')
return preDeployFunction(appObject, updatedData)
}
return updatedData
})
.then(function (updatedData) {
return self.dockerode
.getService(serviceName)
.update(updatedData)
})
.then(function (serviceData) {
// give some time such that the new container is updated.
// also we don't want to fail the update just because prune failed.
setTimeout(function () {
self.pruneContainers()
}, 5000)
return serviceData
})
}
pruneContainers() {
Logger.d('Pruning containers...')
const self = this
return self.dockerode
.pruneContainers() //
.catch(function (error) {
// Error: (HTTP code 409) unexpected - a prune operation is already running
if (error && error.statusCode === 409) {
Logger.d('Skipping prune due to a minor error: ' + error)
return
}
Logger.d('Prune Containers Failed!')
Logger.e(error)
})
}
isNodeManager(nodeId: string) {
const self = this
return self.dockerode
.getNode(nodeId)
.inspect()
.then(function (data) {
return data.Spec.Role === 'manager'
})
}
getLogForService(serviceName: string, tailCount: number, encoding: string) {
const self = this
return Promise.resolve() //
.then(function () {
return self.dockerode
.getService(serviceName) //
.logs({
tail: tailCount,
follow: false,
timestamps:
!!CaptainConstants.configs
.enableDockerLogsTimestamp,
stdout: true,
stderr: true,
})
})
.then(function (data) {
if (Buffer.isBuffer(data)) {
return data.toString(encoding as any)
}
throw new Error(
'Logs are not instance of Buffer! Cannot be parsed!!'
)
})
}
getDockerVersion() {
const self = this
return Promise.resolve().then(function () {
return self.dockerode.version()
})
}
checkRegistryAuth(authObj: DockerAuthObj) {
const self = this
return Promise.resolve().then(function () {
return self.dockerode.checkAuth(authObj)
})
}
getDockerInfo() {
const self = this
return Promise.resolve().then(function () {
return self.dockerode.info()
})
}
deleteImages(imageIds: string[]) {
const self = this
return Promise.resolve().then(function () {
let promises = Promise.resolve()
for (let i = 0; i < imageIds.length; i++) {
const imageId = imageIds[i]
const p = function () {
return self.dockerode
.getImage(imageId)
.remove()
.then(function () {
Logger.d(`Image Deleted: ${imageId}`)
})
.catch(function (err) {
Logger.e(err)
})
}
promises = promises.then(p)
}
return promises
})
}
getImages() {
const self = this
return Promise.resolve().then(function () {
return self.dockerode.listImages()
})
}
getNodeLables(nodeId: string) {
const self = this
return self.dockerode
.getNode(nodeId)
.inspect()
.then(function (data) {
return data.Spec.Labels
})
}
updateNodeLabels(
nodeId: string,
labels: IHashMapGeneric<string>,
nodeName: string
) {
const self = this
return self.dockerode
.getNode(nodeId)
.inspect()
.then(function (data) {
const currentLabels = data.Spec.Labels || {}
Object.keys(labels).forEach(function (key) {
currentLabels[key] = labels[key]
})
return self.dockerode.getNode(nodeId).update({
version: parseInt(data.Version.Index),
Name: nodeName,
Labels: currentLabels,
Role: data.Spec.Role,
Availability: data.Spec.Availability,
})
})
.then(function () {
return true
})
}
}
const dockerApiAddressSplited = (EnvVars.CAPTAIN_DOCKER_API || '').split(':')
const connectionParams: Docker.DockerOptions =
dockerApiAddressSplited.length < 2
? {
socketPath: CaptainConstants.dockerSocketPath,
}
: dockerApiAddressSplited.length === 2
? {
host: dockerApiAddressSplited[0],
port: Number(dockerApiAddressSplited[1]),
}
: {
host: `${dockerApiAddressSplited[0]}:${dockerApiAddressSplited[1]}`,
port: Number(dockerApiAddressSplited[2]),
}
connectionParams.version = CaptainConstants.configs.dockerApiVersion
const dockerApiInstance = new DockerApi(connectionParams)
export default DockerApi | the_stack |
import * as path from 'path';
import * as semver from 'semver';
import { PROJEN_DIR, PROJEN_RC } from '../common';
import { Component } from '../component';
import { Eslint, EslintOptions, NodeProject, NodeProjectOptions, TypeScriptCompilerOptions, TypescriptConfig, TypescriptConfigOptions } from '../javascript';
import { SampleDir } from '../sample-file';
import { Task } from '../task';
import { TextFile } from '../textfile';
import { Projenrc as ProjenrcTs, ProjenrcOptions as ProjenrcTsOptions, TypedocDocgen } from '../typescript';
export interface TypeScriptProjectOptions extends NodeProjectOptions {
/**
* Typescript artifacts output directory
*
* @default "lib"
*/
readonly libdir?: string;
/**
* Typescript sources directory.
*
* @default "src"
*/
readonly srcdir?: string;
/**
* Jest tests directory. Tests files should be named `xxx.test.ts`.
*
* If this directory is under `srcdir` (e.g. `src/test`, `src/__tests__`),
* then tests are going to be compiled into `lib/` and executed as javascript.
* If the test directory is outside of `src`, then we configure jest to
* compile the code in-memory.
*
* @default "test"
*/
readonly testdir?: string;
/**
* Setup eslint.
*
* @default true
*/
readonly eslint?: boolean;
/**
* Eslint options
* @default - opinionated default options
*/
readonly eslintOptions?: EslintOptions;
/**
* TypeScript version to use.
*
* NOTE: Typescript is not semantically versioned and should remain on the
* same minor, so we recommend using a `~` dependency (e.g. `~1.2.3`).
*
* @default "latest"
*/
readonly typescriptVersion?: string;
/**
* Docgen by Typedoc
*
* @default false
*/
readonly docgen?: boolean;
/**
* Docs directory
*
* @default "docs"
*/
readonly docsDirectory?: string;
/**
* Custom TSConfig
* @default - default options
*/
readonly tsconfig?: TypescriptConfigOptions;
/**
* Custom tsconfig options for the development tsconfig.json file (used for testing).
* @default - use the production tsconfig options
*/
readonly tsconfigDev?: TypescriptConfigOptions;
/**
* The name of the development tsconfig.json file.
*
* @default "tsconfig.dev.json"
*/
readonly tsconfigDevFile?: string;
/**
* Do not generate a `tsconfig.json` file (used by jsii projects since
* tsconfig.json is generated by the jsii compiler).
*
* @default false
*/
readonly disableTsconfig?: boolean;
/**
* Generate one-time sample in `src/` and `test/` if there are no files there.
* @default true
*/
readonly sampleCode?: boolean;
/**
* The .d.ts file that includes the type declarations for this module.
* @default - .d.ts file derived from the project's entrypoint (usually lib/index.d.ts)
*/
readonly entrypointTypes?: string;
/**
* Use TypeScript for your projenrc file (`.projenrc.ts`).
*
* @default false
*/
readonly projenrcTs?: boolean;
/**
* Options for .projenrc.ts
*/
readonly projenrcTsOptions?: ProjenrcTsOptions;
}
/**
* TypeScript project
* @pjid typescript
*/
export class TypeScriptProject extends NodeProject {
public readonly docgen?: boolean;
public readonly docsDirectory: string;
public readonly eslint?: Eslint;
public readonly tsconfigEslint?: TypescriptConfig;
public readonly tsconfig?: TypescriptConfig;
/**
* A typescript configuration file which covers all files (sources, tests, projen).
*/
public readonly tsconfigDev: TypescriptConfig;
/**
* The directory in which the .ts sources reside.
*/
public readonly srcdir: string;
/**
* The directory in which compiled .js files reside.
*/
public readonly libdir: string;
/**
* The directory in which tests reside.
*/
public readonly testdir: string;
/**
* The "watch" task.
*/
public readonly watchTask: Task;
constructor(options: TypeScriptProjectOptions) {
super({
...options,
// disable .projenrc.js if typescript is enabled
projenrcJs: options.projenrcTs ? false : options.projenrcJs,
jestOptions: {
...options.jestOptions,
jestConfig: {
...options.jestOptions?.jestConfig,
testMatch: [],
},
},
});
this.srcdir = options.srcdir ?? 'src';
this.libdir = options.libdir ?? 'lib';
this.docgen = options.docgen;
this.docsDirectory = options.docsDirectory ?? 'docs/';
this.compileTask.exec('tsc --build');
this.watchTask = this.addTask('watch', {
description: 'Watch & compile in the background',
exec: 'tsc --build -w',
});
this.testdir = options.testdir ?? 'test';
this.gitignore.include(`/${this.testdir}/`);
this.npmignore?.exclude(`/${this.testdir}/`);
// if the test directory is under `src/`, then we will run our tests against
// the javascript files and not let jest compile it for us.
const compiledTests = this.testdir.startsWith(this.srcdir + path.posix.sep);
if (options.entrypointTypes || this.entrypoint !== '') {
const entrypointTypes = options.entrypointTypes ?? `${path.join(path.dirname(this.entrypoint), path.basename(this.entrypoint, '.js')).replace(/\\/g, '/')}.d.ts`;
this.package.addField('types', entrypointTypes);
}
const compilerOptionDefaults: TypeScriptCompilerOptions = {
alwaysStrict: true,
declaration: true,
esModuleInterop: true,
experimentalDecorators: true,
inlineSourceMap: true,
inlineSources: true,
lib: ['es2019'],
module: 'CommonJS',
noEmitOnError: false,
noFallthroughCasesInSwitch: true,
noImplicitAny: true,
noImplicitReturns: true,
noImplicitThis: true,
noUnusedLocals: true,
noUnusedParameters: true,
resolveJsonModule: true,
strict: true,
strictNullChecks: true,
strictPropertyInitialization: true,
stripInternal: true,
target: 'ES2019',
};
if (!options.disableTsconfig) {
this.tsconfig = new TypescriptConfig(this, mergeTsconfigOptions({
include: [`${this.srcdir}/**/*.ts`],
// exclude: ['node_modules'], // TODO: shouldn't we exclude node_modules?
compilerOptions: {
rootDir: this.srcdir,
outDir: this.libdir,
...compilerOptionDefaults,
},
}, options.tsconfig));
}
const tsconfigDevFile = options.tsconfigDevFile ?? 'tsconfig.dev.json';
this.tsconfigDev = new TypescriptConfig(this, mergeTsconfigOptions({
fileName: tsconfigDevFile,
include: [
PROJEN_RC,
`${this.srcdir}/**/*.ts`,
`${this.testdir}/**/*.ts`,
],
exclude: ['node_modules'],
compilerOptions: compilerOptionDefaults,
}, options.tsconfig, options.tsconfigDev));
this.gitignore.include(`/${this.srcdir}/`);
this.npmignore?.exclude(`/${this.srcdir}/`);
if (this.srcdir !== this.libdir) {
// separated, can ignore the entire libdir
this.gitignore.exclude(`/${this.libdir}`);
} else {
// collocated, can only ignore the compiled output
this.gitignore.exclude(`/${this.libdir}/**/*.js`);
this.gitignore.exclude(`/${this.libdir}/**/*.d.ts`);
}
this.npmignore?.include(`/${this.libdir}/`);
this.npmignore?.include(`/${this.libdir}/**/*.js`);
this.npmignore?.include(`/${this.libdir}/**/*.d.ts`);
this.gitignore.exclude('/dist/');
this.npmignore?.exclude('dist'); // jsii-pacmak expects this to be "dist" and not "/dist". otherwise it will tamper with it
this.npmignore?.exclude('/tsconfig.json');
this.npmignore?.exclude('/.github/');
this.npmignore?.exclude('/.vscode/');
this.npmignore?.exclude('/.idea/');
this.npmignore?.exclude('/.projenrc.js');
this.npmignore?.exclude('tsconfig.tsbuildinfo');
// tests are compiled to `lib/TESTDIR`, so we don't need jest to compile them for us.
// just run them directly from javascript.
if (this.jest && compiledTests) {
this.addDevDeps('@types/jest');
const testout = path.posix.relative(this.srcdir, this.testdir);
const libtest = path.posix.join(this.libdir, testout);
const srctest = this.testdir;
this.npmignore?.exclude(`/${libtest}/`);
this.jest.addTestMatch(`**/${libtest}/**/?(*.)+(spec|test).js?(x)`);
this.jest.addWatchIgnorePattern(`/${this.srcdir}/`);
const resolveSnapshotPath = (test: string, ext: string) => {
const fullpath = test.replace(libtest, srctest);
return path.join(path.dirname(fullpath), '__snapshots__', path.basename(fullpath, '.js') + '.ts' + ext);
};
const resolveTestPath = (snap: string, ext: string) => {
const filename = path.basename(snap, '.ts' + ext) + '.js';
const dir = path.dirname(path.dirname(snap)).replace(srctest, libtest);
return path.join(dir, filename);
};
const resolver = new TextFile(this, path.posix.join(PROJEN_DIR, 'jest-snapshot-resolver.js'));
resolver.addLine(`// ${TextFile.PROJEN_MARKER}`);
resolver.addLine('const path = require("path");');
resolver.addLine(`const libtest = "${libtest}";`);
resolver.addLine(`const srctest= "${srctest}";`);
resolver.addLine('module.exports = {');
resolver.addLine(` resolveSnapshotPath: ${resolveSnapshotPath.toString()},`);
resolver.addLine(` resolveTestPath: ${resolveTestPath.toString()},`);
resolver.addLine(' testPathForConsistencyCheck: path.join(\'some\', \'__tests__\', \'example.test.js\')');
resolver.addLine('};');
this.jest.addSnapshotResolver(`./${resolver.path}`);
}
if (this.jest && !compiledTests) {
this.jest.addTestMatch('**\/__tests__/**\/*.ts?(x)');
this.jest.addTestMatch('**\/?(*.)+(spec|test).ts?(x)');
// create a tsconfig for jest that does NOT include outDir and rootDir and
// includes both "src" and "test" as inputs.
this.jest.addTypeScriptSupport(this.tsconfigDev);
}
if (options.eslint ?? true) {
this.eslint = new Eslint(this, {
tsconfigPath: `./${this.tsconfigDev.fileName}`,
dirs: [this.srcdir],
devdirs: [this.testdir, 'build-tools'],
fileExtensions: ['.ts', '.tsx'],
...options.eslintOptions,
});
this.tsconfigEslint = this.tsconfigDev;
}
const tsver = options.typescriptVersion ? `@${options.typescriptVersion}` : '';
this.addDevDeps(
`typescript${tsver}`,
// @types/node versions numbers match the node runtime versions' major.minor, however, new
// releases are only created when API changes are included in a node release... We might for
// example have dependencies that require `node >= 12.22`, but as 12.21 and 12.22 did not
// include API changes, `@types/node@12.20.x` is the "correct" version to use. As it is not
// possible to easily determine the correct version to use, we pick up the latest version.
//
// Additionally, we default to tracking the 12.x line, as the current earliest LTS release of
// node is 12.x, so this is what corresponds to the broadest compatibility with supported node
// runtimes.
`@types/node@^${semver.major(this.package.minNodeVersion ?? '12.0.0')}`,
);
// generate sample code in `src` and `lib` if these directories are empty or non-existent.
if (options.sampleCode ?? true) {
new SampleCode(this);
}
if (this.docgen) {
new TypedocDocgen(this);
}
const projenrcTypeScript = options.projenrcTs ?? false;
if (projenrcTypeScript) {
new ProjenrcTs(this, options.projenrcTsOptions);
}
}
}
class SampleCode extends Component {
constructor(project: TypeScriptProject) {
super(project);
const srcCode = [
'export class Hello {',
' public sayHello() {',
' return \'hello, world!\';',
' }',
'}',
].join('\n');
const testCode = [
"import { Hello } from '../src';",
'',
"test('hello', () => {",
" expect(new Hello().sayHello()).toBe('hello, world!');",
'});',
].join('\n');
new SampleDir(project, project.srcdir, {
files: {
'index.ts': srcCode,
},
});
new SampleDir(project, project.testdir, {
files: {
'hello.test.ts': testCode,
},
});
}
}
/**
* TypeScript app.
*
* @pjid typescript-app
*/
export class TypeScriptAppProject extends TypeScriptProject {
constructor(options: TypeScriptProjectOptions) {
super({
allowLibraryDependencies: false,
releaseWorkflow: false,
entrypoint: '', // "main" is not needed in typescript apps
package: false,
...options,
});
}
}
/**
* @deprecated use `TypeScriptProject`
*/
export class TypeScriptLibraryProject extends TypeScriptProject {
};
/**
* @deprecated use TypeScriptProjectOptions
*/
export interface TypeScriptLibraryProjectOptions extends TypeScriptProjectOptions {
}
/**
* @internal
*/
export function mergeTsconfigOptions(...options: (TypescriptConfigOptions | undefined)[]): TypescriptConfigOptions {
const definedOptions = options.filter(Boolean) as TypescriptConfigOptions[];
return definedOptions.reduce<TypescriptConfigOptions>((previous, current) => ({
...previous,
...current,
include: [
...previous.include ?? [],
...current.include ?? [],
],
exclude: [
...previous.exclude ?? [],
...current.exclude ?? [],
],
compilerOptions: {
...previous.compilerOptions,
...current.compilerOptions,
},
}), { compilerOptions: {} });
} | the_stack |
export class Agent {
constructor(
account_url: string,
agent_name: string,
agent_password: string,
friendly_name: string,
log_level?: string
);
/**
* Set url of Agent
* {string} url The new URL for the Agency.
* Returns {void}
*/
setUrl(url: string): void;
/**
* Set user and password for user's Agent
* {string} user A TI Agent identity.
* {string} pw The password for the Agency identity.
* Returns {void}
*/
setUserPassword(user: string, pw: string): void;
/**
* Set human readable user name that is displayed in connection, credential or proof UI
* {string} name The human readable name of the user
* Returns {void}
*/
setUserName(name: string): void;
/**
* Enable logging for the agent by setting a logging level.
* {'trace'|'debug'|'info'|'warn'|'error'|'fatal'} log_level The desired logging level.
* Returns {void}
*/
setLoggingLevel(
log_level:
| string
| 'trace'
| 'debug'
| 'info'
| 'warn'
| 'error'
| 'fatal'
): void;
/**
* Get this agent's {AgentInfo}.
* Returns {Promise<AgentInfo>} A promise that resolves with information about the agent.
*/
getIdentity(): Promise<AgentInfo>;
/**
* Create a {AgentInfo} on the account. If self_registration is disabled, you have to create an agent with
* some password, and then change that password as the agent that was created. This function attempts to handle
* both self-registration and non-self-registration scenarios.
* {string} account_admin_agent_name The admin agent on this agent's account. Only needed if create is true.
* {string} account_admin_agent_password The admin agent's password.
* Returns {Promise<AgentInfo>} A promise that resolves with information about the agent that was created.
*/
createIdentity(
account_admin_agent_name: string,
account_admin_agent_password: string
): Promise<AgentInfo>;
/**
* Set this agent's role to TRUST_ANCHOR on the ledger, giving the agent the ability to publish schemas and
* credential definitions, which are needed to issue credentials.
* {string} account_admin_agent_name The admin agent on this agent's account. Only needed if create is true.
* {string} account_admin_agent_password The admin agent's password.
* {string} [seed] A valid trustee seed. Allows this agent to generate the NYM transaction as the network's trustee.
* Returns {Promise<AgentInfo>} A promise that resolves with the updated agent information.
*/
onboardAsTrustAnchor(
account_admin_agent_name: string,
account_admin_agent_password: string,
seed?: string
): Promise<AgentInfo>;
/**
* Get all listeners
* Returns {object[]} Array of listener objects
*/
getListeners(): any[];
/**
* Delete listener
* {string} id The ID of a listener
* Returns {object} The delete response from Agency
*/
deleteListener(id: string): any;
/**
* Get all devices
* Returns {object[]} Array of device objects
*/
getDevices(): any[];
/**
* Delete device
* {string} id The ID of a device
* Returns {object} The delete response from Agency
*/
deleteDevice(id: string): any;
/**
* Creates a {CredentialSchema}, meaning the schema is published on the ledger.
* {string} name The name of the schema.
* {string} version A tuple representing the schema version (1.0, 1.1.2, etc.)
* {string[]} attributes The list of attributes credentials based on this schema must have.
* Returns {Promise<CredentialSchema>} A promise that resolves with the new schema record.
*/
createCredentialSchema(
name: string,
version: string,
attributes: string[]
): Promise<CredentialSchema>;
/**
* Get a {CredentialSchema} record.
* {CredentialSchemaID} id The ID of the schema
* Returns {Promise<CredentialSchema>} A promise that resolves with the schema object, or null if not found
*/
getCredentialSchema(id: CredentialSchemaID): Promise<CredentialSchema>;
/**
* Get a list of all {CredentialSchema}s published by your agent, if no parameters are specified, or a list of
* credential schemas matching the search parameters. You can use the `route` parameter to direct the request to
* other agents.
* {CredentialSchemaQueryParams} [opts] An optional filter for the schemas that are returned.
* {QueryRoute} [route] A list of parameters used to proxy the request to other agents.
* Returns {Promise<CredentialSchema[]>} A promise that resolves with a list of credential schemas.
*/
getCredentialSchemas(
opts?: CredentialSchemaQueryParams | null,
route?: QueryRoute
): Promise<CredentialSchema[]>;
/**
* Create a {CredentialDefinition}
* {CredentialSchemaID} schemaId The ledger ID for the schema.
* Returns {Promise<CredentialDefinition>} The created credential definition.
*/
createCredentialDefinition(
schemaId: CredentialSchemaID
): Promise<CredentialDefinition>;
/**
* Get a {CredentialDefinition}.
* {CredentialDefinitionID} id The credential definition ID.
* Returns {Promise<CredentialDefinition>} A promise that resolves with the credential definition.
*/
getCredentialDefinition(
id: CredentialDefinitionID
): Promise<CredentialDefinition>;
/**
* Get a list of {CredentialDefinition}s matching the given parameters, or all of them, if no parameters are
* given.
* {CredentialDefinitionQueryParams} [opts] Credential definition search parameters.
* {QueryRoute} [route] A list of parameters used to proxy the request to other agents.
* Returns {Promise<CredentialDefinition[]>} A promise that resolves with a list of credential definitions.
*/
getCredentialDefinitions(
opts?: CredentialDefinitionQueryParams,
route?: QueryRoute
): Promise<CredentialDefinition[]>;
/**
* Create a {ProofSchema}.
* {string} name The name of the schema.
* {string} version The version of the schema.
* {object<ProofSchemaAttribute>} [requestedAttributes] A list of requested attributes.
* {object<ProofSchemaPredicate>} [requestedPredicates] A list of requested predicates.
* Returns {Promise<ProofSchema>} A promise that resolves with the created proof schema.
*/
createProofSchema(
name: string,
version: string,
requestedAttributes?: any,
requestedPredicates?: any
): Promise<ProofSchema>;
/**
* Gets a list of {ProofSchema}s matching the query parameters, if any are given, or all proof schemas on the agent.
* {ProofSchemaQueryParams} [opts] Query parameters.
* Returns {Promise<ProofSchema[]>} A promise that resolves with a list of proof schemas
*/
verifierGetProofSchemas(
opts?: ProofSchemaQueryParams
): Promise<ProofSchema[]>;
/**
* Get a {ProofSchema}
* {string} id The proof schema ID.
* Returns {Promise<ProofSchema>} A promise that resolves with the proof schema object.
*/
verifierGetProofSchema(id: string): Promise<ProofSchema>;
/**
* Gets a {Connection}.
* {string} id The ID for a connection.
* Returns {Promise<Connection>} A promise that resolves with the given connection, or rejects if something went wrong.
*/
getConnection(id: string): Promise<Connection>;
/**
* Delete a {Connection}.
* {string} id The ID of an existing connection.
* Returns {Promise<void>} A promise that resolves when the connection is deleted.
*/
deleteConnection(id: string): Promise<void>;
/**
* Returns a list of {Connection}s. If query parameters are provided, only connections matching those parameters will
* be returned. If none are specified, all of the agent's connections will be returned.
* {ConnectionQueryParams} [opts] Connections search parameters.
* Returns {Promise<Connection[]>} A list of all connections or only those matching the query parameters.
*/
getConnections(opts?: ConnectionQueryParams): Promise<Connection[]>;
/**
* Create a {Connection}. If recipient information is provided, the agent will attempt to contact the
* recipient agent and create an inbound connection offer on that agent. Otherwise, the connection offer is only
* created on this agent, and the returned object must be passed to the intended recipient agent out-of-band in
* order to establish the connection.
* {ConnectionRecipient} [to] The recipient agent.
* {Properties} [properties] Optional metadata to add to the connection offer.
* Returns {Promise<Connection>} The connection offer, or the active {Connection} if one is already established.
*/
createConnection(
to?: ConnectionRecipient | null,
properties?: Properties
): Promise<Connection>;
/**
* Accept a connection offer. If a connection id is passed, that connection will be updated from state
* `inbound_offer` to `connected` on this agent. If a connection offer object from another agent is passed, the
* connection will be created and set to the `connected` state on this agent.
* {string|Connection} connection The ID for an existing connection, or an out-of-band connection offer.
* {Properties} [properties] Optional metadata to add to the connection offer.
* Returns {Promise<Connection>} The updated connection information.
*/
acceptConnection(
connection: string | Connection,
properties?: Properties
): Promise<Connection>;
/**
* Waits for a {Connection} to enter the 'connected' or 'rejected'.
* {string} id The connection ID.
* {number} [retries] The number of times we should check the status of the connection before giving up.
* {number} [retry_interval] The number of milliseconds to wait between each connection status check.
* Returns {Promise<Connection>} The accepted {Connection}.
*/
waitForConnection(
id: string,
retries?: number,
retry_interval?: number
): Promise<Connection>;
/**
* Get a {Credential}.
* {string} id The ID of the credential.
* Returns {Promise<Credential>} A promise that resolves with the credential information.
*/
getCredential(id: string): Promise<Credential>;
/**
* Gets a list of all the {Credential}s on the agent that match the given search parameters, or all of the credentials
* on the agent, if no parameters are given.
* {CredentialQueryParams} [opts] Optional search parameters for the credentials
* Returns {Promise<Credential[]>} A promise that resolves with a list of credentials
*/
getCredentials(opts?: CredentialQueryParams): Promise<Credential[]>;
/**
* Delete a {Credential}.
* {string} id The ID of an existing credential or credential offer.
* Returns {Promise<void>} A promise that resolves when the credential is deleted.
*/
deleteCredential(id: string): Promise<void>;
/**
* Creates a {Credential} and sends the credential request to a remote agent.
* {RequestRecipient} to The issuer of the desired credential.
* {SchemaIDObj} source Specifies the schema you'd like the credential to be based on.
* {Properties} [properties] Optional metadata to add to the credential request.
* Returns {Promise<Credential>} The created credential request.
*/
requestCredential(
to: RequestRecipient,
source: SchemaIDObj,
properties?: Properties
): Promise<Credential>;
/**
* Create a {@Credential} as an offer to the given holder.
* {RequestRecipient} to The agent being issued a credential.
* {CredentialDefinitionID|SchemaIDObj} source The schema or cred def the credential is based on.
* {object} attributes The `<string>: <string>` pairs for all the fields in the credentials. The
* list of fields comes from the schema the credential is based on.
* {Properties} [properties] Optional metadata to add to the credential offer.
* Returns {Promise<Credential>} A promise that resolves with the credential offer.
*/
offerCredential(
to: RequestRecipient,
source: CredentialDefinitionID | SchemaIDObj,
attributes: any,
properties?: Properties
): any;
/**
* Updates a credential. You'll really only use this method to accept a credential offer as a holder or fulfill a
* credential request as an issuer.
* Accepting a credential offer:
* agent.updateCredential(cred_id, 'accepted')
* Fulfilling a credential request:
* agent.updateCredential(cred_id, 'outbound_offer', {
* first_name: 'John',
* last_name: 'Doe'
* }
* {string} id The credential ID on the agent.
* {CredentialState} state The updated state of the credential.
* {object} [attributes] The filled out information for the credential. Only required when changing the state
* to 'outbound_offer'.
* Returns {Promise<Credential>} A promise that resolves with the updated credential data.
*/
updateCredential(
id: string,
state: CredentialState,
attributes?: Promise<Credential>
): any;
/**
* Waits for a given {Credential} to enter the 'issued' or 'rejected' states.
* {string} id The ID of a credential.
* {number} [retries] The number of times we should check the status of the credential before giving up.
* {number} [retry_interval] The amount of time, in milliseconds, to wait between checks.
* Returns {Promise<Credential>} A promise that resolves with the finished credential.
*/
waitForCredential(
id: string,
retries?: number,
retry_interval?: number
): Promise<Credential>;
/**
* Get the information for a {Verification}.
* {string} id The ID of the verification.
* Returns {Promise<Verification>} A promise that resolves with the verification information.
*/
getVerification(id: string): Promise<Verification>;
/**
* Get a list of all the {Verification}s on the agent, or a subset of verifications that match the search
* parameters.
* {VerificationQueryParams} [opts] Search parameters.
* Returns {Promise<Verification[]>} A promise that resolves with a list of matching verifications.
*/
getVerifications(opts?: VerificationQueryParams): Promise<Verification[]>;
/**
* Delete a {Verification}.
* {string} id The ID of the verification.
* Returns {Promise<void>} A promise the resolves when the verification is deleted.
*/
deleteVerification(id: string): Promise<void>;
/**
* Creates a {Verification} with another agent. The initial state must be one of 'outbound_proof_request',
* 'outbound_verification_request'.
* {RequestRecipient} to The agent being contacted for verification.
* {string} proof_schema_id The proof schema the verification is based on.
* {VerificationState} state The initial state of the verification.
* {Properties} [properties] Optional metadata to add to the verification.
* Returns {Promise<Verification>} A promise that resolves with the created verification.
*/
createVerification(
to: RequestRecipient,
proof_schema_id: string,
state: VerificationState,
properties?: Properties
): Promise<Verification>;
/**
* Updates a {Verification}. A verifier accepts a `inbound_verification_request` by updating the state to
* `outbound_proof_request`. The prover generates a proof for a `inbound_proof_request` by updating the state to
* `proof_generated`. The prover submits that generated proof request by updating the state to `proof_shared`.
* Sometimes, you have a selection
* {string} id The verification ID.
* {VerificationState} state The updated verification state.
* {ProofSelection} [choices] The list of credentials you want to use for requested attributes and predicates.
* {object<string, string>} [self_attested_attributes] The self-attested data to add to the proof.
* Returns {Promise<Verification>} A Promise that resolves with the updated verification.
*/
updateVerification(
id: string,
state: VerificationState,
choices?: ProofSelection,
self_attested_attributes?: any
): Promise<Verification>;
/**
* Waits for a given {Verification} to enter the `passed` or `failed` state.
* {string} id The verification ID.
* {number} [retries] The number of times we should check the status of the verification before giving up.
* {number} [retry_interval] The amount of time, in milliseconds, to wait between checks.
* Returns {Promise<Verification>} A promise that resolves with the completed verification.
*/
waitForVerification(
id: string,
retries?: number,
retry_interval?: number
): Promise<Verification>;
/**
* Call Agent REST APIs and make request
* {string} path The REST API path
* {object} [options] Set headers, method=GET, POST, PUT, PATCH, DELETE, UPDATE by passing in object {"headers":{...}, "method":...}
* Returns {object} The response object
*/
request(path: string, options?: any): any;
}
/**
* A URL associated with a cloud agent account.
*/
export type AccountURL = string;
/**
* The name of an agent. Generally only useful if you also know the {AccountURL}. Ex. admin, gov-dmv, thrift, etc.
*/
export type AgentName = string;
/**
* The URL needed to connect to an agent. Combines the {AgentName} and {AccountURL}.
*/
export type AgentURL = string;
/**
* Represents an agent on a given cloud agent account.
* {AgentName} name The name of the agent.
* {AgentURL} url The connection url for the agent.
* {string|null} role The role of the agent. TRUST_ANCHORs are allowed to publish credential schemas and
* definitions.
* {Verkey} verkey The key for the agent.
* {DID} did The DID for the agent.
* {string} creation_time A datetime string for when the agent was created.
* {number} expiration A timestamp, in milliseconds, for when the agent's password expires.
* {object} metrics Metrics about the agent, such as incoming connections, etc.
*/
export interface AgentInfo {
name: AgentName;
url: AgentURL;
role: string | null;
verkey: Verkey;
did: DID;
creation_time: string;
expiration: number;
metrics: any;
}
/**
* The identifier for a {CredentialSchema} on both the agent and the ledger. If you're curious, the
* ID is composed of the schema publisher's {DID}, a transaction type, the schema name, and the schema version.
* Ex. "R4PbDKCjZTWFh1vBc5Zaxc:2:Thrift Account:1.0"
*/
export type CredentialSchemaID = string;
/**
* A CredentialSchema represents a list of attributes that a credential based on the schema can contain.
* {
* "attr_names": [
* "first_name",
* "last_name"
* ],
* "id": "R4PbDKCjZTWFh1vBc5Zaxc:2:Thrift Account:1.0",
* "name": "Thrift Account",
* "namever": "Thrift Account:1.0",
* "version": "1.0"
* }
* {CredentialSchemaID} id The ID of the schema.
* {string} name The name of the schema.
* {string} version A tuple representing the schema version (1.0, 1.1.2, etc.).
* {string} namever The name and version joined with a ':'.
* {string[]} attr_names The list of attributes that a credential based on the schema can have.
*/
export interface CredentialSchema {
id: CredentialSchemaID;
name: string;
version: string;
namever: string;
attr_names: string[];
}
/**
* An object listing [BSON query parameters]{https://docs.mongodb.com/manual/reference/operator/query/} that
* correspond to the fields in a {CredentialSchema}. The fields below are just examples to give you an idea;
* there are other queries you can make.
* {
* name: 'My Schema',
* version: { $ne: '1.0' }
* }
* {string} [id] The ID of the schema
* {string} [name] The name of the schema
*/
export interface CredentialSchemaQueryParams { [key: string]: any; }
/**
* A set of parameters that cause the agent to collect a set of responses from other agents that it has connections
* to. It's a list of {Connection} property names and values. For example,
* {
* property1: true,
* property2: 'prop2'
* }
* causes this agent to look for connections with property1=true. It will send propagate the request to each
* relevant connection. The agents receiving the request will look for connections with property2=prop2 custom and
* recursively propagate the request along those connections, etc.
* {boolean} [trustedVerifier] Propagates the request to connections with trusted verifiers.
* {boolean} [trustedIssuer] Propagates the request to connections with trusted issuers.
*/
export interface QueryRoute {
[key: string]: any;
}
/**
* {DID} did The pairwise DID for the remote agent.
* {AgentName} name The agent name for the remote agent.
* {object} results The list of {CredentialSchemas} or {CredentialDefinitions} found by the
* remote agent.
* {number} results.count The number of results found by the remote agent.
* {CredentialSchema[]|CredentialDefinition[]}
*/
export interface AgentResponse {
did: DID;
name: AgentName;
results: CredentialSchema[] | CredentialDefinition[];
}
/**
* {AgentResponse[]} agents A list of agent responses containing
*/
export interface RouteResponse {
agents: AgentResponse[];
}
/**
* Resolves to a published credential definition on the ledger. Consists of a DID, a transaction type (3 means a
* credential definition in Hyperledger Indy), CL, a transaction number, and a tag.
* Ex. 'JeU3p99QCt3p5tjZJyPwUK:3:CL:357:TAG1'
*/
export type CredentialDefinitionID = string;
/**
* When an issuer wants to issue credentials based on a certain schema, they have to publish a credential definition
* on the ledger for that schema.
* {object} data The cryptographic content of the credential definition. Good at filling up logs.
* {CredentialDefinitionID} id The ID of the credential definition on both the agent and the ledger.
* {CredentialSchemaID} schema_id The credential schema this credential definition pertains to.
* {string} schema_name The name of the credential schema.
* {string} version The version of the credential schema.
*/
export interface CredentialDefinition {
data: any;
id: CredentialDefinitionID;
schema_id: CredentialSchemaID;
schema_name: string;
version: string;
}
/**
* An object listing [BSON query parameters]{https://docs.mongodb.com/manual/reference/operator/query/} that
* correspond to the fields in a {CredentialDefinition}. The fields below are just examples to give you an idea;
* there are other queries you can make.
* {
* schema_name: 'My Schema',
* version: { $ne: '1.0' }
* }
* {string} [id] The ID of the credential definition
* {string} [schema_name] The name of the schema for the credential definition
*/
export interface CredentialDefinitionQueryParams { [key: string]: any; }
/**
* Criteria which must be true pertaining to an attribute or predicate in a {ProofSchema}. There is a logical
* AND between keys inside a Restriction and a logical OR between the Restrictions in a list. For example, consider
* the following restrictions field:
* 'restrictions': [{'schema_name': 'myschema', 'schema_version': '1.0'}, {'cred_def_id': 'XXX'}]
* This can be read as (schema_name == 'myschema' AND schema_version == '1.0') OR cred_def_id == 'XXX'. The list of
* possible restrictions:
* {CredentialSchemaID} [schema_id] The DID of a credential schema.
* {DID} [schema_issuer_did] The DID of the schema issuer.
* {string} [schema_name] The name of the schema.
* {string} [schema_version] The value of the schema.
* {DID} [issuer_did] The DID of the issuer of the credential.
* {CredentialDefinitionID} [cred_def_id] The credential definition ID.
*/
export interface Restriction {
schema_id?: CredentialSchemaID | undefined;
schema_issuer_did?: DID | undefined;
schema_name?: string | undefined;
schema_version?: string | undefined;
issuer_did?: DID | undefined;
cred_def_id?: CredentialDefinitionID | undefined;
}
/**
* A requirement in a {ProofSchema} that asks a prover not to provide a value for something, but to prove
* something _about_ a value, such as a value being greater than some limit. You could, for example, ask someone to
* prove that they're older than 21 with the following predicate:
* {
* name: 'age',
* p_type: '>',
* p_value: 21,
* restrictions: [{'cred_def_id': '<credential_definition_id>'}]
* }
* {string} name The name of the attribute.
* {string} p_type The type of the predicate. Defines an operation like ">" to check the attribute value.
* {number} p_value The value of the predicate. Define the boundary for the operation.
* {Restriction[]} restrictions A list of {Restriction}s to limit what credentials can supply the
* attribute for the predicate.
*/
export interface ProofSchemaPredicate {
name: string;
p_type: string;
p_value: number;
restrictions: Restriction[];
}
/**
* Describes a request attribute in a proof request. If you don't specify any restrictions on the attribute, then
* the attribute is 'self attested', meaning the prover can put whatever they want in for that field.
* {Restriction[]} [restrictions] A list of {Restriction}s on to limit what credentials can supply
* the attribute.
*/
export interface ProofSchemaAttribute {
restrictions?: Restriction[] | undefined;
}
/**
* An object describing the contents of a proof request, which is basically a prepared query for a list of verified
* or self attested attributes and predicates from a prover. An example:
* {
* 'name': 'proof-schema1',
* 'version': '1.0',
* 'requested_attributes': {
* 'attr1_referent': {
* 'name': 'attr1',
* 'restrictions': [{'schema_name': 'cred_schema1', 'schema_version': '1.0'}]
* },
* 'attr2_referent': {
* 'name': 'attr2',
* 'restrictions': [{'cred_def_id': '<credential_definition_id>'}]
* },
* 'self_attested_attr1_referent': {
* 'name': 'self-attested-attr1'
* },
* },
* 'requested_predicates': {
* 'predicate1_referent': {
* 'name': 'attr3',
* 'p_type': '>',
* 'p_value': 5,
* 'restrictions': [{'cred_def_id': '<credential_definition_id>'}]
* }
* }
* }
* {string} id The ID of the proof schema.
* {string} name The name of the proof schema. Ex. "proof_of_employment".
* {string} version The version of the proof schema. Ex. "1.0", "1.0.0", etc.
* {object<ProofSchemaAttribute>} requested_attributes A list of attributes to be provided by credentials
* {object<ProofSchemaPredicate>} requested_predicates A list of predicates to be included in the proof
*/
export interface ProofSchema {
id: string;
name: string;
version: string;
requested_attributes: any;
requested_predicates?: any;
}
/**
* An object listing [BSON query parameters]{https://docs.mongodb.com/manual/reference/operator/query/} that
* correspond to the fields in a {ProofSchema}. The fields below are just examples to give you an idea;
* there are other queries you can make.
* {
* name: 'My Schema',
* version: { $ne: '1.0' }
* }
* {string} [name] The name of the proof schema
* {string} [version] The version of the proof schema
*/
export interface ProofSchemaQueryParams { [key: string]: any; }
/**
* A unique identifier use in communication on the Hyperledger Indy ledger. They represent users, agents, issuers, verifiers, etc.
*/
export type DID = string;
/**
* A publicly shared key associated with a DID. The DID owner proves ownership of the DID using the private/signing key associated with this verkey.
*/
export type Verkey = string;
/**
* A string representing image data. Generally used to store icons for decorating {Connection}s, {Credential}s,
* and {Verification}s.
* Ex. 'data:image/png;base64,iVBOR....'
*/
export type ImageData = string;
/**
* Information about an agent involved in a {Connection}.
* {AgentName} name The agent name.
* {string} role The agent's role on the ledger. Can be 'TRUST_ANCHOR' or 'NONE'.
* {AgentURL} url The agent url.
* {object} pairwise Identifying information dedicated to this specific connection.
* {DID} pairwise.did The pairwise connection DID.
* {Verkey} pairwise.verkey The pairwise verkey.
* {object} Identifying information that has been published to the ledger.
* {DID} public.did A DID.
* {Verkey} public.verkey A verkey.
*/
export interface ConnectionAgent {
name: AgentName;
role: string;
url: AgentURL;
pairwise: {
did: DID;
verkey: Verkey;
};
public: {
did: DID;
verkey: Verkey;
};
}
/**
* Represents the state of a {Connection}.
*/
export type ConnectionState =
| 'inbound_offer'
| 'outbound_offer'
| 'connected'
| 'rejected';
/**
* Connections represent a channel for communication between two agents.
* {string} id A unique identifier for this connection.
* {object} properties Properties of the connection. Generally used to sort or decorate connections.
* {ImageData} [properties.icon] An icon to display when someone views the connection.
* {string} [properties.name] A friendly name to display when someone views the connection.
* {string} role This agent's role in the connection. Can be 'offerer' or 'offeree'.
* {ConnectionState} state The state of the connection.
* {ConnectionAgent} [local] Information about this agent's role in the connection. Only present if this
* agent has accepted or initiated the connection.
* {ConnectionAgent} [remote] Information about the other agent's role in this connection. Only present if
* that agent accepted or initiated the connection.
*/
export interface Connection {
id: string;
properties: Properties;
role: string;
state: ConnectionState;
local?: ConnectionAgent | undefined;
remote?: ConnectionAgent | undefined;
}
/**
* An object listing [BSON query parameters]{https://docs.mongodb.com/manual/reference/operator/query/} that
* correspond to the fields in a {Connection} object. The keys listed below are simply examples to give you
* the idea; there are others.
* {ConnectionState} [state] The connection state we're searching for.
* {AgentName} [remote.name] The name of the remote agent to match against.
* {DID} [remote.pairwise.did] The remote pairwise DID to match.
* {
* state: { $ne: 'inbound_offer' },
* 'remote.pairwise.did': 'A4DXofjbeC97WZAHU5MVGK'
* }
*/
export interface ConnectionQueryParams { [key: string]: any; }
/**
* Describes the recipient of a {Connection}. You must specify either the name of an agent in your agent's
* same account, or the full {AgentURL} to a remote agent.
* {AgentURL} [url] The full {AgentURL} for the other agent.
* {AgentName} [name] The name of an agent in your account.
*/
export interface ConnectionRecipient {
url?: AgentURL | undefined;
name?: AgentName | undefined;
}
/**
* {Connection}s, {Credential}s, and {Verification}s can all be extended by adding additional
* properties during their creation. For example, setting an icon in the properties of a connection could cause
* that connection to be displayed with an icon when a user views it in their agent UI. The properties listed below
* are merely examples to demonstrate what these properties could be used for.
* {ImageData} [properties.icon] An image to display when someone views the connection.
* {string} [properties.name] A friendly name to display for the issuer when the connection is viewed.
* {string} [properties.time] A timestamp used to sort the connection in a list.
*/
export interface Properties {
[key: string]: string;
}
/**
* Represents the state of a {Credential} on the agent. The state of a credential changes depending on whether
* a holder or an issuer is viewing the credential. For example, if a holder creates the credential request, they will
* see the state of the credential as 'outbound_request', while the issuer will see 'inbound_request'.
*/
export type CredentialState =
| 'outbound_request'
| 'inbound_request'
| 'outbound_offer'
| 'inbound_offer'
| 'accepted'
| 'rejected'
| 'issued'
| 'stored';
/**
* A Credential starts out as either an outbound_request, if created by a holder, or an outbound_offer, if created by
* an issuer. The state transitions for a credential as implemented by cloud agent are as follows:
* outbound_request (holder) ->
* inbound_request (issuer) ->
* outbound_offer (issuer) ->
* inbound_offer (holder) ->
* accepted OR rejected (holder) ->
* issued (issuer) ->
* stored (holder)
* {object} [offer] List the data contained in the credential. Only present once the credential has reached the offer state.
* {object} offer.attributes Lists the `<string>: <string>` pairs for all the fields in the credentials. The
* list of fields comes from the schema the credential is based on.
* {string} offer.data The full JSON data for the credential encoded as a string.
* {string} schema_name The schema that the credential is based on. Ex. "drivers_license"
* {string} schema_version The version of the schema. Ex. "1.0"
* {CredentialState} state The current state of the credential. This is the field you must update to turn credential offers
* into stored credentials.
* {string} id The identifier for the credential on the agent.
* {object} properties Extra metadata about the credential. Used for things like sorting and decorating
* credentials.
* {string} [properties.time] We use a `time` property to sort credentials based on when they were offered.
* {string} [properties.name] An optional friendly name to display when someone looks at the credential offer.
* {ImageData} [properties.icon] An optional icon to display when someone looks at the credential.
* {string} role The agent's relationship to the credential. Either 'holder' or 'issuer'.
* {CredentialDefinitionID} credential_definition_id The credential definition for this credential.
* {DID} issuer_did The Issuer's DID.
* {object} to Describes the recipient of the initial credential request (holder initiated) or offer
* (issuer initiated). Has either `url` or `name`.
* {AgentName} [to.name] The {AgentName} of the holder.
* {AgentURL} [to.url] The {AgentURL} of the holder.
*/
export interface Credential {
offer?: {
attributes: {[key: string]: string};
data: string;
} | undefined;
schema_name: string;
schema_version: string;
state: CredentialState;
id: string;
properties: Properties;
role: string;
credential_definition_id: CredentialDefinitionID;
issuer_did: DID;
to: {
name?: AgentName | undefined;
url?: AgentURL | undefined;
};
}
/**
* An object listing [BSON query parameters]{https://docs.mongodb.com/manual/reference/operator/query/} that
* correspond to the fields in a {Credential} object. The keys listed below are simply examples to give you
* the idea; there are others.
* {CredentialState} [state] The connection state we're searching for.
* {AgentName} ['to.name'] The name of the remote agent .
* {CredentialDefinitionID} [credential_definition_id] The credential definition.
* {
* state: 'inbound_offer',
* credential_definition_id: 'JeU3p99QCt3p5tjZJyPwUK:3:CL:357:TAG1',
* 'to.name': 'test-holder'
* }
*/
export interface CredentialQueryParams { [key: string]: any; }
/**
* Contains fields necessary to lookup a {CredentialSchema}.
* {string} schema_name The name of the schema. Ex. "drivers_license", "Driver's License", etc.
* {string} schema_version The version of the schema. Ex. "1.0", "0.0.1", etc.
*/
export interface SchemaIDObj {
schema_name: string;
schema_version: string;
}
/**
* Describes the recipient of a {Verification} or a {Credential}. It mus specify either `name` or `did` of an agent
* that you have a {Connection} with. The {AgentName} can only be used to refer to agents that are in
* the same account as this agent.
* {DID} [did] The `remote.pairwise.did` of other agent in your shared {Connection}.
* {AgentName} [name] The name of an agent in your account.
*/
export interface RequestRecipient {
did?: DID | undefined;
name?: AgentName | undefined;
}
/**
* Represents the state of a {Verification} on the agent. The state of a verification changes depending on
* whether a prover or a verifier is viewing the verification. For example, if a prover creates a verification request,
* they will see the state of the verification as 'outbound_verification_request', while the issuer will see
* 'inbound_verification_request'.
*/
export type VerificationState =
| 'outbound_verification_request'
| 'inbound_verification_request'
| 'outbound_proof_request'
| 'inbound_proof_request'
| 'proof_generated'
| 'proof_shared'
| 'passed'
| 'failed';
/**
* Represents all verification and proof requests between a prover and a verifier. If created by the prover, the
* verifications initial state should be "outbound_verification_request". If created by a verifier, the initial state
* should be "outbound_proof_request" by the verifier. The state transitions for a verification from initial request
* to a verified or unverified proof are as follows :
* outbound_verification_request (prover) ->
* inbound_verification_request (verifier) ->
* outbound_proof_request (verifier) ->
* inbound_proof_request (prover) ->
* proof_generated (prover) ->
* proof_shared (prover) ->
* proof_shared (verifier) ->
* passed OR failed (verifier) ->
* passed OR failed (prover)
* {VerificationState} state The current state of the verification.
* {boolean} [allow_proof_request_override] If true, the prover can supply their own updated proof_request
* in the proof_generated phase. Can only be set by the verifier in the outbound_proof_request phase.
* {Choices} [choices] The list of options for generating a proof from the credentials in an agent's wallet.
* Only appears in the `outbound_proof_request` phase.
* {ProofSchema} proof_request The proof schema the verification is based on.
*/
export interface Verification {
id: string;
state: VerificationState;
allow_proof_request_override?: boolean | undefined;
choices?: Choices | undefined;
proof_request: ProofSchema;
}
/**
* An object listing [BSON query parameters]{https://docs.mongodb.com/manual/reference/operator/query/} that
* correspond to the fields in a {Verification} object. The keys listed below are simply examples to give you
* the idea; there are others.
* {string} ['to.name'] The party that the initial verification was sent to in the outbound_verification_request
* or outbound_proof_request phase.
* {VerificationState} [state] The state of the verifications.
* {
* state: 'inbound_offer',
* 'to.name': { $ne: 'test-holder'}
* }
*/
export interface VerificationQueryParams { [key: string]: any; }
/**
* Describes data that could be used to fill out a requested attribute in a proof request. It's data describes
* information from a single credential in the agent's wallet.
* {string} predicate The predicate calculated from the corresponding {Credential}.
* {CredentialDefinitionID} cred_def_id The credential definition the corresponding credential was issued under.
* {CredentialSchemaID} schema_id The schema that the credential is based on.
* {
* 'predicate': 'average GE 10',
* 'cred_def_id': 'Up36FJDNu3YGKvhTJAiZQU:3:CL:31:TAG1',
* 'schema_id': 'EDEuxdBQ3zb6GzWKCNcyW4:2:Transcript:1.0'
* }
*/
export interface PredicateChoice {
predicate: string;
cred_def_id: CredentialDefinitionID;
schema_id: CredentialSchemaID;
}
/**
* Describes data that could be used to fill out a requested attribute in a proof request. It's data describes
* information from a single credential in the agent's wallet.
* {string} name The name of the attribute.
* {string} value The value of the attribute.
* {CredentialDefinitionID} cred_def_id The credential definition the corresponding credential was issued under.
* {CredentialSchemaID} schema_id The schema that the credential is based on.
* {
* 'name': 'first_name',
* 'value': 'Alice',
* 'cred_def_id': 'Up36FJDNu3YGKvhTJAiZQU:3:CL:31:TAG1',
* 'schema_id': 'EDEuxdBQ_3zb6GzWKCNcyW4:2:Transcript:1.0'
* }
*/
export interface AttributeChoice {
name: string;
value: string;
cred_def_id: CredentialDefinitionID;
schema_id: CredentialSchemaID;
}
/**
* Describes a list of {AttributeChoice}s for filling out the requested attributes and predicates from a
* {Verification}'s {ProofSchema}. When generating the proof, the choices can be condensed into a
* {ProofSelection} and passed to the API to control what credentials are used to generate the proof.
* {object} attributes A list of requested attributes. The next field is an example.
* {object<string,AttributeChoice>} [attr1] A list of {AttributeChoice}s.
* {object} predicates A list of requested predicates. The next field is an example.
* {object<string,PredicateChoice>} [pred1] A list of {PredicateChoice}s.
* {
* 'choices': {
* 'attributes': {
* '<attr1>': {
* '<attr1_choice1>': {
* 'name': 'first_name',
* 'value': 'Alice',
* 'cred_def_id': 'Up36FJDNu3YGKvhTJAiZQU:3:CL:31:TAG1',
* 'schema_id': 'EDEuxdBQ_3zb6GzWKCNcyW4:2:Transcript:1.0'
* },
* '<attr1_choice2>': {
* 'name': 'first_name',
* 'value': 'Alice',
* 'cred_def_id': 'Up36FJDNu3YGKvhTJAiZQU:3:CL:31:TAG1',
* 'schema_id': 'EDEuxdBQ3zb6GzWKCNcyW4:2:Transcript:1.0'
* }
* }
* },
* 'predicates': {
* '<pred1>': {
* '<pred1_choice1>': {
* 'predicate': 'average GE 10',
* 'cred_def_id': 'Up36FJDNu3YGKvhTJAiZQU:3:CL:31:TAG1',
* 'schema_id': 'EDEuxdBQ3zb6GzWKCNcyW4:2:Transcript:1.0'
* }
* }
* }
* }
* }
*/
export interface Choices {
attributes: any;
attr1: any;
predicates: any;
pred1: any;
}
/**
* A list of {AttributeChoice}s and {PredicateChoice}s that should be used in the `generate_proof` phase
* of a {Verification}.
* {object<string,AttributeChoice>} attributes A list of requested attributes and their selected credential attributes.
* {object<string,PredicateChoice>} predicates A list of requested predicates and their selected predicates.
* {
* "attributes": {
* "<attr1>": "<attr1_choice2>"
* },
* "predicates": {
* "<pred1>": "<pred1_choice1>"
* }
* }
*/
export interface ProofSelection {
attributes: {
[key: string]: AttributeChoice;
};
predicates: {
[key: string]: PredicateChoice;
};
}
/**
* Describes a method for establishing a connection with another agent. Out-of-band connections require a user to
* post a connection offer to their agent to establish a connection. In-band connections only require a user to
* accept a connection offer that was automatically delivered to their agent. Invitations are like out-of-band
* connections in that they require the user to post the invitation to their agent, but invitations can be accepted
* by multiple users.
*/
export type ConnectionMethod = 'out_of_band' | 'in_band' | 'invitation'; | the_stack |
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, Router } from '@angular/router';
import {
CellActionDescriptor,
checkBoxCell,
DateEntityTableColumn,
EntityColumn,
EntityTableColumn,
EntityTableConfig,
GroupActionDescriptor,
HeaderActionDescriptor
} from '@home/models/entity/entities-table-config.models';
import { TranslateService } from '@ngx-translate/core';
import { DatePipe } from '@angular/common';
import { EntityType, entityTypeResources, entityTypeTranslations } from '@shared/models/entity-type.models';
import { EntityAction } from '@home/models/entity/entity-component.models';
import { RuleChain, RuleChainType } from '@shared/models/rule-chain.models';
import { RuleChainService } from '@core/http/rule-chain.service';
import { RuleChainComponent } from '@modules/home/pages/rulechain/rulechain.component';
import { DialogService } from '@core/services/dialog.service';
import { RuleChainTabsComponent } from '@home/pages/rulechain/rulechain-tabs.component';
import { ImportExportService } from '@home/components/import-export/import-export.service';
import { ItemBufferService } from '@core/services/item-buffer.service';
import { EdgeService } from '@core/http/edge.service';
import { forkJoin, Observable } from 'rxjs';
import {
AddEntitiesToEdgeDialogComponent,
AddEntitiesToEdgeDialogData
} from '@home/dialogs/add-entities-to-edge-dialog.component';
import { MatDialog } from '@angular/material/dialog';
import { isUndefined } from '@core/utils';
import { PageLink } from '@shared/models/page/page-link';
import { Edge } from '@shared/models/edge.models';
import { mergeMap } from 'rxjs/operators';
import { PageData } from '@shared/models/page/page-data';
@Injectable()
export class RuleChainsTableConfigResolver implements Resolve<EntityTableConfig<RuleChain>> {
private readonly config: EntityTableConfig<RuleChain> = new EntityTableConfig<RuleChain>();
private edge: Edge;
constructor(private ruleChainService: RuleChainService,
private dialogService: DialogService,
private dialog: MatDialog,
private importExport: ImportExportService,
private itembuffer: ItemBufferService,
private edgeService: EdgeService,
private translate: TranslateService,
private datePipe: DatePipe,
private router: Router) {
this.config.entityType = EntityType.RULE_CHAIN;
this.config.entityComponent = RuleChainComponent;
this.config.entityTabsComponent = RuleChainTabsComponent;
this.config.entityTranslations = entityTypeTranslations.get(EntityType.RULE_CHAIN);
this.config.entityResources = entityTypeResources.get(EntityType.RULE_CHAIN);
this.config.deleteEntityTitle = ruleChain => this.translate.instant('rulechain.delete-rulechain-title',
{ruleChainName: ruleChain.name});
this.config.deleteEntityContent = () => this.translate.instant('rulechain.delete-rulechain-text');
this.config.deleteEntitiesTitle = count => this.translate.instant('rulechain.delete-rulechains-title', {count});
this.config.deleteEntitiesContent = () => this.translate.instant('rulechain.delete-rulechains-text');
this.config.loadEntity = id => this.ruleChainService.getRuleChain(id.id);
this.config.saveEntity = ruleChain => this.saveRuleChain(ruleChain);
this.config.deleteEntity = id => this.ruleChainService.deleteRuleChain(id.id);
this.config.onEntityAction = action => this.onRuleChainAction(action);
}
resolve(route: ActivatedRouteSnapshot): EntityTableConfig<RuleChain> {
const edgeId = route.params?.edgeId;
const ruleChainScope = route.data?.ruleChainsType ? route.data?.ruleChainsType : 'tenant';
this.config.componentsData = {
ruleChainScope,
edgeId
};
this.config.columns = this.configureEntityTableColumns(ruleChainScope);
this.config.entitiesFetchFunction = this.configureEntityFunctions(ruleChainScope, edgeId);
this.config.groupActionDescriptors = this.configureGroupActions(ruleChainScope);
this.config.addActionDescriptors = this.configureAddActions(ruleChainScope);
this.config.cellActionDescriptors = this.configureCellActions(ruleChainScope);
if (ruleChainScope === 'tenant' || ruleChainScope === 'edges') {
this.config.entitySelectionEnabled = ruleChain => ruleChain && !ruleChain.root;
this.config.deleteEnabled = (ruleChain) => ruleChain && !ruleChain.root;
this.config.entitiesDeleteEnabled = true;
this.config.tableTitle = this.configureTableTitle(ruleChainScope, null);
} else if (ruleChainScope === 'edge') {
this.config.entitySelectionEnabled = ruleChain => this.config.componentsData.edge.rootRuleChainId.id !== ruleChain.id.id;
this.edgeService.getEdge(edgeId).subscribe(edge => {
this.config.componentsData.edge = edge;
this.config.tableTitle = this.configureTableTitle(ruleChainScope, edge);
});
this.config.entitiesDeleteEnabled = false;
}
return this.config;
}
configureEntityTableColumns(ruleChainScope: string): Array<EntityColumn<RuleChain>> {
const columns: Array<EntityColumn<RuleChain>> = [];
columns.push(
new DateEntityTableColumn<RuleChain>('createdTime', 'common.created-time', this.datePipe, '150px'),
new EntityTableColumn<RuleChain>('name', 'rulechain.name', '100%')
);
if (ruleChainScope === 'tenant' || ruleChainScope === 'edge') {
columns.push(
new EntityTableColumn<RuleChain>('root', 'rulechain.root', '60px',
entity => {
if (ruleChainScope === 'edge') {
return checkBoxCell((this.config.componentsData.edge.rootRuleChainId.id === entity.id.id));
} else {
return checkBoxCell(entity.root);
}
})
);
} else if (ruleChainScope === 'edges') {
columns.push(
new EntityTableColumn<RuleChain>('root', 'rulechain.edge-template-root', '60px',
entity => {
return checkBoxCell(entity.root);
}),
new EntityTableColumn<RuleChain>('assignToEdge', 'rulechain.assign-to-edge', '60px',
entity => {
return checkBoxCell(this.isAutoAssignToEdgeRuleChain(entity));
})
);
}
return columns;
}
configureAddActions(ruleChainScope: string): Array<HeaderActionDescriptor> {
const actions: Array<HeaderActionDescriptor> = [];
if (ruleChainScope === 'tenant' || ruleChainScope === 'edges') {
actions.push(
{
name: this.translate.instant('rulechain.create-new-rulechain'),
icon: 'insert_drive_file',
isEnabled: () => true,
onAction: ($event) => this.config.table.addEntity($event)
},
{
name: this.translate.instant('rulechain.import'),
icon: 'file_upload',
isEnabled: () => true,
onAction: ($event) => this.importRuleChain($event)
}
);
}
if (ruleChainScope === 'edge') {
actions.push(
{
name: this.translate.instant('rulechain.assign-new-rulechain'),
icon: 'add',
isEnabled: () => true,
onAction: ($event) => this.addRuleChainsToEdge($event)
}
);
}
return actions;
}
configureEntityFunctions(ruleChainScope: string, edgeId: string): (pageLink) => Observable<PageData<RuleChain>> {
if (ruleChainScope === 'tenant') {
return pageLink => this.fetchRuleChains(pageLink);
} else if (ruleChainScope === 'edges') {
return pageLink => this.fetchEdgeRuleChains(pageLink);
} else if (ruleChainScope === 'edge') {
return pageLink => this.ruleChainService.getEdgeRuleChains(edgeId, pageLink);
}
}
configureTableTitle(ruleChainScope: string, edge: Edge): string {
if (ruleChainScope === 'tenant') {
return this.translate.instant('rulechain.rulechains');
} else if (ruleChainScope === 'edges') {
return this.translate.instant('edge.rulechain-templates');
} else if (ruleChainScope === 'edge') {
return this.config.tableTitle = edge.name + ': ' + this.translate.instant('edge.rulechains');
}
}
configureGroupActions(ruleChainScope: string): Array<GroupActionDescriptor<RuleChain>> {
const actions: Array<GroupActionDescriptor<RuleChain>> = [];
if (ruleChainScope === 'edge') {
actions.push(
{
name: this.translate.instant('rulechain.unassign-rulechains'),
icon: 'assignment_return',
isEnabled: true,
onAction: ($event, entities) => this.unassignRuleChainsFromEdge($event, entities)
}
);
}
return actions;
}
configureCellActions(ruleChainScope: string): Array<CellActionDescriptor<RuleChain>> {
const actions: Array<CellActionDescriptor<RuleChain>> = [];
actions.push(
{
name: this.translate.instant('rulechain.open-rulechain'),
icon: 'settings_ethernet',
isEnabled: () => true,
onAction: ($event, entity) => this.openRuleChain($event, entity)
},
{
name: this.translate.instant('rulechain.export'),
icon: 'file_download',
isEnabled: () => true,
onAction: ($event, entity) => this.exportRuleChain($event, entity)
}
);
if (ruleChainScope === 'tenant') {
actions.push(
{
name: this.translate.instant('rulechain.set-root'),
icon: 'flag',
isEnabled: (entity) => this.isNonRootRuleChain(entity),
onAction: ($event, entity) => this.setRootRuleChain($event, entity)
}
);
}
if (ruleChainScope === 'edges') {
actions.push(
{
name: this.translate.instant('rulechain.set-edge-template-root-rulechain'),
icon: 'flag',
isEnabled: (entity) => this.isNonRootRuleChain(entity),
onAction: ($event, entity) => this.setEdgeTemplateRootRuleChain($event, entity)
},
{
name: this.translate.instant('rulechain.set-auto-assign-to-edge'),
icon: 'bookmark_outline',
isEnabled: (entity) => this.isNotAutoAssignToEdgeRuleChain(entity),
onAction: ($event, entity) => this.setAutoAssignToEdgeRuleChain($event, entity)
},
{
name: this.translate.instant('rulechain.unset-auto-assign-to-edge'),
icon: 'bookmark',
isEnabled: (entity) => this.isAutoAssignToEdgeRuleChain(entity),
onAction: ($event, entity) => this.unsetAutoAssignToEdgeRuleChain($event, entity)
}
);
}
if (ruleChainScope === 'edge') {
actions.push(
{
name: this.translate.instant('rulechain.set-root'),
icon: 'flag',
isEnabled: (entity) => this.isNonRootRuleChain(entity),
onAction: ($event, entity) => this.setRootRuleChain($event, entity)
},
{
name: this.translate.instant('edge.unassign-from-edge'),
icon: 'assignment_return',
isEnabled: (entity) => entity.id.id !== this.config.componentsData.edge.rootRuleChainId.id,
onAction: ($event, entity) => this.unassignFromEdge($event, entity)
}
);
}
return actions;
}
importRuleChain($event: Event) {
if ($event) {
$event.stopPropagation();
}
const expectedRuleChainType = this.config.componentsData.ruleChainScope === 'tenant' ? RuleChainType.CORE : RuleChainType.EDGE;
this.importExport.importRuleChain(expectedRuleChainType).subscribe((ruleChainImport) => {
if (ruleChainImport) {
this.itembuffer.storeRuleChainImport(ruleChainImport);
if (this.config.componentsData.ruleChainScope === 'edges') {
this.router.navigateByUrl(`edgeManagement/ruleChains/ruleChain/import`);
} else {
this.router.navigateByUrl(`ruleChains/ruleChain/import`);
}
}
});
}
openRuleChain($event: Event, ruleChain: RuleChain) {
if ($event) {
$event.stopPropagation();
}
if (this.config.componentsData.ruleChainScope === 'edges') {
this.router.navigateByUrl(`edgeManagement/ruleChains/${ruleChain.id.id}`);
} else if (this.config.componentsData.ruleChainScope === 'edge') {
this.router.navigateByUrl(`edgeInstances/${this.config.componentsData.edgeId}/ruleChains/${ruleChain.id.id}`);
} else {
this.router.navigateByUrl(`ruleChains/${ruleChain.id.id}`);
}
}
saveRuleChain(ruleChain: RuleChain) {
if (isUndefined(ruleChain.type)) {
if (this.config.componentsData.ruleChainScope === 'tenant') {
ruleChain.type = RuleChainType.CORE;
} else if (this.config.componentsData.ruleChainScope === 'edges') {
ruleChain.type = RuleChainType.EDGE;
} else {
// safe fallback to default core type
ruleChain.type = RuleChainType.CORE;
}
}
return this.ruleChainService.saveRuleChain(ruleChain);
}
exportRuleChain($event: Event, ruleChain: RuleChain) {
if ($event) {
$event.stopPropagation();
}
this.importExport.exportRuleChain(ruleChain.id.id);
}
setRootRuleChain($event: Event, ruleChain: RuleChain) {
if ($event) {
$event.stopPropagation();
}
this.dialogService.confirm(
this.translate.instant('rulechain.set-root-rulechain-title', {ruleChainName: ruleChain.name}),
this.translate.instant('rulechain.set-root-rulechain-text'),
this.translate.instant('action.no'),
this.translate.instant('action.yes'),
true
).subscribe((res) => {
if (res) {
if (this.config.componentsData.ruleChainScope === 'edge') {
this.ruleChainService.setEdgeRootRuleChain(this.config.componentsData.edgeId, ruleChain.id.id).subscribe(
(edge) => {
this.config.componentsData.edge = edge;
this.config.table.updateData();
}
);
} else {
this.ruleChainService.setRootRuleChain(ruleChain.id.id).subscribe(
() => {
this.config.table.updateData();
}
);
}
}
}
);
}
onRuleChainAction(action: EntityAction<RuleChain>): boolean {
switch (action.action) {
case 'open':
this.openRuleChain(action.event, action.entity);
return true;
case 'export':
this.exportRuleChain(action.event, action.entity);
return true;
case 'setRoot':
this.setRootRuleChain(action.event, action.entity);
return true;
case 'setEdgeTemplateRoot':
this.setEdgeTemplateRootRuleChain(action.event, action.entity);
return true;
case 'unassignFromEdge':
this.unassignFromEdge(action.event, action.entity);
return true;
case 'setAutoAssignToEdge':
this.setAutoAssignToEdgeRuleChain(action.event, action.entity);
return true;
case 'unsetAutoAssignToEdge':
this.unsetAutoAssignToEdgeRuleChain(action.event, action.entity);
return true;
}
return false;
}
setEdgeTemplateRootRuleChain($event: Event, ruleChain: RuleChain) {
if ($event) {
$event.stopPropagation();
}
this.dialogService.confirm(
this.translate.instant('rulechain.set-edge-template-root-rulechain-title', {ruleChainName: ruleChain.name}),
this.translate.instant('rulechain.set-edge-template-root-rulechain-text'),
this.translate.instant('action.no'),
this.translate.instant('action.yes'),
true
).subscribe((res) => {
if (res) {
this.ruleChainService.setEdgeTemplateRootRuleChain(ruleChain.id.id).subscribe(
() => {
this.config.table.updateData();
}
);
}
}
);
}
addRuleChainsToEdge($event: Event) {
if ($event) {
$event.stopPropagation();
}
this.dialog.open<AddEntitiesToEdgeDialogComponent, AddEntitiesToEdgeDialogData,
boolean>(AddEntitiesToEdgeDialogComponent, {
disableClose: true,
panelClass: ['tb-dialog', 'tb-fullscreen-dialog'],
data: {
edgeId: this.config.componentsData.edgeId,
entityType: EntityType.RULE_CHAIN
}
}).afterClosed()
.subscribe((res) => {
if (res) {
this.edgeService.findMissingToRelatedRuleChains(this.config.componentsData.edgeId).subscribe(
(missingRuleChains) => {
if (missingRuleChains && Object.keys(missingRuleChains).length > 0) {
const formattedMissingRuleChains: Array<string> = new Array<string>();
for (const missingRuleChain of Object.keys(missingRuleChains)) {
const arrayOfMissingRuleChains = missingRuleChains[missingRuleChain];
const tmp = '- \'' + missingRuleChain + '\': \'' + arrayOfMissingRuleChains.join('\', ') + '\'';
formattedMissingRuleChains.push(tmp);
}
const message = this.translate.instant('edge.missing-related-rule-chains-text',
{missingRuleChains: formattedMissingRuleChains.join('<br>')});
this.dialogService.alert(this.translate.instant('edge.missing-related-rule-chains-title'),
message, this.translate.instant('action.close'), true).subscribe(
() => {
this.config.table.updateData();
}
);
} else {
this.config.table.updateData();
}
}
);
}
}
);
}
unassignFromEdge($event: Event, ruleChain: RuleChain) {
if ($event) {
$event.stopPropagation();
}
this.dialogService.confirm(
this.translate.instant('rulechain.unassign-rulechain-title', {ruleChainName: ruleChain.name}),
this.translate.instant('rulechain.unassign-rulechain-from-edge-text'),
this.translate.instant('action.no'),
this.translate.instant('action.yes'),
true
).subscribe((res) => {
if (res) {
this.ruleChainService.unassignRuleChainFromEdge(this.config.componentsData.edgeId, ruleChain.id.id).subscribe(
() => {
this.config.table.updateData();
}
);
}
}
);
}
unassignRuleChainsFromEdge($event: Event, ruleChains: Array<RuleChain>) {
if ($event) {
$event.stopPropagation();
}
this.dialogService.confirm(
this.translate.instant('rulechain.unassign-rulechains-from-edge-title', {count: ruleChains.length}),
this.translate.instant('rulechain.unassign-rulechains-from-edge-text'),
this.translate.instant('action.no'),
this.translate.instant('action.yes'),
true
).subscribe((res) => {
if (res) {
const tasks: Observable<any>[] = [];
ruleChains.forEach(
(ruleChain) => {
tasks.push(this.ruleChainService.unassignRuleChainFromEdge(this.config.componentsData.edgeId, ruleChain.id.id));
}
);
forkJoin(tasks).subscribe(
() => {
this.config.table.updateData();
}
);
}
}
);
}
setAutoAssignToEdgeRuleChain($event: Event, ruleChain: RuleChain) {
if ($event) {
$event.stopPropagation();
}
this.dialogService.confirm(
this.translate.instant('rulechain.set-auto-assign-to-edge-title', {ruleChainName: ruleChain.name}),
this.translate.instant('rulechain.set-auto-assign-to-edge-text'),
this.translate.instant('action.no'),
this.translate.instant('action.yes'),
true
).subscribe((res) => {
if (res) {
this.ruleChainService.setAutoAssignToEdgeRuleChain(ruleChain.id.id).subscribe(
() => {
this.config.table.updateData();
}
);
}
}
);
}
unsetAutoAssignToEdgeRuleChain($event: Event, ruleChain: RuleChain) {
if ($event) {
$event.stopPropagation();
}
this.dialogService.confirm(
this.translate.instant('rulechain.unset-auto-assign-to-edge-title', {ruleChainName: ruleChain.name}),
this.translate.instant('rulechain.unset-auto-assign-to-edge-text'),
this.translate.instant('action.no'),
this.translate.instant('action.yes'),
true
).subscribe((res) => {
if (res) {
this.ruleChainService.unsetAutoAssignToEdgeRuleChain(ruleChain.id.id).subscribe(
() => {
this.config.table.updateData();
}
);
}
}
);
}
isNonRootRuleChain(ruleChain: RuleChain) {
if (this.config.componentsData.ruleChainScope === 'edge') {
return this.config.componentsData.edge.rootRuleChainId &&
this.config.componentsData.edge.rootRuleChainId.id !== ruleChain.id.id;
}
return !ruleChain.root;
}
isAutoAssignToEdgeRuleChain(ruleChain) {
return !ruleChain.root && this.config.componentsData.autoAssignToEdgeRuleChainIds.includes(ruleChain.id.id);
}
isNotAutoAssignToEdgeRuleChain(ruleChain) {
return !ruleChain.root && !this.config.componentsData.autoAssignToEdgeRuleChainIds.includes(ruleChain.id.id);
}
fetchRuleChains(pageLink: PageLink) {
return this.ruleChainService.getRuleChains(pageLink, RuleChainType.CORE);
}
fetchEdgeRuleChains(pageLink: PageLink) {
return this.ruleChainService.getAutoAssignToEdgeRuleChains().pipe(
mergeMap((ruleChains) => {
this.config.componentsData.autoAssignToEdgeRuleChainIds = [];
ruleChains.map(ruleChain => this.config.componentsData.autoAssignToEdgeRuleChainIds.push(ruleChain.id.id));
return this.ruleChainService.getRuleChains(pageLink, RuleChainType.EDGE);
})
);
}
} | the_stack |
import * as assert from 'assert';
import * as path from 'path';
import * as fs from 'fs';
import * as MozSourceMap from 'source-map';
import * as testUtils from '../testUtils';
import { SourceMap } from '../../src/sourceMaps/sourceMap';
import { ISourceMapPathOverrides } from '../../src/debugAdapterInterfaces';
/**
* Unit tests for SourceMap + source-map (the mozilla lib). source-map is included in the test and not mocked
*/
suite('SourceMap', () => {
const GENERATED_PATH = testUtils.pathResolve('/project/src/app.js');
const WEBROOT = testUtils.pathResolve('/project');
const PATH_MAPPING = { '/': WEBROOT };
const SOURCEROOT = '/src/';
const SOURCES = [
'source1.ts',
'source2.ts'
];
const ABSOLUTE_SOURCES = SOURCES.map(source => {
// Join the path segments, then resolve to force proper slashes
return testUtils.pathResolve(
path.join(WEBROOT, SOURCEROOT, source));
});
// Load out.js.map, which should be copied to this folder under 'out' by the build process
const SOURCEMAP_MAPPINGS_JSON = fs.readFileSync(
path.resolve(__dirname, 'testData/app.js.map')
).toString();
setup(() => {
testUtils.setupUnhandledRejectionListener();
});
teardown(() => {
testUtils.removeUnhandledRejectionListener();
});
suite('constructor', () => {
test('does not crash when sourceRoot is undefined', () => {
// Rare and possibly invalid, but I saw it
const sourceMapJSON = getMockSourceMapJSON(SOURCES, undefined);
const sm = new SourceMap(GENERATED_PATH, sourceMapJSON, PATH_MAPPING);
assert(sm);
});
});
suite('.sources', () => {
test('relative sources are made absolute', () => {
const sourceMapJSON = getMockSourceMapJSON(SOURCES, SOURCEROOT);
const sm = new SourceMap(GENERATED_PATH, sourceMapJSON, PATH_MAPPING);
assert.deepEqual(sm.authoredSources, ABSOLUTE_SOURCES);
});
test('sources with absolute paths are used as-is', () => {
const sourceMapJSON = getMockSourceMapJSON(ABSOLUTE_SOURCES, SOURCEROOT);
const sm = new SourceMap(GENERATED_PATH, sourceMapJSON, PATH_MAPPING);
assert.deepEqual(sm.authoredSources, ABSOLUTE_SOURCES);
});
test('file:/// sources are exposed as absolute paths', () => {
const fileSources = ABSOLUTE_SOURCES.map(source => 'file:///' + source);
const sourceMapJSON = getMockSourceMapJSON(fileSources, SOURCEROOT);
const sm = new SourceMap(GENERATED_PATH, sourceMapJSON, PATH_MAPPING);
assert.deepEqual(sm.authoredSources, ABSOLUTE_SOURCES);
});
test('sourceMapPathOverrides are respected', () => {
const sourceMapJSON = getMockSourceMapJSON(SOURCES, SOURCEROOT);
const sm = new SourceMap(GENERATED_PATH, sourceMapJSON, PATH_MAPPING, <ISourceMapPathOverrides>{ '/src/*': testUtils.pathResolve('/project/client/*') });
const expectedSources = SOURCES.map(sourcePath => path.join(testUtils.pathResolve('/project/client'), sourcePath));
assert.deepEqual(sm.authoredSources, expectedSources);
});
});
suite('doesOriginateFrom', () => {
test('returns true for a source that it contains', () => {
const sourceMapJSON = getMockSourceMapJSON(ABSOLUTE_SOURCES, SOURCEROOT);
const sm = new SourceMap(GENERATED_PATH, sourceMapJSON, PATH_MAPPING);
assert(sm.doesOriginateFrom(ABSOLUTE_SOURCES[0]));
});
test('returns false for a source that it does not contain', () => {
const sourceMapJSON = getMockSourceMapJSON(ABSOLUTE_SOURCES, SOURCEROOT);
const sm = new SourceMap(GENERATED_PATH, sourceMapJSON, PATH_MAPPING);
assert(!sm.doesOriginateFrom('c:\\fake\\file.js'));
});
});
suite('originalPositionFor', () => {
let sm: SourceMap;
setup(() => {
sm = new SourceMap(GENERATED_PATH, SOURCEMAP_MAPPINGS_JSON, PATH_MAPPING);
});
function getExpectedResult(line: number, column: number, source = ABSOLUTE_SOURCES[0]): MozSourceMap.MappedPosition {
return {
line,
column,
name: null,
source
};
}
test('return statement', () => {
assert.deepEqual(
sm.authoredPositionFor(/*line=*/11, /*column=*/0),
getExpectedResult(/*line=*/13, /*column=*/8));
assert.deepEqual(
sm.authoredPositionFor(/*line=*/11, /*column=*/8),
getExpectedResult(/*line=*/13, /*column=*/8));
assert.deepEqual(
sm.authoredPositionFor(/*line=*/11, /*column=*/17),
getExpectedResult(/*line=*/13, /*column=*/17));
});
test('first line of a method', () => {
// 'let x = ...'
assert.deepEqual(
sm.authoredPositionFor(/*line=*/9, /*column=*/0),
getExpectedResult(/*line=*/11, /*column=*/8));
assert.deepEqual(
sm.authoredPositionFor(/*line=*/9, /*column=*/8),
getExpectedResult(/*line=*/11, /*column=*/8));
assert.deepEqual(
sm.authoredPositionFor(/*line=*/9, /*column=*/12),
getExpectedResult(/*line=*/11, /*column=*/12));
});
test('private field initializer', () => {
// 'private _x = ...'
assert.deepEqual(
sm.authoredPositionFor(/*line=*/5, /*column=*/0),
getExpectedResult(/*line=*/4, /*column=*/12));
assert.deepEqual(
sm.authoredPositionFor(/*line=*/5, /*column=*/4),
getExpectedResult(/*line=*/4, /*column=*/12));
assert.deepEqual(
sm.authoredPositionFor(/*line=*/5, /*column=*/17),
getExpectedResult(/*line=*/4, /*column=*/14));
});
test('first line of file', () => {
const expected = getExpectedResult(/*line=*/0, /*column=*/0, ABSOLUTE_SOURCES[1]);
// 'function f() { ...'
assert.deepEqual(
sm.authoredPositionFor(/*line=*/18, /*column=*/0),
expected);
assert.deepEqual(
sm.authoredPositionFor(/*line=*/18, /*column=*/9),
expected);
assert.deepEqual(
sm.authoredPositionFor(/*line=*/18, /*column=*/14),
expected);
});
test('last line of file', () => {
// 'f();'
assert.deepEqual(
sm.authoredPositionFor(/*line=*/22, /*column=*/0),
getExpectedResult(/*line=*/5, /*column=*/0, ABSOLUTE_SOURCES[1]));
assert.deepEqual(
sm.authoredPositionFor(/*line=*/22, /*column=*/1),
getExpectedResult(/*line=*/5, /*column=*/1, ABSOLUTE_SOURCES[1]));
assert.deepEqual(
sm.authoredPositionFor(/*line=*/22, /*column=*/5),
getExpectedResult(/*line=*/5, /*column=*/4, ABSOLUTE_SOURCES[1]));
});
test('return null when there is no matching mapping', () => {
assert.deepEqual(
sm.authoredPositionFor(/*line=*/1000, /*column=*/0),
null);
});
});
suite('generatedPositionFor', () => {
let sm: SourceMap;
setup(() => {
sm = new SourceMap(GENERATED_PATH, SOURCEMAP_MAPPINGS_JSON, PATH_MAPPING);
});
function getExpectedResult(line: number, column: number): MozSourceMap.Position {
return <any>{
line,
column,
source: GENERATED_PATH
};
}
test('return statement', () => {
assert.deepEqual(
sm.generatedPositionFor(ABSOLUTE_SOURCES[0], /*line=*/13, /*column=*/0),
getExpectedResult(/*line=*/11, /*column=*/8));
assert.deepEqual(
sm.generatedPositionFor(ABSOLUTE_SOURCES[0], /*line=*/13, /*column=*/8),
getExpectedResult(/*line=*/11, /*column=*/8));
assert.deepEqual(
sm.generatedPositionFor(ABSOLUTE_SOURCES[0], /*line=*/13, /*column=*/17),
getExpectedResult(/*line=*/11, /*column=*/17));
});
test('first line of a method', () => {
// 'let x = ...'
assert.deepEqual(
sm.generatedPositionFor(ABSOLUTE_SOURCES[0], /*line=*/11, /*column=*/0),
getExpectedResult(/*line=*/9, /*column=*/8));
assert.deepEqual(
sm.generatedPositionFor(ABSOLUTE_SOURCES[0], /*line=*/11, /*column=*/8),
getExpectedResult(/*line=*/9, /*column=*/8));
assert.deepEqual(
sm.generatedPositionFor(ABSOLUTE_SOURCES[0], /*line=*/11, /*column=*/19),
getExpectedResult(/*line=*/9, /*column=*/20));
});
test('private field initializer', () => {
// 'private _x = ...'
assert.deepEqual(
sm.generatedPositionFor(ABSOLUTE_SOURCES[0], /*line=*/4, /*column=*/0),
getExpectedResult(/*line=*/5, /*column=*/8));
assert.deepEqual(
sm.generatedPositionFor(ABSOLUTE_SOURCES[0], /*line=*/4, /*column=*/4),
getExpectedResult(/*line=*/5, /*column=*/8));
assert.deepEqual(
sm.generatedPositionFor(ABSOLUTE_SOURCES[0], /*line=*/4, /*column=*/20),
getExpectedResult(/*line=*/5, /*column=*/18));
});
test('first line of file', () => {
// 'function f() { ...'
assert.deepEqual(
sm.generatedPositionFor(ABSOLUTE_SOURCES[1], /*line=*/0, /*column=*/0),
getExpectedResult(/*line=*/18, /*column=*/0));
// This line only has one mapping, so a non-0 column ends up mapped to the next line.
// I think this needs a fix but at the moment there is no scenario where this is called with
// a non-0 column.
assert.deepEqual(
sm.generatedPositionFor(ABSOLUTE_SOURCES[1], /*line=*/0, /*column=*/1),
getExpectedResult(/*line=*/19, /*column=*/4));
assert.deepEqual(
sm.generatedPositionFor(ABSOLUTE_SOURCES[1], /*line=*/0, /*column=*/14),
getExpectedResult(/*line=*/19, /*column=*/4));
});
test('last line of file', () => {
// 'f();'
assert.deepEqual(
sm.generatedPositionFor(ABSOLUTE_SOURCES[1], /*line=*/5, /*column=*/0),
getExpectedResult(/*line=*/22, /*column=*/0));
assert.deepEqual(
sm.generatedPositionFor(ABSOLUTE_SOURCES[1], /*line=*/5, /*column=*/1),
getExpectedResult(/*line=*/22, /*column=*/1));
assert.deepEqual(
sm.generatedPositionFor(ABSOLUTE_SOURCES[1], /*line=*/5, /*column=*/5),
getExpectedResult(/*line=*/22, /*column=*/4));
});
// Discrepency with originalPositionFor bc that's the way the source-map lib works.
// Not sure whether there's a good reason for that.
test('returns the last mapping when there is no matching mapping', () => {
assert.deepEqual(
sm.generatedPositionFor(ABSOLUTE_SOURCES[0], /*line=*/1000, /*column=*/0),
getExpectedResult(/*line=*/17, /*column=*/1));
});
});
});
function getMockSourceMapJSON(sources: string[], sourceRoot?: string): string {
return JSON.stringify({
sources,
sourceRoot,
version: 3,
mappings: []
});
} | the_stack |
import { sortUnique, anyToString } from "../src/util";
import { NodeLabel } from "./node-label";
function sourcePositionLe(a, b) {
if (a.inliningId == b.inliningId) {
return a.scriptOffset - b.scriptOffset;
}
return a.inliningId - b.inliningId;
}
function sourcePositionEq(a, b) {
return a.inliningId == b.inliningId &&
a.scriptOffset == b.scriptOffset;
}
export function sourcePositionToStringKey(sourcePosition: AnyPosition): string {
if (!sourcePosition) return "undefined";
if ('inliningId' in sourcePosition && 'scriptOffset' in sourcePosition) {
return "SP:" + sourcePosition.inliningId + ":" + sourcePosition.scriptOffset;
}
if (sourcePosition.bytecodePosition) {
return "BCP:" + sourcePosition.bytecodePosition;
}
return "undefined";
}
export function sourcePositionValid(l) {
return (typeof l.scriptOffset !== undefined
&& typeof l.inliningId !== undefined) || typeof l.bytecodePosition != undefined;
}
export interface SourcePosition {
scriptOffset: number;
inliningId: number;
}
interface TurboFanOrigin {
phase: string;
reducer: string;
}
export interface NodeOrigin {
nodeId: number;
}
interface BytecodePosition {
bytecodePosition: number;
}
export type Origin = NodeOrigin | BytecodePosition;
export type TurboFanNodeOrigin = NodeOrigin & TurboFanOrigin;
export type TurboFanBytecodeOrigin = BytecodePosition & TurboFanOrigin;
type AnyPosition = SourcePosition | BytecodePosition;
export interface Source {
sourcePositions: Array<SourcePosition>;
sourceName: string;
functionName: string;
sourceText: string;
sourceId: number;
startPosition?: number;
backwardsCompatibility: boolean;
}
interface Inlining {
inliningPosition: SourcePosition;
sourceId: number;
}
interface OtherPhase {
type: "disassembly" | "sequence" | "schedule";
name: string;
data: any;
}
interface InstructionsPhase {
type: "instructions";
name: string;
data: any;
instructionOffsetToPCOffset?: any;
blockIdtoInstructionRange?: any;
nodeIdToInstructionRange?: any;
codeOffsetsInfo?: CodeOffsetsInfo;
}
interface GraphPhase {
type: "graph";
name: string;
data: any;
highestNodeId: number;
nodeLabelMap: Array<NodeLabel>;
}
type Phase = GraphPhase | InstructionsPhase | OtherPhase;
export interface Schedule {
nodes: Array<any>;
}
export class Interval {
start: number;
end: number;
constructor(numbers: [number, number]) {
this.start = numbers[0];
this.end = numbers[1];
}
}
export interface ChildRange {
id: string;
type: string;
op: any;
intervals: Array<[number, number]>;
uses: Array<number>;
}
export interface Range {
child_ranges: Array<ChildRange>;
is_deferred: boolean;
}
export class RegisterAllocation {
fixedDoubleLiveRanges: Map<string, Range>;
fixedLiveRanges: Map<string, Range>;
liveRanges: Map<string, Range>;
constructor(registerAllocation) {
this.fixedDoubleLiveRanges = new Map<string, Range>(Object.entries(registerAllocation.fixed_double_live_ranges));
this.fixedLiveRanges = new Map<string, Range>(Object.entries(registerAllocation.fixed_live_ranges));
this.liveRanges = new Map<string, Range>(Object.entries(registerAllocation.live_ranges));
}
}
export interface Sequence {
blocks: Array<any>;
register_allocation: RegisterAllocation;
}
class CodeOffsetsInfo {
codeStartRegisterCheck: number;
deoptCheck: number;
initPoison: number;
blocksStart: number;
outOfLineCode: number;
deoptimizationExits: number;
pools: number;
jumpTables: number;
}
export class TurbolizerInstructionStartInfo {
gap: number;
arch: number;
condition: number;
}
export class SourceResolver {
nodePositionMap: Array<AnyPosition>;
sources: Array<Source>;
inlinings: Array<Inlining>;
inliningsMap: Map<string, Inlining>;
positionToNodes: Map<string, Array<string>>;
phases: Array<Phase>;
phaseNames: Map<string, number>;
disassemblyPhase: Phase;
lineToSourcePositions: Map<string, Array<AnyPosition>>;
nodeIdToInstructionRange: Array<[number, number]>;
blockIdToInstructionRange: Array<[number, number]>;
instructionToPCOffset: Array<TurbolizerInstructionStartInfo>;
pcOffsetToInstructions: Map<number, Array<number>>;
pcOffsets: Array<number>;
blockIdToPCOffset: Array<number>;
blockStartPCtoBlockIds: Map<number, Array<number>>;
codeOffsetsInfo: CodeOffsetsInfo;
constructor() {
// Maps node ids to source positions.
this.nodePositionMap = [];
// Maps source ids to source objects.
this.sources = [];
// Maps inlining ids to inlining objects.
this.inlinings = [];
// Maps source position keys to inlinings.
this.inliningsMap = new Map();
// Maps source position keys to node ids.
this.positionToNodes = new Map();
// Maps phase ids to phases.
this.phases = [];
// Maps phase names to phaseIds.
this.phaseNames = new Map();
// The disassembly phase is stored separately.
this.disassemblyPhase = undefined;
// Maps line numbers to source positions
this.lineToSourcePositions = new Map();
// Maps node ids to instruction ranges.
this.nodeIdToInstructionRange = [];
// Maps block ids to instruction ranges.
this.blockIdToInstructionRange = [];
// Maps instruction numbers to PC offsets.
this.instructionToPCOffset = [];
// Maps PC offsets to instructions.
this.pcOffsetToInstructions = new Map();
this.pcOffsets = [];
this.blockIdToPCOffset = [];
this.blockStartPCtoBlockIds = new Map();
this.codeOffsetsInfo = null;
}
getBlockIdsForOffset(offset): Array<number> {
return this.blockStartPCtoBlockIds.get(offset);
}
hasBlockStartInfo() {
return this.blockIdToPCOffset.length > 0;
}
setSources(sources, mainBackup) {
if (sources) {
for (const [sourceId, source] of Object.entries(sources)) {
this.sources[sourceId] = source;
this.sources[sourceId].sourcePositions = [];
}
}
// This is a fallback if the JSON is incomplete (e.g. due to compiler crash).
if (!this.sources[-1]) {
this.sources[-1] = mainBackup;
this.sources[-1].sourcePositions = [];
}
}
setInlinings(inlinings) {
if (inlinings) {
for (const [inliningId, inlining] of Object.entries<Inlining>(inlinings)) {
this.inlinings[inliningId] = inlining;
this.inliningsMap.set(sourcePositionToStringKey(inlining.inliningPosition), inlining);
}
}
// This is a default entry for the script itself that helps
// keep other code more uniform.
this.inlinings[-1] = { sourceId: -1, inliningPosition: null };
}
setNodePositionMap(map) {
if (!map) return;
if (typeof map[0] != 'object') {
const alternativeMap = {};
for (const [nodeId, scriptOffset] of Object.entries<number>(map)) {
alternativeMap[nodeId] = { scriptOffset: scriptOffset, inliningId: -1 };
}
map = alternativeMap;
}
for (const [nodeId, sourcePosition] of Object.entries<SourcePosition>(map)) {
if (sourcePosition == undefined) {
console.log("Warning: undefined source position ", sourcePosition, " for nodeId ", nodeId);
}
const inliningId = sourcePosition.inliningId;
const inlining = this.inlinings[inliningId];
if (inlining) {
const sourceId = inlining.sourceId;
this.sources[sourceId].sourcePositions.push(sourcePosition);
}
this.nodePositionMap[nodeId] = sourcePosition;
const key = sourcePositionToStringKey(sourcePosition);
if (!this.positionToNodes.has(key)) {
this.positionToNodes.set(key, []);
}
this.positionToNodes.get(key).push(nodeId);
}
for (const [, source] of Object.entries(this.sources)) {
source.sourcePositions = sortUnique(source.sourcePositions,
sourcePositionLe, sourcePositionEq);
}
}
sourcePositionsToNodeIds(sourcePositions) {
const nodeIds = new Set();
for (const sp of sourcePositions) {
const key = sourcePositionToStringKey(sp);
const nodeIdsForPosition = this.positionToNodes.get(key);
if (!nodeIdsForPosition) continue;
for (const nodeId of nodeIdsForPosition) {
nodeIds.add(nodeId);
}
}
return nodeIds;
}
nodeIdsToSourcePositions(nodeIds): Array<AnyPosition> {
const sourcePositions = new Map();
for (const nodeId of nodeIds) {
const sp = this.nodePositionMap[nodeId];
const key = sourcePositionToStringKey(sp);
sourcePositions.set(key, sp);
}
const sourcePositionArray = [];
for (const sp of sourcePositions.values()) {
sourcePositionArray.push(sp);
}
return sourcePositionArray;
}
forEachSource(f: (value: Source, index: number, array: Array<Source>) => void) {
this.sources.forEach(f);
}
translateToSourceId(sourceId: number, location?: SourcePosition) {
for (const position of this.getInlineStack(location)) {
const inlining = this.inlinings[position.inliningId];
if (!inlining) continue;
if (inlining.sourceId == sourceId) {
return position;
}
}
return location;
}
addInliningPositions(sourcePosition: AnyPosition, locations: Array<SourcePosition>) {
const inlining = this.inliningsMap.get(sourcePositionToStringKey(sourcePosition));
if (!inlining) return;
const sourceId = inlining.sourceId;
const source = this.sources[sourceId];
for (const sp of source.sourcePositions) {
locations.push(sp);
this.addInliningPositions(sp, locations);
}
}
getInliningForPosition(sourcePosition: AnyPosition) {
return this.inliningsMap.get(sourcePositionToStringKey(sourcePosition));
}
getSource(sourceId: number) {
return this.sources[sourceId];
}
getSourceName(sourceId: number) {
const source = this.sources[sourceId];
return `${source.sourceName}:${source.functionName}`;
}
sourcePositionFor(sourceId: number, scriptOffset: number) {
if (!this.sources[sourceId]) {
return null;
}
const list = this.sources[sourceId].sourcePositions;
for (let i = 0; i < list.length; i++) {
const sourcePosition = list[i];
const position = sourcePosition.scriptOffset;
const nextPosition = list[Math.min(i + 1, list.length - 1)].scriptOffset;
if ((position <= scriptOffset && scriptOffset < nextPosition)) {
return sourcePosition;
}
}
return null;
}
sourcePositionsInRange(sourceId: number, start: number, end: number) {
if (!this.sources[sourceId]) return [];
const res = [];
const list = this.sources[sourceId].sourcePositions;
for (const sourcePosition of list) {
if (start <= sourcePosition.scriptOffset && sourcePosition.scriptOffset < end) {
res.push(sourcePosition);
}
}
return res;
}
getInlineStack(sourcePosition?: SourcePosition) {
if (!sourcePosition) return [];
const inliningStack = [];
let cur = sourcePosition;
while (cur && cur.inliningId != -1) {
inliningStack.push(cur);
const inlining = this.inlinings[cur.inliningId];
if (!inlining) {
break;
}
cur = inlining.inliningPosition;
}
if (cur && cur.inliningId == -1) {
inliningStack.push(cur);
}
return inliningStack;
}
recordOrigins(phase: GraphPhase) {
if (phase.type != "graph") return;
for (const node of phase.data.nodes) {
phase.highestNodeId = Math.max(phase.highestNodeId, node.id);
if (node.origin != undefined &&
node.origin.bytecodePosition != undefined) {
const position = { bytecodePosition: node.origin.bytecodePosition };
this.nodePositionMap[node.id] = position;
const key = sourcePositionToStringKey(position);
if (!this.positionToNodes.has(key)) {
this.positionToNodes.set(key, []);
}
const A = this.positionToNodes.get(key);
if (!A.includes(node.id)) A.push(`${node.id}`);
}
// Backwards compatibility.
if (typeof node.pos === "number") {
node.sourcePosition = { scriptOffset: node.pos, inliningId: -1 };
}
}
}
readNodeIdToInstructionRange(nodeIdToInstructionRange) {
for (const [nodeId, range] of Object.entries<[number, number]>(nodeIdToInstructionRange)) {
this.nodeIdToInstructionRange[nodeId] = range;
}
}
readBlockIdToInstructionRange(blockIdToInstructionRange) {
for (const [blockId, range] of Object.entries<[number, number]>(blockIdToInstructionRange)) {
this.blockIdToInstructionRange[blockId] = range;
}
}
getInstruction(nodeId: number): [number, number] {
const X = this.nodeIdToInstructionRange[nodeId];
if (X === undefined) return [-1, -1];
return X;
}
getInstructionRangeForBlock(blockId: number): [number, number] {
const X = this.blockIdToInstructionRange[blockId];
if (X === undefined) return [-1, -1];
return X;
}
readInstructionOffsetToPCOffset(instructionToPCOffset) {
for (const [instruction, numberOrInfo] of Object.entries<number | TurbolizerInstructionStartInfo>(instructionToPCOffset)) {
let info: TurbolizerInstructionStartInfo;
if (typeof numberOrInfo == "number") {
info = { gap: numberOrInfo, arch: numberOrInfo, condition: numberOrInfo };
} else {
info = numberOrInfo;
}
this.instructionToPCOffset[instruction] = info;
if (!this.pcOffsetToInstructions.has(info.gap)) {
this.pcOffsetToInstructions.set(info.gap, []);
}
this.pcOffsetToInstructions.get(info.gap).push(Number(instruction));
}
this.pcOffsets = Array.from(this.pcOffsetToInstructions.keys()).sort((a, b) => b - a);
}
hasPCOffsets() {
return this.pcOffsetToInstructions.size > 0;
}
getKeyPcOffset(offset: number): number {
if (this.pcOffsets.length === 0) return -1;
for (const key of this.pcOffsets) {
if (key <= offset) {
return key;
}
}
return -1;
}
getInstructionKindForPCOffset(offset: number) {
if (this.codeOffsetsInfo) {
if (offset >= this.codeOffsetsInfo.deoptimizationExits) {
if (offset >= this.codeOffsetsInfo.pools) {
return "pools";
} else if (offset >= this.codeOffsetsInfo.jumpTables) {
return "jump-tables";
} else {
return "deoptimization-exits";
}
}
if (offset < this.codeOffsetsInfo.deoptCheck) {
return "code-start-register";
} else if (offset < this.codeOffsetsInfo.initPoison) {
return "deopt-check";
} else if (offset < this.codeOffsetsInfo.blocksStart) {
return "init-poison";
}
}
const keyOffset = this.getKeyPcOffset(offset);
if (keyOffset != -1) {
const infos = this.pcOffsetToInstructions.get(keyOffset).map(instrId => this.instructionToPCOffset[instrId]).filter(info => info.gap != info.condition);
if (infos.length > 0) {
const info = infos[0];
if (!info || info.gap == info.condition) return "unknown";
if (offset < info.arch) return "gap";
if (offset < info.condition) return "arch";
return "condition";
}
}
return "unknown";
}
instructionKindToReadableName(instructionKind) {
switch (instructionKind) {
case "code-start-register": return "Check code register for right value";
case "deopt-check": return "Check if function was marked for deoptimization";
case "init-poison": return "Initialization of poison register";
case "gap": return "Instruction implementing a gap move";
case "arch": return "Instruction implementing the actual machine operation";
case "condition": return "Code implementing conditional after instruction";
case "pools": return "Data in a pool (e.g. constant pool)";
case "jump-tables": return "Part of a jump table";
case "deoptimization-exits": return "Jump to deoptimization exit";
}
return null;
}
instructionRangeToKeyPcOffsets([start, end]: [number, number]): Array<TurbolizerInstructionStartInfo> {
if (start == end) return [this.instructionToPCOffset[start]];
return this.instructionToPCOffset.slice(start, end);
}
instructionToPcOffsets(instr: number): TurbolizerInstructionStartInfo {
return this.instructionToPCOffset[instr];
}
instructionsToKeyPcOffsets(instructionIds: Iterable<number>): Array<number> {
const keyPcOffsets = [];
for (const instructionId of instructionIds) {
keyPcOffsets.push(this.instructionToPCOffset[instructionId].gap);
}
return keyPcOffsets;
}
nodesToKeyPcOffsets(nodes) {
let offsets = [];
for (const node of nodes) {
const range = this.nodeIdToInstructionRange[node];
if (!range) continue;
offsets = offsets.concat(this.instructionRangeToKeyPcOffsets(range));
}
return offsets;
}
nodesForPCOffset(offset: number): [Array<string>, Array<string>] {
if (this.pcOffsets.length === 0) return [[], []];
for (const key of this.pcOffsets) {
if (key <= offset) {
const instrs = this.pcOffsetToInstructions.get(key);
const nodes = [];
const blocks = [];
for (const instr of instrs) {
for (const [nodeId, range] of this.nodeIdToInstructionRange.entries()) {
if (!range) continue;
const [start, end] = range;
if (start == end && instr == start) {
nodes.push("" + nodeId);
}
if (start <= instr && instr < end) {
nodes.push("" + nodeId);
}
}
}
return [nodes, blocks];
}
}
return [[], []];
}
parsePhases(phases) {
const nodeLabelMap = [];
for (const [, phase] of Object.entries<Phase>(phases)) {
switch (phase.type) {
case 'disassembly':
this.disassemblyPhase = phase;
if (phase['blockIdToOffset']) {
for (const [blockId, pc] of Object.entries<number>(phase['blockIdToOffset'])) {
this.blockIdToPCOffset[blockId] = pc;
if (!this.blockStartPCtoBlockIds.has(pc)) {
this.blockStartPCtoBlockIds.set(pc, []);
}
this.blockStartPCtoBlockIds.get(pc).push(Number(blockId));
}
}
break;
case 'schedule':
this.phaseNames.set(phase.name, this.phases.length);
this.phases.push(this.parseSchedule(phase));
break;
case 'sequence':
this.phaseNames.set(phase.name, this.phases.length);
this.phases.push(this.parseSequence(phase));
break;
case 'instructions':
if (phase.nodeIdToInstructionRange) {
this.readNodeIdToInstructionRange(phase.nodeIdToInstructionRange);
}
if (phase.blockIdtoInstructionRange) {
this.readBlockIdToInstructionRange(phase.blockIdtoInstructionRange);
}
if (phase.instructionOffsetToPCOffset) {
this.readInstructionOffsetToPCOffset(phase.instructionOffsetToPCOffset);
}
if (phase.codeOffsetsInfo) {
this.codeOffsetsInfo = phase.codeOffsetsInfo;
}
break;
case 'graph':
const graphPhase: GraphPhase = Object.assign(phase, { highestNodeId: 0 });
this.phaseNames.set(graphPhase.name, this.phases.length);
this.phases.push(graphPhase);
this.recordOrigins(graphPhase);
this.internNodeLabels(graphPhase, nodeLabelMap);
graphPhase.nodeLabelMap = nodeLabelMap.slice();
break;
default:
throw "Unsupported phase type";
}
}
}
internNodeLabels(phase: GraphPhase, nodeLabelMap: Array<NodeLabel>) {
for (const n of phase.data.nodes) {
const label = new NodeLabel(n.id, n.label, n.title, n.live,
n.properties, n.sourcePosition, n.origin, n.opcode, n.control,
n.opinfo, n.type);
const previous = nodeLabelMap[label.id];
if (!label.equals(previous)) {
if (previous != undefined) {
label.setInplaceUpdatePhase(phase.name);
}
nodeLabelMap[label.id] = label;
}
n.nodeLabel = nodeLabelMap[label.id];
}
}
repairPhaseId(anyPhaseId) {
return Math.max(0, Math.min(anyPhaseId | 0, this.phases.length - 1));
}
getPhase(phaseId: number) {
return this.phases[phaseId];
}
getPhaseIdByName(phaseName: string) {
return this.phaseNames.get(phaseName);
}
forEachPhase(f: (value: Phase, index: number, array: Array<Phase>) => void) {
this.phases.forEach(f);
}
addAnyPositionToLine(lineNumber: number | string, sourcePosition: AnyPosition) {
const lineNumberString = anyToString(lineNumber);
if (!this.lineToSourcePositions.has(lineNumberString)) {
this.lineToSourcePositions.set(lineNumberString, []);
}
const A = this.lineToSourcePositions.get(lineNumberString);
if (!A.includes(sourcePosition)) A.push(sourcePosition);
}
setSourceLineToBytecodePosition(sourceLineToBytecodePosition: Array<number> | undefined) {
if (!sourceLineToBytecodePosition) return;
sourceLineToBytecodePosition.forEach((pos, i) => {
this.addAnyPositionToLine(i, { bytecodePosition: pos });
});
}
linetoSourcePositions(lineNumber: number | string) {
const positions = this.lineToSourcePositions.get(anyToString(lineNumber));
if (positions === undefined) return [];
return positions;
}
parseSchedule(phase) {
function createNode(state: any, match) {
let inputs = [];
if (match.groups.args) {
const nodeIdsString = match.groups.args.replace(/\s/g, '');
const nodeIdStrings = nodeIdsString.split(',');
inputs = nodeIdStrings.map(n => Number.parseInt(n, 10));
}
const node = {
id: Number.parseInt(match.groups.id, 10),
label: match.groups.label,
inputs: inputs
};
if (match.groups.blocks) {
const nodeIdsString = match.groups.blocks.replace(/\s/g, '').replace(/B/g, '');
const nodeIdStrings = nodeIdsString.split(',');
const successors = nodeIdStrings.map(n => Number.parseInt(n, 10));
state.currentBlock.succ = successors;
}
state.nodes[node.id] = node;
state.currentBlock.nodes.push(node);
}
function createBlock(state, match) {
let predecessors = [];
if (match.groups.in) {
const blockIdsString = match.groups.in.replace(/\s/g, '').replace(/B/g, '');
const blockIdStrings = blockIdsString.split(',');
predecessors = blockIdStrings.map(n => Number.parseInt(n, 10));
}
const block = {
id: Number.parseInt(match.groups.id, 10),
isDeferred: match.groups.deferred != undefined,
pred: predecessors.sort(),
succ: [],
nodes: []
};
state.blocks[block.id] = block;
state.currentBlock = block;
}
function setGotoSuccessor(state, match) {
state.currentBlock.succ = [Number.parseInt(match.groups.successor.replace(/\s/g, ''), 10)];
}
const rules = [
{
lineRegexps:
[/^\s*(?<id>\d+):\ (?<label>.*)\((?<args>.*)\)$/,
/^\s*(?<id>\d+):\ (?<label>.*)\((?<args>.*)\)\ ->\ (?<blocks>.*)$/,
/^\s*(?<id>\d+):\ (?<label>.*)$/
],
process: createNode
},
{
lineRegexps:
[/^\s*---\s*BLOCK\ B(?<id>\d+)\s*(?<deferred>\(deferred\))?(\ <-\ )?(?<in>[^-]*)?\ ---$/
],
process: createBlock
},
{
lineRegexps:
[/^\s*Goto\s*->\s*B(?<successor>\d+)\s*$/
],
process: setGotoSuccessor
}
];
const lines = phase.data.split(/[\n]/);
const state = { currentBlock: undefined, blocks: [], nodes: [] };
nextLine:
for (const line of lines) {
for (const rule of rules) {
for (const lineRegexp of rule.lineRegexps) {
const match = line.match(lineRegexp);
if (match) {
rule.process(state, match);
continue nextLine;
}
}
}
console.log("Warning: unmatched schedule line \"" + line + "\"");
}
phase.schedule = state;
return phase;
}
parseSequence(phase) {
phase.sequence = { blocks: phase.blocks,
register_allocation: phase.register_allocation ? new RegisterAllocation(phase.register_allocation)
: undefined };
return phase;
}
} | the_stack |
import { stringify } from 'querystring';
import { Url } from 'url';
/* --------------------------------------------------------------------------------------------
* Copyright for portions from https://github.com/microsoft/vscode-extension-samples/tree/master/lsp-sample
* are held by (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
* Copyright (c) 2020 Eric Lau. All rights reserved.
* Licensed under the Eclipse Public License v2.0
*
* Copyright (c) 2021 Reach Platform, Inc. All rights reserved.
* Licensed under the Eclipse Public License v2.0
* ------------------------------------------------------------------------------------------ */
import {
TextDocuments,
Diagnostic,
DiagnosticSeverity,
ProposedFeatures,
InitializeParams,
DidChangeConfigurationNotification,
CompletionItem,
CompletionItemKind,
TextDocumentPositionParams,
TextDocumentSyncKind,
InitializeResult,
CodeAction,
CodeActionKind,
CodeActionParams,
CodeActionContext,
WorkspaceEdit,
HoverParams,
Hover,
} from 'vscode-languageserver';
// edit env variable to track extension usage; see
// https://nodejs.org/api/process.html#processenv
import { env } from "process";
env.REACH_IDE = "1";
// Do this import from vscode-languageserver/node instead of
// vscode-languageserver to avoid
// "Expected 2-3 arguments, but got 1.ts(2554)
// server.d.ts(866, 202):
// An argument for 'watchDog' was not provided."
// error from TypeScript later
import { createConnection } from 'vscode-languageserver/node';
import {
TextDocument, Range, TextEdit
} from 'vscode-languageserver-textdocument';
import { KEYWORD_TO_COMPLETION_ITEM_KIND, REACH_KEYWORDS } from './keywordCompletion';
// Do this import differently so we can add types, to avoid a
// "No index signature with a parameter of type 'string' was found... ts(7053)"
// error later. See
// https://stackoverflow.com/questions/42986950/how-to-define-import-variable-type
// Also, if we do this import this way, we don't have to add
// "resolveJsonModule": true,
// to tsconfig.json.
const KEYWORD_TO_DOCUMENTATION: { [ keyword: string ] : string } = require(
'../../data/keywordToDocumentation.json'
);
// for "smart auto-complete" for things like
// Reach.App, Participant.Set, Array.zip, etc.
import {
KEYWORD_WITH_PERIOD_TO_KEYWORDS_LIST,
KEYWORD_TO_ITEM_KIND_IMPORT
} from "./mapKeywordsWithAPeriodToAKeywordList";
// Create a connection for the server. The connection uses Node's IPC as a transport.
// Also include all preview / proposed LSP features.
let connection = createConnection(ProposedFeatures.all);
// Create a simple text document manager. The text document manager
// supports full document sync only
let documents: TextDocuments<TextDocument> = new TextDocuments(TextDocument);
let hasConfigurationCapability: boolean = false;
let hasWorkspaceFolderCapability: boolean = false;
let hasDiagnosticRelatedInformationCapability: boolean = false;
const DIAGNOSTIC_SOURCE: string = 'Reach';
const DID_YOU_MEAN_PREFIX = 'Did you mean: ';
let reachTempIndexFile: string;
const REACH_TEMP_FILE_NAME = "index.rsh";
const { exec } = require("child_process");
const { indexOfRegex, lastIndexOfRegex } = require('index-of-regex')
const fs = require('fs')
const os = require('os')
const path = require('path')
let tempFolder: string;
let workspaceFolder: string;
connection.onInitialize((params: InitializeParams) => {
fs.mkdtemp(path.join(os.tmpdir(), 'reach-ide-'), (err: string, folder: string) => {
if (err) {
connection.console.error(err);
throw err;
}
// Use a format like 'reach-ide-SUFFIX/reach-ide'
tempFolder = path.join(folder, 'reach-ide');
fs.mkdir(tempFolder, (err2:string) => {
if (err2) {
connection.console.error(err2);
throw err2;
}
reachTempIndexFile = path.join(tempFolder, REACH_TEMP_FILE_NAME);
connection.console.log("Temp folder: " + tempFolder);
});
});
let capabilities = params.capabilities;
// Does the client support the `workspace/configuration` request?
// If not, we will fall back using global settings
hasConfigurationCapability = !!(
capabilities.workspace && !!capabilities.workspace.configuration
);
hasWorkspaceFolderCapability = !!(
capabilities.workspace && !!capabilities.workspace.workspaceFolders
);
hasDiagnosticRelatedInformationCapability = !!(
capabilities.textDocument &&
capabilities.textDocument.publishDiagnostics &&
capabilities.textDocument.publishDiagnostics.relatedInformation
);
const result: InitializeResult = {
capabilities: {
textDocumentSync: TextDocumentSyncKind.Full,
// Tell the client that the server supports code completion
completionProvider: {
resolveProvider: true,
triggerCharacters: ["."]
},
/* codeLensProvider : {
resolveProvider: true
},
,*/
hoverProvider: {
workDoneProgress: false
},
codeActionProvider: {
codeActionKinds: [CodeActionKind.QuickFix]
}
}
};
if (hasWorkspaceFolderCapability) {
result.capabilities.workspace = {
workspaceFolders: {
supported: true
}
};
}
return result;
});
connection.onInitialized(() => {
if (hasConfigurationCapability) {
// Register for all configuration changes.
connection.client.register(DidChangeConfigurationNotification.type, undefined);
}
if (hasWorkspaceFolderCapability) {
connection.workspace.onDidChangeWorkspaceFolders(_event => {
connection.console.log('Workspace folder change event received.');
});
}
});
const DEFAULT_MAX_PROBLEMS = 100;
interface ReachIdeSettings {
maxNumberOfProblems: number;
executableLocation: string;
}
let defaultSettings: ReachIdeSettings;
let globalSettings: ReachIdeSettings;
// Cache the settings of all open documents
let documentSettings: Map<string, Thenable<ReachIdeSettings>> = new Map();
connection.onDidChangeConfiguration(change => {
if (hasConfigurationCapability) {
// Reset all cached document settings
documentSettings.clear();
} else {
globalSettings = <ReachIdeSettings>(
(change.settings.reachide || defaultSettings)
);
}
// Revalidate all open text documents
documents.all().forEach(validateTextDocument);
});
function getDocumentSettings(resource: string): Thenable<ReachIdeSettings> {
if (!hasConfigurationCapability) {
return Promise.resolve(globalSettings);
}
let result = documentSettings.get(resource);
if (!result) {
result = connection.workspace.getConfiguration({
scopeUri: resource,
section: 'reachide'
});
documentSettings.set(resource, result);
}
return result;
}
documents.onDidOpen((event) => {
connection.console.log(`Document opened: ${event.document.uri}`);
let doc = event.document.uri;
let folderUrl : URL = new URL(doc.substring(0, doc.lastIndexOf('/')));
workspaceFolder = folderUrl.pathname;
connection.console.log(`Workspace folder: ${workspaceFolder}`);
// The global settings, used when the `workspace/configuration` request is not supported by the client.
// Please note that this is not the case when using this server with the client provided in this example
// but could happen with other clients.
defaultSettings = { maxNumberOfProblems: DEFAULT_MAX_PROBLEMS, executableLocation: path.join(workspaceFolder, "reach") };
globalSettings = defaultSettings;
});
// Only keep settings for open documents
documents.onDidClose(e => {
documentSettings.delete(e.document.uri);
});
// The content of a text document has changed. This event is emitted
// when the text document first opened or when its content has changed.
documents.onDidChangeContent(change => {
validateTextDocument(change.document);
});
let theCompilerIsCompiling = false,
weNeedToCompileAgain = false;
async function validateTextDocument(textDocument: TextDocument): Promise<void> {
let textDocumentFromURI = documents.get(textDocument.uri)
let textDocumentContents = textDocumentFromURI?.getText()
// In this simple example we get the settings for every validate run.
let settings = await getDocumentSettings(textDocument.uri);
let diagnostics: Diagnostic[] = [];
// Download the Reach shell script if it does not exist
try {
if (fs.existsSync('./reach')) {
connection.console.log("Reach shell script exists");
} else {
connection.console.log("Reach shell script not found, downloading now...");
await exec("curl https://raw.githubusercontent.com/reach-sh/reach-lang/master/reach -o reach ; chmod +x reach", (error: { message: any; }, stdout: any, stderr: any) => {
if (error) {
connection.console.error(`Reach download error: ${error.message}`);
return;
}
if (stderr) {
connection.console.error(`Reach download stderr: ${stderr}`);
return;
}
connection.console.log(`Reach download stdout: ${stdout}`);
});
}
} catch (err) {
connection.console.log("Failed to check if Reach shell scripts exists, downloading anyways...");
await exec("curl https://raw.githubusercontent.com/reach-sh/reach-lang/master/reach -o reach ; chmod +x reach", (error: { message: any; }, stdout: any, stderr: any) => {
if (error) {
connection.console.error(`Reach download error: ${error.message}`);
return;
}
if (stderr) {
connection.console.error(`Reach download stderr: ${stderr}`);
return;
}
connection.console.log(`Reach download stdout: ${stdout}`);
});
}
// Compile temp file instead of this current file
fs.writeFile(reachTempIndexFile, textDocumentContents, function (err: any) {
if (err) {
connection.console.error(`Failed to write temp source file: ${err}`);
return;
}
connection.console.log(`Temp source file ${reachTempIndexFile} saved!`);
});
const exeLoc = settings?.executableLocation?.trim() || '';
const reachPath = (exeLoc == '' || exeLoc == './reach')
? path.join(workspaceFolder, "reach")
: exeLoc;
if (theCompilerIsCompiling) {
weNeedToCompileAgain = true;
console.debug(
"Compilation already in process; will recompile",
new Date().toLocaleTimeString()
);
return;
}
theCompilerIsCompiling = true;
console.debug(
"Starting compilation at",
new Date().toLocaleTimeString()
);
await exec("cd " + tempFolder + " && " + reachPath + " compile " + REACH_TEMP_FILE_NAME + " --error-format-json --stop-after-eval", (error: { message: any; }, stdout: any, stderr: any) => {
// This callback function should execute exactly
// when this compilation command has finished.
// "child_process.exec(): spawns a shell...
// passing the stdout and stderr to a callback
// function when complete". See
// https://nodejs.org/api/child_process.html#child-process
console.debug(
"Compilation should now have finished.",
new Date().toLocaleTimeString()
);
theCompilerIsCompiling = false;
if (weNeedToCompileAgain) {
weNeedToCompileAgain = false;
validateTextDocument(textDocument);
return;
}
if (error) {
connection.console.log(`Found compile error: ${error.message}`);
const errorLocations: ErrorLocation[] = findErrorLocations(error.message);
let problems = 0;
errorLocations.forEach(err => {
connection.console.log(`Displaying error message: ` + err.errorMessage);
let maxProblems = settings?.maxNumberOfProblems || DEFAULT_MAX_PROBLEMS;
if (problems < maxProblems) {
problems++;
addDiagnostic(
err,
`${err.errorMessage}`,
'Reach compilation encountered an error.',
DiagnosticSeverity.Error,
err.code,
err.suggestions,
DIAGNOSTIC_SOURCE
);
}
});
return;
}
/** This doesn't seem to show anything useful at the moment
if (stderr) {
connection.console.error(`Reach compiler: ${stderr}`);
return;
}
*/
connection.console.log(`Reach compiler output: ${stdout}`);
});
// Send the computed diagnostics to VSCode (before the above promise finishes, just to clear stuff).
connection.sendDiagnostics({ uri: textDocument.uri, diagnostics });
function addDiagnostic(element: ErrorLocation, message: string, details: string, severity: DiagnosticSeverity, code: string | undefined, suggestions: string[], source: string) {
const href = `https://docs.reach.sh/${code}.html`;
let diagnostic: Diagnostic = {
severity: severity,
range: element.range,
message: message,
source,
code: code,
codeDescription: {
href
}
};
if (hasDiagnosticRelatedInformationCapability) {
diagnostic.relatedInformation = [
{
location: {
uri: textDocument.uri,
range: Object.assign({}, diagnostic.range)
},
message: suggestions.length ? DID_YOU_MEAN_PREFIX + suggestions : details
},
];
}
diagnostics.push(diagnostic);
// Send the computed diagnostics to VSCode.
connection.sendDiagnostics({ uri: textDocument.uri, diagnostics });
}
}
connection.onDidChangeWatchedFiles(_change => {
// Monitored files have change in VSCode
connection.console.log('We received an file change event');
});
export interface ErrorLocation {
code: string;
range: Range;
errorMessage: string; // e.g. id ref: Invalid unbound identifier: declassify.
suggestions: string[]; // e.g. literally this whole thing: "declassify","array","assert","assume","closeTo"
}
// Based on
// https://github.com/reach-sh/reach-lang/blob/master/hs/src/Reach/AST/Base.hs#L84
type ReachCompilerErrorJSON = {
ce_position: number[];
ce_suggestions: string[];
ce_errorMessage: string;
ce_offendingToken: string | null;
ce_errorCode: string;
}
function findErrorLocations(compileErrors: string): ErrorLocation[] {
// Example output to parse
/*
WARNING: Found orphan containers (tut_ethereum-devnet_1) for this project. If you removed or renamed this service in your compose file, you can run this command with the --remove-orphans flag to clean it up.
Creating tut_reach_run ... done
reachc: error: ./.index.rsh:18:23:id ref: Invalid unbound identifier: declaaaaaaaaassify. Did you mean: ["declassify","addressEq","array","assert","assume"]
CallStack (from HasCallStack):
error, called at src/Reach/AST.hs:58:3 in reach-0.1.2-KZ4oXxVSV3mFfbu8tz29Bg:Reach.AST
expect_throw, called at src/Reach/Eval.hs:441:7 in reach-0.1.2-KZ4oXxVSV3mFfbu8tz29Bg:Reach.Eval
env_lookup, called at src/Reach/Eval.hs:1638:41 in reach-0.1.2-KZ4oXxVSV3mFfbu8tz29Bg:Reach.Eval
*/
let pattern = /error: .*/g // look for error string
let m: RegExpExecArray | null;
let problems = 0;
let locations: ErrorLocation[] = [];
while ((m = pattern.exec(compileErrors)) && problems < 100 /*settings.maxNumberOfProblems*/) {
connection.console.log(`Found pattern: ${m}`);
// ERROR MESSAGE m: error: <json>
const errorJson: ReachCompilerErrorJSON = JSON.parse(m[0].substring(7));
//connection.console.log(`Tokens: ` + tokens);
const linePos = errorJson.ce_position[0] - 1;
const charPos = errorJson.ce_position[1] - 1;
const suggestions = errorJson.ce_suggestions;
const actualMessage = errorJson.ce_errorMessage;
const offendingToken = errorJson.ce_offendingToken;
const reachCompilerErrorCode = errorJson.ce_errorCode;
const start ={ line: linePos, character: charPos };
const end = offendingToken ?
{ line: linePos, character: charPos + offendingToken.length }
: { line: linePos + 1, character: 0 };
// App options currently have error position at the `:` of a json field: `<k> : <v>`.
// In other words, the highlighting for error "RE0013" is weird;
// it highlights a colon instead of a word, so we have special
// logic for this error code that we don't have for others.
if (reachCompilerErrorCode === "RE0013") {
// If we have this error code, an offendingToken will exist,
// which is why we can assert to TypeScript that
// offendingToken is non-null with the "!" operator.
// https://stackoverflow.com/questions/38874928/operator-in-typescript-after-object-method
start.character -= offendingToken!.length;
end.character -= offendingToken!.length;
}
let location: ErrorLocation = {
code: reachCompilerErrorCode,
range: { start: start, end: end },
errorMessage: actualMessage,
suggestions: suggestions
};
locations.push(location);
}
return locations;
}
connection.onCodeAction(
async (_params: CodeActionParams): Promise<CodeAction[]> => {
let codeActions: CodeAction[] = [];
let textDocument = documents.get(_params.textDocument.uri)
if (textDocument === undefined) {
return codeActions;
}
let context: CodeActionContext = _params.context;
let diagnostics: Diagnostic[] = context.diagnostics;
codeActions = await getCodeActions(diagnostics, textDocument, _params);
return codeActions;
}
)
async function getCodeActions(diagnostics: Diagnostic[], textDocument: TextDocument, params: CodeActionParams): Promise<CodeAction[]> {
let codeActions: CodeAction[] = [];
const labelPrefix = 'Replace with ';
// Get quick fixes for each diagnostic
diagnostics.forEach(diagnostic => {
const { range, relatedInformation } = diagnostic;
const message = (relatedInformation || [])[0]?.message || "";
// Diagnostics are either suggestions or generic 'Reach compilation error encountered' messages
if (message.startsWith(DID_YOU_MEAN_PREFIX)) {
const suggestions = message.substring(DID_YOU_MEAN_PREFIX.length).split(',');
suggestions.forEach(suggestion => {
codeActions.push(getQuickFix(diagnostic, labelPrefix + suggestion, range, suggestion, textDocument));
});
} else if (diagnostic.code === "RE0048") {
const title = "Add Reach program header.";
// Extract the error message from Reach's
// compiler, from the diagnostic variable.
const { message } = diagnostic;
// This is a relatively robust regular
// expression. It'll find a match even if
// the compiler's error message changes to
// "reach 0.1";, 'reach 0.1', `reach 0.1`,
// or "reach 1001.74", for example.
const regEx: RegExp =
/('|"|`)reach \d+\.\d+\1;?/;
const regExMatch = message.match(regEx);
// If, for some reason, a match doesn't
// exist, which should never happen, use
// 'reach 0.1'; as fallback text.
let newText: string = "'reach 0.1';";
if (regExMatch) {
newText = regExMatch[0];
console.debug(newText, regExMatch);
}
// Add newlines to improve readability.
newText += "\n\n";
const textEdit: TextEdit = {
newText,
range
};
const changes = {
[ textDocument.uri ]: [ textEdit ]
};
const edit: WorkspaceEdit = {
changes
};
const codeAction: CodeAction = {
edit,
diagnostics: [ diagnostic ],
kind: CodeActionKind.QuickFix,
title
};
codeActions.push(codeAction);
}
});
return codeActions;
}
function getQuickFix(diagnostic: Diagnostic, title: string, range: Range, replacement: string, textDocument: TextDocument): CodeAction {
let textEdit: TextEdit = {
range: range,
newText: replacement
};
let workspaceEdit: WorkspaceEdit = {
changes: { [textDocument.uri]: [textEdit] }
}
let codeAction: CodeAction = {
title: title,
kind: CodeActionKind.QuickFix,
edit: workspaceEdit,
diagnostics: [diagnostic]
}
return codeAction;
}
const GET_KEYWORDS_FOR = (
currentLine: string | undefined,
map: { [key: string]: string[]; },
fallbackCompletionList: string[]
): string[] => {
for (const keywordWithPeriod in map)
if (currentLine?.endsWith(keywordWithPeriod))
return map[keywordWithPeriod];
return fallbackCompletionList;
};
// This handler provides the initial list of the
// completion items.
connection.onCompletion((
textDocumentPosition: TextDocumentPositionParams
): CompletionItem[] => {
const {
textDocument,
position
} = textDocumentPosition;
console.debug(position);
const currentDocument = documents.get(
textDocument.uri
);
// Grab the current line.
const currentLine = currentDocument?.getText(
{
start: {
line: position.line,
character: 0
},
end: position
}
);
console.debug(currentLine);
// Do we have "smart auto-complete" for this
// keyword? If so, just give the "smart"
// suggestions. Otherwise, give the regular
// suggestions.
const keywords: string[] = GET_KEYWORDS_FOR(
currentLine,
KEYWORD_WITH_PERIOD_TO_KEYWORDS_LIST,
REACH_KEYWORDS
);
// The passed parameter contains the position of
// the text document in which code complete got
// requested.
return keywords.map(keyword => ({
label: keyword,
kind: KEYWORD_TO_COMPLETION_ITEM_KIND[
keyword
] || CompletionItemKind.Text,
data: undefined,
detail: `(${
KEYWORD_TO_ITEM_KIND_IMPORT[keyword]
})`,
documentation: {
kind: 'markdown',
value: getReachKeywordMarkdown(keyword)
},
}));
});
function insertSnippet(_textDocumentPosition: TextDocumentPositionParams, snippetText: string, completionItems: CompletionItem[], imports: string | undefined, label: string, sortOrder: number) {
let textEdit: TextEdit = {
range: {
start: _textDocumentPosition.position,
end: _textDocumentPosition.position
},
newText: snippetText
};
let completionItem: CompletionItem = {
label: label,
kind: CompletionItemKind.Snippet,
data: undefined,
textEdit: textEdit,
sortText: String(sortOrder)
};
// check if imports should be added
let textDocument = documents.get(_textDocumentPosition.textDocument.uri)
let textDocumentContents = textDocument?.getText()
if (imports !== undefined && (textDocumentContents === undefined || !String(textDocumentContents).includes(imports))) {
let additionalTextEdit = {
range: {
start: { line: 0, character: 0 },
end: { line: 0, character: 0 }
},
newText: imports
};
completionItem.additionalTextEdits = [additionalTextEdit]
}
completionItems.push(completionItem);
}
// This handler resolves additional information for the item selected in
// the completion list.
connection.onCompletionResolve(
(item: CompletionItem): CompletionItem => {
return item;
}
);
connection.onHover(
async (_params: HoverParams): Promise<Hover> => {
let textDocument = documents.get(_params.textDocument.uri)
let position = _params.position
let hover: Hover = {
contents: ""
}
if (textDocument !== undefined) {
var start = {
line: position.line,
character: 0,
};
var end = {
line: position.line + 1,
character: 0,
};
var text = textDocument.getText({ start, end });
var index = textDocument.offsetAt(position) - textDocument.offsetAt(start);
var word = getWord(text, index, true);
if (isReachKeyword(word)) {
let buf = await getReachKeywordMarkdown(word);
hover.contents = buf;
return hover;
}
var word = getWord(text, index, false);
if (isReachKeyword(word)) {
let buf = await getReachKeywordMarkdown(word);
hover.contents = buf;
return hover;
}
}
return hover;
}
);
function isReachKeyword(word: string): boolean {
return KEYWORD_TO_COMPLETION_ITEM_KIND[word] != undefined;
}
function getReachKeywordMarkdown(word: string): string {
// source: https://docs.reach.sh/ref-programs-module.html#%28tech._source._file%29
// then input to: https://euangoddard.github.io/clipboard2markdown/
// then input to: https://www.freeformatter.com/javascript-escape.html
// If we don't have documentation for `word`,
// then just set `buf` to the empty string.
let buf = KEYWORD_TO_DOCUMENTATION[word] || '';
buf = buf.replace(/`/g, ''); // Get rid of all code formatting which messes up hyperlinks
return buf;
}
function getWord(text: string, index: number, includeDot: boolean) {
var beginSubstring = text.substring(0, index);
var endSubstring = text.substring(index, text.length);
var boundaryRegex;
if (includeDot) {
boundaryRegex = /[^0-9a-zA-Z.]{1}/g; // boundaries are: not alphanumeric or dot
} else {
boundaryRegex = /[^0-9a-zA-Z]{1}/g; // boundaries are: not alphanumeric or dot
}
var first = lastIndexOfRegex(beginSubstring, boundaryRegex) + 1;
var last = index + indexOfRegex(endSubstring, boundaryRegex);
return text.substring(first !== -1 ? first : 0, last !== -1 ? last : text.length - 1);
}
// Make the text document manager listen on the connection
// for open, change and close text document events
documents.listen(connection);
// Listen on the connection
connection.listen(); | the_stack |
import { useEffect, useMemo, useContext, useRef, useState } from 'react';
import type { FormInstance } from 'antd';
import { Button, Collapse, Form, Popconfirm } from 'antd';
import classNames from 'classnames';
import molecule from '@dtinsight/molecule';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { DATA_SOURCE_ENUM, formItemLayout, KAFKA_DATA_TYPE } from '@/constant';
import stream from '@/api';
import {
isHaveCollection,
isHavePartition,
isHaveSchema,
isHaveTableColumn,
isHaveTableList,
isHaveTopic,
isAvro,
isKafka,
isSqlServer,
isRDB,
} from '@/utils/is';
import ResultForm from './form';
import type { IDataSourceUsedInSyncProps, IFlinkSinkProps } from '@/interface';
import type { IRightBarComponentProps } from '@/services/rightBarService';
import { FormContext } from '@/services/rightBarService';
const { Panel } = Collapse;
export const NAME_FIELD = 'panelColumn';
interface IFormFieldProps {
[NAME_FIELD]: Partial<IFlinkSinkProps>[];
}
const DEFAULT_INPUT_VALUE: Partial<IFlinkSinkProps> = {
type: DATA_SOURCE_ENUM.MYSQL,
columns: [],
parallelism: 1,
bulkFlushMaxActions: 100,
batchWaitInterval: 1000,
batchSize: 100,
enableKeyPartitions: false,
updateMode: 'append',
allReplace: 'false',
};
export default function FlinkResultPanel({ current }: IRightBarComponentProps) {
const currentPage = current?.tab?.data || {};
const { form } = useContext(FormContext) as { form: FormInstance<IFormFieldProps> };
const [panelActiveKey, setActiveKey] = useState<string[]>([]);
/**
* 数据源选择数据,以 type 作为键值
*/
const [dataSourceList, setDataSourceList] = useState<
Record<string, IDataSourceUsedInSyncProps[]>
>({});
/**
* 表选择数据,第一层对象以 sourceId 和 schema 为键值,第二层以 searchKey 为键值
* @example
* 搜索 s 的结果:
* ```js
* {
* [sourceId-schema]:{
* 's': any[]
* }
* }
* ```
*/
const [tableOptionList, setTableOptionList] = useState<Record<string, Record<string, any[]>>>(
{},
);
/**
* 表字段选择的类型,以 sourceId-table-schema 作为键值
*/
const [tableColumnsList, setTableColumnsList] = useState<
Record<string, { key: string; type: string }[]>
>({});
const [topicOptionList, setTopicOptionList] = useState<Record<string, any[]>>({});
// 添加或删除 panel 的标志位
const isAddOrRemove = useRef(false);
/**
* 获取数据源列表
*/
const getTypeOriginData = (type?: DATA_SOURCE_ENUM) => {
if (type !== undefined && !dataSourceList[type]) {
stream.getTypeOriginData({ type }).then((v) => {
if (v.code === 1) {
setDataSourceList((list) => {
const next = { ...list };
next[type] = v.data || [];
return next;
});
}
});
}
};
/**
* 获取Schema列表
* @deprecated 暂时不需要去请求 schema 数据
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const getSchemaData = (..._args: any[]) => {};
/**
* 获取表列表
*/
const getTableType = async (
params: { sourceId?: number; type: DATA_SOURCE_ENUM; schema?: string },
searchKey: string = '',
) => {
// postgresql schema必填处理
const disableReq =
(params.type === DATA_SOURCE_ENUM.POSTGRESQL ||
params.type === DATA_SOURCE_ENUM.KINGBASE8 ||
isSqlServer(params.type)) &&
!params.schema;
if (params.sourceId && !disableReq) {
const res = await stream.listTablesBySchema({
sourceId: params.sourceId,
schema: params.schema || '',
isSys: false,
searchKey,
});
setTableOptionList((list) => {
const next = { ...list };
if (!next[`${params.sourceId}-${params.schema || ''}`]) {
next[`${params.sourceId}-${params.schema || ''}`] = {};
}
next[`${params.sourceId}-${params.schema || ''}`][searchKey] =
res.code === 1 ? res.data : [];
return next;
});
}
};
/**
* 获取表字段列表
*/
const getTableColumns = (sourceId?: number, tableName?: string, schema = '') => {
if (!sourceId || !tableName) {
return;
}
if (!tableColumnsList[`${sourceId}-${tableName}-${schema}`]) {
stream
.getStreamTableColumn({
sourceId,
tableName,
schema,
flinkVersion: currentPage?.componentVersion,
})
.then((v) => {
setTableColumnsList((list) => {
const next = { ...list };
next[`${sourceId}-${tableName}-${schema}`] = v.code === 1 ? v.data : [];
return next;
});
});
}
};
/**
* @deprecated 暂时不需要请求分区
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const loadPartitions = async (...args: any[]) => {};
/**
* 获取 topic 列表
*/
const getTopicType = (sourceId?: number) => {
if (sourceId !== undefined && !topicOptionList[sourceId]) {
stream.getTopicType({ sourceId }).then((v) => {
setTopicOptionList((list) => {
const next = { ...list };
next[sourceId] = v.code === 1 ? v.data : [];
return next;
});
});
}
};
const handlePanelChanged = (type: 'add' | 'delete', index?: string) => {
return new Promise<void>((resolve) => {
if (type === 'add') {
isAddOrRemove.current = true;
getTypeOriginData(DEFAULT_INPUT_VALUE.type);
resolve();
} else {
isAddOrRemove.current = true;
const nextPanelAcitveKey = panelActiveKey.concat();
const idx = nextPanelAcitveKey.indexOf(index!);
if (idx > -1) {
nextPanelAcitveKey.splice(idx, 1);
setActiveKey(nextPanelAcitveKey);
}
resolve();
}
});
};
const handleSyncFormToTab = () => {
const sink = form?.getFieldsValue()[NAME_FIELD];
// 将表单的值保存至 tab 中
molecule.editor.updateTab({
id: current!.tab!.id,
data: {
...current!.tab!.data,
sink,
},
});
};
/**
* 该方法做两件事
* 1. 改变某值所引起的副作用
* 2. 请求相关接口获取数据
*/
const handleFormValuesChange = (changedValues: IFormFieldProps, values: IFormFieldProps) => {
if (isAddOrRemove.current) {
isAddOrRemove.current = false;
handleSyncFormToTab();
return;
}
// 当前正在修改的数据索引
const changeIndex = changedValues[NAME_FIELD].findIndex((col) => col);
const changeKeys = Object.keys(changedValues[NAME_FIELD][changeIndex]);
if (changeKeys.includes('type')) {
const value = changedValues[NAME_FIELD][changeIndex].type;
const nextValue = { ...values };
const kafkaType =
value === DATA_SOURCE_ENUM.KAFKA_CONFLUENT
? KAFKA_DATA_TYPE.TYPE_AVRO_CONFLUENT
: KAFKA_DATA_TYPE.TYPE_JSON;
// reset fields
nextValue[NAME_FIELD][changeIndex] = {
...DEFAULT_INPUT_VALUE,
type: value,
batchWaitInterval: isRDB(value) ? 1000 : undefined,
batchSize: isRDB(value) ? 100 : undefined,
sinkDataType: isKafka(value) ? kafkaType : undefined,
};
form?.setFieldsValue(nextValue);
getTypeOriginData(value);
}
if (changeKeys.includes('sourceId')) {
const value = changedValues[NAME_FIELD][changeIndex].sourceId;
const nextValue = { ...values };
const kafkaType =
nextValue[NAME_FIELD][changeIndex].type === DATA_SOURCE_ENUM.KAFKA_CONFLUENT
? KAFKA_DATA_TYPE.TYPE_AVRO_CONFLUENT
: KAFKA_DATA_TYPE.TYPE_JSON;
// reset fields
nextValue[NAME_FIELD][changeIndex] = {
...DEFAULT_INPUT_VALUE,
type: nextValue[NAME_FIELD][changeIndex].type,
sourceId: value,
customParams: nextValue[NAME_FIELD][changeIndex].customParams,
batchWaitInterval: nextValue[NAME_FIELD][changeIndex].batchWaitInterval,
batchSize: nextValue[NAME_FIELD][changeIndex].batchSize,
sinkDataType: isKafka(value) ? kafkaType : undefined,
};
form?.setFieldsValue(nextValue);
const panel = nextValue[NAME_FIELD][changeIndex];
if (isHaveCollection(panel.type!)) {
getTableType({ sourceId: value, type: panel.type!, schema: panel.schema });
}
if (isHaveTableList(panel.type)) {
getTableType({ sourceId: value, type: panel.type!, schema: panel.schema });
if (isHaveSchema(panel.type!)) {
getSchemaData();
}
}
if (isHaveTopic(panel.type)) {
getTopicType(value);
}
}
if (changeKeys.includes('schema')) {
const value = changedValues[NAME_FIELD][changeIndex].schema;
const nextValue = { ...values };
// reset fields
nextValue[NAME_FIELD][changeIndex] = {
...DEFAULT_INPUT_VALUE,
type: nextValue[NAME_FIELD][changeIndex].type,
sourceId: nextValue[NAME_FIELD][changeIndex].sourceId,
customParams: nextValue[NAME_FIELD][changeIndex].customParams,
batchWaitInterval: nextValue[NAME_FIELD][changeIndex].batchWaitInterval,
batchSize: nextValue[NAME_FIELD][changeIndex].batchSize,
schema: value,
};
form?.setFieldsValue(nextValue);
const panel = nextValue[NAME_FIELD][changeIndex];
if (isHaveTableList(panel.type)) {
getTableType({ sourceId: panel.sourceId, type: panel.type!, schema: value });
}
}
if (changeKeys.includes('table')) {
const value = changedValues[NAME_FIELD][changeIndex].table;
const nextValue = { ...values };
// reset fields
nextValue[NAME_FIELD][changeIndex] = {
...DEFAULT_INPUT_VALUE,
type: nextValue[NAME_FIELD][changeIndex].type,
sourceId: nextValue[NAME_FIELD][changeIndex].sourceId,
schema: nextValue[NAME_FIELD][changeIndex].schema,
customParams: nextValue[NAME_FIELD][changeIndex].customParams,
batchWaitInterval: nextValue[NAME_FIELD][changeIndex].batchWaitInterval,
batchSize: nextValue[NAME_FIELD][changeIndex].batchSize,
table: value,
};
form?.setFieldsValue(nextValue);
const panel = nextValue[NAME_FIELD][changeIndex];
if (isHaveTableColumn(panel.type)) {
getTableColumns(panel.sourceId, panel.table, panel.schema);
}
if (isHavePartition(panel.type)) {
loadPartitions();
}
}
if (changeKeys.includes('collection')) {
const value = changedValues[NAME_FIELD][changeIndex].collection;
const nextValue = { ...values };
// reset fields
nextValue[NAME_FIELD][changeIndex] = {
...DEFAULT_INPUT_VALUE,
type: nextValue[NAME_FIELD][changeIndex].type,
sourceId: nextValue[NAME_FIELD][changeIndex].sourceId,
schema: nextValue[NAME_FIELD][changeIndex].schema,
customParams: nextValue[NAME_FIELD][changeIndex].customParams,
batchWaitInterval: nextValue[NAME_FIELD][changeIndex].batchWaitInterval,
batchSize: nextValue[NAME_FIELD][changeIndex].batchSize,
table: nextValue[NAME_FIELD][changeIndex].table,
collection: value,
};
form?.setFieldsValue(nextValue);
const panel = nextValue[NAME_FIELD][changeIndex];
if (isHaveTableColumn(panel.type)) {
getTableColumns(panel.sourceId, panel.collection, panel.schema);
}
if (isHavePartition(panel.type)) {
loadPartitions();
}
}
if (changeKeys.includes('sinkDataType')) {
const value = changedValues[NAME_FIELD][changeIndex].sinkDataType;
if (!isAvro(value)) {
const nextValue = { ...values };
nextValue[NAME_FIELD][changeIndex].schemaInfo = undefined;
form.setFieldsValue(nextValue);
}
}
if (changeKeys.includes('columnsText')) {
const nextValue = { ...values };
nextValue[NAME_FIELD][changeIndex].partitionKeys = undefined;
form.setFieldsValue(nextValue);
}
handleSyncFormToTab();
};
const currentInitData = (sink: IFlinkSinkProps[]) => {
sink.forEach((v, index) => {
getTypeOriginData(v.type);
if (isHaveCollection(v.type)) {
getTableType({ sourceId: v.sourceId, type: v.type, schema: v.schema });
}
if (isHaveTableList(v.type)) {
getTableType({ sourceId: v.sourceId, type: v.type, schema: v.schema });
if (isHaveSchema(v.type)) {
getSchemaData(index, v.sourceId);
}
if (isHaveTableColumn(v.type)) {
getTableColumns(v.sourceId, v.table, v?.schema);
}
}
if (isHaveTopic(v.type)) {
getTopicType(v.sourceId);
}
if (isHavePartition(v.type)) {
loadPartitions(index, v.sourceId, v.table);
}
});
};
useEffect(() => {
const { sink } = currentPage;
if (sink && sink.length > 0) {
currentInitData(sink);
}
}, [current]);
const initialValues = useMemo(() => {
return { [NAME_FIELD]: current?.tab?.data.sink || [] };
}, []);
return (
<molecule.component.Scrollable>
<div className="panel-content">
<Form<IFormFieldProps>
{...formItemLayout}
form={form}
onValuesChange={handleFormValuesChange}
initialValues={initialValues}
>
<Form.List name={NAME_FIELD}>
{(fields, { add, remove }) => (
<>
<Collapse
activeKey={panelActiveKey}
bordered={false}
onChange={(key) => setActiveKey(key as string[])}
destroyInactivePanel
>
{fields.map((field, index) => {
const { sourceId, type, schema, table, tableName } =
form?.getFieldValue(NAME_FIELD)[index] || {};
return (
<Panel
header={
<div className="input-panel-title">
<span>{` 结果表 ${index + 1} ${
tableName ? `(${tableName})` : ''
}`}</span>
</div>
}
key={field.key.toString()}
extra={
<Popconfirm
placement="topLeft"
title="你确定要删除此结果表吗?"
onConfirm={() =>
handlePanelChanged(
'delete',
field.key.toString(),
).then(() => {
remove(field.name);
})
}
{...{
onClick: (e: any) => {
e.stopPropagation();
},
}}
>
<DeleteOutlined
className={classNames('title-icon')}
/>
</Popconfirm>
}
style={{ position: 'relative' }}
className="input-panel"
>
<ResultForm
index={index}
getTableType={getTableType}
dataSourceOptionList={dataSourceList[type]}
tableOptionType={
tableOptionList[
`${sourceId}-${schema || ''}`
]
}
tableColumnOptionType={
tableColumnsList[
`${sourceId}-${table}-${schema || ''}`
]
}
topicOptionType={topicOptionList[sourceId]}
componentVersion={currentPage.componentVersion}
/>
</Panel>
);
})}
</Collapse>
<Button
size="large"
block
onClick={() =>
handlePanelChanged('add').then(() =>
add({ ...DEFAULT_INPUT_VALUE }),
)
}
icon={<PlusOutlined />}
>
<span>添加结果表</span>
</Button>
</>
)}
</Form.List>
</Form>
</div>
</molecule.component.Scrollable>
);
} | the_stack |
import { IAppInsightsDeprecated } from "../../../src/ApplicationInsightsDeprecated";
import { ApplicationInsightsContainer } from "../../../src/ApplicationInsightsContainer";
import { IApplicationInsights, Snippet } from "../../../src/Initialization";
import { Sender } from "@microsoft/applicationinsights-channel-js";
import { SinonSpy } from "sinon";
import { AITestClass, Assert, PollingAssert } from "@microsoft/ai-test-framework";
import { createSnippetV5 } from "./testSnippet";
import { hasOwnProperty, isNotNullOrUndefined, ITelemetryItem, objForEachKey } from "@microsoft/applicationinsights-core-js";
import { ContextTagKeys, DistributedTracingModes, IConfig, IDependencyTelemetry, RequestHeaders, Util } from "@microsoft/applicationinsights-common";
import { getGlobal } from "@microsoft/applicationinsights-shims";
import { TelemetryContext } from "@microsoft/applicationinsights-properties-js";
const TestInstrumentationKey = 'b7170927-2d1c-44f1-acec-59f4e1751c11';
const _expectedBeforeProperties = [
"config",
"cookie"
];
const _expectedAfterProperties = [
"appInsights",
"core",
"context"
];
const _expectedTrackMethods = [
"startTrackPage",
"stopTrackPage",
"trackException",
"trackEvent",
"trackMetric",
"trackPageView",
"trackTrace",
"trackDependencyData",
"setAuthenticatedUserContext",
"clearAuthenticatedUserContext",
"trackPageViewPerformance",
"addTelemetryInitializer",
"flush"
];
const _expectedMethodsAfterInitialization = [
"getCookieMgr"
];
function getSnippetConfig(sessionPrefix: string) {
return {
src: "",
cfg: {
connectionString: `InstrumentationKey=${TestInstrumentationKey}`,
disableAjaxTracking: false,
disableFetchTracking: false,
enableRequestHeaderTracking: true,
enableResponseHeaderTracking: true,
maxBatchInterval: 500,
disableExceptionTracking: false,
namePrefix: `sessionPrefix`,
enableCorsCorrelation: true,
distributedTracingMode: DistributedTracingModes.AI_AND_W3C,
samplingPercentage: 50
} as IConfig
};
};
export class SnippetInitializationTests extends AITestClass {
// Context
private tagKeys = new ContextTagKeys();
// Sinon
private errorSpy: SinonSpy;
private successSpy: SinonSpy;
private loggingSpy: SinonSpy;
private isFetchPolyfill:boolean = false;
private sessionPrefix: string = Util.newId();
private trackSpy: SinonSpy;
private envelopeConstructorSpy: SinonSpy;
constructor(emulateEs3: boolean) {
super("SnippetInitializationTests", emulateEs3);
}
// Add any new snippet configurations to this map
private _theSnippets = {
"v5": createSnippetV5
};
public testInitialize() {
this._disableDynProtoBaseFuncs(); // We need to disable the useBaseInst performance setting as the sinon spy fools the internal logic and the spy is bypassed
try {
this.useFakeServer = true;
this.fakeServerAutoRespond = true;
this.isFetchPolyfill = fetch && fetch["polyfill"];
console.log("* testInitialize()");
} catch (e) {
console.error('Failed to initialize', e);
}
}
public testCleanup() {
}
public registerTests() {
objForEachKey(this._theSnippets, (snippetName, snippetCreator) => {
this.testCase({
name: "[" + snippetName + "] check NO support for 1.0 apis",
test: () => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix))) as any;
Assert.ok(theSnippet, 'ApplicationInsights SDK exists');
Assert.ok(!(theSnippet as IAppInsightsDeprecated).downloadAndSetup, "The [" + snippetName + "] snippet should NOT have the downloadAndSetup"); // has legacy method
}
});
this.testCaseAsync({
name: "[" + snippetName + "] : Public Members exist",
stepDelay: 100,
steps: [() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix))) as any;
_expectedTrackMethods.forEach(method => {
Assert.ok(theSnippet[method], `${method} exists`);
Assert.equal('function', typeof theSnippet[method], `${method} is a function`);
let funcSpy;
if (method === "trackDependencyData" || method === "flush") {
// we don't have any available reference to the underlying call, so while we want to check
// that this functions exists we can't validate that it is called
} else if (method === "setAuthenticatedUserContext" || method === "clearAuthenticatedUserContext") {
funcSpy = this.sandbox.spy(theSnippet.context.user, method);
} else if (method === "addTelemetryInitializer") {
funcSpy = this.sandbox.spy(theSnippet.core, method);
} else {
funcSpy = this.sandbox.spy(theSnippet.appInsights, method);
}
try {
theSnippet[method]();
} catch(e) {
// Do nothing
}
if (funcSpy) {
Assert.ok(funcSpy.called, "Function [" + method + "] of the appInsights should have been called")
}
});
_expectedMethodsAfterInitialization.forEach(method => {
Assert.ok(theSnippet[method], `${method} exists`);
Assert.equal('function', typeof theSnippet[method], `${method} is a function`);
let funcSpy = this.sandbox.spy(theSnippet.appInsights, method);
try {
theSnippet[method]();
} catch(e) {
// Do nothing
}
if (funcSpy) {
Assert.ok(funcSpy.called, "Function [" + method + "] of the appInsights should have been called")
}
});
}, PollingAssert.createPollingAssert(() => {
try {
Assert.ok(true, "* waiting for scheduled actions to send events " + new Date().toISOString());
if(this.successSpy.called) {
let currentCount: number = 0;
this.successSpy.args.forEach(call => {
call[0].forEach(message => {
// Ignore the internal SendBrowserInfoOnUserInit message (Only occurs when running tests in a browser)
if (!message || message.indexOf("AI (Internal): 72 ") == -1) {
currentCount ++;
}
});
});
return currentCount > 0;
}
return false;
} catch (e) {
Assert.ok(false, "Exception:" + e);
}
}, "waiting for sender success", 30, 1000) as any]
});
this.testCase({
name: "Check properties exist",
test: () => {
let preSnippet = snippetCreator(getSnippetConfig(this.sessionPrefix));
_expectedBeforeProperties.forEach(property => {
Assert.ok(hasOwnProperty(preSnippet, property), `${property} has property`);
Assert.ok(isNotNullOrUndefined(preSnippet[property]), `${property} exists`);
});
_expectedAfterProperties.forEach(property => {
Assert.ok(!hasOwnProperty(preSnippet, property), `${property} does not exist`);
});
let theSnippet = this._initializeSnippet(preSnippet) as any;
_expectedAfterProperties.forEach(property => {
Assert.ok(hasOwnProperty(theSnippet, property) , `${property} exists`);
Assert.notEqual('function', typeof theSnippet[property], `${property} is not a function`);
});
Assert.ok(isNotNullOrUndefined(theSnippet.core), "Make sure the core is set");
Assert.ok(isNotNullOrUndefined(theSnippet.appInsights.core), "Make sure the appInsights core is set");
Assert.equal(theSnippet.core, theSnippet.appInsights.core, "Make sure the core instances are actually the same");
}
});
this.testCase({
name: "Check cookie manager access",
test: () => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix))) as any;
let coreCookieMgr = theSnippet.core.getCookieMgr();
Assert.ok(isNotNullOrUndefined(coreCookieMgr), "Make sure the cookie manager is returned");
Assert.equal(true, coreCookieMgr.isEnabled(), "Cookies should be enabled")
Assert.equal(coreCookieMgr, theSnippet.getCookieMgr(), "Make sure the cookie manager is returned");
let appInsightsCookieMgr = theSnippet.appInsights.core.getCookieMgr();
Assert.ok(isNotNullOrUndefined(appInsightsCookieMgr), "Make sure the cookie manager is returned");
Assert.equal(true, appInsightsCookieMgr.isEnabled(), "Cookies should be enabled")
Assert.equal(appInsightsCookieMgr, theSnippet.getCookieMgr(), "Make sure the cookie manager is returned");
Assert.equal(coreCookieMgr, appInsightsCookieMgr, "Make sure the cookie managers are the same");
Assert.equal(true, theSnippet.getCookieMgr().isEnabled(), "Cookies should be enabled")
}
});
this.testCase({
name: "Check cookie manager access as disabled",
test: () => {
let theConfig = getSnippetConfig(this.sessionPrefix);
theConfig.cfg.disableCookiesUsage = true;
let theSnippet = this._initializeSnippet(snippetCreator(theConfig)) as any;
let coreCookieMgr = theSnippet.core.getCookieMgr();
Assert.ok(isNotNullOrUndefined(coreCookieMgr), "Make sure the cookie manager is returned");
Assert.equal(false, coreCookieMgr.isEnabled(), "Cookies should be disabled")
Assert.equal(coreCookieMgr, theSnippet.getCookieMgr(), "Make sure the cookie manager is returned");
let appInsightsCookieMgr = theSnippet.appInsights.core.getCookieMgr();
Assert.ok(isNotNullOrUndefined(appInsightsCookieMgr), "Make sure the cookie manager is returned");
Assert.equal(false, appInsightsCookieMgr.isEnabled(), "Cookies should be disabled")
Assert.equal(appInsightsCookieMgr, theSnippet.getCookieMgr(), "Make sure the cookie manager is returned");
Assert.equal(coreCookieMgr, appInsightsCookieMgr, "Make sure the cookie managers are the same");
Assert.equal(false, theSnippet.getCookieMgr().isEnabled(), "Cookies should be disabled")
}
});
this.addAnalyticsApiTests(snippetName, snippetCreator);
this.addAsyncTests(snippetName, snippetCreator);
this.addDependencyPluginTests(snippetName, snippetCreator);
this.addPropertiesPluginTests(snippetName, snippetCreator);
});
}
public addAnalyticsApiTests(snippetName: string, snippetCreator: (config:any) => Snippet): void {
this.testCase({
name: 'E2E.AnalyticsApiTests: Public Members exist',
test: () => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix))) as any;
_expectedTrackMethods.forEach(method => {
Assert.ok(theSnippet[method], `${method} exists`);
Assert.equal('function', typeof theSnippet[method], `${method} is a function`);
});
_expectedMethodsAfterInitialization.forEach(method => {
Assert.ok(theSnippet[method], `${method} does exists`);
Assert.equal('function', typeof theSnippet[method], `${method} is a function`);
});
}
});
}
public addAsyncTests(snippetName: string, snippetCreator: (config:any) => Snippet): void {
this.testCaseAsync({
name: 'E2E.GenericTests: trackEvent sends to backend',
stepDelay: 100,
steps: [() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
theSnippet.trackEvent({ name: 'event', properties: { "prop1": "value1" }, measurements: { "measurement1": 200 } });
}].concat(this.asserts(1)).concat(() => {
const payloadStr: string[] = this.getPayloadMessages(this.successSpy);
if (payloadStr.length > 0) {
const payload = JSON.parse(payloadStr[0]);
const data = payload.data;
Assert.ok(data && data.baseData && data.baseData.properties["prop1"]);
Assert.ok(data && data.baseData && data.baseData.measurements["measurement1"]);
}
})
});
this.testCaseAsync({
name: 'E2E.GenericTests: trackTrace sends to backend',
stepDelay: 100,
steps: [() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
theSnippet.trackTrace({ message: 'trace', properties: { "foo": "bar", "prop2": "value2" } });
}].concat(this.asserts(1)).concat(() => {
const payloadStr: string[] = this.getPayloadMessages(this.successSpy);
const payload = JSON.parse(payloadStr[0]);
const data = payload.data;
Assert.ok(data && data.baseData &&
data.baseData.properties["foo"] && data.baseData.properties["prop2"]);
Assert.equal("bar", data.baseData.properties["foo"]);
Assert.equal("value2", data.baseData.properties["prop2"]);
})
});
this.testCaseAsync({
name: 'E2E.GenericTests: trackException sends to backend',
stepDelay: 100,
steps: [() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
let exception: Error = null;
try {
window['a']['b']();
Assert.ok(false, 'trackException test not run');
} catch (e) {
exception = e;
theSnippet.trackException({ exception });
}
Assert.ok(exception);
}].concat(this.asserts(1))
});
this.testCaseAsync({
name: 'E2E.GenericTests: legacy trackException sends to backend',
stepDelay: 100,
steps: [() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
let exception: Error = null;
try {
window['a']['b']();
Assert.ok(false, 'trackException test not run');
} catch (e) {
exception = e;
theSnippet.trackException({ error: exception } as any);
}
Assert.ok(exception);
}].concat(this.asserts(1))
});
this.testCaseAsync({
name: "TelemetryContext: track metric",
stepDelay: 100,
steps: [
() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
console.log("* calling trackMetric " + new Date().toISOString());
for (let i = 0; i < 100; i++) {
theSnippet.trackMetric({ name: "test" + i, average: Math.round(100 * Math.random()) });
}
console.log("* done calling trackMetric " + new Date().toISOString());
}
].concat(this.asserts(100))
});
this.testCaseAsync({
name: `TelemetryContext: track page view ${window.location.pathname}`,
stepDelay: 500,
steps: [
() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
theSnippet.trackPageView({}); // sends 2
}
]
.concat(this.asserts(2))
.concat(() => {
const payloadStr: string[] = this.getPayloadMessages(this.successSpy);
if (payloadStr.length > 0) {
const payload = JSON.parse(payloadStr[0]);
const data = payload.data;
Assert.ok(data.baseData.id, "pageView id is defined");
Assert.ok(data.baseData.id.length > 0);
Assert.ok(payload.tags["ai.operation.id"]);
Assert.equal(data.baseData.id, payload.tags["ai.operation.id"], "pageView id matches current operation id");
} else {
Assert.ok(false, "successSpy not called");
}
})
});
this.testCaseAsync({
name: "TelemetryContext: track page view performance",
stepDelay: 100,
steps: [
() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
theSnippet.trackPageViewPerformance({ name: 'name', uri: 'url' });
}
].concat(this.asserts(1))
});
this.testCaseAsync({
name: "TelemetryContext: track all types in batch",
stepDelay: 100,
steps: [
() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
let exception = null;
try {
window["a"]["b"]();
} catch (e) {
exception = e;
}
Assert.ok(exception);
theSnippet.trackException({ exception });
theSnippet.trackMetric({ name: "test", average: Math.round(100 * Math.random()) });
theSnippet.trackTrace({ message: "test" });
theSnippet.trackPageView({}); // sends 2
theSnippet.trackPageViewPerformance({ name: 'name', uri: 'http://someurl' });
theSnippet.flush();
}
].concat(this.asserts(6))
});
this.testCaseAsync({
name: "TelemetryContext: track all types in a large batch",
stepDelay: 100,
steps: [
() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
let exception = null;
try {
window["a"]["b"]();
} catch (e) {
exception = e;
}
Assert.ok(exception);
for (let i = 0; i < 100; i++) {
theSnippet.trackException({ exception });
theSnippet.trackMetric({ name: "test", average: Math.round(100 * Math.random()) });
theSnippet.trackTrace({ message: "test" });
theSnippet.trackPageView({ name: `${i}` }); // sends 2 1st time
}
}
].concat(this.asserts(401, false))
});
this.testCaseAsync({
name: "TelemetryInitializer: E2E override envelope data",
stepDelay: 100,
steps: [
() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
// Setup
const telemetryInitializer = {
init: (envelope) => {
envelope.baseData.name = 'other name'
return true;
}
}
// Act
theSnippet.addTelemetryInitializer(telemetryInitializer.init);
theSnippet.trackMetric({ name: "test", average: Math.round(100 * Math.random()) });
}
]
.concat(this.asserts(1))
.concat(() => {
const payloadStr: string[] = this.getPayloadMessages(this.successSpy);
if (payloadStr.length > 0) {
let payloadItems = payloadStr.length;
Assert.equal(1, payloadItems, 'Only 1 track item is sent');
const payload = JSON.parse(payloadStr[0]);
Assert.ok(payload);
if (payload && payload.baseData) {
const nameResult: string = payload.data.baseData.metrics[0].name;
const nameExpect: string = 'other name';
Assert.equal(nameExpect, nameResult, 'telemetryinitializer override successful');
}
}
})
});
}
public addDependencyPluginTests(snippetName: string, snippetCreator: (config:any) => Snippet): void {
this.testCaseAsync({
name: "TelemetryContext: trackDependencyData",
stepDelay: 100,
steps: [
() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
const data: IDependencyTelemetry = {
target: 'http://abc',
responseCode: 200,
type: 'GET',
id: 'abc'
}
theSnippet.trackDependencyData(data);
}
].concat(this.asserts(1))
});
if (!this.isEmulatingEs3) {
// If we are emulating ES3 then XHR is not hooked
this.testCaseAsync({
name: "TelemetryContext: auto collection of ajax requests",
stepDelay: 100,
steps: [
() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://httpbin.org/status/200');
xhr.send();
Assert.ok(true);
}
].concat(this.asserts(1))
});
}
let global = getGlobal();
if (global && global.fetch && !this.isEmulatingEs3) {
this.testCaseAsync({
name: "DependenciesPlugin: auto collection of outgoing fetch requests " + (this.isFetchPolyfill ? " using polyfill " : ""),
stepDelay: 5000,
steps: [
() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
fetch('https://httpbin.org/status/200', { method: 'GET', headers: { 'header': 'value'} });
Assert.ok(true, "fetch monitoring is instrumented");
},
() => {
fetch('https://httpbin.org/status/200', { method: 'GET' });
Assert.ok(true, "fetch monitoring is instrumented");
},
() => {
fetch('https://httpbin.org/status/200');
Assert.ok(true, "fetch monitoring is instrumented");
}
]
.concat(this.asserts(3, false, false))
.concat(() => {
let args = [];
this.trackSpy.args.forEach(call => {
let message = call[0].baseData.message||"";
// Ignore the internal SendBrowserInfoOnUserInit message (Only occurs when running tests in a browser)
if (message.indexOf("AI (Internal): 72 ") == -1) {
args.push(call[0]);
}
});
let type = "Fetch";
if (this.isFetchPolyfill) {
type = "Ajax";
Assert.ok(true, "Using fetch polyfill");
}
Assert.equal(3, args.length, "track is called 3 times");
let baseData = args[0].baseData;
Assert.equal(type, baseData.type, "request is " + type + " type");
Assert.equal('value', baseData.properties.requestHeaders['header'], "fetch request's user defined request header is stored");
Assert.ok(baseData.properties.responseHeaders, "fetch request's reponse header is stored");
baseData = args[1].baseData;
Assert.equal(3, Object.keys(baseData.properties.requestHeaders).length, "two request headers set up when there's no user defined request header");
Assert.ok(baseData.properties.requestHeaders[RequestHeaders.requestIdHeader], "Request-Id header");
Assert.ok(baseData.properties.requestHeaders[RequestHeaders.requestContextHeader], "Request-Context header");
Assert.ok(baseData.properties.requestHeaders[RequestHeaders.traceParentHeader], "traceparent");
const id: string = baseData.id;
const regex = id.match(/\|.{32}\..{16}\./g);
Assert.ok(id.length > 0);
Assert.equal(1, regex.length)
Assert.equal(id, regex[0]);
})
});
} else {
this.testCase({
name: "DependenciesPlugin: No crash when fetch not supported",
test: () => {
Assert.ok(true, "fetch monitoring is correctly not instrumented")
}
});
}
}
public addPropertiesPluginTests(snippetName: string, snippetCreator: (config:any) => Snippet): void {
this.testCaseAsync({
name: 'Custom Tags: allowed to send custom properties via addTelemetryInitializer',
stepDelay: 100,
steps: [
() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
theSnippet.addTelemetryInitializer((item: ITelemetryItem) => {
item.tags[this.tagKeys.cloudName] = "my.custom.cloud.name";
});
theSnippet.trackEvent({ name: "Custom event via addTelemetryInitializer" });
}
]
.concat(this.asserts(1, false, false))
.concat(PollingAssert.createPollingAssert(() => {
const payloadStr: string[] = this.getPayloadMessages(this.successSpy);
if (payloadStr.length) {
const payload = JSON.parse(payloadStr[0]);
Assert.equal(1, payloadStr.length, 'Only 1 track item is sent - ' + payload.name);
Assert.ok(payload);
if (payload && payload.tags) {
const tagResult: string = payload.tags && payload.tags[this.tagKeys.cloudName];
const tagExpect: string = 'my.custom.cloud.name';
Assert.equal(tagResult, tagExpect, 'telemetryinitializer tag override successful');
return true;
}
return false;
}
}, 'Set custom tags') as any)
});
this.testCaseAsync({
name: 'Custom Tags: allowed to send custom properties via addTelemetryInitializer & shimmed addTelemetryInitializer',
stepDelay: 100,
steps: [
() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
theSnippet.addTelemetryInitializer((item: ITelemetryItem) => {
item.tags.push({[this.tagKeys.cloudName]: "my.shim.cloud.name"});
});
theSnippet.trackEvent({ name: "Custom event" });
}
]
.concat(this.asserts(1))
.concat(PollingAssert.createPollingAssert(() => {
const payloadStr: string[] = this.getPayloadMessages(this.successSpy);
if (payloadStr.length > 0) {
Assert.equal(1, payloadStr.length, 'Only 1 track item is sent');
const payload = JSON.parse(payloadStr[0]);
Assert.ok(payload);
if (payload && payload.tags) {
const tagResult: string = payload.tags && payload.tags[this.tagKeys.cloudName];
const tagExpect: string = 'my.shim.cloud.name';
Assert.equal(tagResult, tagExpect, 'telemetryinitializer tag override successful');
return true;
}
return false;
}
}, 'Set custom tags') as any)
});
this.testCaseAsync({
name: 'Custom Tags: allowed to send custom properties via shimmed addTelemetryInitializer',
stepDelay: 100,
steps: [
() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
theSnippet.addTelemetryInitializer((item: ITelemetryItem) => {
item.tags[this.tagKeys.cloudName] = "my.custom.cloud.name";
item.tags[this.tagKeys.locationCity] = "my.custom.location.city";
item.tags.push({[this.tagKeys.locationCountry]: "my.custom.location.country"});
item.tags.push({[this.tagKeys.operationId]: "my.custom.operation.id"});
});
theSnippet.trackEvent({ name: "Custom event via shimmed addTelemetryInitializer" });
}
]
.concat(this.asserts(1))
.concat(PollingAssert.createPollingAssert(() => {
const payloadStr: string[] = this.getPayloadMessages(this.successSpy);
if (payloadStr.length > 0) {
const payload = JSON.parse(payloadStr[0]);
Assert.equal(1, payloadStr.length, 'Only 1 track item is sent - ' + payload.name);
if (payloadStr.length > 1) {
this.dumpPayloadMessages(this.successSpy);
}
Assert.ok(payload);
if (payload && payload.tags) {
const tagResult1: string = payload.tags && payload.tags[this.tagKeys.cloudName];
const tagExpect1: string = 'my.custom.cloud.name';
Assert.equal(tagResult1, tagExpect1, 'telemetryinitializer tag override successful');
const tagResult2: string = payload.tags && payload.tags[this.tagKeys.locationCity];
const tagExpect2: string = 'my.custom.location.city';
Assert.equal(tagResult2, tagExpect2, 'telemetryinitializer tag override successful');
const tagResult3: string = payload.tags && payload.tags[this.tagKeys.locationCountry];
const tagExpect3: string = 'my.custom.location.country';
Assert.equal(tagResult3, tagExpect3, 'telemetryinitializer tag override successful');
const tagResult4: string = payload.tags && payload.tags[this.tagKeys.operationId];
const tagExpect4: string = 'my.custom.operation.id';
Assert.equal(tagResult4, tagExpect4, 'telemetryinitializer tag override successful');
return true;
}
return false;
}
}, 'Set custom tags') as any)
});
this.testCaseAsync({
name: 'AuthenticatedUserContext: setAuthenticatedUserContext authId',
stepDelay: 100,
steps: [
() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
const context = (theSnippet.context) as TelemetryContext;
context.user.setAuthenticatedUserContext('10001');
theSnippet.trackTrace({ message: 'authUserContext test' });
}
]
.concat(this.asserts(1))
.concat(PollingAssert.createPollingAssert(() => {
let payloadStr = this.getPayloadMessages(this.successSpy);
if (payloadStr.length > 0) {
let payloadEvents = payloadStr.length;
let thePayload:string = payloadStr[0];
if (payloadEvents !== 1) {
// Only 1 track should be sent
return false;
}
const payload = JSON.parse(thePayload);
if (payload && payload.tags) {
const tagName: string = this.tagKeys.userAuthUserId;
return '10001' === payload.tags[tagName];
}
}
return false;
}, 'user.authenticatedId') as any)
});
this.testCaseAsync({
name: 'AuthenticatedUserContext: setAuthenticatedUserContext authId and accountId',
stepDelay: 100,
steps: [
() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
const context = (theSnippet.context) as TelemetryContext;
context.user.setAuthenticatedUserContext('10001', 'account123');
theSnippet.trackTrace({ message: 'authUserContext test' });
}
]
.concat(this.asserts(1))
.concat(PollingAssert.createPollingAssert(() => {
const payloadStr: string[] = this.getPayloadMessages(this.successSpy);
if (payloadStr.length > 0) {
if (payloadStr.length !== 1) {
// Only 1 track should be sent
return false;
}
const payload = JSON.parse(payloadStr[0]);
if (payload && payload.tags) {
const authTag: string = this.tagKeys.userAuthUserId;
const accountTag: string = this.tagKeys.userAccountId;
return '10001' === payload.tags[authTag] /*&&
'account123' === payload.tags[accountTag] */; // bug https://msazure.visualstudio.com/One/_workitems/edit/3508825
}
}
return false;
}, 'user.authenticatedId') as any)
});
this.testCaseAsync({
name: 'AuthenticatedUserContext: setAuthenticatedUserContext non-ascii authId and accountId',
stepDelay: 100,
steps: [
() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
const context = (theSnippet.context) as TelemetryContext;
context.user.setAuthenticatedUserContext("\u0428", "\u0429");
theSnippet.trackTrace({ message: 'authUserContext test' });
}
]
.concat(this.asserts(1))
.concat(PollingAssert.createPollingAssert(() => {
const payloadStr: string[] = this.getPayloadMessages(this.successSpy);
if (payloadStr.length > 0) {
if (payloadStr.length !== 1) {
// Only 1 track should be sent
return false;
}
const payload = JSON.parse(payloadStr[0]);
if (payload && payload.tags) {
const authTag: string = this.tagKeys.userAuthUserId;
const accountTag: string = this.tagKeys.userAccountId;
return '\u0428' === payload.tags[authTag] /* &&
'\u0429' === payload.tags[accountTag] */; // bug https://msazure.visualstudio.com/One/_workitems/edit/3508825
}
}
return false;
}, 'user.authenticatedId') as any)
});
this.testCaseAsync({
name: 'AuthenticatedUserContext: clearAuthenticatedUserContext',
stepDelay: 100,
steps: [
() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
const context = (theSnippet.context) as TelemetryContext;
context.user.setAuthenticatedUserContext('10002', 'account567');
context.user.clearAuthenticatedUserContext();
theSnippet.trackTrace({ message: 'authUserContext test' });
}
]
.concat(this.asserts(1))
.concat(PollingAssert.createPollingAssert(() => {
const payloadStr: string[] = this.getPayloadMessages(this.successSpy);
if (payloadStr.length > 0) {
if (payloadStr.length !== 1) {
// Only 1 track should be sent
return false;
}
const payload = JSON.parse(payloadStr[0]);
if (payload && payload.tags) {
const authTag: string = this.tagKeys.userAuthUserId;
const accountTag: string = this.tagKeys.userAccountId;
return undefined === payload.tags[authTag] &&
undefined === payload.tags[accountTag];
}
}
return false;
}, 'user.authenticatedId') as any)
});
// This doesn't need to be e2e
this.testCase({
name: 'AuthenticatedUserContext: setAuthenticatedUserContext does not set the cookie by default',
test: () => {
// Setup
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
const context = (theSnippet.context) as TelemetryContext;
const authSpy: SinonSpy = this.sandbox.spy(context.user, 'setAuthenticatedUserContext');
const cookieSpy: SinonSpy = this.sandbox.spy(Util, 'setCookie');
// Act
context.user.setAuthenticatedUserContext('10002', 'account567');
// Test
Assert.ok(authSpy.calledOnce, 'setAuthenticatedUserContext called');
Assert.equal(false, authSpy.calledWithExactly('10001', 'account567', false), 'Correct default args to setAuthenticatedUserContext');
Assert.ok(cookieSpy.notCalled, 'cookie never set');
}
});
this.testCase({
name: 'Sampling: sampleRate is generated as a field in the envelope when it is less than 100',
test:() => {
let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix)));
theSnippet.trackEvent({ name: 'event' });
Assert.ok(this.envelopeConstructorSpy.called);
const envelope = this.envelopeConstructorSpy.returnValues[0];
Assert.equal(envelope.sampleRate, 50, "sampleRate is generated");
}
})
}
private _initializeSnippet(snippet: Snippet): IApplicationInsights {
try {
this.useFakeServer = false;
// Call the initialization
((ApplicationInsightsContainer.getAppInsights(snippet, snippet.version)) as IApplicationInsights);
// Setup Sinon stuff
const appInsights = (snippet as any).appInsights;
this.onDone(() => {
if (snippet["unload"]) {
snippet["unload"](false);
} else if (snippet["appInsightsNew"]) {
snippet["appInsightsNew"].unload(false);
}
});
Assert.ok(appInsights, "The App insights instance should be populated");
Assert.ok(appInsights.core, "The Core exists");
Assert.equal(appInsights.core, (snippet as any).core, "The core instances should match");
Assert.equal(true, appInsights.isInitialized(), 'App Analytics is initialized');
Assert.equal(true, appInsights.core.isInitialized(), 'Core is initialized');
const sender: Sender = appInsights.core.getTransmissionControls()[0][0] as Sender;
this.errorSpy = this.sandbox.spy(sender, '_onError');
this.successSpy = this.sandbox.spy(sender, '_onSuccess');
this.loggingSpy = this.sandbox.stub(appInsights.core.logger, 'throwInternal');
this.trackSpy = this.sandbox.spy(appInsights.core, 'track')
this.sandbox.stub((sender as any)._sample, 'isSampledIn').returns(true);
this.envelopeConstructorSpy = this.sandbox.spy(Sender, 'constructEnvelope');
} catch (e) {
console.error('Failed to initialize');
Assert.ok(false, e);
}
// Note: Explicitly returning the original snippet as this should have been updated!
return snippet as any;
}
private boilerPlateAsserts = () => {
Assert.ok(this.successSpy.called, "success");
Assert.ok(!this.errorSpy.called, "no error sending");
const isValidCallCount = this.loggingSpy.callCount === 0;
Assert.ok(isValidCallCount, "logging spy was called 0 time(s)");
if (!isValidCallCount) {
while (this.loggingSpy.args.length) {
Assert.ok(false, "[warning thrown]: " + this.loggingSpy.args.pop());
}
}
}
private asserts: any = (expectedCount: number) => [() => {
const message = "polling: " + new Date().toISOString();
Assert.ok(true, message);
console.log(message);
if (this.successSpy.called) {
this.boilerPlateAsserts();
this.testCleanup();
} else if (this.errorSpy.called || this.loggingSpy.called) {
this.boilerPlateAsserts();
}
},
(PollingAssert.createPollingAssert(() => {
Assert.ok(true, "* checking success spy " + new Date().toISOString());
if(this.successSpy.called) {
let currentCount: number = 0;
this.successSpy.args.forEach(call => {
call[0].forEach(message => {
// Ignore the internal SendBrowserInfoOnUserInit message (Only occurs when running tests in a browser)
if (!message || message.indexOf("AI (Internal): 72 ") == -1) {
currentCount ++;
}
});
});
console.log('curr: ' + currentCount + ' exp: ' + expectedCount);
return currentCount === expectedCount;
} else {
return false;
}
}, "sender succeeded", 30, 1000))];
} | the_stack |
/*
* ---------------------------------------------------------
* Copyright(C) Microsoft Corporation. All rights reserved.
* ---------------------------------------------------------
*
* ---------------------------------------------------------
* Generated file, DO NOT EDIT
* ---------------------------------------------------------
*/
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
import * as restm from 'typed-rest-client/RestClient';
import vsom = require('./VsoClient');
import basem = require('./ClientApiBases');
import VsoBaseInterfaces = require('./interfaces/common/VsoBaseInterfaces');
import FileContainerInterfaces = require("./interfaces/FileContainerInterfaces");
import VSSInterfaces = require("./interfaces/common/VSSInterfaces");
export interface IFileContainerApiBase extends basem.ClientApiBase {
createItems(items: VSSInterfaces.VssJsonCollectionWrapperV<FileContainerInterfaces.FileContainerItem[]>, containerId: number, scope?: string): Promise<FileContainerInterfaces.FileContainerItem[]>;
deleteItem(containerId: number, itemPath: string, scope?: string): Promise<void>;
getContainers(scope?: string, artifactUris?: string): Promise<FileContainerInterfaces.FileContainer[]>;
getItems(containerId: number, scope?: string, itemPath?: string, metadata?: boolean, format?: string, downloadFileName?: string, includeDownloadTickets?: boolean, isShallow?: boolean, ignoreRequestedMediaType?: boolean, includeBlobMetadata?: boolean, saveAbsolutePath?: boolean): Promise<FileContainerInterfaces.FileContainerItem[]>;
}
export class FileContainerApiBase extends basem.ClientApiBase implements IFileContainerApiBase {
constructor(baseUrl: string, handlers: VsoBaseInterfaces.IRequestHandler[], options?: VsoBaseInterfaces.IRequestOptions) {
super(baseUrl, handlers, 'node-FileContainer-api', options);
}
/**
* Creates the specified items in in the referenced container.
*
* @param {VSSInterfaces.VssJsonCollectionWrapperV<FileContainerInterfaces.FileContainerItem[]>} items
* @param {number} containerId
* @param {string} scope - A guid representing the scope of the container. This is often the project id.
*/
public async createItems(
items: VSSInterfaces.VssJsonCollectionWrapperV<FileContainerInterfaces.FileContainerItem[]>,
containerId: number,
scope?: string
): Promise<FileContainerInterfaces.FileContainerItem[]> {
return new Promise<FileContainerInterfaces.FileContainerItem[]>(async (resolve, reject) => {
let routeValues: any = {
containerId: containerId
};
let queryValues: any = {
scope: scope,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.4",
"Container",
"e4f5c81e-e250-447b-9fef-bd48471bea5e",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<FileContainerInterfaces.FileContainerItem[]>;
res = await this.rest.create<FileContainerInterfaces.FileContainerItem[]>(url, items, options);
let ret = this.formatResponse(res.result,
FileContainerInterfaces.TypeInfo.FileContainerItem,
true);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Deletes the specified items in a container.
*
* @param {number} containerId - Container Id.
* @param {string} itemPath - Path to delete.
* @param {string} scope - A guid representing the scope of the container. This is often the project id.
*/
public async deleteItem(
containerId: number,
itemPath: string,
scope?: string
): Promise<void> {
if (itemPath == null) {
throw new TypeError('itemPath can not be null or undefined');
}
return new Promise<void>(async (resolve, reject) => {
let routeValues: any = {
containerId: containerId
};
let queryValues: any = {
itemPath: itemPath,
scope: scope,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.4",
"Container",
"e4f5c81e-e250-447b-9fef-bd48471bea5e",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<void>;
res = await this.rest.del<void>(url, options);
let ret = this.formatResponse(res.result,
null,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Gets containers filtered by a comma separated list of artifact uris within the same scope, if not specified returns all containers
*
* @param {string} scope - A guid representing the scope of the container. This is often the project id.
* @param {string} artifactUris
*/
public async getContainers(
scope?: string,
artifactUris?: string
): Promise<FileContainerInterfaces.FileContainer[]> {
return new Promise<FileContainerInterfaces.FileContainer[]>(async (resolve, reject) => {
let routeValues: any = {
};
let queryValues: any = {
scope: scope,
artifactUris: artifactUris,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.4",
"Container",
"e4f5c81e-e250-447b-9fef-bd48471bea5e",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<FileContainerInterfaces.FileContainer[]>;
res = await this.rest.get<FileContainerInterfaces.FileContainer[]>(url, options);
let ret = this.formatResponse(res.result,
FileContainerInterfaces.TypeInfo.FileContainer,
true);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* @param {number} containerId
* @param {string} scope
* @param {string} itemPath
* @param {boolean} metadata
* @param {string} format
* @param {string} downloadFileName
* @param {boolean} includeDownloadTickets
* @param {boolean} isShallow
* @param {boolean} ignoreRequestedMediaType
* @param {boolean} includeBlobMetadata
* @param {boolean} saveAbsolutePath
*/
public async getItems(
containerId: number,
scope?: string,
itemPath?: string,
metadata?: boolean,
format?: string,
downloadFileName?: string,
includeDownloadTickets?: boolean,
isShallow?: boolean,
ignoreRequestedMediaType?: boolean,
includeBlobMetadata?: boolean,
saveAbsolutePath?: boolean
): Promise<FileContainerInterfaces.FileContainerItem[]> {
return new Promise<FileContainerInterfaces.FileContainerItem[]>(async (resolve, reject) => {
let routeValues: any = {
containerId: containerId
};
let queryValues: any = {
scope: scope,
itemPath: itemPath,
metadata: metadata,
'$format': format,
downloadFileName: downloadFileName,
includeDownloadTickets: includeDownloadTickets,
isShallow: isShallow,
ignoreRequestedMediaType: ignoreRequestedMediaType,
includeBlobMetadata: includeBlobMetadata,
saveAbsolutePath: saveAbsolutePath,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.4",
"Container",
"e4f5c81e-e250-447b-9fef-bd48471bea5e",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<FileContainerInterfaces.FileContainerItem[]>;
res = await this.rest.get<FileContainerInterfaces.FileContainerItem[]>(url, options);
let ret = this.formatResponse(res.result,
FileContainerInterfaces.TypeInfo.FileContainerItem,
true);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
} | the_stack |
import React, { PureComponent } from 'react';
import _ from 'lodash';
import { NavModel, DataSourcePluginMeta, getBootConfig, DataSourcePlugin, DataSourceApi, DataQuery, DataSourceJsonData, DataSourceSettings, getBackendSrv, setBootConfig, currentLang, getHistory } from 'src/packages/datav-core/src'
import { InlineFormLabel, LegacyForms, ConfirmModal, Button } from 'src/packages/datav-core/src/ui'
import { withRouter } from 'react-router-dom';
import { Input, notification, Alert } from 'antd';
import Page from 'src/views/Layouts/Page/Page';
import { loadDataSourcePlugin, testDataSource } from 'src/plugins/loader';
import { PluginSettings } from './PluginSettings'
import globalEvents from 'src/views/App/globalEvents';
import { connect } from 'react-redux';
import { StoreState } from 'src/types'
import localeData from 'src/core/library/locale'
import { getState } from 'src/store/store';
import { FormattedMessage } from 'react-intl';
const { Switch } = LegacyForms
type GenericDataSourcePlugin = DataSourcePlugin<DataSourceApi<DataQuery, DataSourceJsonData>>;
interface Props {
match: any
history: any
locale: string
}
interface State {
mode: string
dataSource: DataSourceSettings;
datasourceMeta: DataSourcePluginMeta
navModel: NavModel
plugin?: GenericDataSourcePlugin
hasFetched: boolean
testingStatus?: {
status: boolean
message?: any
}
confirmVisible: boolean
}
enum DatasourceMode {
New = "new",
Edit = "edit"
}
const layout = {
wrapperCol: { span: 16 },
labelCol: { span: 16 }
};
export class EditDataSourcePage extends PureComponent<Props, State> {
constructor(props) {
super(props)
const datasourceId = _.toNumber(this.props.match.params.datasourceID)
let mode = DatasourceMode.Edit
if (!datasourceId) {
// not number, new datasource mode, otherwise, edit datasource mode
mode = DatasourceMode.New
}
let ds;
if (mode === DatasourceMode.New) {
ds = {
isDefault: Object.keys(getBootConfig().datasources).length === 0,
name: '',
url: '',
jsonData: {
}
}
}
let meta: DataSourcePluginMeta;
let node = {} as any
let hasFetched = false
if (mode === DatasourceMode.New) {
meta = getBootConfig().datasourceMetas[this.props.match.params.datasourceID]
ds.type = meta.id
node = {
img: meta.info.logos.small,
id: 'datasource-new',
title: localeData[currentLang]['datasource.add'],
href: 'datasources/new',
subTitle: localeData[currentLang]['common.type'] + ': ' + meta.name,
}
hasFetched = true
}
this.state = {
mode: mode,
datasourceMeta: meta,
navModel: {
main: node,
node: node,
},
dataSource: ds,
hasFetched: hasFetched,
confirmVisible: false
}
this.onFinish = this.onFinish.bind(this)
}
async componentWillMount() {
if (this.state.mode === DatasourceMode.Edit) {
const res = await getBackendSrv().get(`/api/datasources/${this.props.match.params.datasourceID}`)
const ds: DataSourceSettings = res.data
console.log(getBootConfig().datasourceMetas)
const meta = getBootConfig().datasourceMetas[ds.type]
const node = {
img: meta.info.logos.small,
id: 'datasource-new',
text: localeData[getState().application.locale]['datasource.edit'],
href: 'datasources/new',
subTitle: localeData[getState().application.locale]['common.type'] + ' : ' + meta.name,
}
this.setState({
...this.state,
dataSource: ds,
datasourceMeta: meta,
hasFetched: true,
navModel: {
main: node,
node: node,
},
})
}
const plugin = await loadDataSourcePlugin(this.state.datasourceMeta.id)
this.setState({
...this.state,
plugin
})
}
async delDataSource() {
const res = await getBackendSrv().delete(`/api/datasources/${this.state.dataSource.id}`)
const res1 = await getBackendSrv().get('/api/bootConfig');
setBootConfig(res1.data)
if (res.status === 'success') {
globalEvents.showMessage(() => notification['success']({
message: "Success",
description: localeData[currentLang]['info.targetDeleted'],
duration: 5
}))
this.props.history.push('/cfg/datasources')
}
}
async onFinish() {
if (_.isEmpty(this.state.dataSource.name)) {
notification['error']({
message: "Error",
description: localeData[currentLang]['datasource.nameEmpty'],
duration: 5
})
return
}
// save options to backend
if (this.state.mode === DatasourceMode.New) {
const res = await getBackendSrv().post('/api/datasources/new', this.state.dataSource)
const res1 = await getBackendSrv().get('/api/bootConfig');
setBootConfig(res1.data)
// replace url with datasource id
this.props.history.replace('/datasources/edit/' + res.data.id)
this.setState({
...this.state,
dataSource: res.data,
mode: DatasourceMode.Edit
})
} else {
getBackendSrv().put('/api/datasources/edit', this.state.dataSource)
}
testDataSource(this.state.dataSource.name).then(() => {
this.setState({
...this.state,
testingStatus: {
status: true
}
})
}).catch((err) => {
this.setState({
...this.state,
testingStatus: {
status: true,
message: err.message ?? err.data.message
}
})
})
};
onFinishFailed(errorInfo) {
console.log('Failed:', errorInfo);
};
onModelChange = (dataSource: DataSourceSettings) => {
this.setState({
...this.state,
dataSource
})
};
render() {
const { locale } = this.props
return (
<Page navModel={this.state.navModel}>
<Page.Contents isLoading={!this.state.hasFetched}>
{
this.state.hasFetched &&
<>
<h3 className="page-heading"><FormattedMessage id="common.basicSetting" /></h3>
<div className="gf-form-group">
<div className="gf-form-inline">
<div className="gf-form max-width-30" style={{ marginRight: '3px' }}>
<InlineFormLabel
tooltip={<FormattedMessage id="datasource.nameTooltip" />}
>
<FormattedMessage id="common.name" />
</InlineFormLabel>
<Input placeholder="Name" defaultValue={this.state.dataSource.name} onChange={(e) => { this.setState({ ...this.state, dataSource: { ...this.state.dataSource, name: e.currentTarget.value } }) }} />
</div>
<Switch
label={localeData[locale]['common.default']}
checked={this.state.dataSource.isDefault}
//@ts-ignore
onChange={(e) => { this.setState({ ...this.state, dataSource: { ...this.state.dataSource, isDefault: e.target.checked } }) }}
/>
</div>
</div>
{this.state.plugin && (
<PluginSettings
plugin={this.state.plugin}
dataSource={this.state.dataSource}
dataSourceMeta={this.state.datasourceMeta}
onChange={this.onModelChange}
/>
)}
<div className="gf-form-group max-width-30">
{
this.state.testingStatus && this.state.testingStatus.status && !this.state.testingStatus.message && <Alert
className="ub-mb2"
message={<FormattedMessage id="common.congratulations" />}
description={<FormattedMessage id="datasource.isWorking" />}
type="success"
showIcon
/>
}
{
this.state.testingStatus && this.state.testingStatus.status && this.state.testingStatus.message && <Alert
className="ub-mb2"
message={<FormattedMessage id="datasource.testFailed" />}
description={this.state.testingStatus.message}
type="error"
showIcon
/>
}
<Button variant="primary" onClick={() => this.onFinish()}>
<FormattedMessage id="common.save" /> & <FormattedMessage id="common.test" />
</Button>
<Button variant="destructive" className="ub-ml2" onClick={() => this.setState({ ...this.state, confirmVisible: true })}>
<FormattedMessage id="common.delete" />
</Button>
<Button variant="secondary" className="ub-ml2" onClick={() => getHistory().push('/cfg/datasources')}>
<FormattedMessage id="common.back" />
</Button>
<ConfirmModal
isOpen={this.state.confirmVisible}
title={localeData[locale]['datasource.delete']}
body={<FormattedMessage id="datasource.deleteTitle" />}
confirmText="Delete"
onConfirm={() => this.delDataSource()}
onDismiss={() => this.setState({ ...this.state, confirmVisible: false })}
/>
</div>
</>
}
</Page.Contents>
</Page>
);
}
}
export const mapStateToProps = (state: StoreState) => ({
locale: state.application.locale
});
export default withRouter(connect(mapStateToProps)(EditDataSourcePage)); | the_stack |
import { ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { NavigationEnd, NavigationStart, Router, RouterState } from '@angular/router';
import { HttpTestingController } from '@angular/common/http/testing';
import { Observable, of } from 'rxjs';
import { LocalStorageService, SessionStorageService } from 'ngx-webstorage';
import { TranslateService } from '@ngx-translate/core';
import { ArtemisTestModule } from '../test.module';
import { GuidedTour } from 'app/guided-tour/guided-tour.model';
import { GuidedTourService } from 'app/guided-tour/guided-tour.service';
import { GuidedTourState, Orientation, ResetParticipation, UserInteractionEvent } from 'app/guided-tour/guided-tour.constants';
import { GuidedTourComponent } from 'app/guided-tour/guided-tour.component';
import { GuidedTourMapping, GuidedTourSetting } from 'app/guided-tour/guided-tour-setting.model';
import { AssessmentTaskTourStep, ModelingTaskTourStep, TextTourStep, UserInterActionTourStep } from 'app/guided-tour/guided-tour-step.model';
import { AccountService } from 'app/core/auth/account.service';
import { Course } from 'app/entities/course.model';
import { MockTranslateService, TranslatePipeMock } from '../helpers/mocks/service/mock-translate.service';
import { AssessmentObject, GuidedTourAssessmentTask, GuidedTourModelingTask, personUML } from 'app/guided-tour/guided-tour-task.model';
import { completedTour } from 'app/guided-tour/tours/general-tour';
import { HttpResponse } from '@angular/common/http';
import { ParticipationService } from 'app/exercises/shared/participation/participation.service';
import { Exercise, ExerciseType } from 'app/entities/exercise.model';
import { InitializationState } from 'app/entities/participation/participation.model';
import { NavbarComponent } from 'app/shared/layouts/navbar/navbar.component';
import { StudentParticipation } from 'app/entities/participation/student-participation.model';
import { MockSyncStorage } from '../helpers/mocks/service/mock-sync-storage.service';
import { CourseManagementService } from 'app/course/manage/course-management.service';
import { MockComponent, MockDirective, MockPipe } from 'ng-mocks';
import { SafeResourceUrlPipe } from 'app/shared/pipes/safe-resource-url.pipe';
import { User } from 'app/core/user/user.model';
import { ProfileService } from 'app/shared/layouts/profiles/profile.service';
import { ProfileInfo } from 'app/shared/layouts/profiles/profile-info.model';
import { TranslateDirective } from 'app/shared/language/translate.directive';
import { LoadingNotificationComponent } from 'app/shared/notification/loading-notification/loading-notification.component';
import { NotificationSidebarComponent } from 'app/shared/notification/notification-sidebar/notification-sidebar.component';
import { MockHasAnyAuthorityDirective } from '../helpers/mocks/directive/mock-has-any-authority.directive';
import { NgbCollapse, NgbDropdown } from '@ng-bootstrap/ng-bootstrap';
import { ActiveMenuDirective } from 'app/shared/layouts/navbar/active-menu.directive';
import { FindLanguageFromKeyPipe } from 'app/shared/language/find-language-from-key.pipe';
import { MockRouter } from '../helpers/mocks/mock-router';
class MockRouterWithEvents {
public url = 'courses';
public events = new Observable((observer) => {
observer.next(new NavigationStart(0, 'courses'));
observer.next(new NavigationEnd(1, 'courses', 'courses'));
observer.complete();
});
public routerState = {} as RouterState;
}
describe('GuidedTourService', () => {
const tour: GuidedTour = {
settingsKey: 'tour',
resetParticipation: ResetParticipation.EXERCISE_PARTICIPATION,
steps: [
new TextTourStep({ highlightSelector: '.random-selector', headlineTranslateKey: '', contentTranslateKey: '' }),
new TextTourStep({ headlineTranslateKey: '', contentTranslateKey: '', orientation: Orientation.TOPLEFT }),
],
};
const tourWithUserInteraction: GuidedTour = {
settingsKey: 'tour_user_interaction',
resetParticipation: ResetParticipation.EXERCISE_PARTICIPATION,
steps: [
new UserInterActionTourStep({
highlightSelector: '.random-selector',
headlineTranslateKey: '',
contentTranslateKey: '',
userInteractionEvent: UserInteractionEvent.CLICK,
}),
new TextTourStep({ headlineTranslateKey: '', contentTranslateKey: '', orientation: Orientation.TOPLEFT, pageUrl: 'courses' }),
],
};
const tourWithCourseAndExercise: GuidedTour = {
settingsKey: 'tour_with_course_and_exercise',
resetParticipation: ResetParticipation.EXERCISE_PARTICIPATION,
steps: [
new TextTourStep({ headlineTranslateKey: '', contentTranslateKey: '' }),
new TextTourStep({ headlineTranslateKey: '', contentTranslateKey: '', orientation: Orientation.TOPLEFT }),
],
};
const tourWithModelingTask: GuidedTour = {
settingsKey: 'tour_modeling_task',
resetParticipation: ResetParticipation.EXERCISE_PARTICIPATION,
steps: [
new ModelingTaskTourStep({
headlineTranslateKey: '',
contentTranslateKey: '',
modelingTask: new GuidedTourModelingTask(personUML.name, ''),
userInteractionEvent: UserInteractionEvent.MODELING,
}),
],
};
describe('Service method', () => {
let service: GuidedTourService;
let httpMock: HttpTestingController;
const expected = new GuidedTourSetting('guided_tour_key', 1, GuidedTourState.STARTED);
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ArtemisTestModule],
providers: [
{ provide: LocalStorageService, useClass: MockSyncStorage },
{ provide: SessionStorageService, useClass: MockSyncStorage },
],
}).compileComponents();
service = TestBed.inject(GuidedTourService);
httpMock = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
it('should call the correct update URL and return the right JSON object', () => {
service.guidedTourSettings = [];
service['updateGuidedTourSettings']('guided_tour_key', 1, GuidedTourState.STARTED).subscribe();
const req = httpMock.expectOne({ method: 'PUT' });
const resourceUrl = SERVER_API_URL + 'api/guided-tour-settings';
expect(req.request.url).toBe(`${resourceUrl}`);
expect(service.guidedTourSettings).toEqual([expected]);
});
it('should call the correct delete URL', () => {
service.guidedTourSettings = [new GuidedTourSetting('guided_tour_key', 1, GuidedTourState.STARTED)];
service['deleteGuidedTourSetting']('guided_tour_key').subscribe();
const req = httpMock.expectOne({ method: 'DELETE' });
const resourceUrl = SERVER_API_URL + 'api/guided-tour-settings';
expect(req.request.url).toBe(`${resourceUrl}/guided_tour_key`);
expect(service.guidedTourSettings).toEqual([]);
});
});
describe('Guided tour methods', () => {
let guidedTourComponent: GuidedTourComponent;
let guidedTourComponentFixture: ComponentFixture<GuidedTourComponent>;
let router: Router;
let guidedTourService: GuidedTourService;
let participationService: ParticipationService;
let courseService: CourseManagementService;
let findParticipationStub: jest.SpyInstance;
let deleteParticipationStub: jest.SpyInstance;
let deleteGuidedTourSettingStub: jest.SpyInstance;
let navigateByUrlSpy: jest.SpyInstance;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ArtemisTestModule],
declarations: [
GuidedTourComponent,
MockDirective(TranslateDirective),
TranslatePipeMock,
MockPipe(SafeResourceUrlPipe),
MockComponent(LoadingNotificationComponent),
MockComponent(NotificationSidebarComponent),
MockDirective(NgbCollapse),
MockHasAnyAuthorityDirective,
MockDirective(ActiveMenuDirective),
MockDirective(NgbDropdown),
MockPipe(FindLanguageFromKeyPipe),
],
providers: [
{ provide: LocalStorageService, useClass: MockSyncStorage },
{ provide: SessionStorageService, useClass: MockSyncStorage },
{ provide: TranslateService, useClass: MockTranslateService },
{ provide: Router, useClass: MockRouter },
],
})
.compileComponents()
.then(() => {
guidedTourComponentFixture = TestBed.createComponent(GuidedTourComponent);
guidedTourComponent = guidedTourComponentFixture.componentInstance;
router = TestBed.inject(Router);
guidedTourService = TestBed.inject(GuidedTourService);
participationService = TestBed.inject(ParticipationService);
courseService = TestBed.inject(CourseManagementService);
findParticipationStub = jest.spyOn(participationService, 'findParticipationForCurrentUser');
deleteParticipationStub = jest.spyOn(participationService, 'deleteForGuidedTour');
// @ts-ignore
deleteGuidedTourSettingStub = jest.spyOn(guidedTourService, 'deleteGuidedTourSetting');
navigateByUrlSpy = jest.spyOn(router, 'navigateByUrl');
});
});
function prepareGuidedTour(guidedTour: GuidedTour) {
// Prepare GuidedTourService and GuidedTourComponent
jest.spyOn(guidedTourService, 'init').mockImplementation();
jest.spyOn(guidedTourService, 'getLastSeenTourStepIndex').mockReturnValue(0);
jest.spyOn<any, any>(guidedTourService, 'checkSelectorValidity').mockReturnValue(true);
jest.spyOn<any, any>(guidedTourService, 'checkTourState').mockReturnValue(true);
jest.spyOn<any, any>(guidedTourService, 'updateGuidedTourSettings').mockReturnValue(of());
jest.spyOn<any, any>(guidedTourService, 'enableTour').mockImplementation(() => {
guidedTourService['availableTourForComponent'] = guidedTour;
guidedTourService.currentTour = guidedTour;
});
jest.spyOn<any, any>(guidedTourComponent, 'subscribeToDotChanges').mockImplementation(() => {});
}
function startCourseOverviewTour(guidedTour: GuidedTour) {
guidedTourComponent.ngAfterViewInit();
guidedTourComponentFixture.ngZone!.run(() => {
router.navigateByUrl('/courses');
});
// Start course overview tour
expect(guidedTourComponentFixture.debugElement.query(By.css('.tour-step'))).toBe(null);
guidedTourService['enableTour'](guidedTour, true);
guidedTourService['startTour']();
guidedTourComponentFixture.detectChanges();
expect(guidedTourComponentFixture.debugElement.query(By.css('.tour-step'))).not.toBe(null);
expect(guidedTourService.isOnFirstStep).toBeTrue();
expect(guidedTourService.currentTourStepDisplay).toBe(1);
expect(guidedTourService.currentTourStepCount).toBe(2);
}
describe('Tours without user interaction', () => {
beforeEach(() => {
prepareGuidedTour(tour);
startCourseOverviewTour(tour);
});
it('should start and finish the course overview guided tour', async () => {
// Navigate to next step
const nextButton = guidedTourComponentFixture.debugElement.query(By.css('.next-button'));
expect(nextButton).not.toBe(null);
nextButton.nativeElement.click();
expect(guidedTourService.isOnLastStep).toBeTrue();
// Finish guided tour
nextButton.nativeElement.click();
guidedTourComponentFixture.detectChanges();
const tourStep = guidedTourComponentFixture.debugElement.query(By.css('.tour-step'));
expect(tourStep).toBe(null);
});
it('should start and skip the tour', () => {
const skipButton = guidedTourComponentFixture.debugElement.query(By.css('.btn-close'));
expect(skipButton).not.toBe(null);
skipButton.nativeElement.click();
guidedTourComponentFixture.detectChanges();
const tourStep = guidedTourComponentFixture.debugElement.query(By.css('.tour-step'));
expect(tourStep).toBe(null);
});
it('backdrop should prevent from advancing', () => {
const backdrop = guidedTourComponentFixture.debugElement.queryAll(By.css('.guided-tour-overlay'));
expect(backdrop).toHaveLength(1);
backdrop.forEach((overlay) => {
overlay.nativeElement.click();
});
guidedTourComponentFixture.detectChanges();
expect(guidedTourService.isOnFirstStep).toBeTrue();
});
});
describe('Tours with user interaction', () => {
beforeEach(() => {
prepareGuidedTour(tourWithUserInteraction);
startCourseOverviewTour(tourWithUserInteraction);
});
it('should disable the next button', () => {
guidedTourComponentFixture.detectChanges();
const nextButton = guidedTourComponentFixture.debugElement.nativeElement.querySelector('.next-button').disabled;
expect(nextButton).not.toBe(null);
});
});
describe('Tour for a certain course and exercise', () => {
const guidedTourMapping = { courseShortName: 'tutorial', tours: { tour_with_course_and_exercise: 'git' } } as GuidedTourMapping;
const exercise1 = { id: 1, shortName: 'git', type: ExerciseType.PROGRAMMING } as Exercise;
const exercise2 = { id: 2, shortName: 'test', type: ExerciseType.PROGRAMMING } as Exercise;
const exercise3 = { id: 3, shortName: 'git', type: ExerciseType.MODELING } as Exercise;
const course1 = { id: 1, shortName: 'tutorial', exercises: [exercise2, exercise1] } as Course;
const course2 = { id: 2, shortName: 'test' } as Course;
function resetCurrentTour(): void {
guidedTourService['currentCourse'] = undefined;
guidedTourService['currentExercise'] = undefined;
guidedTourService.currentTour = completedTour;
guidedTourService.resetTour();
}
function currentCourseAndExerciseUndefined(): void {
expect(guidedTourService.currentTour).toBe(undefined);
expect(guidedTourService['currentCourse']).toBe(undefined);
expect(guidedTourService['currentExercise']).toBe(undefined);
}
beforeEach(() => {
guidedTourService.guidedTourMapping = guidedTourMapping;
prepareGuidedTour(tourWithCourseAndExercise);
resetCurrentTour();
});
it('should start the tour for the matching course title', () => {
jest.spyOn(courseService, 'findWithExercises').mockReturnValue(of({ body: course1 } as HttpResponse<any>));
const courses = [course1];
// enable tour for matching course title
guidedTourService.enableTourForCourseOverview(courses, tourWithCourseAndExercise, true);
expect(guidedTourService.currentTour).toEqual(tourWithCourseAndExercise);
expect(guidedTourService['currentCourse']).toEqual(course1);
expect(guidedTourService['currentExercise']).toEqual(exercise1);
resetCurrentTour();
guidedTourService.guidedTourMapping = { courseShortName: 'tutorial', tours: { tour_with_course_and_exercise: '' } } as GuidedTourMapping;
// enable tour for matching course title
guidedTourService.enableTourForCourseOverview(courses, tourWithCourseAndExercise, true);
expect(guidedTourService.currentTour).toEqual(tourWithCourseAndExercise);
expect(guidedTourService['currentCourse']).toEqual(course1);
expect(guidedTourService['currentExercise']).toBe(undefined);
resetCurrentTour();
});
it('should disable the tour for not matching course title', () => {
const courses = [course2];
// disable tour for not matching titles
guidedTourService.enableTourForCourseOverview(courses, tourWithCourseAndExercise, true);
currentCourseAndExerciseUndefined();
});
it('should start the tour for the matching exercise short name', () => {
// disable tour for exercises without courses
guidedTourService.currentTour = undefined;
guidedTourService.enableTourForExercise(exercise1, tourWithCourseAndExercise, true);
currentCourseAndExerciseUndefined();
resetCurrentTour();
// disable tour for not matching course and exercise identifiers
exercise2.course = course2;
guidedTourService.enableTourForExercise(exercise2, tourWithCourseAndExercise, true);
currentCourseAndExerciseUndefined();
resetCurrentTour();
// disable tour for not matching course identifier
exercise3.course = course2;
guidedTourService.enableTourForExercise(exercise3, tourWithCourseAndExercise, true);
currentCourseAndExerciseUndefined();
resetCurrentTour();
// enable tour for matching course and exercise identifiers
exercise1.course = course1;
guidedTourService.enableTourForExercise(exercise1, tourWithCourseAndExercise, true);
expect(guidedTourService.currentTour).toEqual(tourWithCourseAndExercise);
expect(guidedTourService['currentCourse']).toEqual(course1);
expect(guidedTourService['currentExercise']).toEqual(exercise1);
});
it('should start the tour for the matching course / exercise short name', () => {
guidedTourService.currentTour = undefined;
// enable tour for matching course / exercise short name
guidedTourService.enableTourForCourseExerciseComponent(course1, tourWithCourseAndExercise, true);
expect(guidedTourService.currentTour).toEqual(tourWithCourseAndExercise);
course1.exercises!.forEach((exercise) => {
exercise.course = course1;
if (exercise === exercise1) {
expect(guidedTourService['isGuidedTourAvailableForExercise'](exercise)).toBeTrue();
} else {
expect(guidedTourService['isGuidedTourAvailableForExercise'](exercise)).toBeFalse();
}
});
// disable tour for not matching course without exercise
guidedTourService.currentTour = undefined;
guidedTourService.enableTourForCourseExerciseComponent(course2, tourWithCourseAndExercise, true);
expect(guidedTourService.currentTour).toBe(undefined);
// disable tour for not matching course but matching exercise identifier
guidedTourService.currentTour = undefined;
course2.exercises = [exercise3];
guidedTourService.enableTourForCourseExerciseComponent(course2, tourWithCourseAndExercise, true);
expect(guidedTourService.currentTour).toBe(undefined);
});
describe('Tour with student participation', () => {
const studentParticipation1 = { id: 1, student: { id: 1 }, exercise: exercise1, initializationState: InitializationState.INITIALIZED } as StudentParticipation;
const studentParticipation2 = { id: 2, student: { id: 1 }, exercise: exercise3, initializationState: InitializationState.INITIALIZED } as StudentParticipation;
const httpResponse1 = { body: studentParticipation1 } as HttpResponse<StudentParticipation>;
const httpResponse2 = { body: studentParticipation2 } as HttpResponse<StudentParticipation>;
const exercise4 = { id: 4, title: 'git', type: ExerciseType.MODELING } as Exercise;
function prepareParticipation(exercise: Exercise, studentParticipation: StudentParticipation, httpResponse: HttpResponse<StudentParticipation>) {
exercise.course = course1;
exercise.studentParticipations = [studentParticipation];
navigateByUrlSpy.mockClear();
findParticipationStub.mockClear();
findParticipationStub.mockReturnValue(of(httpResponse));
deleteParticipationStub.mockClear();
deleteParticipationStub.mockReturnValue(of(undefined));
deleteGuidedTourSettingStub.mockClear();
deleteGuidedTourSettingStub.mockReturnValue(of(undefined));
}
it('should find and delete the student participation for exercise', () => {
course1.exercises!.push(exercise4);
prepareParticipation(exercise1, studentParticipation1, httpResponse1);
guidedTourService.enableTourForExercise(exercise1, tourWithCourseAndExercise, true);
guidedTourService.restartTour();
expect(findParticipationStub).toHaveBeenCalledOnce();
expect(findParticipationStub).toHaveBeenCalledWith(1);
expect(deleteParticipationStub).toHaveBeenCalledOnce();
expect(deleteParticipationStub).toHaveBeenCalledWith(1, { deleteBuildPlan: true, deleteRepository: true });
expect(deleteGuidedTourSettingStub).toHaveBeenCalledOnce();
expect(deleteGuidedTourSettingStub).toHaveBeenCalledWith('tour_with_course_and_exercise');
expect(navigateByUrlSpy).toHaveBeenCalledOnce();
expect(navigateByUrlSpy).toHaveBeenCalledWith('/courses/1/exercises');
prepareParticipation(exercise4, studentParticipation2, httpResponse2);
guidedTourService.enableTourForExercise(exercise4, tourWithCourseAndExercise, true);
guidedTourService.restartTour();
expect(findParticipationStub).toHaveBeenCalledOnce();
expect(findParticipationStub).toHaveBeenCalledWith(4);
expect(deleteParticipationStub).toHaveBeenCalledOnce();
expect(deleteParticipationStub).toHaveBeenCalledWith(2, { deleteBuildPlan: false, deleteRepository: false });
expect(deleteGuidedTourSettingStub).toHaveBeenCalledOnce();
expect(deleteGuidedTourSettingStub).toHaveBeenCalledWith('tour_with_course_and_exercise');
expect(navigateByUrlSpy).toHaveBeenCalledOnce();
expect(navigateByUrlSpy).toHaveBeenCalledWith('/courses/1/exercises');
const index = course1.exercises!.findIndex((exercise) => (exercise.id = exercise4.id));
course1.exercises!.splice(index, 1);
});
});
});
describe('Modeling check', () => {
it('should enable the next step if the results are correct', inject(
[],
fakeAsync(() => {
const enableNextStep = jest.spyOn<any, any>(guidedTourService, 'enableNextStepClick').mockImplementation();
guidedTourService.currentTour = tourWithModelingTask;
guidedTourService.updateModelingResult(personUML.name, true);
tick(0);
expect(enableNextStep).toHaveBeenCalledOnce();
}),
));
});
describe('getGuidedTourAvailabilityStream', () => {});
describe('checkModelingComponent', () => {});
describe('updateModelingResult', () => {});
describe('componentPageLoaded', () => {});
describe('isCurrentStep', () => {
const step1 = new TextTourStep({ highlightSelector: '.random-selector', headlineTranslateKey: '', contentTranslateKey: '' });
const step2 = new TextTourStep({ headlineTranslateKey: '', contentTranslateKey: '', orientation: Orientation.TOPLEFT });
const guidedTour: GuidedTour = {
settingsKey: 'tour2',
resetParticipation: ResetParticipation.EXERCISE_PARTICIPATION,
steps: [step1, step2],
};
it('should return true if it is the current Step', () => {
guidedTourService.currentTour = guidedTour;
expect(guidedTourService.isCurrentStep(step1)).toBeTrue();
guidedTourService.currentTourStepIndex += 1;
expect(guidedTourService.isCurrentStep(step2)).toBeTrue();
});
it('should return false if it is not the current Step', () => {
guidedTourService.currentTour = guidedTour;
expect(guidedTourService.isCurrentStep(step2)).toBeFalse();
guidedTourService.currentTourStepIndex += 1;
expect(guidedTourService.isCurrentStep(step1)).toBeFalse();
});
it('should return false if current Tour is undefined', () => {
expect(guidedTourService.isCurrentStep(step1)).toBeFalse();
});
});
describe('isCurrentTour', () => {
it('should return true if it is the current Tour', () => {
guidedTourService.currentTour = tour;
expect(guidedTourService.isCurrentTour(tour)).toBeTrue();
});
it('should return false if it is not the current Tour', () => {
expect(guidedTourService.isCurrentTour(tour)).toBeFalse();
});
it('should return false if the current Tour is undefined', () => {
guidedTourService.currentTour = tourWithCourseAndExercise;
expect(guidedTourService.isCurrentTour(tour)).toBeFalse();
});
});
describe('getCurrentStepString', () => {
it('should return nothing if currentTour is undefined', () => {
expect(guidedTourService.getCurrentStepString()).toBe(undefined);
});
it('should return correct string if currentTour is defined', () => {
guidedTourService.currentTour = tour;
expect(guidedTourService.getCurrentStepString()).toBe('1 / 2');
});
});
describe('backStep, nextStep', () => {
let currentDotSubjectSpy: any;
let resetSpy: any;
beforeEach(() => {
currentDotSubjectSpy = jest.spyOn<any, any>(guidedTourService.currentDotSubject, 'next');
resetSpy = jest.spyOn<any, any>(guidedTourService, 'resetTour');
});
afterEach(() => {
jest.clearAllMocks();
});
it('backStep should just return if currentTour is not defined', () => {
guidedTourService.backStep();
expect(currentDotSubjectSpy).toHaveBeenCalledTimes(0);
expect(resetSpy).toHaveBeenCalledTimes(0);
});
it('backStep should reset tour if currentTour is defined', () => {
guidedTourService.currentTour = tour;
guidedTourService.backStep();
expect(currentDotSubjectSpy).toHaveBeenCalledOnce();
expect(resetSpy).toHaveBeenCalledOnce();
});
it('nextStep should just return if currentTour is not defined', () => {
guidedTourService.nextStep();
expect(currentDotSubjectSpy).toHaveBeenCalledTimes(0);
expect(resetSpy).toHaveBeenCalledTimes(0);
});
it('nextStep should reset return if currentTour is defined', () => {
guidedTourService.currentTour = tour;
guidedTourService.nextStep();
expect(currentDotSubjectSpy).toHaveBeenCalledOnce();
});
it('nextStep and backStep should return to initial step', fakeAsync(() => {
guidedTourService.currentTour = tour;
const initialStep = guidedTourService.currentTourStepIndex;
guidedTourService.nextStep();
tick();
guidedTourService.backStep();
tick();
expect(currentDotSubjectSpy).toHaveBeenCalledTimes(2);
expect(guidedTourService.currentTourStepIndex).toBe(initialStep);
}));
});
describe('finishGuidedTour', () => {
it('should just return if currentTour is not defined', () => {
guidedTourService.finishGuidedTour();
});
});
describe('skipTour', () => {
it('should just return if currentTour is not defined', () => {
guidedTourService.skipTour();
});
});
describe('subscribeToAndUpdateGuidedTourSettings', () => {});
describe('getLastSeenTourStepIndex', () => {});
describe('resetTour', () => {});
describe('enableUserInteraction', () => {
const addEventListener = jest.fn();
const htmlTarget = { addEventListener } as any;
let observeMutationsStub: jest.SpyInstance;
let handleWaitForSelectorEventSpy: jest.SpyInstance;
let querySelectorSpy: jest.SpyInstance;
beforeEach(() => {
guidedTourService.currentTour = tour;
observeMutationsStub = jest.spyOn(guidedTourService, 'observeMutations');
handleWaitForSelectorEventSpy = jest.spyOn<any, any>(guidedTourService, 'handleWaitForSelectorEvent');
querySelectorSpy = jest.spyOn(document, 'querySelector');
querySelectorSpy.mockClear();
});
afterEach(() => {
jest.clearAllMocks();
});
it('should enableUserInteraction with UserInteractionEvent.WAIT_FOR_SELECTOR', fakeAsync(() => {
const userInteractionEvent = UserInteractionEvent.WAIT_FOR_SELECTOR;
guidedTourService.enableUserInteraction({} as any, userInteractionEvent);
expect(handleWaitForSelectorEventSpy).toHaveBeenCalledOnce();
expect(querySelectorSpy).toHaveBeenCalledTimes(0);
}));
it('should enableUserInteraction with UserInteractionEvent.CLICK', fakeAsync(() => {
const userInteractionEvent = UserInteractionEvent.CLICK;
guidedTourService.enableUserInteraction(htmlTarget, userInteractionEvent);
expect(querySelectorSpy).toHaveBeenCalledTimes(0);
}));
it('should enableUserInteraction with UserInteractionEvent.ACE_EDITOR', fakeAsync(() => {
const userInteractionEvent = UserInteractionEvent.ACE_EDITOR;
observeMutationsStub.mockReturnValue(of({ addedNodes: { length: 0 } as NodeList, removedNodes: { length: 0 } as NodeList } as MutationRecord));
guidedTourService.enableUserInteraction(htmlTarget, userInteractionEvent);
expect(querySelectorSpy).toHaveBeenCalledOnce();
}));
it('should enableUserInteraction with UserInteractionEvent.MODELING', fakeAsync(() => {
const userInteractionEvent = UserInteractionEvent.MODELING;
observeMutationsStub.mockReturnValue(of({ addedNodes: { length: 0 } as NodeList, removedNodes: { length: 0 } as NodeList } as MutationRecord));
guidedTourService.enableUserInteraction(htmlTarget, userInteractionEvent);
expect(querySelectorSpy).toHaveBeenCalledOnce();
}));
it('should enableUserInteraction with UserInteractionEvent.ASSESS_SUBMISSION', fakeAsync(() => {
const isAssessmentCorrectSpy = jest.spyOn<any, any>(guidedTourService, 'isAssessmentCorrect');
const userInteractionEvent = UserInteractionEvent.ASSESS_SUBMISSION;
guidedTourService.enableUserInteraction(htmlTarget, userInteractionEvent);
expect(isAssessmentCorrectSpy).toHaveBeenCalledOnce();
expect(querySelectorSpy).toHaveBeenCalledTimes(0);
}));
});
describe('observeMutations', () => {});
describe('initGuidedTour', () => {});
describe('restartTour', () => {});
describe('preventBackdropFromAdvancing', () => {});
describe('enableTourForCourseExerciseComponent', () => {});
describe('enableTourForCourseOverview', () => {});
describe('enableTourForExercise', () => {
const exerciseText = { id: 456, course: { id: 123 } as Course, type: ExerciseType.TEXT } as Exercise;
const exerciseProgramming = { id: 456, course: { id: 123 } as Course, type: ExerciseType.PROGRAMMING } as Exercise;
const guidedTourMapping = { courseShortName: 'tutorial', tours: { tour_with_course_and_exercise: 'git' } } as GuidedTourMapping;
let enableTourSpy: any;
let startTourSpy: any;
const guidedTourSettings = [new GuidedTourSetting('guided_tour_key', 1, GuidedTourState.STARTED)];
beforeEach(() => {
enableTourSpy = jest.spyOn<any, any>(guidedTourService, 'enableTour').mockImplementation();
startTourSpy = jest.spyOn<any, any>(guidedTourService, 'startTour').mockImplementation();
jest.spyOn<any, any>(guidedTourService, 'checkTourState').mockImplementation();
guidedTourService.guidedTourMapping = guidedTourMapping;
guidedTourService.guidedTourSettings = [];
});
afterEach(() => {
jest.restoreAllMocks();
});
describe('return undefined if parameters are undefined', () => {
it('should return undefined if exercise.course is undefined', fakeAsync(() => {
const inputExercise = {} as Exercise;
expect(guidedTourService.enableTourForExercise(inputExercise, tour, true)).toBe(undefined);
expect(enableTourSpy).toHaveBeenCalledTimes(0);
}));
it('should return undefined if guidedTour mapping is undefined', fakeAsync(() => {
guidedTourService.guidedTourMapping = undefined;
expect(guidedTourService.enableTourForExercise(exerciseText, tour, true)).toBe(undefined);
}));
});
it('should enableTourForExercise for text exercise', fakeAsync(() => {
expect(guidedTourService.enableTourForExercise(exerciseText, tour, true)).toEqual(exerciseText);
expect(enableTourSpy).toHaveBeenCalledOnce();
expect(startTourSpy).toHaveBeenCalledTimes(0);
}));
it('should enableTourForExercise for text exercise', fakeAsync(() => {
expect(guidedTourService.enableTourForExercise(exerciseText, tour, true)).toEqual(exerciseText);
expect(enableTourSpy).toHaveBeenCalledOnce();
expect(startTourSpy).toHaveBeenCalledTimes(0);
}));
it('should enableTourForExercise for programming exercise', fakeAsync(() => {
expect(guidedTourService.enableTourForExercise(exerciseProgramming, tour, true)).toEqual(exerciseProgramming);
expect(enableTourSpy).toHaveBeenCalledOnce();
expect(startTourSpy).toHaveBeenCalledTimes(0);
}));
it('should enableTourForExercise for text exercise with init set to false', fakeAsync(() => {
guidedTourService.guidedTourSettings = guidedTourSettings;
expect(guidedTourService.enableTourForExercise(exerciseText, tour, false)).toEqual(exerciseText);
expect(enableTourSpy).toHaveBeenCalledOnce();
expect(startTourSpy).toHaveBeenCalledTimes(0);
}));
});
describe('updateAssessmentResult', () => {
let tourWithAssessmentTourSteps: GuidedTour;
let tourWithAssessmentTourStep: GuidedTour;
let enableNextStepSpy: any;
beforeEach(() => {
const assessmentObject = new AssessmentObject(2, 3);
const assessmentObjectScoreZero = new AssessmentObject(2, 0);
const assessmentTask = new GuidedTourAssessmentTask('t', assessmentObject);
tourWithAssessmentTourSteps = {
settingsKey: 'tour',
resetParticipation: ResetParticipation.EXERCISE_PARTICIPATION,
steps: [
{ assessmentTask } as AssessmentTaskTourStep,
new TextTourStep({ highlightSelector: '.random-selector', headlineTranslateKey: '', contentTranslateKey: '' }),
new TextTourStep({ headlineTranslateKey: '', contentTranslateKey: '', orientation: Orientation.TOPLEFT }),
],
};
tourWithAssessmentTourStep = {
settingsKey: 'tour',
resetParticipation: ResetParticipation.EXERCISE_PARTICIPATION,
steps: [{ assessmentTask: new GuidedTourAssessmentTask('t', assessmentObjectScoreZero) } as AssessmentTaskTourStep],
};
enableNextStepSpy = jest.spyOn<any, any>(guidedTourService, 'enableNextStepClick').mockImplementation();
});
afterEach(() => {
jest.clearAllMocks();
});
it('should updateAssessmentResult and enableNextStepClick', fakeAsync(() => {
guidedTourService.currentTour = tourWithAssessmentTourSteps;
guidedTourService.updateAssessmentResult(2, 3);
tick(0);
expect(enableNextStepSpy).toHaveBeenCalledOnce();
}));
it('should updateAssessmentResult and not enableNextStepClick as number of assessments is not correct', fakeAsync(() => {
guidedTourService.currentTour = tourWithAssessmentTourSteps;
guidedTourService.updateAssessmentResult(3, 3);
tick(0);
expect(enableNextStepSpy).toHaveBeenCalledTimes(0);
}));
it('should updateAssessmentResult and not enableNextStepClick as score not correct', fakeAsync(() => {
guidedTourService.currentTour = tourWithAssessmentTourSteps;
guidedTourService.updateAssessmentResult(2, 1);
tick(0);
expect(enableNextStepSpy).toHaveBeenCalledTimes(0);
}));
it('should not updateAssessmentResult as there is no assessmentTask', fakeAsync(() => {
guidedTourService.currentTour = tour;
guidedTourService.updateAssessmentResult(2, 1);
tick(0);
expect(enableNextStepSpy).toHaveBeenCalledTimes(0);
}));
it('should not updateAssessmentResult as the totalScore is 0', fakeAsync(() => {
guidedTourService.currentTour = tourWithAssessmentTourStep;
guidedTourService.updateAssessmentResult(2, 0);
tick(0);
expect(enableNextStepSpy).toHaveBeenCalledOnce();
}));
});
});
describe('GuidedTourService init', () => {
let guidedTourComponentFixture: ComponentFixture<GuidedTourComponent>;
let accountService: AccountService;
let profileService: ProfileService;
let guidedTourService: GuidedTourService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ArtemisTestModule],
declarations: [GuidedTourComponent, MockDirective(TranslateDirective), TranslatePipeMock, MockPipe(SafeResourceUrlPipe), MockComponent(NavbarComponent)],
providers: [
{ provide: LocalStorageService, useClass: MockSyncStorage },
{ provide: SessionStorageService, useClass: MockSyncStorage },
{ provide: Router, useClass: MockRouterWithEvents },
],
})
.compileComponents()
.then(() => {
guidedTourComponentFixture = TestBed.createComponent(GuidedTourComponent);
guidedTourService = TestBed.inject(GuidedTourService);
accountService = TestBed.inject(AccountService);
profileService = TestBed.inject(ProfileService);
});
});
it('should initialize', fakeAsync(() => {
const tourSettings = [{ guidedTourKey: 'test', guidedTourStep: 0 } as GuidedTourSetting];
const authStateMock = jest.spyOn(accountService, 'getAuthenticationState').mockReturnValue(of({ guidedTourSettings: tourSettings } as User));
const tourMapping = { courseShortName: 'test-course' } as GuidedTourMapping;
const profileInfoMock = jest.spyOn(profileService, 'getProfileInfo').mockReturnValue(of({ guidedTourMapping: tourMapping } as ProfileInfo));
// Fake mapping and settings to enable the tour. Should be overwritten by the return value of the profile service
guidedTourService.guidedTourMapping = { courseShortName: 'test', tours: { tour_user_interaction: '' } } as GuidedTourMapping;
guidedTourService.guidedTourSettings = [{ guidedTourKey: 'test-2', guidedTourStep: 0 } as GuidedTourSetting];
guidedTourService.enableTourForCourseOverview([{ id: 1, shortName: 'test' } as Course], tourWithUserInteraction, true);
guidedTourService.currentTour = tourWithUserInteraction;
tick(500);
guidedTourService.currentTourStepIndex = 0;
// guidedTourService.init() is called via the component initialization
guidedTourComponentFixture.detectChanges();
expect(authStateMock).toHaveBeenCalledOnce();
expect(guidedTourService.guidedTourSettings).toEqual(tourSettings);
expect(profileInfoMock).toHaveBeenCalledOnce();
expect(guidedTourService.guidedTourMapping).toEqual(tourMapping);
}));
});
}); | the_stack |
import { ClarityIcons } from '../icon.service.js';
import { IconAlias, IconShapeTuple } from '../interfaces/icon.interfaces.js';
import { administratorIcon, administratorIconName } from '../shapes/administrator.js';
import { animationIcon, animationIconName } from '../shapes/animation.js';
import { applicationIcon, applicationIconName } from '../shapes/application.js';
import { applicationsIcon, applicationsIconName } from '../shapes/applications.js';
import { archiveIcon, archiveIconName } from '../shapes/archive.js';
import { assignUserIcon, assignUserIconName } from '../shapes/assign-user.js';
import { atomIcon, atomIconName } from '../shapes/atom.js';
import { backupRestoreIcon, backupRestoreIconName } from '../shapes/backup-restore.js';
import { backupIcon, backupIconName } from '../shapes/backup.js';
import { barCodeIcon, barCodeIconName } from '../shapes/bar-code.js';
import { batteryIcon, batteryIconName } from '../shapes/battery.js';
import { blockIcon, blockIconName } from '../shapes/block.js';
import { blocksGroupIcon, blocksGroupIconName } from '../shapes/blocks-group.js';
import { bluetoothOffIcon, bluetoothOffIconName } from '../shapes/bluetooth-off.js';
import { bluetoothIcon, bluetoothIconName } from '../shapes/bluetooth.js';
import { buildingIcon, buildingIconName } from '../shapes/building.js';
import { bundleIcon, bundleIconName } from '../shapes/bundle.js';
import { capacitorIcon, capacitorIconName } from '../shapes/capacitor.js';
import { cdDvdIcon, cdDvdIconName } from '../shapes/cd-dvd.js';
import { certificateIcon, certificateIconName } from '../shapes/certificate.js';
import { ciCdIcon, ciCdIconName } from '../shapes/ci-cd.js';
import { cloudNetworkIcon, cloudNetworkIconName } from '../shapes/cloud-network.js';
import { cloudScaleIcon, cloudScaleIconName } from '../shapes/cloud-scale.js';
import { cloudTrafficIcon, cloudTrafficIconName } from '../shapes/cloud-traffic.js';
import { clusterIcon, clusterIconName } from '../shapes/cluster.js';
import { codeIcon, codeIconName } from '../shapes/code.js';
import { computerIcon, computerIconName } from '../shapes/computer.js';
import { connectIcon, connectIconName } from '../shapes/connect.js';
import { containerVolumeIcon, containerVolumeIconName } from '../shapes/container-volume.js';
import { containerIcon, containerIconName } from '../shapes/container.js';
import { controlLunIcon, controlLunIconName } from '../shapes/control-lun.js';
import { cpuIcon, cpuIconName } from '../shapes/cpu.js';
import { dashboardIcon, dashboardIconName } from '../shapes/dashboard.js';
import { dataClusterIcon, dataClusterIconName } from '../shapes/data-cluster.js';
import { deployIcon, deployIconName } from '../shapes/deploy.js';
import { devicesIcon, devicesIconName } from '../shapes/devices.js';
import { disconnectIcon, disconnectIconName } from '../shapes/disconnect.js';
import { displayIcon, displayIconName } from '../shapes/display.js';
import { downloadCloudIcon, downloadCloudIconName } from '../shapes/download-cloud.js';
import { exportIcon, exportIconName } from '../shapes/export.js';
import { fileShare2Icon, fileShare2IconName } from '../shapes/file-share-2.js';
import { fileShareIcon, fileShareIconName } from '../shapes/file-share.js';
import { flaskIcon, flaskIconName } from '../shapes/flask.js';
import { floppyIcon, floppyIconName } from '../shapes/floppy.js';
import { hardDiskIcon, hardDiskIconName } from '../shapes/hard-disk.js';
import { hardDriveDisksIcon, hardDriveDisksIconName } from '../shapes/hard-drive-disks.js';
import { hardDriveIcon, hardDriveIconName } from '../shapes/hard-drive.js';
import { helixIcon, helixIconName } from '../shapes/helix.js';
import { hostGroupIcon, hostGroupIconName } from '../shapes/host-group.js';
import { hostIcon, hostIconName } from '../shapes/host.js';
import { importIcon, importIconName } from '../shapes/import.js';
import { inductorIcon, inductorIconName } from '../shapes/inductor.js';
import { installIcon, installIconName } from '../shapes/install.js';
import { keyboardIcon, keyboardIconName } from '../shapes/keyboard.js';
import { layersIcon, layersIconName } from '../shapes/layers.js';
import { linkIcon, linkIconName } from '../shapes/link.js';
import { mediaChangerIcon, mediaChangerIconName } from '../shapes/media-changer.js';
import { memoryIcon, memoryIconName } from '../shapes/memory.js';
import { mobileIcon, mobileIconName } from '../shapes/mobile.js';
import { mouseIcon, mouseIconName } from '../shapes/mouse.js';
import { namespaceIcon, namespaceIconName } from '../shapes/namespace.js';
import { networkGlobeIcon, networkGlobeIconName } from '../shapes/network-globe.js';
import { networkSettingsIcon, networkSettingsIconName } from '../shapes/network-settings.js';
import { networkSwitchIcon, networkSwitchIconName } from '../shapes/network-switch.js';
import { noWifiIcon, noWifiIconName } from '../shapes/no-wifi.js';
import { nodeGroupIcon, nodeGroupIconName } from '../shapes/node-group.js';
import { nodeIcon, nodeIconName } from '../shapes/node.js';
import { nodesIcon, nodesIconName } from '../shapes/nodes.js';
import { nvmeIcon, nvmeIconName } from '../shapes/nvme.js';
import { pdfFileIcon, pdfFileIconName } from '../shapes/pdf-file.js';
import { phoneHandsetIcon, phoneHandsetIconName } from '../shapes/phone-handset.js';
import { pluginIcon, pluginIconName } from '../shapes/plugin.js';
import { podIcon, podIconName } from '../shapes/pod.js';
import { processOnVmIcon, processOnVmIconName } from '../shapes/process-on-vm.js';
import { qrCodeIcon, qrCodeIconName } from '../shapes/qr-code.js';
import { rackServerIcon, rackServerIconName } from '../shapes/rack-server.js';
import { radarIcon, radarIconName } from '../shapes/radar.js';
import { resistorIcon, resistorIconName } from '../shapes/resistor.js';
import { resourcePoolIcon, resourcePoolIconName } from '../shapes/resource-pool.js';
import { routerIcon, routerIconName } from '../shapes/router.js';
import { rulerPencilIcon, rulerPencilIconName } from '../shapes/ruler-pencil.js';
import { scriptExecuteIcon, scriptExecuteIconName } from '../shapes/script-execute.js';
import { scriptScheduleIcon, scriptScheduleIconName } from '../shapes/script-schedule.js';
import { shieldCheckIcon, shieldCheckIconName } from '../shapes/shield-check.js';
import { shieldXIcon, shieldXIconName } from '../shapes/shield-x.js';
import { shieldIcon, shieldIconName } from '../shapes/shield.js';
import { squidIcon, squidIconName } from '../shapes/squid.js';
import { ssdIcon, ssdIconName } from '../shapes/ssd.js';
import { storageAdapterIcon, storageAdapterIconName } from '../shapes/storage-adapter.js';
import { storageIcon, storageIconName } from '../shapes/storage.js';
import { tabletIcon, tabletIconName } from '../shapes/tablet.js';
import { tapeDriveIcon, tapeDriveIconName } from '../shapes/tape-drive.js';
import { terminalIcon, terminalIconName } from '../shapes/terminal.js';
import { unarchiveIcon, unarchiveIconName } from '../shapes/unarchive.js';
import { uninstallIcon, uninstallIconName } from '../shapes/uninstall.js';
import { unlinkIcon, unlinkIconName } from '../shapes/unlink.js';
import { uploadCloudIcon, uploadCloudIconName } from '../shapes/upload-cloud.js';
import { usbIcon, usbIconName } from '../shapes/usb.js';
import { vmIcon, vmIconName } from '../shapes/vm.js';
import { vmwAppIcon, vmwAppIconName } from '../shapes/vmw-app.js';
import { wifiIcon, wifiIconName } from '../shapes/wifi.js';
import { xlsFileIcon, xlsFileIconName } from '../shapes/xls-file.js';
import { internetOfThingsIcon, internetOfThingsIconName } from '../shapes/internet-of-things.js';
import { thinClientIcon, thinClientIconName } from '../shapes/thin-client.js';
import { digitalSignatureIcon, digitalSignatureIconName } from '../shapes/digital-signature.js';
import { updateIcon, updateIconName } from '../shapes/update.js';
import { forkingIcon, forkingIconName } from '../shapes/forking.js';
export const technologyCollectionIcons: IconShapeTuple[] = [
administratorIcon,
animationIcon,
applicationIcon,
applicationsIcon,
archiveIcon,
assignUserIcon,
atomIcon,
backupIcon,
backupRestoreIcon,
barCodeIcon,
batteryIcon,
blockIcon,
blocksGroupIcon,
bluetoothIcon,
bluetoothOffIcon,
buildingIcon,
bundleIcon,
capacitorIcon,
cdDvdIcon,
certificateIcon,
ciCdIcon,
cloudNetworkIcon,
cloudScaleIcon,
cloudTrafficIcon,
clusterIcon,
codeIcon,
computerIcon,
connectIcon,
containerIcon,
containerVolumeIcon,
controlLunIcon,
cpuIcon,
dashboardIcon,
dataClusterIcon,
deployIcon,
devicesIcon,
digitalSignatureIcon,
disconnectIcon,
displayIcon,
downloadCloudIcon,
exportIcon,
fileShareIcon,
fileShare2Icon,
flaskIcon,
floppyIcon,
forkingIcon,
hardDriveIcon,
hardDriveDisksIcon,
hardDiskIcon,
helixIcon,
hostIcon,
hostGroupIcon,
importIcon,
inductorIcon,
installIcon,
internetOfThingsIcon,
keyboardIcon,
layersIcon,
linkIcon,
mediaChangerIcon,
memoryIcon,
mobileIcon,
mouseIcon,
namespaceIcon,
networkGlobeIcon,
networkSettingsIcon,
networkSwitchIcon,
nodeGroupIcon,
nodeIcon,
nodesIcon,
noWifiIcon,
nvmeIcon,
pdfFileIcon,
phoneHandsetIcon,
pluginIcon,
podIcon,
processOnVmIcon,
qrCodeIcon,
rackServerIcon,
radarIcon,
resistorIcon,
resourcePoolIcon,
routerIcon,
rulerPencilIcon,
scriptExecuteIcon,
scriptScheduleIcon,
shieldIcon,
shieldCheckIcon,
shieldXIcon,
squidIcon,
ssdIcon,
storageIcon,
storageAdapterIcon,
tabletIcon,
tapeDriveIcon,
terminalIcon,
thinClientIcon,
unarchiveIcon,
uninstallIcon,
unlinkIcon,
updateIcon,
uploadCloudIcon,
usbIcon,
vmIcon,
vmwAppIcon,
wifiIcon,
xlsFileIcon,
];
export const technologyCollectionAliases: IconAlias[] = [
[hostIconName, ['server']],
[terminalIconName, ['command']],
[mobileIconName, ['mobile-phone']],
[certificateIconName, ['license']],
[noWifiIconName, ['disconnected']],
[phoneHandsetIconName, ['receiver']],
[rulerPencilIconName, ['design']],
[helixIconName, ['dna']],
[fileShareIconName, ['folder-share']],
];
/**
* Function that can be called to load the core icon set.
*
* ```typescript
* import '@cds/core/icon/register.js';
* import { loadTechnologyIconSet } from '@cds/core/icon';
*
* loadTechnologyIconSet();
* ```
*
*/
export function loadTechnologyIconSet() {
ClarityIcons.addIcons(...technologyCollectionIcons);
ClarityIcons.addAliases(...technologyCollectionAliases);
}
declare module '@cds/core/internal' {
interface IconRegistrySources {
[administratorIconName]: string;
[animationIconName]: string;
[applicationIconName]: string;
[applicationsIconName]: string;
[archiveIconName]: string;
[assignUserIconName]: string;
[atomIconName]: string;
[backupIconName]: string;
[backupRestoreIconName]: string;
[barCodeIconName]: string;
[batteryIconName]: string;
[blockIconName]: string;
[blocksGroupIconName]: string;
[bluetoothIconName]: string;
[bluetoothOffIconName]: string;
[buildingIconName]: string;
[bundleIconName]: string;
[capacitorIconName]: string;
[cdDvdIconName]: string;
[certificateIconName]: string;
[ciCdIconName]: string;
[cloudNetworkIconName]: string;
[cloudScaleIconName]: string;
[cloudTrafficIconName]: string;
[clusterIconName]: string;
[codeIconName]: string;
[computerIconName]: string;
[connectIconName]: string;
[containerIconName]: string;
[containerVolumeIconName]: string;
[controlLunIconName]: string;
[cpuIconName]: string;
[dashboardIconName]: string;
[dataClusterIconName]: string;
[deployIconName]: string;
[devicesIconName]: string;
[digitalSignatureIconName]: string;
[disconnectIconName]: string;
[displayIconName]: string;
[downloadCloudIconName]: string;
[exportIconName]: string;
[fileShareIconName]: string;
[fileShare2IconName]: string;
[flaskIconName]: string;
[floppyIconName]: string;
[forkingIconName]: string;
[hardDriveIconName]: string;
[hardDriveDisksIconName]: string;
[hardDiskIconName]: string;
[helixIconName]: string;
[hostIconName]: string;
[hostGroupIconName]: string;
[importIconName]: string;
[inductorIconName]: string;
[installIconName]: string;
[internetOfThingsIconName]: string;
[keyboardIconName]: string;
[layersIconName]: string;
[linkIconName]: string;
[mediaChangerIconName]: string;
[memoryIconName]: string;
[mobileIconName]: string;
[mouseIconName]: string;
[namespaceIconName]: string;
[networkGlobeIconName]: string;
[networkSettingsIconName]: string;
[networkSwitchIconName]: string;
[nodeGroupIconName]: string;
[nodeIconName]: string;
[nodesIconName]: string;
[noWifiIconName]: string;
[nvmeIconName]: string;
[pdfFileIconName]: string;
[phoneHandsetIconName]: string;
[pluginIconName]: string;
[podIconName]: string;
[processOnVmIconName]: string;
[qrCodeIconName]: string;
[rackServerIconName]: string;
[radarIconName]: string;
[resistorIconName]: string;
[resourcePoolIconName]: string;
[routerIconName]: string;
[rulerPencilIconName]: string;
[scriptExecuteIconName]: string;
[scriptScheduleIconName]: string;
[shieldIconName]: string;
[shieldCheckIconName]: string;
[shieldXIconName]: string;
[squidIconName]: string;
[ssdIconName]: string;
[storageIconName]: string;
[storageAdapterIconName]: string;
[tabletIconName]: string;
[tapeDriveIconName]: string;
[terminalIconName]: string;
[thinClientIconName]: string;
[unarchiveIconName]: string;
[uninstallIconName]: string;
[unlinkIconName]: string;
[updateIconName]: string;
[uploadCloudIconName]: string;
[usbIconName]: string;
[vmIconName]: string;
[vmwAppIconName]: string;
[wifiIconName]: string;
[xlsFileIconName]: string;
}
} | the_stack |
import { MultiSelect, TaggingEventArgs, MultiSelectChangeEventArgs, ISelectAllEventArgs } from '../../src/multi-select/multi-select';
import { Browser, isNullOrUndefined, EmitType } from '@syncfusion/ej2-base';
import { createElement, L10n } from '@syncfusion/ej2-base';
import { dropDownBaseClasses, PopupEventArgs } from '../../src/drop-down-base/drop-down-base';
import { DataManager, ODataV4Adaptor, Query } from '@syncfusion/ej2-data';
import { CheckBoxSelection } from '../../src/multi-select/checkbox-selection';
import {profile , inMB, getMemoryProfile} from '../common/common.spec';
MultiSelect.Inject(CheckBoxSelection);
L10n.load({
'fr-BE': {
'dropdowns': {
'noRecordsTemplate': "Aucun enregistrement trouvé",
'actionFailureTemplate': "Modèle d'échec d'action",
'selectAllText': 'Check & UnCheck All',
}
}
});
let datasource: { [key: string]: Object }[] = [{ id: 'list1', text: 'JAVA', icon: 'icon' }, { id: 'list2', text: 'C#' },
{ id: 'list3', text: 'C++' }, { id: 'list4', text: '.NET', icon: 'icon' }, { id: 'list5', text: 'Oracle' }];
let datasource2: { [key: string]: Object }[] = [{ id: 'id2', text: 'PHP' }, { id: 'id1', text: 'HTML' }, { id: 'id3', text: 'PERL' },
{ id: 'list1', text: 'JAVA' }, { id: 'list2', text: 'Python' }, { id: 'list5', text: 'Oracle' }];
let multiSelectData: multiSelectStyles = {
container: "e-multi-select-wrapper",
selectedListContainer: "e-chips-collection",
delimViewContainer: "e-delim-view e-delim-values",
delimContainer: "e-delim-values",
listContainer: "e-content e-dropdownbase",
chips: "e-chips",
chipSelection: "e-chip-selected",
chipsClose: "e-chips-close",
individualListClose: "",
closeiconhide: 'e-close-icon-hide',
inputContainer: "e-searcher e-zero-size",
inputElement: "e-dropdownbase",
inputFocus: "e-focus",
overAllClose: "e-chips-close e-close-hooker",
popupListWrapper: "e-ddl e-popup e-multi-select-list-wrapper e-control e-popup-open",
overAllList: "e-list-parent e-ul",
listItem: "e-list-item e-active e-item-focus",
ListItemSelected: "e-active",
ListItemHighlighted: "e-item-focus",
containerChildlength: 5,
defaultChildlength: 5,
inputARIA: ['aria-expanded', 'role', 'aria-activedescendant', 'aria-haspopup', 'aria-owns', 'aria-disabled'],
listARIA: ['aria-hidden', 'role'],
mobileChip: 'e-mob-chip'
}
interface multiSelectStyles {
container: string;
mobileChip: string,
selectedListContainer: string;
delimContainer: string;
chips: string,
chipSelection: string;
chipsClose: string,
individualListClose: string;
inputContainer: string;
inputElement: string;
delimViewContainer: string;
inputFocus: string;
overAllClose: string;
popupListWrapper: string;
listContainer: string;
overAllList: string;
listItem: string;
ListItemSelected: string;
ListItemHighlighted: string;
containerChildlength: number;
defaultChildlength: number;
inputARIA: Array<string>;
listARIA: Array<string>;
closeiconhide: string;
}
let mouseEventArgs: any = { preventDefault: function () { }, target: null };
let keyboardEventArgs = {
preventDefault: function () { },
altKey: false,
ctrlKey: false,
shiftKey: false,
char: '',
key: '',
charCode: 22,
keyCode: 22,
which: 22,
code: 22
};
describe('MultiSelect', () => {
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
let css: string = ".e-spinner-pane::after { content: 'Material'; display: none;} ";
let style: HTMLStyleElement = document.createElement('style'); style.type = 'text/css';
let styleNode: Node = style.appendChild(document.createTextNode(css));
document.getElementsByTagName('head')[0].appendChild(style);
describe('rendering validation', () => {
let listObj: any;
let popupObj: any;
let checkObj: any
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
beforeAll(() => {
document.body.appendChild(element);
});
afterAll(() => {
if (element) {
listObj.destroy();
element.remove();
}
checkObj = new CheckBoxSelection();
checkObj.destroy();
});
// it('multiselect- enableCheckBoxSelection', () => {
// listObj = new MultiSelect({ dataSource: datasource, mode: 'CheckBox', fields: { text: "text", value: "text" }, value: ["JAVA"] });
// listObj.appendTo(element);
// let wrapper: HTMLElement = (<any>listObj).inputElement.parentElement.parentElement;
// //wrapper structure validation.
// expect((<any>listObj).inputElement.getAttribute('readonly') === 'true').toBe(true);
// expect(wrapper.nodeName).toEqual("DIV");//1
// expect(wrapper.classList.toString()).toEqual(multiSelectData.container);
// //expect(wrapper.childNodes.length).toEqual(multiSelectData.containerChildlength);
// if (wrapper.firstChild) {
// //expect(wrapper.firstChild.nodeName).toEqual("SPAN");
// expect(wrapper.firstElementChild.classList.toString()).toEqual(multiSelectData.delimContainer);
// expect(wrapper.firstElementChild.textContent.split(',').length).toEqual(2);
// if (wrapper.firstChild.nextSibling) {
// //Input Wrapper structure validation.
// expect(wrapper.firstChild.nextSibling.nodeName).toEqual("SPAN");
// expect(wrapper.firstElementChild.nextElementSibling.classList.toString()).toEqual(multiSelectData.delimViewContainer);//7
// if (wrapper.firstChild.nextSibling.nextSibling) {
// //wrapper element validation.
// expect(wrapper.firstChild.nextSibling.nextSibling.nodeName).toEqual("SPAN");//8
// expect(wrapper.firstElementChild.nextElementSibling.nextElementSibling.classList.toString()).toEqual(multiSelectData.inputContainer);//9
// if (wrapper.firstChild.nextSibling.nextSibling.nextSibling) {
// //Close element validation.
// expect(wrapper.firstChild.nextSibling.nextSibling.nextSibling.nodeName).toEqual("SPAN");//8
// expect(wrapper.firstElementChild.nextElementSibling.nextElementSibling.nextElementSibling.classList.toString()).toEqual(multiSelectData.overAllClose);//9
// } else {
// expect(true).toBe(false);
// }
// } else {
// expect(true).toBe(false);
// }
// } else {
// expect(true).toBe(false);
// }
// } else {
// expect(true).toBe(false);
// }
// //Input element validation.
// expect((<any>listObj).inputElement.nodeName).toEqual("INPUT");//10
// expect((<any>listObj).inputElement.classList.toString()).toEqual(multiSelectData.inputElement);//11
// for (let a = 0; a < multiSelectData.inputARIA.length; a++) {
// expect((<any>listObj).inputElement.getAttribute(multiSelectData.inputARIA[a])).not.toBe(null);//12
// }
// expect((<any>listObj).inputElement.classList.toString()).toEqual(multiSelectData.inputElement);//13
// listObj.showPopup();
// expect((<any>listObj).checkBoxSelectionModule.checkWrapper.classList.contains('e-checkbox-wrapper')).toBe(true);
// expect(document.getElementsByClassName("e-checkbox-wrapper").length === (<any>listObj).list.querySelectorAll('li').length).toBe(true);
// expect((<any>listObj).mainListCollection[0].lastElementChild.getAttribute('aria-checked') === 'true').toBe(true);
// expect((<any>listObj).mainListCollection[0].classList.contains('e-active')).toBe(true);
// (<any>listObj).focusIn();
// listObj.hidePopup();
// listObj.destroy();
// });
it('enable selectall', () => {
listObj = new MultiSelect({
dataSource: datasource,
mode: 'CheckBox', fields: { text: "text", value: "text" }, value: ["JAVA"]
});
listObj.appendTo(element);
listObj.showSelectAll = true;
listObj.dataBind();
listObj.showPopup();
expect((<any>listObj).checkBoxSelectionModule.checkAllParent.classList.contains('e-selectall-parent')).toBe(true);
});
it('disable selectall', () => {
listObj = new MultiSelect({
dataSource: datasource,
mode: 'CheckBox', fields: { text: "text", value: "text" }, value: ["JAVA"], showSelectAll: true
});
listObj.appendTo(element);
listObj.showSelectAll = false;
listObj.dataBind();
expect(listObj.showSelectAll).toBe(false);
});
it('change selectallText', () => {
listObj = new MultiSelect({
dataSource: datasource,
mode: 'CheckBox', fields: { text: "text", value: "text" }, value: ["JAVA"], showSelectAll: true
});
listObj.appendTo(element);
listObj.selectAllText = 'check All';
listObj.dataBind();
listObj.showPopup();
expect(listObj.checkBoxSelectionModule.selectAllSpan.innerText === 'check All').toBe(true);
listObj.destroy();
});
});
describe('showSelectAll', () => {
let listObj: any;
let popupObj: any;
let checkObj: any;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
beforeAll(() => {
document.body.innerHTML = '';
document.body.appendChild(element);
});
afterAll(() => {
if (element) {
listObj.destroy();
element.remove();
}
checkObj = new CheckBoxSelection();
checkObj.destroy();
});
it('wrapper element - Delim Mode', (done) => {
listObj = new MultiSelect({
dataSource: datasource, showSelectAll: true, mode: 'CheckBox',
fields: { text: "text", value: "text" }, value: ["JAVA"]
});
listObj.appendTo(element);
let wrapper: HTMLElement = (<any>listObj).inputElement.parentElement.parentElement;
listObj.showPopup();
setTimeout(() => {
expect(listObj.checkBoxSelectionModule.checkAllParent.classList.contains('e-selectall-parent')).toBe(true);
expect(listObj.checkBoxSelectionModule.checkAllParent.classList.contains('e-selectall-parent')).toBe(true);
expect(listObj.checkBoxSelectionModule.checkAllParent.innerText === "Select All").toBe(true);
expect(listObj.checkBoxSelectionModule.checkAllParent.lastElementChild.classList.contains('e-all-text')).toBe(true);
listObj.dispatchEvent(listObj.checkBoxSelectionModule.checkAllParent, "mousedown");
expect(listObj.popupObj.element.getElementsByClassName('e-check').length - 1 === listObj.value.length).toBe(true);
expect(listObj.checkBoxSelectionModule.checkWrapper.getAttribute('aria-checked') === 'true').toBe(true);
listObj.dispatchEvent(listObj.checkBoxSelectionModule.checkAllParent, "mousedown");
expect(listObj.checkBoxSelectionModule.checkWrapper.getAttribute('aria-checked') === 'false').toBe(true);
expect(listObj.popupObj.element.getElementsByClassName('e-check').length === 0).toBe(true);
listObj.selectAll(true);
expect(listObj.popupObj.element.getElementsByClassName('e-check').length - 1 === listObj.value.length).toBe(true);
expect(listObj.checkBoxSelectionModule.checkWrapper.getAttribute('aria-checked') === 'true').toBe(true);
listObj.selectAll(false);
expect(listObj.checkBoxSelectionModule.checkWrapper.getAttribute('aria-checked') === 'false').toBe(true);
expect(listObj.popupObj.element.getElementsByClassName('e-check').length === 0).toBe(true);
listObj.dispatchEvent(listObj.checkBoxSelectionModule.checkAllParent.firstElementChild.lastElementChild, "mousedown");
listObj.checkBoxSelectionModule.clickHandler({
preventDefault: () => { }, currentTarget: listObj.checkBoxSelectionModule.checkAllParent.firstElementChild.lastElementChild
});
listObj.checkBoxSelectionModule.onBlurHandler(mouseEventArgs);
listObj.showPopup();
listObj.checkBoxSelectionModule.onBlurHandler({
mouseEventArgs, relatedTarget: listObj.checkBoxSelectionModule.filterInput
});
listObj.destroy();
done();
}, 450);
});
it('document click', () => {
listObj = new MultiSelect({
dataSource: datasource, mode: 'CheckBox',
fields: { text: "text", value: "text" }, value: ["JAVA"]
});
listObj.appendTo(element);
let wrapper: HTMLElement = (<any>listObj).inputElement.parentElement.parentElement;
listObj.showPopup();
let mouseEventArgs: any = { preventDefault: function () { }, target: null };
mouseEventArgs.target = document.body;
listObj.checkBoxSelectionModule.onDocumentClick(mouseEventArgs);
expect(document.body.contains(listObj.popupObj.element)).toBe(false);
});
});
describe('checkbox with searchbox', () => {
let listObj: any;
let popupObj: any;
let checkObj: any;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
beforeAll(() => {
document.body.appendChild(element);
});
afterAll(() => {
if (element) {
listObj.destroy();
element.remove();
}
checkObj = new CheckBoxSelection();
Browser.userAgent = navigator.userAgent;
checkObj.destroy();
});
it('filtering basic coverage', () => {
let checker: boolean = false
listObj = new MultiSelect({
dataSource: datasource2,
showSelectAll: true, mode: 'CheckBox',
fields: { value: 'text', text: 'text' }, allowFiltering: true,
selectAllText: 'Check & UnCheck All',
filtering: function (e) {
checker = true;
let query: Query = new Query().select(['text', 'id']);
query = (e.text !== '') ? query.where('text', 'startswith', e.text, true) : query;
e.updateData(datasource, query);
}
});
listObj.appendTo(element);
//open action validation
listObj.showPopup();
(<any>listObj).checkBoxSelectionModule.filterInput.value = "JAVA"
//open action validation
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 70;
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
(<any>listObj).keyUp(keyboardEventArgs);
let element1: HTMLElement = (<any>listObj).list.querySelector('li[data-value="JAVA"]');
expect(element1.classList.contains(dropDownBaseClasses.selected)).toBe(false);
(<any>listObj).checkBoxSelectionModule.filterInput.value = "";
keyboardEventArgs.keyCode = 70;
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
(<any>listObj).keyUp(keyboardEventArgs);
keyboardEventArgs.keyCode = 8;
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
(<any>listObj).keyUp(keyboardEventArgs);
(<any>listObj).checkBoxSelectionModule.filterInput.value = "JAVA";
//open action validation
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
keyboardEventArgs.keyCode = 8;
(<any>listObj).keyUp(keyboardEventArgs);
let coll = (<any>listObj).liCollections;
(<any>listObj).liCollections = undefined;
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
(<any>listObj).keyUp(keyboardEventArgs);
(<any>listObj).liCollections = coll;
expect(checker).toBe(true);
listObj.destroy();
});
it('filtering no data', () => {
let checker: boolean = false
listObj = new MultiSelect({
dataSource: datasource2,
showSelectAll: true, mode: 'CheckBox',
fields: { value: 'text', text: 'text' }, allowFiltering: true,
selectAllText: 'Check & UnCheck All',
filtering: function (e) {
checker = true;
let query: Query = new Query().select(['text', 'id']);
query = (e.text !== '') ? query.where('text', 'startswith', e.text, true) : query;
e.updateData(datasource, query);
}
});
listObj.appendTo(element);
//open action validation
listObj.showPopup();
(<any>listObj).checkBoxSelectionModule.filterInput.value = "JAVAT"
//open action validation
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 70;
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
(<any>listObj).keyUp(keyboardEventArgs);
expect(checker).toBe(true);
listObj.hidePopup();
listObj.destroy();
});
it('IE 11 browser validation', () => {
Browser.userAgent = 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; Tablet PC 2.0; rv:11.0) like Gecko';
listObj = new MultiSelect({
dataSource: datasource2,
showSelectAll: true, mode: 'CheckBox',
fields: { value: 'text', text: 'text' }, allowFiltering: true,
selectAllText: 'Check & UnCheck All',
});
listObj.appendTo(element);
//open action validation
let mouseEvenArg: any = { preventDefault: function () { }, target: listObj.overAllWrapper };
listObj.wrapperClick(mouseEvenArg);
expect(document.querySelectorAll('.e-ddl.e-popup')).not.toBe(null);
mouseEventArgs.target = document.getElementById('header');
listObj.checkBoxSelectionModule.onBlurHandler(mouseEventArgs);
let mouseEven: any = { preventDefault: function () { }, target: null };
mouseEven.target = document.body;
listObj.checkBoxSelectionModule.onDocumentClick(mouseEven);
expect(listObj.overAllWrapper === document.activeElement).toBe(false);
listObj.destroy();
});
});
describe('Add item using addItem method in existing group item', () => {
let listObj: any;
let checkObj: any;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
let data: { [key: string]: Object }[] = [
{ "Vegetable": "Cabbage", "Category": "Leafy and Salad", "Id": "item1" },
{ "Vegetable": "Chickpea", "Category": "Beans", "Id": "item2" },
{ "Vegetable": "Garlic", "Category": "Bulb and Stem", "Id": "item3" },
{ "Vegetable": "Green bean", "Category": "Beans", "Id": "item4" },
{ "Vegetable": "Horse gram", "Category": "Beans", "Id": "item5" },
{ "Vegetable": "Nopal", "Category": "Bulb and Stem", "Id": "item6" }];
let item: { [key: string]: Object }[] = [
{ "Vegetable": "brinjal", "Category": "Leafy and Salad", "Id": "item7" },
{ "Vegetable": "green gram", "Category": "Beans", "Id": "item8" }];
beforeAll(() => {
document.body.appendChild(element);
});
afterAll(() => {
if (element) {
listObj.destroy();
element.remove();
}
checkObj = new CheckBoxSelection();
Browser.userAgent = navigator.userAgent;
checkObj.destroy();
});
it('Adding item in the existing group', () => {
listObj = new MultiSelect({
dataSource: data,
mode: 'CheckBox',
fields: { groupBy: 'Category', text: 'Vegetable', value: 'Id' },
});
listObj.appendTo('#multiselect');
listObj.showPopup();
expect(listObj.ulElement.querySelectorAll('li').length === 9).toBe(true);
listObj.addItem(item);
expect(listObj.ulElement.querySelectorAll('li').length === 11).toBe(true);
});
});
describe('Add item using addItem method in new group item', () => {
let listObj: any;
let checkObj: any;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
let data: { [key: string]: Object }[] = [
{ "Vegetable": "Cabbage", "Category": "Leafy and Salad", "Id": "item1" },
{ "Vegetable": "Chickpea", "Category": "Beans", "Id": "item2" },
{ "Vegetable": "Garlic", "Category": "Bulb and Stem", "Id": "item3" },
{ "Vegetable": "Green bean", "Category": "Beans", "Id": "item4" },
{ "Vegetable": "Horse gram", "Category": "Beans", "Id": "item5" },
{ "Vegetable": "Nopal", "Category": "Bulb and Stem", "Id": "item6" }];
let item: { [key: string]: Object }[] = [
{ "Vegetable": "brinjal", "Category": "Leafy and Salad", "Id": "item7" },
{ "Vegetable": "green gram", "Category": "Potato", "Id": "item8" }];
beforeAll(() => {
document.body.appendChild(element);
});
afterAll(() => {
if (element) {
listObj.destroy();
element.remove();
}
checkObj = new CheckBoxSelection();
Browser.userAgent = navigator.userAgent;
checkObj.destroy();
});
it('filtering basic coverage', () => {
listObj = new MultiSelect({
dataSource: data,
mode: 'CheckBox',
fields: { groupBy: 'Category', text: 'Vegetable', value: 'Id' },
});
listObj.appendTo('#multiselect');
listObj.showPopup();
expect(listObj.ulElement.querySelectorAll('li').length === 9).toBe(true);
listObj.addItem(item);
expect(listObj.ulElement.querySelectorAll('li').length === 12).toBe(true);
});
});
describe('Add item using addItem method with show select all', () => {
let listObj: any;
let checkObj: any;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
let data: { [key: string]: Object }[] = [
{ "Vegetable": "Cabbage", "Category": "Leafy and Salad", "Id": "item1" },
{ "Vegetable": "Chickpea", "Category": "Beans", "Id": "item2" },
{ "Vegetable": "Garlic", "Category": "Bulb and Stem", "Id": "item3" },
{ "Vegetable": "Green bean", "Category": "Beans", "Id": "item4" },
{ "Vegetable": "Horse gram", "Category": "Beans", "Id": "item5" },
{ "Vegetable": "Nopal", "Category": "Bulb and Stem", "Id": "item6" }];
let item: { [key: string]: Object }[] = [
{ "Vegetable": "brinjal", "Category": "Leafy and Salad", "Id": "item7" },
{ "Vegetable": "green gram", "Category": "Potato", "Id": "item8" }];
beforeAll(() => {
document.body.appendChild(element);
});
afterAll(() => {
if (element) {
listObj.destroy();
element.remove();
}
checkObj = new CheckBoxSelection();
Browser.userAgent = navigator.userAgent;
checkObj.destroy();
});
it('Select all item', (done) => {
listObj = new MultiSelect({
dataSource: data,
mode: 'CheckBox',
showSelectAll: true,
fields: { groupBy: 'Category', text: 'Vegetable', value: 'Id' },
});
listObj.appendTo('#multiselect');
listObj.showPopup();
setTimeout(() => {
expect(listObj.checkBoxSelectionModule.checkAllParent.classList.contains('e-selectall-parent')).toBe(true);
expect(listObj.checkBoxSelectionModule.checkAllParent.classList.contains('e-selectall-parent')).toBe(true);
expect(listObj.checkBoxSelectionModule.checkAllParent.innerText === "Select All").toBe(true);
expect(listObj.checkBoxSelectionModule.checkAllParent.lastElementChild.classList.contains('e-all-text')).toBe(true);
expect(listObj.ulElement.querySelectorAll('li').length === 9).toBe(true);
listObj.dispatchEvent(listObj.checkBoxSelectionModule.checkAllParent, "mousedown");
expect(listObj.popupObj.element.getElementsByClassName('e-check').length - 1 === data.length).toBe(true);
listObj.addItem(item);
expect(listObj.ulElement.querySelectorAll('li').length === 12).toBe(true);
expect(listObj.popupObj.element.getElementsByClassName('e-check').length - 1 === data.length).toBe(true);
listObj.destroy();
done();
}, 450);
});
});
describe('Select all item with enable group checkbox mode', () => {
let listObj: any;
let checkObj: any;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
let data: { [key: string]: Object }[] = [
{ "Vegetable": "Cabbage", "Category": "Leafy and Salad", "Id": "item1" },
{ "Vegetable": "Chickpea", "Category": "Beans", "Id": "item2" },
{ "Vegetable": "Garlic", "Category": "Bulb and Stem", "Id": "item3" },
{ "Vegetable": "Green bean", "Category": "Beans", "Id": "item4" },
{ "Vegetable": "Horse gram", "Category": "Beans", "Id": "item5" },
{ "Vegetable": "Nopal", "Category": "Bulb and Stem", "Id": "item6" }];
let item: { [key: string]: Object }[] = [
{ "Vegetable": "brinjal", "Category": "Leafy and Salad", "Id": "item7" },
{ "Vegetable": "green gram", "Category": "Beans", "Id": "item8" }];
beforeAll(() => {
document.body.appendChild(element);
});
afterAll(() => {
if (element) {
listObj.destroy();
element.remove();
}
checkObj = new CheckBoxSelection();
Browser.userAgent = navigator.userAgent;
checkObj.destroy();
});
it('Select all item with enable group checkbox mode', (done) => {
listObj = new MultiSelect({
dataSource: data,
mode: 'CheckBox',
enableGroupCheckBox: true,
showSelectAll: true,
fields: { groupBy: 'Category', text: 'Vegetable', value: 'Id' },
});
listObj.appendTo('#multiselect');
listObj.showPopup();
setTimeout(() => {
expect(listObj.checkBoxSelectionModule.checkAllParent.classList.contains('e-selectall-parent')).toBe(true);
expect(listObj.checkBoxSelectionModule.checkAllParent.classList.contains('e-selectall-parent')).toBe(true);
expect(listObj.checkBoxSelectionModule.checkAllParent.innerText === "Select All").toBe(true);
expect(listObj.checkBoxSelectionModule.checkAllParent.lastElementChild.classList.contains('e-all-text')).toBe(true);
expect(listObj.ulElement.querySelectorAll('li').length === 9).toBe(true);
listObj.dispatchEvent(listObj.checkBoxSelectionModule.checkAllParent, "mousedown");
expect(listObj.popupObj.element.getElementsByClassName('e-check').length - 1 === data.concat(item).length + 1).toBe(true);
listObj.addItem(item);
expect(listObj.ulElement.querySelectorAll('li').length === 11).toBe(true);
expect(listObj.popupObj.element.getElementsByClassName('e-check').length - 1 === data.concat(item).length + 1).toBe(true);
listObj.destroy();
done();
}, 450);
});
});
describe('Allowfiltering support in mobile', () => {
let ele: HTMLElement = document.createElement('input');
ele.id = 'newlist';
let listObj: any;
let checkObj: any;
let data: { [key: string]: Object }[] = [{ id: 'list1', text: 'JAVA', icon: 'icon' }, { id: 'list2', text: 'C#' },
{ id: 'list3', text: 'C++' }, { id: 'list4', text: '.NET', icon: 'icon' }, { id: 'list5', text: 'Oracle' },
{ id: 'lit2', text: 'PHP' }, { id: 'list22', text: 'Phython' }, { id: 'list32', text: 'Perl' },
{ id: 'list42', text: 'Core' }, { id: 'lis2', text: 'C' }, { id: 'list12', text: 'C##' }];
beforeAll(() => {
let androidPhoneUa: string = 'Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JWR66Y) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.92 Safari/537.36';
Browser.userAgent = androidPhoneUa;
document.body.appendChild(ele);
listObj = new MultiSelect({
dataSource: datasource2, showSelectAll: true, mode: 'CheckBox', fields: { value: 'text', text: 'text' }, allowFiltering: true,
filtering: function (e) {
let query: Query = new Query().select(['text', 'id']);
query = (e.text !== '') ? query.where('text', 'startswith', e.text, true) : query;
e.updateData(datasource, query);
}
});
listObj.appendTo('#newlist');
});
afterAll(() => {
if (ele) {
ele.remove();
}
Browser.userAgent = navigator.userAgent;
})
it('EJ2-22343 - Selected value not cleared bootstrap modal only in mobile', (done) => {
listObj.open = (): void => {
setTimeout((): void => {
listObj.checkBoxSelectionModule.clickOnBackIcon();
setTimeout((): void => {
expect(document.activeElement).toBe(listObj.inputElement);
listObj.open = null;
done();
}, 200);
}, 100);
};
listObj.showPopup();
})
it('allowFiltering enabled', () => {
listObj.showPopup();
expect(listObj.popupObj.element.style.maxHeight).toBe('100%');
})
it('clear text & search icon in search textbox', () => {
(<any>listObj).checkBoxSelectionModule.filterInput.value = 'a';
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 70;
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
(<any>listObj).keyUp(keyboardEventArgs);
(<any>listObj).checkBoxSelectionModule.clickOnBackIcon();
(<any>listObj).checkBoxSelectionModule.filterInput.value = 'a';
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 70;
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
(<any>listObj).keyUp(keyboardEventArgs);
expect((<any>listObj).checkBoxSelectionModule.clearIconElement.style.visibility).toBe('visible');
listObj.checkBoxSelectionModule.clearText(mouseEventArgs);
listObj.checkBoxSelectionModule.removeEventListener();
})
it('mobile backstate hide popup', (done) => {
(<any>window).onpopstate();
setTimeout((): void => {
expect(listObj.popupObj.element.classList.contains('e-popup-close')).toBe(true);
done();
}, 500);
})
it('active state change on scrolling', () => {
(<any>listObj).checkBoxSelectionModule.filterInput.value = 'a';
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 70;
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
(<any>listObj).keyUp(keyboardEventArgs);
listObj.list.scrollTop = 100;
expect(document.activeElement !== listObj.filterInput).toBe(true);
listObj.checkBoxSelectionModule.clickOnBackIcon();
expect(listObj.overAllWrapper.classList.contains('e-input-group')).toBe(true);
(<any>listObj).showPopup();
listObj.checkBoxSelectionModule.clickOnBackIcon();
(<any>listObj).hidePopup();
listObj.checkBoxSelectionModule.removeEventListener();
listObj.destroy();
});
});
describe('templating with checkbox', () => {
let listObj: MultiSelect;
let popupObj: any;
let checkObj: any;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { 'type': 'text' } });
let empList: { [key: string]: Object }[] = [
{ text: 'Mona Sak', eimg: '1', status: 'Available', country: 'USA' },
{ text: 'Kapil Sharma', eimg: '2', status: 'Available', country: 'USA' },
{ text: 'Erik Linden', eimg: '3', status: 'Available', country: 'England' },
{ text: 'Kavi Tam', eimg: '4', status: 'Available', country: 'England' },
{ text: "Harish Sree", eimg: "5", status: "Available", country: 'USA' },
];
let originalTimeout: number;
beforeAll(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 6000;
document.body.innerHTML = '';
document.body.appendChild(element);
});
afterAll(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
if (element) {
listObj.destroy();
element.remove();
}
checkObj = new CheckBoxSelection();
checkObj.destroy();
});
it('Validation for the group template', (done) => {
let checkObj: CheckBoxSelection;
let listObj: MultiSelect;
listObj = new MultiSelect({
dataSource: empList,
fields: { text: 'text', groupBy: 'country' },
headerTemplate: '<div class="head"> Photo <span style="padding-left:42px"> Contact Info </span></div>',
itemTemplate: '<div><img class="eimg" src="../Employees/${eimg}.png" alt="employee"/>' +
'<div class="ename"> ${text} </div><div class="temp"> ${country} </div></div>',
footerTemplate: '<div class="Foot"> Total Items Count: 5 </div>',
valueTemplate: '<span><img class="tempImg" src="../Employees/${eimg}.png" height="20px" width="20px" alt="employee"/>' +
'<span class="tempName"> ${text} </span></span>',
width: '250px',
showSelectAll: true,
mode: 'CheckBox',
placeholder: 'Select an employee',
popupWidth: '250px',
popupHeight: '300px'
});
listObj.appendTo(element);
listObj.showPopup();
setTimeout(() => {
expect('<div class="head">Photo<span style="padding-left:42px"> Contact Info </span></div>').toBe((<any>listObj).header.innerHTML);
expect('<div class="Foot"> Total Items Count: 5 </div>').toBe((<any>listObj).footer.innerHTML);
expect((<any>listObj).checkBoxSelectionModule.checkAllParent.classList.contains('e-selectall-parent')).toBe(true);
expect((<any>listObj).checkBoxSelectionModule.checkAllParent.classList.contains('e-selectall-parent')).toBe(true);
expect((<any>listObj).checkBoxSelectionModule.checkAllParent.innerText === "Select All").toBe(true);
expect((<any>listObj).checkBoxSelectionModule.checkAllParent.lastElementChild.classList.contains('e-all-text')).toBe(true);
(<any>listObj).dispatchEvent((<any>listObj).checkBoxSelectionModule.checkAllParent, "mousedown");
expect(document.getElementsByClassName('e-check').length - 1 === listObj.value.length).toBe(true);
expect((<any>listObj).checkBoxSelectionModule.checkWrapper.getAttribute('aria-checked') === 'true').toBe(true);
(<any>listObj).dispatchEvent((<any>listObj).checkBoxSelectionModule.checkAllParent, "mousedown");
expect((<any>listObj).checkBoxSelectionModule.checkWrapper.getAttribute('aria-checked') === 'false').toBe(true);
expect(document.getElementsByClassName('e-check').length === 0).toBe(true);
listObj.selectAll(true);
expect(document.getElementsByClassName('e-check').length - 1 === listObj.value.length).toBe(true);
expect((<any>listObj).checkBoxSelectionModule.checkWrapper.getAttribute('aria-checked') === 'true').toBe(true);
listObj.selectAll(false);
expect((<any>listObj).checkBoxSelectionModule.checkWrapper.getAttribute('aria-checked') === 'false').toBe(true);
expect(document.getElementsByClassName('e-check').length === 0).toBe(true);
mouseEventArgs.target = (<any>listObj).ulElement.querySelector("li.e-list-item");
mouseEventArgs.type = 'click';
(<any>listObj).onMouseClick(mouseEventArgs);
expect(listObj.value[0] === "Mona Sak").toBe(true);
mouseEventArgs.target = (<any>listObj).popupWrapper.querySelector(".head");
(<any>listObj).onMouseClick(mouseEventArgs);
listObj.hidePopup();
listObj.destroy();
done();
}, 2000);
});
it('disable selectall with template', (done) => {
let checkObj: CheckBoxSelection;
let listObj: MultiSelect;
listObj = new MultiSelect({
dataSource: empList,
fields: { text: 'text', groupBy: 'country' },
headerTemplate: '<div class="head"> Photo <span style="padding-left:42px"> Contact Info </span></div>',
itemTemplate: '<div><img class="eimg" src="../Employees/${eimg}.png" alt="employee"/>' +
'<div class="ename"> ${text} </div><div class="temp"> ${country} </div></div>',
footerTemplate: '<div class="Foot"> Total Items Count: 5 </div>',
valueTemplate: '<span><img class="tempImg" src="../Employees/${eimg}.png" height="20px" width="20px" alt="employee"/>' +
'<span class="tempName"> ${text} </span></span>',
width: '250px',
mode: 'CheckBox',
placeholder: 'Select an employee',
popupWidth: '250px',
showSelectAll: true,
popupHeight: '300px'
});
listObj.appendTo(element);
listObj.showPopup();
setTimeout(function () {
expect('<div class="head">Photo<span style="padding-left:42px"> Contact Info </span></div>').toBe((<any>listObj).header.innerHTML);
expect('<div class="Foot"> Total Items Count: 5 </div>').toBe((<any>listObj).footer.innerHTML);
expect((<any>listObj).checkBoxSelectionModule.checkAllParent.classList.contains('e-selectall-parent')).toBe(true);
expect((<any>listObj).isPopupOpen()).toBe(true);
listObj.hidePopup();
listObj.destroy();
done();
}, 2000);
});
});
describe('openOnClick property in mulitselect with checkbox mode', () => {
let ele: HTMLElement = document.createElement('input');
ele.id = 'newlist';
let multiObj: any;
beforeAll(() => {
document.body.appendChild(ele);
document.body.appendChild(ele);
});
afterAll(() => {
if (ele) {
ele.remove();
}
})
it('openOnClick property', (done) => {
let multiObj = new MultiSelect({
dataSource: datasource2, openOnClick: false, mode: 'CheckBox', fields: { value: 'text', text: 'text' }
});
multiObj.appendTo('#newlist');
multiObj.showPopup();
setTimeout(function () {
mouseEventArgs.type = 'click';
mouseEventArgs.target = (<any>multiObj).overAllWrapper;
(<any>multiObj).wrapperClick(mouseEventArgs);
expect(document.body.contains((<any>multiObj).popupObj.element)).toBe(false);
keyboardEventArgs.keyCode = 70;
(<any>multiObj).keyDownStatus = true;
(<any>multiObj).keyUp(keyboardEventArgs);
expect(document.body.contains((<any>multiObj).popupObj.element)).toBe(true);
done();
}, 500);
});
});
// multiselect all property with checkbox.
describe('Property validation on initial render', () => {
let listObj: MultiSelect;
let popupObj: any;
let checkObj: CheckBoxSelection;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { 'type': 'text' } });
beforeAll(() => {
document.body.innerHTML = '';
document.body.appendChild(element);
});
afterAll(() => {
if (element) {
listObj.destroy();
element.remove();
}
checkObj = new CheckBoxSelection();
checkObj.destroy();
});
/**
* API validation.
*/
it('validate dimention APIs', () => {
let datasource33: { [key: string]: Object }[] = datasource2.slice();
datasource33.push({ id: 'list6', text: 'Oracle_Java_C#_Python_Flask_DJango' })
L10n.load({
'fr-BE': {
'dropdowns': {
'noRecordsTemplate': "Aucun enregistrement trouvé",
'actionFailureTemplate': "Modèle d'échec d'action",
"overflowCountTemplate": "More +${count} items",
'selectAllText': 'Check & UnCheck All',
}
}
});
listObj = new MultiSelect({
dataSource: datasource33,
mode: 'CheckBox',
showSelectAll: true,
fields: { value: 'id', text: 'text' },
width: "300px",
popupHeight: "100px",
popupWidth: "250px",
locale: 'fr-BE'
});
listObj.appendTo(element);
(<any>listObj).viewWrapper.setAttribute('style', "white-space: nowrap;");
listObj.value = ['list6', 'list5', 'list4', 'list3'];
listObj.dataBind();
expect((<HTMLElement>(<any>listObj).viewWrapper).childElementCount).toBe(1);
listObj.destroy();
});
/**
* API validation.
*/
it('validate dimention APIs', () => {
listObj = new MultiSelect({
mode: 'CheckBox',
dataSource: datasource2,
width: "300px",
popupHeight: "100px",
popupWidth: "250px"
});
listObj.appendTo(element);
let wrapper: HTMLElement = (<any>listObj).inputElement.parentElement.parentElement;
if (wrapper) {
expect(wrapper.getBoundingClientRect().width).toBe(300);//31
} else {
expect(true).toBe(false);
}
listObj.showPopup();
let listWarapper: HTMLElement = <HTMLElement>document.querySelector("#multiselect_popup");
if (listWarapper) {
let listElement: HTMLElement = <HTMLElement>listWarapper.querySelector(".e-list-parent");
expect(listWarapper.getBoundingClientRect().width).toBe(250);//32
//expect(listWarapper.getBoundingClientRect().height).toBe(100);//33
} else {
expect(true).toBe(false);
}
listObj.width = "200px";
listObj.dataBind();
if (wrapper) {
expect(wrapper.getBoundingClientRect().width).toBe(200);//31
} else {
expect(true).toBe(false);
}
if (listWarapper) {
let listElement: HTMLElement = <HTMLElement>listWarapper.querySelector(".e-list-parent");
expect(listWarapper.getBoundingClientRect().width).toBe(250);//32
//expect(listWarapper.getBoundingClientRect().height).toBe(100);//33
} else {
expect(true).toBe(false);
}
listObj.destroy();
});
it('Validating the Delimeter Cahr', () => {
listObj = new MultiSelect({
mode: 'CheckBox',
dataSource: datasource2,
fields: { text: "text", value: "text" },
value: ["PHP", "JAVA"],
});
listObj.appendTo(element);
expect((<any>listObj).delimiterWrapper.innerHTML.trim()).not.toBe("");
expect((<any>listObj).viewWrapper.innerHTML.trim()).toBe("PHP, JAVA");
listObj.setProperties({ delimiterChar: ';' })
expect((<any>listObj).delimiterWrapper.innerHTML.trim()).toBe("PHP; JAVA;");
expect((<any>listObj).viewWrapper.innerHTML.trim()).toBe("PHP; JAVA");
listObj.destroy();
});
it('validate item selection on render API-Value', () => {
listObj = new MultiSelect({
mode: 'CheckBox',
dataSource: datasource2, fields: { text: "text", value: "text" }, value: ["PHP", "JAVA"]
});
listObj.appendTo(element);
listObj.dataBind();
let wrapper: HTMLElement = (<any>listObj).inputElement.parentElement.parentElement;
if (wrapper && wrapper.firstElementChild)
expect(wrapper.firstElementChild.childNodes.length).toEqual(1);
else
expect(true).toBe(false);
listObj.destroy();
});
it('validate item selection on render API-Text', () => {
listObj = new MultiSelect({ mode: 'CheckBox', dataSource: datasource2, fields: { text: "text", value: "text" } });
listObj.appendTo(element);
listObj.value = ["PHP", "JAVA"];
listObj.dataBind();
expect(listObj.value.toString()).toEqual("PHP,JAVA");//34
listObj.destroy();
});
it('validate item selection on render API-Value', () => {
listObj = new MultiSelect({ dataSource: ['JAVA', 'PHP', 'PYTHON'] });
listObj.value = ["PHP", "JAVA"];
listObj.dataBind();
listObj.appendTo(element);
let wrapper: HTMLElement = (<any>listObj).inputElement.parentElement.parentElement;
if (wrapper && wrapper.firstElementChild)
expect(wrapper.firstElementChild.childNodes.length).toEqual(2);//34
else
expect(true).toBe(false);
listObj.destroy();
});
it('validate datasource binding without init value selection.', () => {
listObj = new MultiSelect({ mode: 'CheckBox', fields: { text: "Text", value: "text" } });
listObj.appendTo(element);
listObj.dataSource = datasource2;
listObj.dataBind();
expect(listObj.value).toEqual(null);
listObj.destroy();
//listObj.query = new Query().take(4);
});
it('down && up key press after scroll by manually', (done) => {
//
let list: any = new MultiSelect({
dataSource: datasource2, mode: 'CheckBox',
fields: { text: "text", value: "text" }
});
let keyEventArgs: any = { preventDefault: (): void => { }, action: 'down' };
list.appendTo(element);
list.showPopup();
setTimeout(() => {
expect(list.isPopupOpen()).toBe(true);
list.list.style.overflow = 'auto';
list.list.style.height = '48px';
list.list.style.display = 'block';
keyboardEventArgs.keyCode = 40;
list.list.scrollTop = 90;
list.onKeyDown(keyboardEventArgs);
list.onKeyDown(keyboardEventArgs);
list.onKeyDown(keyboardEventArgs);
list.onKeyDown(keyboardEventArgs);
list.onKeyDown(keyboardEventArgs);
keyboardEventArgs.keyCode = 113;
list.onKeyDown(keyboardEventArgs);
expect(list.list.scrollTop !== 90).toBe(true);
keyboardEventArgs.keyCode = 38;
list.onKeyDown(keyboardEventArgs);
expect(list.list.scrollTop !== 0).toBe(true);
list.list.scrollTop = 0;
list.onKeyDown(keyboardEventArgs);
list.onKeyDown(keyboardEventArgs);
keyboardEventArgs.keyCode = 40;
list.onKeyDown(keyboardEventArgs);
list.onKeyDown(keyboardEventArgs);
keyboardEventArgs.keyCode = 33;
list.onKeyDown(keyboardEventArgs);
list.onKeyDown(keyboardEventArgs);
keyboardEventArgs.keyCode = 34;
list.onKeyDown(keyboardEventArgs);
list.onKeyDown(keyboardEventArgs);
list.destroy();
done()
}, 450);
});
it('down && up key press after scroll by manually', (done) => {
//
let list: any = new MultiSelect({ mode: 'CheckBox', });
let keyEventArgs: any = { preventDefault: (): void => { }, action: 'down' };
list.appendTo(element);
list.showPopup();
setTimeout(() => {
expect(list.isPopupOpen()).toBe(true);
list.list.style.overflow = 'auto';
list.list.style.height = '48px';
list.list.style.display = 'block';
keyboardEventArgs.keyCode = 40;
list.list.scrollTop = 90;
list.onKeyDown(keyboardEventArgs);
list.onKeyDown(keyboardEventArgs);
list.onKeyDown(keyboardEventArgs);
list.onKeyDown(keyboardEventArgs);
list.onKeyDown(keyboardEventArgs);
expect(list.list.scrollTop !== 90).toBe(true);
keyboardEventArgs.keyCode = 38;
list.onKeyDown(keyboardEventArgs);
list.list.scrollTop = 0;
list.onKeyDown(keyboardEventArgs);
list.onKeyDown(keyboardEventArgs);
keyboardEventArgs.keyCode = 40;
list.onKeyDown(keyboardEventArgs);
list.onKeyDown(keyboardEventArgs);
keyboardEventArgs.keyCode = 33;
list.onKeyDown(keyboardEventArgs);
list.onKeyDown(keyboardEventArgs);
keyboardEventArgs.keyCode = 34;
list.onKeyDown(keyboardEventArgs);
list.onKeyDown(keyboardEventArgs);
list.destroy();
done()
}, 450);
});
it('validate datasource binding Keyup.', () => {
keyboardEventArgs.keyCode = 71;
listObj = new MultiSelect({ mode: 'CheckBox', fields: { text: "Text", value: "text" } });
listObj.appendTo(element);
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
(<any>listObj).keyUp(keyboardEventArgs);
let wrapper: HTMLElement = (<any>listObj).chipCollectionWrapper;
expect((<any>listObj).liCollections.length).toEqual(0);//34
listObj.destroy();
//listObj.query = new Query().take(4);
});
it('validate datasource binding with Query property.', () => {
listObj = new MultiSelect({ fields: { text: "text", value: "text" } });
listObj.appendTo(element);
listObj.dataSource = datasource2;
listObj.query = new Query().take(4);
listObj.value = ['Python'];
listObj.dataBind();
expect((<any>listObj).list.querySelectorAll("li").length).toEqual(4);//34
listObj.destroy();
});
it('validate datasource binding with-out data value set with clear all', () => {
let listObj: any;
listObj = new MultiSelect({ mode: 'CheckBox', fields: { text: "Text", value: "text" } });
listObj.appendTo(element);
listObj.value = ['Python'];
listObj.dataBind();
listObj.showPopup();
listObj.selectAll(true);
expect((<any>listObj).list).not.toEqual(null);//34
listObj.showOverAllClear();
listObj.clearAll(mouseEventArgs);
listObj.destroy();
});
it('validate on render API-placeholder', () => {
listObj = new MultiSelect({ dataSource: datasource2, mode: 'CheckBox', placeholder: "Select your choice" });
listObj.appendTo(element);
let wrapper: HTMLElement = (<any>listObj).inputElement.parentElement.parentElement;
if (wrapper && wrapper.firstElementChild && wrapper.firstChild.nextSibling) {
expect((<any>listObj).inputElement.getAttribute("placeholder")).not.toBe(null)//35
}
else
expect(true).toBe(false);
listObj.placeholder = 'Sample Check';
listObj.dataBind();
if (wrapper && wrapper.firstElementChild && wrapper.firstChild.nextSibling) {
expect((<any>listObj).inputElement.getAttribute("placeholder")).toBe('Sample Check')//35
} else {
expect(true).toBe(false);
}
listObj.destroy();
});
/**
* cssClass property.
*/
it('cssClass ', () => {
listObj = new MultiSelect({ dataSource: datasource2, mode: 'CheckBox', cssClass: 'closeState' });
listObj.appendTo(element);
listObj.dataBind();
expect((<any>listObj).overAllWrapper.classList.contains('closeState')).toEqual(true);//27
//popupWrapper
expect((<any>listObj).popupWrapper.classList.contains('closeState')).toBe(true);//37
listObj.cssClass = 'CloseSet';
listObj.dataBind();
expect((<any>listObj).overAllWrapper.classList.contains('closeState')).toEqual(false);//27
//popupWrapper
expect((<any>listObj).popupWrapper.classList.contains('closeState')).toBe(false);//37
expect((<any>listObj).overAllWrapper.classList.contains('CloseSet')).toEqual(true);//27
//popupWrapper
expect((<any>listObj).popupWrapper.classList.contains('CloseSet')).toBe(true);//37
listObj.destroy();
});
/**
* htmlAttributes
*/
it('htmlAttributes', () => {
listObj = new MultiSelect({ dataSource: datasource2, mode: 'CheckBox', });
listObj.appendTo(element);
let wrapper: HTMLElement = (<any>listObj).overAllWrapper;
listObj.htmlAttributes = { title: 'sample', name: 'dropdown', class: 'e-ddl-list', disabled: 'disabled', readonly: 'readonly', style: 'margin: 0', role: 'listbox', placeholder: 'new text' };
listObj.dataBind();
expect((<any>listObj).hiddenElement.getAttribute('name')).toBe('dropdown');//Need tp add it to the select element/
expect(wrapper.classList.contains('e-ddl-list')).toBe(true);//38
expect(wrapper.classList.contains('e-disabled')).toBe(true);
expect((<any>listObj).inputElement.getAttribute('placeholder')).toBe('new text');
expect(wrapper.getAttribute('role')).toBe('listbox');////39
expect(wrapper.getAttribute('style')).toBe('margin: 0');
expect(wrapper.getAttribute('style')).toBe('margin: 0');
expect((<any>listObj).element).not.toBe(null);
listObj.destroy();
});
/**
* enableRtl
*/
it('enableRtl ', () => {
listObj = new MultiSelect({ dataSource: datasource2, mode: 'CheckBox', });
listObj.appendTo(element);
let wrapper: HTMLElement = (<any>listObj).overAllWrapper;
listObj.showPopup();
listObj.enableRtl = true;
listObj.dataBind();
let listWarapper = <HTMLElement>document.querySelector("#multiselect_popup");
expect(wrapper.classList.contains('e-rtl')).toEqual(true);//40
if (listWarapper)
expect(listWarapper.classList.contains('e-rtl')).toBe(true);//41
else
expect(true).toBe(false);
listObj.hidePopup();
listObj.enableRtl = false;
listObj.dataBind();
listObj.showPopup();
expect(wrapper.classList.contains('e-rtl')).toEqual(false);//42
if (listWarapper)
expect(listWarapper.classList.contains('e-rtl')).toBe(false);//43
else
expect(true).toBe(false);
listObj.destroy();
});
/**
* showClearButton
*/
it('showClearButton false', () => {
listObj = new MultiSelect({ dataSource: datasource2, mode: 'CheckBox', showClearButton: false, value: ['PHP'], fields: { text: "text", value: "text" } });
listObj.appendTo(element);
listObj.showClearButton = false;
listObj.dataBind();
expect((<any>listObj).componentWrapper.classList.contains(multiSelectData.closeiconhide)).toBe(true);
listObj.destroy();
})
/**
* List Click Action
*/
it('Lit Click action with hide selected item and select event checkup.', () => {
let status: boolean = false;
listObj = new MultiSelect({
dataSource: datasource2, mode: 'CheckBox', fields: { text: "text", value: "text" }, select: function () {
status = true;
}, hideSelectedItem: true
});
listObj.appendTo(element);
listObj.showPopup();
let list: Array<HTMLElement> = (<any>listObj).list.querySelectorAll('li');
expect(list[0].classList.contains('e-hide-listitem')).toBe(false);
mouseEventArgs.target = list[0];
mouseEventArgs.type = 'click';
(<any>listObj).onMouseClick(mouseEventArgs);
expect(list[0].classList.contains('e-hide-listitem')).toBe(false);
expect(status).toBe(true);
listObj.destroy();
});
/**
* maximumSelectionLength.
*/
it('maximumSelectionLength.', () => {
listObj = new MultiSelect({
dataSource: datasource2, mode: 'CheckBox', fields: { text: "text", value: "text" },
showSelectAll: true,
maximumSelectionLength: 7
});
listObj.appendTo(element);
listObj.showPopup();
let list: Array<HTMLElement> = (<any>listObj).list.querySelectorAll('li');
mouseEventArgs.target = list[0];
mouseEventArgs.type = 'click';
(<any>listObj).onMouseClick(mouseEventArgs);
mouseEventArgs.target = list[1];
(<any>listObj).onMouseClick(mouseEventArgs);
let wrapper: HTMLElement = (<any>listObj).inputElement.parentElement.parentElement;
expect(wrapper.firstElementChild.childNodes.length).toEqual(1);//48
mouseEventArgs.target = list[2];
mouseEventArgs.type = 'click';
(<any>listObj).onMouseClick(mouseEventArgs);
mouseEventArgs.target = list[3];
(<any>listObj).onMouseClick(mouseEventArgs);
mouseEventArgs.target = list[4];
(<any>listObj).onMouseClick(mouseEventArgs);
mouseEventArgs.target = list[5];
(<any>listObj).onMouseClick(mouseEventArgs);
(<any>listObj).onBlurHandler(mouseEventArgs);
listObj.dataBind();
expect(listObj.value.length).toEqual(6);//49
listObj.enabled = false;
listObj.dataBind();
listObj.showPopup();
(<any>listObj).onMouseClick(mouseEventArgs);
listObj.selectAll(false);
listObj.selectAll(true);
listObj.destroy();
});
it('maximumSelectionLength disabled items.', () => {
listObj = new MultiSelect({
dataSource: datasource2, mode: 'CheckBox', fields: { text: "text", value: "text" },
showSelectAll: true,
maximumSelectionLength: 3
});
listObj.appendTo(element);
listObj.showPopup();
let list: Array<HTMLElement> = (<any>listObj).list.querySelectorAll('li');
mouseEventArgs.target = list[0];
mouseEventArgs.type = 'click';
(<any>listObj).onMouseClick(mouseEventArgs);
mouseEventArgs.target = list[1];
(<any>listObj).onMouseClick(mouseEventArgs);
let wrapper: HTMLElement = (<any>listObj).inputElement.parentElement.parentElement;
expect(wrapper.firstElementChild.childNodes.length).toEqual(1);//48
mouseEventArgs.target = list[2];
mouseEventArgs.type = 'click';
(<any>listObj).onMouseClick(mouseEventArgs);
expect((<any>listObj).liCollections.length === (<any>listObj).list.querySelectorAll('.e-disable').length + (<any>listObj).maximumSelectionLength).toBe(true);
listObj.hidePopup();
listObj.destroy();
});
/**
* enabled property
*/
it('enabled ', () => {
listObj = new MultiSelect({ dataSource: datasource2, mode: 'CheckBox', showDropDownIcon: true });
listObj.appendTo(element);
let wrapper: HTMLElement = (<any>listObj).inputElement.parentElement.parentElement;
listObj.enabled = false;
listObj.dataBind();
listObj.value = ['JAVA'];
listObj.dataBind();
expect((<any>listObj).overAllWrapper.classList.contains('e-disabled')).toEqual(true);//55
expect((<any>listObj).inputElement.getAttribute('aria-disabled')).toEqual('true');
expect((<any>listObj).inputElement.getAttribute('disabled')).not.toBe(null);
listObj.enabled = true;
listObj.dataBind();
expect((<any>listObj).overAllWrapper.classList.contains('e-disabled')).toEqual(false);//55
expect((<any>listObj).inputElement.getAttribute('aria-disabled')).toEqual('false');
expect((<any>listObj).inputElement.getAttribute('disabled')).toBe(null);
(<any>listObj).showDropDownIcon = false;
(<any>listObj).dataBind();
listObj.destroy();
});
/**
* Interaction automation.
*/
it('Hover event validation', () => {
listObj = new MultiSelect({ dataSource: datasource2, mode: 'CheckBox', fields: { text: "text", value: "text" } });
listObj.appendTo(element);
listObj.showPopup();
let element1: HTMLElement = (<any>listObj).list.querySelector('li[data-value="JAVA"]');
expect(element1.classList.contains(dropDownBaseClasses.hover)).toBe(false);
mouseEventArgs.target = element1;
mouseEventArgs.type = 'hover';
(<any>listObj).onMouseOver(mouseEventArgs);
expect(element1.classList.contains(dropDownBaseClasses.hover)).toBe(true);
(<any>listObj).onMouseLeave();
expect(element1.classList.contains(dropDownBaseClasses.hover)).toBe(false);
listObj.enabled = false;
(<any>listObj).onMouseOver(mouseEventArgs);
expect(element1.classList.contains(dropDownBaseClasses.hover)).not.toBe(true);
listObj.destroy();
});
// onMouseClick(e:MouseEvent)
/**
* Interaction automation.
*/
it('select event validation', () => {
listObj = new MultiSelect({ dataSource: datasource2, mode: 'CheckBox', fields: { text: "text", value: "text" }, width: "10px" });
listObj.appendTo(element);
listObj.showPopup();
let element1: HTMLElement = (<any>listObj).list.querySelector('li[data-value="JAVA"]');
expect(element.classList.contains(dropDownBaseClasses.selected)).toBe(false);
mouseEventArgs.target = element1;
mouseEventArgs.type = 'click';
(<any>listObj).onMouseClick(mouseEventArgs);
expect(element1.classList.contains(dropDownBaseClasses.selected)).toBe(true);
(<any>listObj).onMouseClick(mouseEventArgs);
expect(element1.classList.contains(dropDownBaseClasses.selected)).toBe(false);
let elements: HTMLElement[] = (<any>listObj).list.querySelectorAll('li[data-value]');
for (let index: number = 0; index < elements.length; index++) {
mouseEventArgs.target = elements[index];
(<any>listObj).onMouseClick(mouseEventArgs);
}
(<any>listObj).onBlurHandler(mouseEventArgs);
(<any>listObj).windowResize();
(<any>listObj).removeFocus();
(<any>listObj).selectListByKey();
(<any>listObj).enableSelectionOrder = false;
(<any>listObj).dataBind();
listObj.destroy();
});
/**
* Interaction automation. mouseClick for filtering
*/
it('select event validation with mouse', () => {
listObj = new MultiSelect({
dataSource: datasource2, mode: 'CheckBox', fields: { value: 'text', text: 'text' }, allowFiltering: true,
filtering: function (e) {
let query: Query = new Query().select(['text', 'id']);
query = (e.text !== '') ? query.where('text', 'startswith', e.text, true) : query;
e.updateData(datasource, query);
}
});
listObj.appendTo(element);
//open action validation
listObj.showPopup();
let element1: HTMLElement = (<any>listObj).list.querySelector('li[data-value="JAVA"]');
expect(element1.classList.contains(dropDownBaseClasses.selected)).toBe(false);
mouseEventArgs.target = element1;
mouseEventArgs.type = 'click';
(<any>listObj).onMouseClick(mouseEventArgs);
expect(element1.classList.contains(dropDownBaseClasses.selected)).toBe(true);
element1 = (<any>listObj).list.querySelector('li[data-value="JAVA"]');
(<any>listObj).onMouseClick(mouseEventArgs);
expect(element1.classList.contains(dropDownBaseClasses.selected)).toBe(false);
listObj.destroy();
});
it('filtering basic coverage', () => {
listObj = new MultiSelect({
dataSource: datasource2, mode: 'CheckBox', fields: { value: 'text', text: 'text' }, allowFiltering: true,
filtering: function (e) {
let query: Query = new Query().select(['text', 'id']);
query = (e.text !== '') ? query.where('text', 'startswith', e.text, true) : query;
e.updateData(datasource, query);
}
});
listObj.appendTo(element);
//open action validation
listObj.showPopup();
(<any>listObj).checkBoxSelectionModule.filterInput.value = "JAVA";
//open action validation
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 70;
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
(<any>listObj).keyUp(keyboardEventArgs);
let element1: HTMLElement = (<any>listObj).list.querySelector('li[data-value="JAVA"]');
expect(element1.classList.contains(dropDownBaseClasses.selected)).toBe(false);
(<any>listObj).checkBoxSelectionModule.filterInput.value = "";
keyboardEventArgs.keyCode = 70;
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
(<any>listObj).keyUp(keyboardEventArgs);
keyboardEventArgs.keyCode = 8;
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
(<any>listObj).keyUp(keyboardEventArgs);
listObj.destroy();
});
it('filtering inbuild support coverage', () => {
listObj = new MultiSelect({
dataSource: datasource2, mode: 'CheckBox', fields: { value: 'text', text: 'text' }, allowFiltering: true,
});
listObj.appendTo(element);
//open action validation
listObj.showPopup();
(<any>listObj).checkBoxSelectionModule.filterInput.value = "JAVA";
//open action validation
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 70;
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
(<any>listObj).keyUp(keyboardEventArgs);
let element1: HTMLElement = (<any>listObj).list.querySelector('li[data-value="JAVA"]');
expect(element1.classList.contains(dropDownBaseClasses.selected)).toBe(false);
(<any>listObj).checkBoxSelectionModule.filterInput.value = "";
keyboardEventArgs.keyCode = 70;
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
(<any>listObj).keyUp(keyboardEventArgs);
keyboardEventArgs.keyCode = 8;
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
(<any>listObj).keyUp(keyboardEventArgs);
listObj.destroy();
});
it('filtering basic coverage', () => {
listObj = new MultiSelect({
dataSource: datasource2, mode: 'CheckBox', fields: { value: 'text', text: 'text' }, allowFiltering: true,
filtering: function (e) {
let query: Query = new Query().select(['text', 'id']);
query = (e.text !== '') ? query.where('text', 'startswith', e.text, true) : query;
e.updateData(datasource, query);
}
});
listObj.appendTo(element);
//open action validation
listObj.showPopup();
(<any>listObj).checkBoxSelectionModule.filterInput.value = "JAVA!";
//open action validation
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 8;
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
(<any>listObj).keyUp(keyboardEventArgs);
let elem: HTMLElement[] = (<any>listObj).list.querySelectorAll('li.' + dropDownBaseClasses.focus);
expect(elem.length).toBe(0);
listObj.destroy();
});
/*
*/
/**
* Interaction automation. mouseClick for filtering
*/
it('select event validation with keyboard interaction', () => {
listObj = new MultiSelect({
dataSource: datasource2, mode: 'CheckBox', fields: { value: 'text', text: 'text' }, allowFiltering: true,
filtering: function (e) {
let query: Query = new Query().select(['text', 'id']);
query = (e.text !== '') ? query.where('text', 'startswith', e.text, true) : query;
e.updateData(datasource, query);
}
});
(<any>listObj).windowResize();
listObj.appendTo(element);
//open action validation
listObj.showPopup();
let elem: HTMLElement[] = (<any>listObj).list.querySelectorAll('li.' + dropDownBaseClasses.li);
expect(elem[0].classList.contains(dropDownBaseClasses.selected)).toBe(false);
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 40;
(<any>listObj).onKeyDown(keyboardEventArgs);
keyboardEventArgs.keyCode = 32;
(<any>listObj).onKeyDown(keyboardEventArgs);
expect(elem[0].classList.contains(dropDownBaseClasses.selected)).toBe(true);
listObj.maximumSelectionLength = 0;
(<any>listObj).onKeyDown(keyboardEventArgs);
listObj.destroy();
});
/*
*/
/**
* Interaction automation.
*/
it('select event validation with keyboard interaction-Esc key-default', (done) => {
listObj = new MultiSelect({ closePopupOnSelect: false, mode: 'CheckBox', dataSource: datasource2, fields: { value: 'text', text: 'text' }, value: ['JAVA', 'Python'] });
listObj.appendTo(element);
//open action validation
listObj.showPopup();
setTimeout((): void => {
let list: Array<HTMLElement> = (<any>listObj).list.querySelectorAll('li');
mouseEventArgs.target = list[3];
mouseEventArgs.type = 'click';
(<any>listObj).tempValues = listObj.value.slice();
(<any>listObj).onMouseClick(mouseEventArgs);
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 27;
(<any>listObj).onKeyDown(keyboardEventArgs);
expect((<any>listObj).isPopupOpen()).toBe(false);
expect(listObj.value.length).toBe(3);
(<any>listObj).onKeyDown(keyboardEventArgs);
expect(listObj.value.length).toBe(3);
listObj.destroy();
done();
}, 200);
});
it('select event validation with keyboard interaction-Esc key-Box', (done) => {
listObj = new MultiSelect({ closePopupOnSelect: false, mode: 'CheckBox', dataSource: datasource2, fields: { value: 'text', text: 'text' }, value: ['JAVA', 'Python'], });
listObj.appendTo(element);
//open action validation
listObj.showPopup();
setTimeout((): void => {
let list: Array<HTMLElement> = (<any>listObj).list.querySelectorAll('li');
mouseEventArgs.target = list[3];
mouseEventArgs.type = 'click';
(<any>listObj).tempValues = listObj.value.slice();
(<any>listObj).onMouseClick(mouseEventArgs);
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 27;
(<any>listObj).onKeyDown(keyboardEventArgs);
expect((<any>listObj).isPopupOpen()).toBe(false);
expect(listObj.value.length).toBe(3);
(<any>listObj).onKeyDown(keyboardEventArgs);
expect(listObj.value.length).toBe(3);
listObj.destroy();
done();
}, 200);
});
it('select event validation with keyboard interaction-Esc key-Box no value interaction.', (done) => {
listObj = new MultiSelect({ dataSource: datasource2, mode: 'CheckBox', fields: { value: 'text', text: 'text' }, });
listObj.appendTo(element);
//open action validation
listObj.showPopup();
setTimeout((): void => {
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 27;
(<any>listObj).onKeyDown(keyboardEventArgs);
expect(listObj.value).toBe(null);
listObj.destroy();
done();
}, 200);
});
it('select event validation with keyboard interaction-Esc key-Delim', (done) => {
listObj = new MultiSelect({ closePopupOnSelect: false, mode: 'CheckBox', dataSource: datasource2, fields: { value: 'text', text: 'text' }, value: ['JAVA', 'Python'], });
listObj.appendTo(element);
//open action validation
listObj.showPopup();
setTimeout((): void => {
let list: Array<HTMLElement> = (<any>listObj).list.querySelectorAll('li');
mouseEventArgs.target = list[3];
mouseEventArgs.type = 'click';
(<any>listObj).tempValues = listObj.value.slice();
(<any>listObj).onMouseClick(mouseEventArgs);
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 27;
(<any>listObj).onKeyDown(keyboardEventArgs);
expect((<any>listObj).isPopupOpen()).toBe(false);
expect(listObj.value.length).toBe(3);
(<any>listObj).onKeyDown(keyboardEventArgs);
expect(listObj.value.length).toBe(3);
listObj.destroy();
done();
}, 200);
});
/*
*/
/**
* Interaction automation.
*/
it('select event validation with keyboard interaction-Esc key-default', (done) => {
listObj = new MultiSelect({ closePopupOnSelect: false, mode: 'CheckBox', dataSource: datasource2, fields: { value: 'text', text: 'text' } });
listObj.appendTo(element);
//open action validation
listObj.showPopup();
setTimeout((): void => {
let list: Array<HTMLElement> = (<any>listObj).list.querySelectorAll('li');
mouseEventArgs.target = list[0];
mouseEventArgs.type = 'click';
(<any>listObj).tempValues = listObj.value;
(<any>listObj).onMouseClick(mouseEventArgs);
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 27;
(<any>listObj).onKeyDown(keyboardEventArgs);
expect((<any>listObj).isPopupOpen()).toBe(false);
expect(listObj.value.length).toBe(1);
(<any>listObj).onKeyDown(keyboardEventArgs);
expect(listObj.value.length).toBe(1);
listObj.destroy();
done();
}, 200);
});
it('select event validation with keyboard interaction-Esc key-Box', (done) => {
listObj = new MultiSelect({ closePopupOnSelect: false, mode: 'CheckBox', dataSource: datasource2, fields: { value: 'text', text: 'text' }, });
listObj.appendTo(element);
//open action validation
listObj.showPopup();
setTimeout((): void => {
let list: Array<HTMLElement> = (<any>listObj).list.querySelectorAll('li');
mouseEventArgs.target = list[0];
mouseEventArgs.type = 'click';
(<any>listObj).tempValues = listObj.value;
(<any>listObj).onMouseClick(mouseEventArgs);
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 27;
(<any>listObj).onKeyDown(keyboardEventArgs);
expect((<any>listObj).isPopupOpen()).toBe(false);
expect(listObj.value.length).toBe(1);
(<any>listObj).onKeyDown(keyboardEventArgs);
expect(listObj.value.length).toBe(1);
listObj.destroy();
done();
}, 200);
});
it('select event validation with keyboard interaction-Esc key-Delim', () => {
listObj = new MultiSelect({ closePopupOnSelect: false, mode: 'CheckBox', dataSource: datasource2, fields: { value: 'text', text: 'text' }, });
listObj.appendTo(element);
//open action validation
listObj.showPopup();
let list: Array<HTMLElement> = (<any>listObj).list.querySelectorAll('li');
mouseEventArgs.target = list[0];
mouseEventArgs.type = 'click';
(<any>listObj).tempValues = listObj.value;
(<any>listObj).onMouseClick(mouseEventArgs);
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 27;
(<any>listObj).onKeyDown(keyboardEventArgs);
expect((<any>listObj).isPopupOpen()).toBe(false);
expect(listObj.value.length).toBe(1);
(<any>listObj).onKeyDown(keyboardEventArgs);
expect(listObj.value.length).toBe(1);
expect((<any>listObj).delimiterWrapper.style.display).toBe('none');
listObj.destroy();
});
/**
* Interaction automation.
*/
it('List click event validation', () => {
listObj = new MultiSelect({ dataSource: datasource2, mode: 'CheckBox', fields: { text: "text", value: "text" }, closePopupOnSelect: true });
listObj.appendTo(element);
(<any>listObj).wrapperClick(mouseEventArgs);
expect((<any>listObj).popupObj.element.parentElement).not.toBe(null);
let list: Array<HTMLElement> = (<any>listObj).list.querySelectorAll('li');
mouseEventArgs.target = list[0];
mouseEventArgs.type = 'click';
(<any>listObj).onMouseClick(mouseEventArgs);
expect((<any>listObj).popupObj.element.parentElement).not.toBe(null);
(<any>listObj).inputFocus = true;
(<any>listObj).wrapperClick(mouseEventArgs);
expect((<any>listObj).popupObj.element.parentElement).toBe(null);
(<any>listObj).wrapperClick(mouseEventArgs);
expect((<any>listObj).popupObj.element.parentElement).not.toBe(null);
(<MultiSelect>listObj).setProperties({ readonly: true });
(<any>listObj).wrapperClick(mouseEventArgs);
expect((<any>listObj).popupObj.element.parentElement).toBe(null);
listObj.destroy();
});
//expect((<any>listObj).overAllClear.style.display).not.toEqual(null);//46
/**
* Interaction automation.
*/
it('List hover event validation', () => {
listObj = new MultiSelect({ dataSource: datasource2, mode: 'CheckBox', fields: { text: "text", value: "text" }, closePopupOnSelect: true, value: ["JAVA"] });
listObj.appendTo(element);
expect((<any>listObj).overAllClear.style.display).toBe('none');
(<any>listObj).mouseIn();
expect((<any>listObj).overAllClear.style.display).toBe('');
(<any>listObj).mouseOut();
expect((<any>listObj).overAllClear.style.display).toBe('none');
(<any>listObj).mouseIn();
expect((<any>listObj).overAllClear.style.display).toBe('');
(<any>listObj).inputFocus = true;
(<any>listObj).mouseOut();
expect((<any>listObj).overAllClear.style.display).not.toBe('none');
(<any>listObj).overAllWrapper.style.width = "400px";
(<any>listObj).showPopup();
(<any>listObj).windowResize();
listObj.value = <string[]>[];
listObj.dataBind();
(<any>listObj).inputElement.value = '';
(<any>listObj).mouseIn();
expect((<any>listObj).overAllClear.style.display).toBe('none');
listObj.enabled = false;
listObj.dataBind();
listObj.value = ['JAVA'];
listObj.dataBind();
(<any>listObj).windowResize();
listObj.destroy();
});
/**
* Keyboard Interaction automation for delim mode.
*/
it('Multiselect-Chip interaction validation with delim mode', () => {
listObj = new MultiSelect({ dataSource: datasource2, mode: 'CheckBox', fields: { text: "text", value: "text" }, closePopupOnSelect: true, value: ['JAVA', 'Python', 'Oracle', 'HTML', 'PHP'] });
listObj.appendTo(element);
//validate the back-space key with out content.
expect((<any>listObj).delimiterWrapper.innerHTML).not.toBe('');
(<any>listObj).removeChipSelection();
keyboardEventArgs.keyCode = 8;
(<any>listObj).checkBoxSelectionModule.filterInput.value = '';
(<any>listObj).onKeyDown(keyboardEventArgs);
(<any>listObj).onKeyDown(keyboardEventArgs);
(<any>listObj).onKeyDown(keyboardEventArgs);
(<any>listObj).onKeyDown(keyboardEventArgs);
(<any>listObj).onKeyDown(keyboardEventArgs);
expect((<any>listObj).viewWrapper.innerHTML).not.toBe('');
(<any>listObj).addValue("content", "212");
listObj.value = <string[]>[];
listObj.dataBind();
(<any>listObj).onKeyDown(keyboardEventArgs);
listObj.destroy();
});
/**
* Keyboard Interaction automation.
*/
it('Multiselect-popup interaction validation', () => {
listObj = new MultiSelect({ dataSource: datasource2, mode: 'CheckBox', fields: { text: "text", value: "text" }, closePopupOnSelect: true, value: ['JAVA', 'Python', 'Oracle', 'HTML', 'PHP'] });
listObj.appendTo(element);
//open action validation
keyboardEventArgs.altKey = true;
keyboardEventArgs.keyCode = 40;
(<any>listObj).onKeyDown(keyboardEventArgs);
expect((<any>listObj).popupWrapper.parentElement).not.toBe(null);
//close action validation
keyboardEventArgs.keyCode = 38;
(<any>listObj).onKeyDown(keyboardEventArgs);
expect((<any>listObj).popupWrapper.parentElement).toBe(null);
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 32;
(<any>listObj).onKeyDown(keyboardEventArgs);
expect((<any>listObj).popupWrapper.parentElement).toBe(null);
keyboardEventArgs.altKey = true;
keyboardEventArgs.keyCode = 38;
(<any>listObj).onKeyDown(keyboardEventArgs);
expect((<any>listObj).popupWrapper.parentElement).toBe(null);
(<any>listObj).checkBoxSelectionModule.filterInput.value = "JAVA1";
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 32;
(<any>listObj).onKeyDown(keyboardEventArgs);
expect((<any>listObj).popupWrapper.parentElement).toBe(null);
(<any>listObj).showPopup();
keyboardEventArgs.keyCode = 27;
(<any>listObj).onKeyDown(keyboardEventArgs);
expect((<any>listObj).popupWrapper.parentElement).toBe(null);
listObj.destroy();
});
it('Multiselect-popup interaction validation', () => {
let selectStatus: boolean = false;
listObj = new MultiSelect({
dataSource: datasource2, mode: 'CheckBox',
select: function () {
selectStatus = true;
},
fields: { text: "text", value: "text" }, value: ['HTML', 'PHP']
});
listObj.appendTo(element);
listObj.showPopup();
let element1: HTMLElement = <HTMLElement>(<any>listObj).ulElement.querySelector('li[data-value="PHP"]');
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 32;
expect((<HTMLElement>(<any>listObj).ulElement.querySelector('li[data-value="JAVA"]')).classList[0] === 'e-list-item').toBe(true);
listObj.destroy();
});
/**
* Keyboard Interaction automation.
*/
it('Multiselect-List interaction validation', () => {
listObj = new MultiSelect({ dataSource: datasource2, mode: 'CheckBox', fields: { text: "text", value: "text" }, closePopupOnSelect: false });
listObj.appendTo(element);
//open action validation
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 40;
(<any>listObj).onKeyDown(keyboardEventArgs);
expect((<any>listObj).popupWrapper.parentElement).not.toBe(null);
let elem: HTMLElement[] = (<any>listObj).list.querySelectorAll('li.' + dropDownBaseClasses.li);
(<any>listObj).onKeyDown(keyboardEventArgs);
expect((<any>listObj).list.querySelector('li.' + dropDownBaseClasses.focus)).toBe(elem[0]);
(<any>listObj).onKeyDown(keyboardEventArgs);
expect((<any>listObj).list.querySelector('li.' + dropDownBaseClasses.focus)).toBe(elem[1]);
keyboardEventArgs.keyCode = 38;
(<any>listObj).onKeyDown(keyboardEventArgs);
expect((<any>listObj).list.querySelector(
'li.' + dropDownBaseClasses.focus).getAttribute('data-value')).toBe(elem[0].getAttribute('data-value'));
keyboardEventArgs.keyCode = 32;
(<any>listObj).onKeyDown(keyboardEventArgs);
expect(listObj.value.length).toBe(1);
keyboardEventArgs.keyCode = 35;
(<any>listObj).onKeyDown(keyboardEventArgs);
expect((<any>listObj).list.querySelector(
'li.' + dropDownBaseClasses.focus).getAttribute('data-value')).toBe(elem[elem.length - 1].getAttribute('data-value'));
keyboardEventArgs.keyCode = 36;
(<any>listObj).onKeyDown(keyboardEventArgs);
expect((<any>listObj).list.querySelector(
'li.' + dropDownBaseClasses.focus).getAttribute('data-value')).toBe(elem[0].getAttribute('data-value'));
listObj.destroy();
});
/**
* Keyboard Interaction automation.
*/
it('Multiselect input interaction validation', () => {
listObj = new MultiSelect({
dataSource: datasource2,
mode: 'CheckBox',
fields: { text: "text", value: "text" }, closePopupOnSelect: false,
filtering: function (e) {
let query: Query = new Query().select(['text', 'id']);
query = (e.text !== '') ? query.where('text', 'startswith', e.text, true) : query;
e.updateData(datasource2, query);
}
});
listObj.appendTo(element);
(<any>listObj).showPopup();
(<any>listObj).checkBoxSelectionModule.filterInput.value = "JAVA";
//open action validation
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 70;
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
(<any>listObj).keyUp(keyboardEventArgs);
expect((<any>listObj).list.querySelectorAll('li[data-value="JAVA"]').length === 1).toBe(true);
(<any>listObj).checkBoxSelectionModule.filterInput.value = "Python";
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
(<any>listObj).keyUp(keyboardEventArgs);
expect((<any>listObj).list.querySelectorAll('li[data-value="Python"]').length === 1).toBe(true);
listObj.destroy();
});
it('filtering Event - with Key interactions', () => {
let checker: boolean = false, checker1: boolean = false;
listObj = new MultiSelect({
dataSource: datasource2,
mode: 'CheckBox', value: ["JAVA"], placeholder: 'Select Dropdown', allowFiltering: true,
showDropDownIcon: true,
filtering: function (e) {
checker = true;
let query: Query = new Query().select(['text', 'id']);
query = (e.text !== '') ? query.where('text', 'startswith', e.text, true) : query;
e.updateData(datasource, query);
}
});
listObj.appendTo(element);
(<any>listObj).checkBoxSelectionModule.filterInput.value = "JAVA";
//open action validation
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
keyboardEventArgs.keyCode = 8;
(<any>listObj).keyUp(keyboardEventArgs);
let coll = (<any>listObj).liCollections;
(<any>listObj).liCollections = undefined;
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
(<any>listObj).keyUp(keyboardEventArgs);
(<any>listObj).liCollections = coll;
expect(checker).toBe(true);
listObj.destroy();
});
});
describe('Remote data binding', () => {
let listObj: MultiSelect;
let popupObj: any;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect' });
let remoteData: DataManager = new DataManager({ url: '/api/Employees', adaptor: new ODataV4Adaptor });
beforeAll(() => {
document.body.innerHTML = '';
document.body.appendChild(element);
});
afterAll(() => {
if (element) {
element.remove();
}
});
/**
* remoteData binding with selectAll method
*/
it('remoteData binding with selectAll method ', (done) => {
listObj = new MultiSelect({
hideSelectedItem: false,
mode: 'CheckBox',
showSelectAll: true,
dataSource: remoteData, query: new Query().take(4), fields: { value: 'EmployeeID', text: 'FirstName' }
});
listObj.appendTo(element);
listObj.selectAll(true);
setTimeout(() => {
(<any>listObj).moveByList(1);
expect(listObj.value.length).toBe(4);
listObj.destroy();
done();
}, 800);
});
});
describe('EJ2-19524 - UI breaking when use lengthy place holder', () => {
let listObj: MultiSelect;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
let datasource: { [key: string]: Object }[] = [
{ id: 'list1', text: 'JAVA' },
{ id: 'list2', text: 'C#' },
{ id: 'list3', text: 'C++' },
{ id: 'list4', text: '.NET' },
{ id: 'list5', text: 'Oracle' },
{ id: 'list6', text: 'GO' },
{ id: 'list7', text: 'Haskell' },
{ id: 'list8', text: 'Racket' },
{ id: 'list8', text: 'F#' }];
beforeAll(() => {
document.body.appendChild(element);
listObj = new MultiSelect({
dataSource: datasource,
fields: { text: "text", value: "id" },
placeholder: 'My placeholder 12345566789',
width: 100,
showDropDownIcon: true
});
listObj.appendTo(element);
});
afterAll(() => {
if (element) {
listObj.destroy();
element.remove();
}
});
it('Select all in check box mode', () => {
listObj = new MultiSelect({ hideSelectedItem: false, dataSource: datasource2,
placeholder: "select counties" ,showDropDownIcon: true , width: 300, mode : 'CheckBox' , filterBarPlaceholder:"Select value" , showSelectAll: true });
listObj.appendTo(element);
listObj.showPopup();
mouseEventArgs.type = "mousedown";
mouseEventArgs.target = document.getElementsByClassName('e-all-text')[0];
mouseEventArgs.currentTarget = document.getElementsByClassName('e-selectall-parent')[0];
(<any>listObj).checkBoxSelectionModule.clickHandler(mouseEventArgs);
let wrapper: HTMLElement = (<any>listObj).inputElement.parentElement.parentElement;
if (wrapper && wrapper.firstElementChild && wrapper.firstChild.nextSibling) {
expect((<any>listObj).searchWrapper.classList.contains('e-zero-size')).toBe(true);
}
else
expect(true).toBe(false);
listObj.destroy();
});
});
describe('mulitselect checkbox IE blur event', () => {
let ele: HTMLElement = document.createElement('input');
ele.id = 'newlist';
let multiObj: any;
beforeAll(() => {
document.body.appendChild(ele);
document.body.appendChild(ele);
});
afterAll(() => {
if (ele) {
ele.remove();
}
})
it('IE blur event', () => {
Browser.userAgent = 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; Tablet PC 2.0; rv:11.0) like Gecko';
let multiObj = new MultiSelect({
hideSelectedItem: false, dataSource: datasource2, fields: { value: 'text', text: 'text' },
mode: 'CheckBox',
});
multiObj.appendTo('#newlist');
//open action validation
(<any>multiObj).value = ['JAVA'];
(<any>multiObj).dataBind();
expect((<any>multiObj.value.length)).toBe(1);
(<any>multiObj).onBlurHandler(mouseEventArgs);
Browser.userAgent = navigator.userAgent;
multiObj.destroy();
});
});
describe('itemCreated fields event', () => {
let mouseEventArgs: any = { which: 3, button: 2, preventDefault: function () { }, target: null };
let dropDowns: any;
let e: any = { preventDefault: function () { }, target: null };
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'dropdown' });
beforeAll(() => {
document.body.appendChild(element);
});
afterAll(() => {
dropDowns.destroy();
element.remove();
});
it(' set disable to first item', (done) => {
let count: number = 0;
dropDowns = new MultiSelect({
dataSource: datasource,
mode: 'CheckBox',
fields: <Object>{
value: 'text', itemCreated: (e: any) => {
if (count === 0) {
e.item.classList.add('e-disabled');
}
}
}
});
dropDowns.appendTo(element);
dropDowns.renderPopup();
dropDowns.inputElement.value = 'a';
e.keyCode = 72;
dropDowns.onInput(e);;
dropDowns.keyUp(e);
setTimeout(() => {
expect(dropDowns.list.querySelectorAll('li')[0].classList.contains('e-disabled')).toBe(true);
done();
}, 500);
});
});
describe('mulitselect null value set dynamically', () => {
let ele: HTMLElement = document.createElement('input');
ele.id = 'newlist';
let multiObj: any;
beforeAll(() => {
document.body.appendChild(ele);
});
afterAll(() => {
if (ele) {
ele.remove();
}
})
it('value set null', () => {
let multiObj = new MultiSelect({
hideSelectedItem: false, dataSource: datasource2, fields: { value: 'text', text: 'text' },
mode: 'CheckBox',
value: ['JAVA'],
showSelectAll: true,
});
multiObj.appendTo('#newlist');
(<any>multiObj).value = null;
(<any>multiObj).dataBind();
expect((<any>multiObj.value)).toBe(null);
multiObj.destroy();
});
it('focus & blur Event.', (done) => {
let checker: boolean = false;
let listObj: any;
listObj = new MultiSelect({
mode: 'CheckBox', dataSource: datasource2, focus: function () {
checker = true;
}, blur: function () {
checker = true;
}
});
listObj.appendTo('#newlist');
listObj.renderPopup();
setTimeout(function () {
(<any>listObj).escapeAction();
listObj.value = ['Java'];
listObj.dataBind();
(<any>listObj).focusAtLastListItem(null);
(<any>listObj).focus();
expect(checker).toBe(true);//64
checker = false;
(<any>listObj).onBlurHandler();
(<any>listObj).focusAtLastListItem('null');
expect(checker).toBe(true);//65
(<any>listObj).onListMouseDown({ preventDefault: function () { } });
(<any>listObj).checkBoxSelectionModule.onBlurHandler({ preventDefault: function () { } });
expect((<any>listObj).scrollFocusStatus).toBe(false);
listObj.destroy();
done();
}, 500);
});
});
describe(' bug(EJ2-8937): Change event at initial rendering ', () => {
let ele: HTMLElement = document.createElement('input');
ele.id = 'newlist';
let isNotLocalChange: boolean = true;
let isNotRemoteChange: boolean = true;
beforeAll(() => {
document.body.appendChild(ele);
});
afterAll(() => {
if (ele) {
ele.remove();
}
})
it(' change event not trigger in local data', () => {
let changeCount: number = 0;
let multiObj = new MultiSelect({
dataSource: datasource2,
fields: { value: 'text', text: 'text' },
mode: 'CheckBox',
value: ['JAVA'],
change: () => {
isNotLocalChange = false;
changeCount = changeCount + 1;
}
});
multiObj.appendTo('#newlist');
expect(isNotLocalChange).toBe(true);
expect(changeCount).toBe(0);
multiObj.value = null;
multiObj.dataBind();
expect(isNotLocalChange).toBe(false);
expect(changeCount).toBe(1);
multiObj.destroy();
});
it(' change event not trigger in remote data', (done) => {
let changeCount: number = 0;
let remoteData: DataManager = new DataManager({ url: '/api/Employees', adaptor: new ODataV4Adaptor });
let multiObj = new MultiSelect({
dataSource: remoteData,
fields: { value: 'EmployeeID', text: 'FirstName' },
mode: 'CheckBox',
value: [1005],
change: () => {
isNotRemoteChange = false;
changeCount = changeCount + 1;
}
});
multiObj.appendTo('#newlist');
setTimeout(() => {
expect(isNotRemoteChange).toBe(true);
multiObj.value = null;
multiObj.dataBind();
expect(isNotRemoteChange).toBe(false);
expect(changeCount).toBe(1);
multiObj.destroy();
done();
}, 800)
});
});
describe(' bug(EJ2-8828): Filterbar placeholder is not working while change through onPropertyChange', () => {
let ele: HTMLElement = document.createElement('input');
ele.id = 'newlist';
let isNotLocalChange: boolean = true;
let isNotRemoteChange: boolean = true;
beforeAll(() => {
document.body.appendChild(ele);
});
afterAll(() => {
if (ele) {
ele.remove();
}
})
it(' change the filterBarPlaceholder through onPropertyChange', (done) => {
let changeCount: number = 0;
let multiObj: any = new MultiSelect({
dataSource: datasource2,
fields: { value: 'text', text: 'text' },
mode: 'CheckBox',
filterBarPlaceholder: "Select a value"
});
multiObj.appendTo('#newlist');
multiObj.showPopup();
setTimeout(() => {
expect(multiObj.checkBoxSelectionModule.filterInput.getAttribute('placeholder') === "Select a value").toBe(true);
multiObj.filterBarPlaceholder = 'Search here';
multiObj.dataBind();
expect(multiObj.checkBoxSelectionModule.filterInput.getAttribute('placeholder') === "Search here").toBe(true);
multiObj.destroy();
done();
}, 450);
});
});
describe('text property', () => {
let ele: HTMLElement = document.createElement('input');
ele.id = 'newlist';
let multiObj: any;
beforeAll(() => {
document.body.appendChild(ele);
});
afterAll(() => {
if (ele) {
ele.remove();
}
})
it('get selected text', (done) => {
let multiObj = new MultiSelect({
dataSource: datasource2, mode: 'CheckBox', fields: { value: 'text', text: 'text' }, value: ['PHP', 'HTML']
});
multiObj.appendTo('#newlist');
setTimeout(() => {
expect((<any>multiObj).text === "PHP,HTML").toBe(true);
(<any>multiObj).destroy();
done();
}, 450);
});
it('focus the wrapper click', () => {
let multiObj = new MultiSelect({
dataSource: datasource2, mode: 'CheckBox', fields: { value: 'text', text: 'text' }, value: ['PHP', 'HTML']
});
multiObj.appendTo('#newlist');
let mouseEvenArg: any = { preventDefault: function () { }, target: (<any>multiObj).overAllWrapper };
(<any>multiObj).wrapperClick(mouseEvenArg);
expect((<any>multiObj).isPopupOpen()).toBe(true);
(<any>multiObj).wrapperClick(mouseEvenArg);
expect((<any>multiObj).isPopupOpen()).toBe(false);
expect((<any>multiObj).overAllWrapper.classList.contains('e-input-focus')).toBe(true);
let mouseEventArgs: any = { preventDefault: function () { }, target: null };
mouseEventArgs.target = document.body;
(<any>multiObj).checkBoxSelectionModule.onDocumentClick(mouseEventArgs);
});
it('focus the input and click the document', () => {
let multiObj = new MultiSelect({
dataSource: datasource2, mode: 'CheckBox', fields: { value: 'text', text: 'text' }, value: ['PHP', 'HTML']
});
multiObj.appendTo('#newlist');
let mouseEvenArg: any = { preventDefault: function () { }, target: (<any>multiObj).overAllWrapper };
(<any>multiObj).wrapperClick(mouseEvenArg);
expect((<any>multiObj).isPopupOpen()).toBe(true);
(<any>multiObj).wrapperClick(mouseEvenArg);
expect((<any>multiObj).isPopupOpen()).toBe(false);
expect((<any>multiObj).overAllWrapper.classList.contains('e-input-focus')).toBe(true);
let mouseEventArgs: any = { preventDefault: function () { }, target: null };
mouseEventArgs.target = document.body;
(<any>multiObj).checkBoxSelectionModule.onDocumentClick(mouseEventArgs);
expect((<any>multiObj).overAllWrapper.classList.contains('e-input-focus')).toBe(false);
});
it('reordering the selected value', () => {
let multiObj = new MultiSelect({
dataSource: datasource2, mode: 'CheckBox', fields: { value: 'text', text: 'text' }, value: ['PHP', 'HTML']
});
multiObj.appendTo('#newlist');
multiObj.showPopup();
let list: Array<HTMLElement> = (<any>multiObj).list.querySelectorAll('li');
mouseEventArgs.target = list[2];
mouseEventArgs.type = 'click';
(<any>multiObj).onMouseClick(mouseEventArgs);
expect((<any>multiObj).value.length).toBe(3);
keyboardEventArgs.keyCode = 8;
(<any>multiObj).keyDownStatus = true;
(<any>multiObj).onKeyDown(keyboardEventArgs);
(<any>multiObj).keyUp(keyboardEventArgs);
expect((<any>multiObj).mainList.querySelectorAll('li')[2].getAttribute('data-value') === list[2].getAttribute('data-value')).toBe(true);
});
});
describe('Dynamically set datasource', () => {
let ele: HTMLElement = document.createElement('input');
ele.id = 'newlist';
let multiObj: any;
beforeAll(() => {
document.body.appendChild(ele);
document.body.appendChild(ele);
});
afterAll(() => {
if (ele) {
ele.remove();
}
})
it('enable selectall popup hight changed', () => {
let multiObj = new MultiSelect({
dataSource: [], mode: 'CheckBox', fields: { value: 'text', text: 'text' }, showSelectAll: true,
});
multiObj.appendTo('#newlist');
multiObj.dataSource = datasource2;
multiObj.dataBind();
multiObj.showPopup();
expect((<any>multiObj).isPopupOpen()).toBe(true);
let filterHeight: any = document.getElementsByClassName('e-filter-parent')[0];
filterHeight = filterHeight.offsetHeight;
let selectHeight: any = document.getElementsByClassName('e-selectall-parent')[0];
selectHeight = selectHeight.offsetHeight;
let popupHeight: any = parseInt((<any>multiObj).popupWrapper.style.maxHeight);
let listHeight: any = parseInt((<any>multiObj).list.style.maxHeight);
let total = popupHeight - (filterHeight + selectHeight);
expect(listHeight === total).toBe(true);
(<any>multiObj).destroy();
});
});
describe('mulitselect openOnClick with checkbox validation', () => {
let ele: HTMLElement = document.createElement('input');
ele.id = 'newlist';
let multiObj: any;
beforeAll(() => {
document.body.appendChild(ele);
document.body.appendChild(ele);
});
afterAll(() => {
if (ele) {
ele.remove();
}
})
it('openOnClick', (done) => {
let multiObj = new MultiSelect({
dataSource: datasource2, openOnClick: false, mode: 'CheckBox', fields: { value: 'text', text: 'text' }
});
multiObj.appendTo('#newlist');
multiObj.showPopup();
setTimeout(function () {
mouseEventArgs.type = 'click';
mouseEventArgs.target = (<any>multiObj).overAllWrapper;
(<any>multiObj).wrapperClick(mouseEventArgs);
expect(document.body.contains((<any>multiObj).popupObj.element)).toBe(false);
(<any>multiObj).inputElement.value = "JAVA";
//open action validation
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 70;
(<any>multiObj).keyDownStatus = true;
(<any>multiObj).keyUp(keyboardEventArgs);
expect(document.body.contains((<any>multiObj).popupObj.element)).toBe(true);
let element1: HTMLElement = (<any>multiObj).list.querySelector('li[data-value="JAVA"]');
expect(element1.classList.contains(dropDownBaseClasses.selected)).toBe(false);
multiObj.destroy();
done();
}, 500);
});
});
describe('Popup close while click on outside of filterbar', () => {
let ele: HTMLElement = document.createElement('input');
ele.id = 'newlist';
let multiObj: any;
beforeAll(() => {
document.body.appendChild(ele);
document.body.appendChild(ele);
});
afterAll(() => {
if (ele) {
ele.remove();
}
})
it('click outside of filterbar', () => {
let multiObj = new MultiSelect({
dataSource: datasource2, mode: 'CheckBox', fields: { value: 'text', text: 'text' }
});
multiObj.appendTo('#newlist');
multiObj.showPopup();
let mouseEventArgs: any = { preventDefault: function () { }, target: (<any>multiObj).filterParent };
(<any>multiObj).checkBoxSelectionModule.onDocumentClick(mouseEventArgs);
expect((<any>multiObj).isPopupOpen()).toBe(true);
multiObj.destroy();
});
});
describe(' bug(EJ2-8836): MultiSelect checkbox not focusout while double click on header and then click on document', () => {
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'dropdown' });
beforeEach(() => {
document.body.appendChild(element);
});
afterEach(() => {
element.remove();
});
it(' Close the popup while click on document', (done) => {
let keyEventArgs: any = { preventDefault: (): void => { }, action: 'down' };
let dropDowns: any = new MultiSelect({
dataSource: ['Java Script', 'AS.NET MVC'],
value: ['Java Script'],
allowFiltering: true,
mode: 'CheckBox'
});
dropDowns.appendTo(element);
dropDowns.showPopup();
setTimeout(() => {
mouseEventArgs.type = 'click';
mouseEventArgs.target = document.body;
dropDowns.checkBoxSelectionModule.onDocumentClick(mouseEventArgs);
dropDowns.checkBoxSelectionModule.onBlurHandler(mouseEventArgs);
setTimeout(() => {
expect(dropDowns.isPopupOpen()).toBe(false);
dropDowns.destroy();
done();
}, 450);
}, 450);
});
it(' Close the popup while click on inner element', (done) => {
Browser.userAgent = 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; Tablet PC 2.0; rv:11.0) like Gecko';
let keyEventArgs: any = { preventDefault: (): void => { }, action: 'down' };
let dropDowns: any = new MultiSelect({
dataSource: ['Java Script', 'AS.NET MVC'],
value: ['Java Script'],
allowFiltering: true,
mode: 'CheckBox',
});
dropDowns.appendTo(element);
dropDowns.showPopup();
setTimeout(() => {
mouseEventArgs.type = 'click';
mouseEventArgs.target = dropDowns.list;
dropDowns.checkBoxSelectionModule.onDocumentClick(mouseEventArgs);
dropDowns.checkBoxSelectionModule.onBlurHandler(mouseEventArgs);
setTimeout(() => {
expect(dropDowns.isPopupOpen()).toBe(true);
dropDowns.destroy();
Browser.userAgent = navigator.userAgent;
done();
}, 450)
}, 450);
});
});
describe(' EJ2-15642: Selection reordering issues', () => {
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'dropdown' });
let dropDowns: any;
beforeAll(() => {
document.body.appendChild(element);
dropDowns = new MultiSelect({
dataSource: ['Java Script', 'AS.NET MVC', 'Java', 'C#'],
showSelectAll: true,
allowFiltering: true,
mode: 'CheckBox'
});
dropDowns.appendTo(element);
});
afterAll(() => {
element.remove();
});
it(' create the new ul element for reordering selected items ', (done) => {
dropDowns.showPopup();
setTimeout(() => {
let list: Array<HTMLElement> = (<any>dropDowns).ulElement.querySelectorAll('li');
mouseEventArgs.target = list[0];
mouseEventArgs.type = 'click';
(<any>dropDowns).onMouseClick(mouseEventArgs);
mouseEventArgs.target = document.body;
dropDowns.checkBoxSelectionModule.onDocumentClick(mouseEventArgs);
dropDowns.showPopup();
setTimeout(() => {
expect(dropDowns.list.querySelectorAll('ul').length === 2).toBe(true);
done();
}, 450);
}, 450);
});
it(' select the second item and move it into reordering list ', (done) => {
dropDowns.showPopup();
setTimeout(() => {
let list: Array<HTMLElement> = (<any>dropDowns).ulElement.querySelectorAll('li');
mouseEventArgs.target = list[1];
mouseEventArgs.type = 'click';
(<any>dropDowns).onMouseClick(mouseEventArgs);
mouseEventArgs.target = document.body;
dropDowns.checkBoxSelectionModule.onDocumentClick(mouseEventArgs);
dropDowns.showPopup();
setTimeout(() => {
expect(dropDowns.list.querySelectorAll('ul').length === 2).toBe(true);
expect(dropDowns.list.querySelectorAll('ul')[0].childNodes.length === 2).toBe(true);
done();
}, 450);
}, 450);
});
it(' deselect the item from reordering list ', (done) => {
dropDowns.showPopup();
setTimeout(() => {
let ulChild: any = dropDowns.ulElement.querySelectorAll('li');
let length = ulChild.length;
let list: Array<HTMLElement> = (<any>dropDowns).list.querySelectorAll('li');
mouseEventArgs.target = list[1];
mouseEventArgs.type = 'click';
(<any>dropDowns).onMouseClick(mouseEventArgs);
mouseEventArgs.target = document.body;
dropDowns.checkBoxSelectionModule.onDocumentClick(mouseEventArgs);
dropDowns.showPopup();
setTimeout(() => {
expect(dropDowns.list.querySelectorAll('ul').length === 2).toBe(true);
expect(dropDowns.list.querySelectorAll('ul')[0].childNodes.length === 1).toBe(true);
expect(dropDowns.ulElement.querySelectorAll('li').length === length + 1).toBe(true);
done();
}, 450);
}, 450);
});
it(' selection maintain while filtering the lists ', (done) => {
dropDowns.va
dropDowns.showPopup();
setTimeout(() => {
dropDowns.checkBoxSelectionModule.filterInput.value = "Java Script";
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 70;
dropDowns.keyDownStatus = true;
dropDowns.onInput(keyboardEventArgs);;
dropDowns.keyUp(keyboardEventArgs);
let selectAll: HTMLElement = dropDowns.popupObj.element.querySelector('.e-selectall-parent .e-all-text');
expect(selectAll.textContent === 'Unselect All').toBe(true);
done();
}, 450);
});
});
describe(' checkbox width additem', () => {
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'dropdown' });
let mulObj: any;
beforeAll(() => {
document.body.appendChild(element);
mulObj = new MultiSelect({
dataSource: datasource2,
fields: { value: 'text', text: 'text' },
allowFiltering: true,
mode: 'CheckBox'
});
mulObj.appendTo(element);
});
afterAll(() => {
element.remove();
});
it(' addItem method ', () => {
let item: any = { text: 'msoffice', value: 'ms' }
expect(mulObj.dataSource.length === 6).toBe(true);
mulObj.addItem(item);
mulObj.showPopup();
expect(mulObj.ulElement.querySelectorAll('li').length === 7).toBe(true);
let list: HTMLElement = (<any>mulObj).ulElement.querySelector('li[data-value="msoffice"]');
expect(list.firstElementChild.classList.contains('e-checkbox-wrapper')).toBe(true);
});
});
describe(' dynamically change clear button', () => {
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'dropdown' });
let mulObj: any;
beforeAll(() => {
document.body.appendChild(element);
mulObj = new MultiSelect({
dataSource: datasource2,
fields: { value: 'text', text: 'text' },
allowFiltering: true,
value: ['JAVA'],
mode: 'CheckBox'
});
mulObj.appendTo(element);
});
afterAll(() => {
element.remove();
});
it(' default value changes ', () => {
mulObj.dispatchEvent(mulObj.componentWrapper, "mousemove");
expect(mulObj.overAllClear.style.display === '').toBe(true);
mulObj.showClearButton = false;
mulObj.dispatchEvent(mulObj.componentWrapper, "mousemove");
expect(mulObj.overAllClear.style.display === 'none').toBe(true);
});
});
describe('dynamically changed show select all', () => {
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'dropdown' });
let dropDowns: any;
beforeAll(() => {
document.body.appendChild(element);
dropDowns = new MultiSelect({
dataSource: ['Java Script', 'AS.NET MVC', 'Java', 'C#'],
showSelectAll: true,
allowFiltering: true,
mode: 'CheckBox'
});
dropDowns.appendTo(element);
});
afterAll(() => {
element.remove();
});
it('change property', () => {
dropDowns.showPopup();
expect(dropDowns.filterParent.querySelector('.e-selectall-parent')).toBe(null);
dropDowns.showSelectAll = false;
dropDowns.dataBind();
dropDowns.showSelectAll = true;
dropDowns.dataBind();
dropDowns.showPopup();
expect(dropDowns.filterParent.querySelector('.e-selectall-parent')).toBe(null);
});
});
describe('check search box value', () => {
let listObj: any;
let popupObj: any;
let checkObj: any;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
beforeAll(() => {
document.body.appendChild(element);
});
afterAll(() => {
if (element) {
listObj.destroy();
element.remove();
}
checkObj = new CheckBoxSelection();
Browser.userAgent = navigator.userAgent;
checkObj.destroy();
});
it('input value', () => {
listObj = new MultiSelect({
dataSource: datasource2,
showSelectAll: true, mode: 'CheckBox',
fields: { value: 'text', text: 'text' }, allowFiltering: true,
selectAllText: 'Check & UnCheck All'
});
listObj.appendTo(element);
//open action validation
listObj.showPopup();
(<any>listObj).checkBoxSelectionModule.filterInput.value = "JAVA"
//open action validation
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 70;
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);;
(<any>listObj).keyUp(keyboardEventArgs);
let element1: HTMLElement = (<any>listObj).list.querySelector('li[data-value="JAVA"]');
listObj.hidePopup();
listObj.showPopup();
expect((<any>listObj).checkBoxSelectionModule.filterInput.value === '').toBe(true);
listObj.destroy();
});
});
describe('CR issue - EJ2-17555 - validation issue', () => {
let listObj: MultiSelect;
let checkObj: any
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
let ele: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'textChild', attrs: { type: "text" } });
beforeAll(() => {
document.body.appendChild(element);
document.body.appendChild(ele);
});
afterAll(() => {
if (element) {
listObj.destroy();
element.remove();
}
if(ele) {
ele.remove();
}
checkObj = new CheckBoxSelection();
checkObj.destroy();
});
it('ensure change event', (done) => {
listObj = new MultiSelect({
dataSource: datasource,
mode: 'CheckBox', fields: { text: "text", value: "text" }, value: ["JAVA"],
showSelectAll: true,
showDropDownIcon: true,
allowFiltering: true,
open: () => {
var mouseEventArgs = {preventDefault: function(){}, currentTarget: (<any>listObj).checkBoxSelectionModule.checkAllParent };
(<any>listObj).checkBoxSelectionModule.clickHandler(mouseEventArgs);
(<any>listObj).onBlurHandler();
},
change: () => {
expect(true).toBe(true);
done();
}
});
listObj.appendTo(element);
listObj.showSelectAll = true;
listObj.dataBind();
listObj.showPopup();
});
});
describe('EJ2-13211 - remote selection not maintain', () => {
let listObj: MultiSelect;
let originalTimeout: number;
let checkObj: any
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
let ele: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'textChild', attrs: { type: "text" } });
let datasource: { [key: string]: Object }[] = [
{ id: 'level1', sports: 'American Football' }, { id: 'level2', sports: 'Badminton' },
{ id: 'level3', sports: 'Basketball' }, { id: 'level4', sports: 'Cricket' },
{ id: 'level5', sports: 'Football' }, { id: 'level6', sports: 'Golf' },
{ id: 'level7', sports: 'Hockey' }, { id: 'level8', sports: 'Rugby' },
{ id: 'level9', sports: 'Snooker' }, { id: 'level10', sports: 'Tennis' },
];
beforeAll(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 8000;
document.body.appendChild(element);
document.body.appendChild(ele);
listObj = new MultiSelect({
dataSource: datasource,
mode: 'CheckBox',
fields: { text: "sports", value: "id" },
text: 'Tennis',
showSelectAll: true,
showDropDownIcon: true,
enableSelectionOrder: false,
popupHeight: 100
});
listObj.appendTo(element);
listObj.dataBind();
});
afterAll(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
if (element) {
listObj.destroy();
element.remove();
}
if(ele) {
ele.remove();
}
checkObj = new CheckBoxSelection();
checkObj.destroy();
});
it('ensure text property - Initial assignment', () => {
listObj.showPopup();
expect(listObj.value.length).toBeGreaterThan(0);
});
it('ensure list scroll', () => {
expect((<any>listObj).list.querySelector('.e-active').innerText).toBe('Tennis');
});
it('ensure text property - Dynamic assignment', (done) => {
listObj.change = (args: MultiSelectChangeEventArgs): void => {
expect(args.value.length).toBeGreaterThan(0);
expect(args.value[0]).toBe('level9');
done();
}
listObj.text = 'Snooker';
});
});
describe('EJ2-20084 - Multiselect select all and un select all not working properly', () => {
let listObj: MultiSelect;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
let datasource: { [key: string]: Object }[] = [
{ id: 'list1', text: 'JAVA' },
{ id: 'list2', text: 'C#' },
{ id: 'list3', text: 'C++' },
{ id: 'list4', text: '.NET' },
{ id: 'list5', text: 'Oracle' },
{ id: 'list6', text: 'GO' },
{ id: 'list7', text: 'Haskell' },
{ id: 'list8', text: 'Racket' },
{ id: 'list8', text: 'F#' }];
let popup: HTMLElement;
let originalTimeout: number;
beforeAll(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 2000;
document.body.appendChild(element);
});
afterAll(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
if (element) {
listObj.destroy();
element.remove();
}
});
it('check select all', (done) => {
listObj = new MultiSelect({
dataSource: datasource,
fields: { text: "text", value: "id" },
popupHeight: 50,
mode: 'CheckBox',
showSelectAll: true,
change: (): void => {
if (popup) {
setTimeout(() => {
expect(popup.querySelectorAll('.e-check').length).toBe(0);
}, 0);
done();
}
},
open: (args: PopupEventArgs): void => {
popup = args.popup.element;
listObj.value = [];
}
});
listObj.appendTo(element);
listObj.selectAll(true);
listObj.dataBind();
listObj.showPopup();
});
it('check select all without open', (done) => {
listObj = new MultiSelect({
dataSource: datasource,
fields: { text: "text", value: "id" },
popupHeight: 50,
mode: 'CheckBox',
showSelectAll: true,
open: (): void => {
expect((<any>listObj).list.querySelectorAll('.e-check').length).toBe(0);
done();
}
});
listObj.appendTo(element);
listObj.selectAll(true);
listObj.dataBind();
listObj.value = [];
listObj.dataBind();
listObj.showPopup();
});
});
describe('EJ2-20148 - MultiSelect Dropdown value does not update', () => {
let listObj: MultiSelect;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
let datasource: { [key: string]: Object }[] = [
{
label: 'ACTIVITY_FEED__ACTIVITY_FEED_PAGE_INCOMING_TAB__FACEBOOK_ACTIVITY',
value: '1',
iconClass: 'fb',
}
];
let popup: HTMLElement;
let originalTimeout: number;
beforeAll(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 2000;
document.body.appendChild(element);
});
afterAll(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
if (element) {
listObj.destroy();
element.remove();
}
});
it('check select all', (done) => {
listObj = new MultiSelect({
dataSource: datasource,
placeholder: 'ACTIVITY_FEED__ACTIVITY_FEED_PAGE_INCOMING_TAB__SHOW_ACTIVITY_FROM_PLACEHOLDER',
fields: { text: 'label', value: 'value', iconCss: 'iconClass' },
popupHeight: 50,
mode: 'CheckBox',
showClearButton: true,
open: (): void => {
expect(isNullOrUndefined((<any>listObj).checkWrapper)).toBe(true);
done();
}
});
listObj.appendTo(element);
listObj.value = ['1'];
listObj.dataBind();
listObj.showPopup();
});
});
describe('EJ2-20390 - Checking SelectAll option in MultiSelect select items in reverse order', () => {
let listObj: MultiSelect;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
let datasource: { [key: string]: Object }[] = [
{ Name: 'Australia', Code: 'AU' },
{ Name: 'Bermuda', Code: 'BM' },
{ Name: 'Canada', Code: 'CA' },
{ Name: 'Cameroon', Code: 'CM' },
{ Name: 'Denmark', Code: 'DK' },
{ Name: 'France', Code: 'FR' },
{ Name: 'Finland', Code: 'FI' },
];
let originalTimeout: number;
beforeAll(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
document.body.appendChild(element);
listObj = new MultiSelect({
dataSource: datasource,
fields: { text: 'Name' },
popupHeight: 50,
mode: 'CheckBox',
showSelectAll: true
});
listObj.appendTo(element);
});
afterAll(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
if (element) {
listObj.destroy();
element.remove();
}
});
it('check select all', (done) => {
listObj.selectedAll = (args: ISelectAllEventArgs): void => {
expect((args.itemData[0] as { [key: string]: Object }).Name).toBe('Australia');
expect(listObj.value[0]).toBe('Australia');
done();
};
listObj.selectAll(true);
});
});
describe('EJ2-21529 - Need to provide support for without filtering in mutliselect checkbox mode - false', () => {
let listObj: MultiSelect;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
let datasource: { [key: string]: Object }[] = [
{ Name: 'Australia', Code: 'AU' },
{ Name: 'Bermuda', Code: 'BM' },
{ Name: 'Canada', Code: 'CA' },
{ Name: 'Cameroon', Code: 'CM' },
{ Name: 'Denmark', Code: 'DK' },
{ Name: 'France', Code: 'FR' },
{ Name: 'Finland', Code: 'FI' },
];
let originalTimeout: number;
beforeAll(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
document.body.appendChild(element);
listObj = new MultiSelect({
dataSource: datasource,
fields: { text: 'Name' },
popupHeight: 50,
mode: 'CheckBox',
showSelectAll: true,
allowFiltering: false
});
listObj.appendTo(element);
});
afterAll(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
if (element) {
listObj.destroy();
element.remove();
}
});
it('check filtering element', (done) => {
listObj.open = (args: PopupEventArgs): void => {
expect(args.popup.element.querySelectorAll('.e-input-filter').length).toBe(0);
done();
};
listObj.showPopup();
});
});
describe('EJ2-21529 - Need to provide support for without filtering in mutliselect checkbox mode - true', () => {
let listObj: MultiSelect;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
let datasource: { [key: string]: Object }[] = [
{ Name: 'Australia', Code: 'AU' },
{ Name: 'Bermuda', Code: 'BM' },
{ Name: 'Canada', Code: 'CA' },
{ Name: 'Cameroon', Code: 'CM' },
{ Name: 'Denmark', Code: 'DK' },
{ Name: 'France', Code: 'FR' },
{ Name: 'Finland', Code: 'FI' },
];
let originalTimeout: number;
beforeAll(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
document.body.appendChild(element);
listObj = new MultiSelect({
dataSource: datasource,
fields: { text: 'Name' },
popupHeight: 50,
mode: 'CheckBox',
showSelectAll: true,
allowFiltering: true
});
listObj.appendTo(element);
});
afterAll(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
if (element) {
listObj.destroy();
element.remove();
}
});
it('check filtering element', (done) => {
listObj.open = (args: PopupEventArgs): void => {
expect(args.popup.element.querySelectorAll('.e-input-filter').length).toBe(1);
done();
};
listObj.showPopup();
});
});
describe('EJ2-21529 - Need to provide support for without filtering in mutliselect checkbox mode - null', () => {
let listObj: MultiSelect;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
let datasource: { [key: string]: Object }[] = [
{ Name: 'Australia', Code: 'AU' },
{ Name: 'Bermuda', Code: 'BM' },
{ Name: 'Canada', Code: 'CA' },
{ Name: 'Cameroon', Code: 'CM' },
{ Name: 'Denmark', Code: 'DK' },
{ Name: 'France', Code: 'FR' },
{ Name: 'Finland', Code: 'FI' },
];
let originalTimeout: number;
beforeAll(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
document.body.appendChild(element);
listObj = new MultiSelect({
dataSource: datasource,
fields: { text: 'Name' },
popupHeight: 50,
mode: 'CheckBox',
showSelectAll: true
});
listObj.appendTo(element);
});
afterAll(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
if (element) {
listObj.destroy();
element.remove();
}
});
it('check filtering element', (done) => {
listObj.open = (args: PopupEventArgs): void => {
expect(args.popup.element.querySelectorAll('.e-input-filter').length).toBe(1);
done();
};
listObj.showPopup();
});
});
describe('EJ2-21529 - Need to provide support for without filtering in mutliselect checkbox mode - Dynamic assignment to false', () => {
let listObj: MultiSelect;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
let datasource: { [key: string]: Object }[] = [
{ Name: 'Australia', Code: 'AU' },
{ Name: 'Bermuda', Code: 'BM' },
{ Name: 'Canada', Code: 'CA' },
{ Name: 'Cameroon', Code: 'CM' },
{ Name: 'Denmark', Code: 'DK' },
{ Name: 'France', Code: 'FR' },
{ Name: 'Finland', Code: 'FI' },
];
let originalTimeout: number;
beforeAll(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
document.body.appendChild(element);
listObj = new MultiSelect({
dataSource: datasource,
fields: { text: 'Name' },
popupHeight: 50,
mode: 'CheckBox',
showSelectAll: true
});
listObj.appendTo(element);
listObj.allowFiltering = false;
});
afterAll(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
if (element) {
listObj.destroy();
element.remove();
}
});
it('check filtering element', (done) => {
listObj.open = (args: PopupEventArgs): void => {
expect(args.popup.element.querySelectorAll('.e-input-filter').length).toBe(0);
done();
};
listObj.showPopup();
});
});
describe('EJ2-21529 - Need to provide support for without filtering in mutliselect checkbox mode - Dynamic assignment to true', () => {
let listObj: MultiSelect;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
let datasource: { [key: string]: Object }[] = [
{ Name: 'Australia', Code: 'AU' },
{ Name: 'Bermuda', Code: 'BM' },
{ Name: 'Canada', Code: 'CA' },
{ Name: 'Cameroon', Code: 'CM' },
{ Name: 'Denmark', Code: 'DK' },
{ Name: 'France', Code: 'FR' },
{ Name: 'Finland', Code: 'FI' },
];
let originalTimeout: number;
beforeAll(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
document.body.appendChild(element);
listObj = new MultiSelect({
dataSource: datasource,
fields: { text: 'Name' },
popupHeight: 50,
mode: 'CheckBox',
showSelectAll: true,
allowFiltering: false
});
listObj.appendTo(element);
listObj.allowFiltering = true;
});
afterAll(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
if (element) {
listObj.destroy();
element.remove();
}
});
it('check filtering element', (done) => {
listObj.open = (args: PopupEventArgs): void => {
expect(args.popup.element.querySelectorAll('.e-input-filter').length).toBe(1);
done();
};
listObj.showPopup();
});
});
describe('EJ2-22723 - SelectAll performance improvement', () => {
let listObj: MultiSelect;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'license', attrs: { type: 'text'}});
let items: string[] = [];
for (let i: number = 0 ; i < 200; i++) {
items.push('Items' + i);
};
beforeAll(() => {
document.body.appendChild(element);
});
afterAll(() => {
if (element) {
listObj.destroy();
element.remove();
}
});
it('Value selection', (done) => {
listObj = new MultiSelect({
placeholder: "Choose Option",
dataSource: items,
mode: 'CheckBox',
showSelectAll: true,
showDropDownIcon: true,
filterBarPlaceholder: 'Search countries',
popupHeight: '350px',
selectedAll: (args: ISelectAllEventArgs): void => {
expect(listObj.value.length).toBe(199);
done();
}
});
listObj.appendTo(element);
listObj.dataBind();
listObj.selectAll(true);
});
});
describe('EJ2-23849 - Multiselect total count template width specification', () => {
let listObj: MultiSelect;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
let datasource: { [key: string]: Object }[] = [
{ Name: 'Australia', Code: 'AU' },
{ Name: 'Bermuda', Code: 'BM' },
{ Name: 'Canada', Code: 'CA' },
{ Name: 'Cameroon', Code: 'CM' },
{ Name: 'Denmark', Code: 'DK' },
{ Name: 'France', Code: 'FR' },
{ Name: 'Finland', Code: 'FI' },
];
let originalTimeout: number;
beforeAll(() => {
document.body.appendChild(element);
listObj = new MultiSelect({
dataSource: datasource,
fields: { text: 'Name', value: 'Code' },
popupHeight: 50,
width: 50,
showDropDownIcon: true,
mode: 'CheckBox',
value: ['AU']
});
listObj.appendTo(element);
});
afterAll(() => {
if (element) {
listObj.destroy();
element.remove();
}
});
it('check total count width', () => {
expect(!isNullOrUndefined((<any>listObj).viewWrapper.style.width)).toBe(true);
});
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
})
});
describe('EJ2-39990 MultiSelect component in mobile mode with initial value page not scrolled', () => {
let listObj: MultiSelect;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
let datasource: { [key: string]: Object }[] = [
{ Name: 'Australia', Code: 'AU' },
{ Name: 'Bermuda', Code: 'BM' },
{ Name: 'Canada', Code: 'CA' },
{ Name: 'Cameroon', Code: 'CM' },
{ Name: 'Denmark', Code: 'DK' },
{ Name: 'France', Code: 'FR' },
{ Name: 'Finland', Code: 'FI' },
];
let originalTimeout: number;
beforeAll(() => {
let androidPhoneUa: string = 'Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JWR66Y) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.92 Safari/537.36';
Browser.userAgent = androidPhoneUa;
document.body.appendChild(element);
});
afterAll(() => {
if (element) {
listObj.destroy();
element.remove();
}
Browser.userAgent = navigator.userAgent;
});
it('check with checkbox', () => {
listObj = new MultiSelect({
dataSource: datasource,
fields: { text: 'Name', value: 'Code' },
popupHeight: 50,
mode: 'CheckBox',
value: ['AU']
});
listObj.appendTo(element);
expect(document.body.classList.contains('e-popup-full-page')).toBe(false);
(<any>listObj).renderPopup();
listObj.showPopup();
expect((<any>listObj).isPopupOpen()).toBe(true);
expect(document.body.classList.contains('e-popup-full-page')).toBe(true);
listObj.hidePopup();
listObj.destroy();
});
});
describe('EJ2-39868 Some items in the dropdown hides when using the header template in the mobile mode', () => {
let listObj: MultiSelect;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
let datasource: { [key: string]: Object }[] = [
{ Name: 'Australia', Code: 'AU' },
{ Name: 'Bermuda', Code: 'BM' },
{ Name: 'Canada', Code: 'CA' },
{ Name: 'Cameroon', Code: 'CM' },
{ Name: 'Denmark', Code: 'DK' },
{ Name: 'France', Code: 'FR' },
{ Name: 'Finland', Code: 'FI' },
];
let originalTimeout: number;
beforeAll(() => {
let androidPhoneUa: string = 'Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JWR66Y) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.92 Safari/537.36';
Browser.userAgent = androidPhoneUa;
document.body.appendChild(element);
});
afterAll(() => {
if (element) {
listObj.destroy();
element.remove();
}
Browser.userAgent = navigator.userAgent;
});
it('check without showselectAll', () => {
listObj = new MultiSelect({
dataSource: datasource,
fields: { text: 'Name', value: 'Code' },
popupHeight: 50,
mode: 'CheckBox',
value: ['AU'],
});
listObj.appendTo(element);
(<any>listObj).renderPopup();
listObj.showPopup();
expect((<any>listObj).isPopupOpen()).toBe(true);
expect((<any>listObj).checkBoxSelectionModule.checkAllParent).toBeUndefined;
expect(document.getElementsByClassName('e-selectall-parent')[0]).toBeUndefined;
listObj.hidePopup();
listObj.destroy();
});
it('check with showSelectAll', () => {
listObj = new MultiSelect({
dataSource: datasource,
fields: { text: 'Name', value: 'Code' },
popupHeight: 50,
mode: 'CheckBox',
value: ['AU'],
showSelectAll: true,
});
listObj.appendTo(element);
(<any>listObj).renderPopup();
listObj.showPopup();
expect((<any>listObj).isPopupOpen()).toBe(true);
expect(isNullOrUndefined((<any>listObj).checkBoxSelectionModule.checkAllParent)).toBe(false);
expect(isNullOrUndefined(document.getElementsByClassName('e-selectall-parent')[0])).toBe(false);
listObj.hidePopup();
listObj.destroy();
});
});
describe('EJ2-44277', () => {
let listObj: MultiSelect;
let count: number = 0;
let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect', attrs: { type: "text" } });
let datasource: { [key: string]: Object }[] = [
{ Name: 'Australia', Code: 'AU' },
{ Name: 'Bermuda', Code: 'BM' },
{ Name: 'Canada', Code: 'CA' },
{ Name: 'Cameroon', Code: 'CM' },
{ Name: 'Denmark', Code: 'DK' },
{ Name: 'France', Code: 'FR' },
{ Name: 'Finland', Code: 'FI' },
];
let originalTimeout: number;
beforeAll(() => {
document.body.appendChild(element);
listObj = new MultiSelect({
dataSource: datasource,
fields: { text: 'Name', value: 'Code' },
showDropDownIcon: true,
allowFiltering: true,
mode: 'CheckBox',
filtering: function(e) {
count++;
}
});
listObj.appendTo(element);
});
afterAll(() => {
if (element) {
listObj.destroy();
element.remove();
}
});
it('filter event triggering on clear icon click after entering value', () => {
mouseEventArgs.type = 'click';
mouseEventArgs.target = (<any>listObj).overAllWrapper;
(<any>listObj).wrapperClick(mouseEventArgs);
(<any>listObj).checkBoxSelectionModule.filterInput.value = "A";
keyboardEventArgs.altKey = false;
keyboardEventArgs.keyCode = 65;
(<any>listObj).keyDownStatus = true;
(<any>listObj).onInput(keyboardEventArgs);
(<any>listObj).keyUp(keyboardEventArgs);
expect(count).toBe(1);
(<any>listObj).checkBoxSelectionModule.clearText(mouseEventArgs);
expect(count).toBe(2);
});
});
describe('EJ2-44211- The focus class maintained after move the focus to another component in multiselect', () => {
let listObj1: MultiSelect;
let listObj2: MultiSelect;
let element1: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect1', attrs: { type: "text" } });
let element2: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'multiselect2', attrs: { type: "text" } });
let datasource: { [key: string]: Object }[] = [
{ Name: 'Australia', Code: 'AU' },
{ Name: 'Bermuda', Code: 'BM' },
{ Name: 'Canada', Code: 'CA' },
{ Name: 'Cameroon', Code: 'CM' },
{ Name: 'Denmark', Code: 'DK' },
{ Name: 'France', Code: 'FR' },
{ Name: 'Finland', Code: 'FI' },
];
let mouseEventArgs: any = { preventDefault: function () { }, target: null };
beforeEach(() => {
document.body.appendChild(element1);
document.body.appendChild(element2);
listObj1 = new MultiSelect({
dataSource: datasource,
fields: { text: 'Name' },
mode: 'CheckBox',
});
listObj1.appendTo(element1);
listObj2 = new MultiSelect({
dataSource: datasource,
fields: { text: 'Name' },
popupHeight: 50,
mode: 'CheckBox',
});
listObj2.appendTo(element2);
});
afterEach(() => {
if (element1) {
listObj1.destroy();
element1.remove();
}
if (element2) {
listObj2.destroy();
element2.remove();
}
});
it('remove focus class on focusing out the control', (done) => {
mouseEventArgs.type = 'click';
mouseEventArgs.target = (<any>listObj1).viewWrapper;
setTimeout(()=>{
(<any>listObj1).wrapperClick(mouseEventArgs);
mouseEventArgs.target = document.body;
(<any>listObj1).checkBoxSelectionModule.onDocumentClick(mouseEventArgs);
expect((<any>listObj1).isPopupOpen()).toBe(false);
expect((<any>listObj1).overAllWrapper.classList.contains('e-input-focus')).toBe(false);
done();
}, 800);
});
it('remove focus from current control while focusing other control', (done) => {
mouseEventArgs.type = 'click';
mouseEventArgs.target = (<any>listObj1).overAllWrapper;
setTimeout(()=>{
(<any>listObj1).wrapperClick(mouseEventArgs);
expect((<any>listObj1).isPopupOpen()).toBe(true);
mouseEventArgs.target = (<any>listObj1).overAllWrapper;
(<any>listObj1).wrapperClick(mouseEventArgs);
expect((<any>listObj1).overAllWrapper.classList.contains('e-input-focus')).toBe(true);
mouseEventArgs.target = (<any>listObj2).overAllWrapper;
(<any>listObj2).wrapperClick(mouseEventArgs);
expect((<any>listObj1).overAllWrapper.classList.contains('e-input-focus')).toBe(false);
mouseEventArgs.target = (<any>listObj2).overAllWrapper;
(<any>listObj2).wrapperClick(mouseEventArgs);
expect((<any>listObj2).overAllWrapper.classList.contains('e-input-focus')).toBe(true);
mouseEventArgs.target = document.body;
(<any>listObj2).checkBoxSelectionModule.onDocumentClick(mouseEventArgs);
expect((<any>listObj2).isPopupOpen()).toBe(false);
expect((<any>listObj2).overAllWrapper.classList.contains('e-input-focus')).toBe(false);
done();
}, 800);
});
}); | the_stack |
import { app } from "electron";
import * as path from "path";
import { Subscription } from "rxjs";
import { createLogger, format, Logger, transports } from "winston";
import { IpcEvents, MessageObject } from "../../../shared/models";
import { IpcMain } from "../ipc-main";
import { AppServer } from "./app-server";
import { AppUserInterface } from "./app-user-interface";
import { AppUserSettings } from "./app-user-settings";
// Disable hardware acceleration as it is currently not needed.
app.disableHardwareAcceleration();
/**
* Module responsible for handling main app logic.
*/
export class AppManager {
/**
* Create `AppManager` instance.
*
* @param userDirectory Directory where settings and error log will be stored.
* @param settingsFilename Filename of settings file.
* @returns `AppManager` instance or nothing if other instance of app is already running.
*/
public static async create(userDirectory: string, settingsFilename: string) {
if (app.requestSingleInstanceLock()) {
await app.whenReady();
const settingsPath = path.join(userDirectory, settingsFilename);
const settings = new AppUserSettings();
let lastSettingsReadError: Error | null = null;
try {
const readSettings = await settings.readSettings(settingsPath);
settings.current = readSettings !== null ? readSettings : settings.current;
} catch (error) {
lastSettingsReadError = error;
}
let ipc: IpcMain<IpcEvents> | null = null;
let ui: AppUserInterface | null = null;
if (!settings.current.headless) {
// Required for MacOS
app.on("activate", () => ui?.open(true).catch((error) => manager.logError(error, { isFatal: true })));
// Prevent app exit upon renderer window close
app.on("window-all-closed", (event: Event) => {
event.preventDefault();
});
const exitCallback = () => {
manager.exit().catch((error) => manager.logError(error, { isFatal: true }));
};
const serverRestartCallback = () => {
server.start(settings.current.server).catch((error) => manager.logError(error, { isFatal: true }));
};
const showRendererCallback = () => {
ui?.open(true).catch((error) => manager.logError(error, { isFatal: true }));
};
ui = new AppUserInterface(exitCallback, serverRestartCallback, showRendererCallback);
ipc = new IpcMain<IpcEvents>();
}
const server = new AppServer(ui);
const manager = new AppManager(ui, settings, server, ipc, userDirectory, settingsPath);
if (lastSettingsReadError !== null) {
manager.logError(lastSettingsReadError, { display: true });
}
else {
try {
const serverSettings = settings.current.server;
await server.start(serverSettings);
manager.logInfo(`Started server@${serverSettings.address}:${serverSettings.port}`);
} catch (error) {
manager.logError(error, { display: true });
if (settings.current.headless) {
manager.logError(new Error("Exiting the app since nothing can be done in headless mode!"),
{ isFatal: true });
}
}
}
return manager;
}
}
/**
* Stores various subscriptions.
*/
private subscriptions = new Subscription();
/**
* Instance of winston logger.
*/
private logger: Logger;
/**
* All received and emitter messages.
*/
private messages: MessageObject[] = [];
private constructor(
private ui: AppUserInterface | null,
private settings: AppUserSettings,
private server: AppServer,
private ipc: IpcMain<IpcEvents> | null,
private userDirectory: string,
private settingsPath: string,
) {
// Create logger before anything else
this.logger = createLogger({
exitOnError: false,
format: format.combine(
format.timestamp(),
format.printf((data) => {
return `[${data.timestamp}] ${data.stack || data.message}`;
}),
),
transports: [
new transports.Console({ level: "silly" }),
new transports.File({ level: "error", filename: path.join(this.userDirectory, "sgfc.log") }),
],
});
// Verify headless mode validity
if (settings.current.headless !== (this.ui === null && this.ipc === null)) {
this.logError(new Error(`Invalid headless mode!`), { isFatal: true });
return;
}
// Setup connections to UI if possible
this.ipc?.receiver.onError.add((error) => this.logError(error, { isFatal: true }));
this.bindEvents();
// Try to get current controller status before subscribing
const logDeviceInfo = (data: string | null, isConnected: boolean) => {
if (data !== null) {
this.logInfo(`Device status: ${isConnected ? "Connected" : "Disconnected"}`, { stack: data });
}
};
logDeviceInfo(this.server.controller.infoString, this.server.controller.isOpen());
// Add various event subscriptions
this.subscriptions.add(this.server.serverInstance.onError.subscribe((value) => {
this.logError(value, { display: true });
})).add(this.server.serverInstance.onInfo.subscribe((value) => {
this.logInfo(value);
})).add(this.server.controller.onOpenClose.subscribe((value) => {
logDeviceInfo(value.info, value.status);
}));
// Log a message to output
this.logInfo(`App started successfully${settings.current.headless ? " in headless mode" : ""}.`);
}
/**
* Clean up and exit app.
*/
public async exit() {
await this.server.prepareToExit();
this.ui?.prepareToExit();
this.ipc?.receiver
.removeDataHandler(false)
.removeNotification(false);
this.subscriptions.unsubscribe();
app.quit();
}
/**
* Log info message and optionally display it on renderer.
* @param info Info to send.
* @param options Additional actions to do.
*/
public logInfo(info: string, options?: { stack?: string, display?: boolean }) {
// tslint:disable-next-line: no-unnecessary-initializer
const { stack = undefined, display = false } = options || {};
const message: MessageObject = {
data: { message: info, stack },
type: "info",
};
this.logger.info(`${info}${stack ? `\n${stack}` : ""}`);
this.logMessageToRenderer(message, display);
}
/**
* Log error and optionally exit app or display it on renderer.
* @param error Error to log.
* @param options Additional actions to do.
*/
public logError(error: Error, options?: { isFatal?: boolean, display?: boolean }) {
const { isFatal = false, display = false } = options || {};
const message: MessageObject = {
data: { name: error.name, message: error.message, stack: error.stack },
type: "error",
};
this.logger.error(error);
if (isFatal) {
Promise.resolve(this.exit());
} else {
this.logMessageToRenderer(message, display);
}
}
/**
* Emits message to be logged by renderer.
* @param message Message to log.
* @param display Specify whether the message should be displayed explicitly to user.
*/
public logMessageToRenderer(message: MessageObject, display: boolean = false) {
const index = this.messages.push(message) - 1;
if (this.ui !== null) {
if (display || this.ui.ready) {
this.ui.open(display)
.then((renderer) => {
this.ipc!.createSender(renderer.webContents).notify(
"POST",
"sync-messages",
{
displayIndex: display ? index : undefined,
},
);
}).catch((value) => this.logError(value, { isFatal: true }));
}
}
}
/**
* Assign server related events.
*/
private serverEvents() {
const serverSettings = Object.assign({}, this.settings.current.server);
this.ipc?.receiver.on("GET", "settings:server", () => {
return serverSettings;
}).on("PUT", "settings:server:address", (data) => {
serverSettings.address = data;
}).on("PUT", "settings:server:port", (data) => {
serverSettings.port = data;
}).on("POST", "restart-server", (data, sender) => {
return this.server.start(serverSettings).then(() => {
this.settings.current.server = Object.assign({}, serverSettings);
return this.settings.writeSettings(this.settingsPath);
}).then(() => {
this.logInfo(`Restarted server @${serverSettings.address}:${serverSettings.port}`, { display: true });
}).catch((error) => {
this.logError(error, { display: true });
});
});
}
/**
* Assign data stream related events.
*/
private dataStreamEvents() {
let subscription: Subscription = new Subscription();
this.ipc?.receiver.on("POST", "data-stream", (stream, response) => {
this.subscriptions.remove(subscription);
subscription.unsubscribe();
if (stream) {
subscription = this.server.controller.onReport.subscribe((data) => {
response.notify("PUT", "data-stream", data);
});
this.subscriptions.add(subscription);
}
});
}
/**
* Assign filter related events.
*/
private filterEvents() {
this.ipc?.receiver.on("GET", "settings:filter", () => {
return this.settings.current.filter;
}).on("PUT", "settings:filter", (data) => {
this.settings.current.filter.type = data.type;
(this.settings.current.filter.data[data.type] as number[]) = data.value;
this.server.controller.setFilter(data);
this.settings.writeSettings(this.settingsPath)
.catch((error) => this.logError(error, { isFatal: true }));
});
}
/**
* Assign device status change related events.
*/
private deviceStatusEvents() {
let subscription: Subscription = new Subscription();
this.ipc?.receiver.on("POST", "device-status", (streamStatus, response) => {
this.subscriptions.remove(subscription);
subscription.unsubscribe();
if (streamStatus) {
subscription = this.server.controller.onOpenClose.subscribe((value) => {
response.notify("PUT", "device-status", value.status);
});
this.subscriptions.add(subscription);
response.notify("PUT", "device-status", this.server.controller.isOpen());
}
});
}
/**
* Assign UDP related events.
*/
private connectionStatusEvents() {
let subscription: Subscription = new Subscription();
this.ipc?.receiver.on("POST", "connection-status", (streamStatus, response) => {
this.subscriptions.remove(subscription);
subscription.unsubscribe();
if (streamStatus) {
subscription = this.server.serverInstance.onStatusChange.subscribe((value) => {
response.notify("PUT", "connection-status", value);
});
this.subscriptions.add(subscription);
}
});
}
/**
* Assign motion data related events.
*/
private motionDataEvents() {
let subscription: Subscription = new Subscription();
this.ipc?.receiver.on("POST", "motion-data-stream", (stream, response) => {
this.subscriptions.remove(subscription);
subscription.unsubscribe();
if (stream) {
subscription = this.server.controller.onMotionsData.subscribe((data) => {
response.notify("POST", "motion-data-stream", data);
});
this.subscriptions.add(subscription);
}
});
}
/**
* Assign message exchange related events.
*/
private messageEvents() {
this.ipc?.receiver.on("POST", "sync-messages", (message) => {
if (message.type === "error") {
this.logError(message.data);
} else {
this.logInfo(message.data.message, { stack: message.data.stack });
}
}).on("GET", "messages", (sliceAtIndex) => {
return this.messages.slice(sliceAtIndex);
});
}
/**
* Bind all of the events.
*/
private bindEvents() {
this.serverEvents();
this.dataStreamEvents();
this.filterEvents();
this.motionDataEvents();
this.deviceStatusEvents();
this.connectionStatusEvents();
this.messageEvents();
}
} | the_stack |
import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { CoreError } from '@classes/errors/error';
import { CoreFileUploaderHelper } from '@features/fileuploader/services/fileuploader-helper';
import { CanLeave } from '@guards/can-leave';
import { CoreNavigator } from '@services/navigator';
import { CoreSites, CoreSitesReadingStrategy } from '@services/sites';
import { CoreSync } from '@services/sync';
import { CoreDomUtils } from '@services/utils/dom';
import { CoreFormFields, CoreForms } from '@singletons/form';
import { Translate } from '@singletons';
import { CoreEvents } from '@singletons/events';
import {
AddonModAssignAssign,
AddonModAssignSubmission,
AddonModAssignProvider,
AddonModAssign,
AddonModAssignSubmissionStatusOptions,
AddonModAssignGetSubmissionStatusWSResponse,
AddonModAssignSavePluginData,
} from '../../services/assign';
import { AddonModAssignHelper } from '../../services/assign-helper';
import { AddonModAssignOffline } from '../../services/assign-offline';
import { AddonModAssignSync } from '../../services/assign-sync';
/**
* Page that allows adding or editing an assigment submission.
*/
@Component({
selector: 'page-addon-mod-assign-edit',
templateUrl: 'edit.html',
})
export class AddonModAssignEditPage implements OnInit, OnDestroy, CanLeave {
@ViewChild('editSubmissionForm') formElement?: ElementRef;
title: string; // Title to display.
assign?: AddonModAssignAssign; // Assignment.
courseId!: number; // Course ID the assignment belongs to.
moduleId!: number; // Module ID the submission belongs to.
userSubmission?: AddonModAssignSubmission; // The user submission.
allowOffline = false; // Whether offline is allowed.
submissionStatement?: string; // The submission statement.
submissionStatementAccepted = false; // Whether submission statement is accepted.
loaded = false; // Whether data has been loaded.
protected userId: number; // User doing the submission.
protected isBlind = false; // Whether blind is used.
protected editText: string; // "Edit submission" translated text.
protected saveOffline = false; // Whether to save data in offline.
protected hasOffline = false; // Whether the assignment has offline data.
protected isDestroyed = false; // Whether the component has been destroyed.
protected forceLeave = false; // To allow leaving the page without checking for changes.
constructor(
protected route: ActivatedRoute,
) {
this.userId = CoreSites.getCurrentSiteUserId(); // Right now we can only edit current user's submissions.
this.editText = Translate.instant('addon.mod_assign.editsubmission');
this.title = this.editText;
}
/**
* Component being initialized.
*/
ngOnInit(): void {
this.moduleId = CoreNavigator.getRouteNumberParam('cmId')!;
this.courseId = CoreNavigator.getRouteNumberParam('courseId')!;
this.isBlind = !!CoreNavigator.getRouteNumberParam('blindId');
this.fetchAssignment().finally(() => {
this.loaded = true;
});
}
/**
* Check if we can leave the page or not.
*
* @return Resolved if we can leave it, rejected if not.
*/
async canLeave(): Promise<boolean> {
if (this.forceLeave) {
return true;
}
// Check if data has changed.
const changed = await this.hasDataChanged();
if (changed) {
await CoreDomUtils.showConfirm(Translate.instant('core.confirmcanceledit'));
}
// Nothing has changed or user confirmed to leave. Clear temporary data from plugins.
AddonModAssignHelper.clearSubmissionPluginTmpData(this.assign!, this.userSubmission, this.getInputData());
CoreForms.triggerFormCancelledEvent(this.formElement, CoreSites.getCurrentSiteId());
return true;
}
/**
* Fetch assignment data.
*
* @return Promise resolved when done.
*/
protected async fetchAssignment(): Promise<void> {
const currentUserId = CoreSites.getCurrentSiteUserId();
try {
// Get assignment data.
this.assign = await AddonModAssign.getAssignment(this.courseId, this.moduleId);
this.title = this.assign.name || this.title;
if (!this.isDestroyed) {
// Block the assignment.
CoreSync.blockOperation(AddonModAssignProvider.COMPONENT, this.assign.id);
}
// Wait for sync to be over (if any).
await AddonModAssignSync.waitForSync(this.assign.id);
// Get submission status. Ignore cache to get the latest data.
const options: AddonModAssignSubmissionStatusOptions = {
userId: this.userId,
isBlind: this.isBlind,
cmId: this.assign.cmid,
filter: false,
readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK,
};
let submissionStatus: AddonModAssignGetSubmissionStatusWSResponse;
try {
submissionStatus = await AddonModAssign.getSubmissionStatus(this.assign.id, options);
this.userSubmission =
AddonModAssign.getSubmissionObjectFromAttempt(this.assign, submissionStatus.lastattempt);
} catch (error) {
// Cannot connect. Get cached data.
options.filter = true;
options.readingStrategy = CoreSitesReadingStrategy.PREFER_CACHE;
submissionStatus = await AddonModAssign.getSubmissionStatus(this.assign.id, options);
this.userSubmission =
AddonModAssign.getSubmissionObjectFromAttempt(this.assign, submissionStatus.lastattempt);
// Check if the user can edit it in offline.
const canEditOffline =
await AddonModAssignHelper.canEditSubmissionOffline(this.assign, this.userSubmission);
if (!canEditOffline) {
// Submission cannot be edited in offline, reject.
this.allowOffline = false;
throw error;
}
}
if (!submissionStatus.lastattempt?.canedit) {
// Can't edit. Reject.
throw new CoreError(Translate.instant('core.nopermissions', { $a: this.editText }));
}
this.allowOffline = true; // If offline isn't allowed we shouldn't have reached this point.
// Only show submission statement if we are editing our own submission.
if (this.assign.requiresubmissionstatement && !this.assign.submissiondrafts && this.userId == currentUserId) {
this.submissionStatement = this.assign.submissionstatement;
} else {
this.submissionStatement = undefined;
}
try {
// Check if there's any offline data for this submission.
const offlineData = await AddonModAssignOffline.getSubmission(this.assign.id, this.userId);
this.hasOffline = offlineData?.plugindata && Object.keys(offlineData.plugindata).length > 0;
} catch {
// No offline data found.
this.hasOffline = false;
}
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'Error getting assigment data.');
// Leave the player.
this.leaveWithoutCheck();
}
}
/**
* Get the input data.
*
* @return Input data.
*/
protected getInputData(): CoreFormFields {
return CoreForms.getDataFromForm(document.forms['addon-mod_assign-edit-form']);
}
/**
* Check if data has changed.
*
* @return Promise resolved with boolean: whether data has changed.
*/
protected async hasDataChanged(): Promise<boolean> {
// Usually the hasSubmissionDataChanged call will be resolved inmediately, causing the modal to be shown just an instant.
// We'll wait a bit before showing it to prevent this "blink".
const modal = await CoreDomUtils.showModalLoading();
const data = this.getInputData();
return AddonModAssignHelper.hasSubmissionDataChanged(this.assign!, this.userSubmission, data).finally(() => {
modal.dismiss();
});
}
/**
* Leave the view without checking for changes.
*/
protected leaveWithoutCheck(): void {
this.forceLeave = true;
CoreNavigator.back();
}
/**
* Get data to submit based on the input data.
*
* @param inputData The input data.
* @return Promise resolved with the data to submit.
*/
protected async prepareSubmissionData(inputData: CoreFormFields): Promise<AddonModAssignSavePluginData> {
// If there's offline data, always save it in offline.
this.saveOffline = this.hasOffline;
try {
return await AddonModAssignHelper.prepareSubmissionPluginData(
this.assign!,
this.userSubmission,
inputData,
this.hasOffline,
);
} catch (error) {
if (this.allowOffline && !this.saveOffline) {
// Cannot submit in online, prepare for offline usage.
this.saveOffline = true;
return await AddonModAssignHelper.prepareSubmissionPluginData(
this.assign!,
this.userSubmission,
inputData,
true,
);
}
throw error;
}
}
/**
* Save the submission.
*/
async save(): Promise<void> {
// Check if data has changed.
const changed = await this.hasDataChanged();
if (!changed) {
// Nothing to save, just go back.
this.leaveWithoutCheck();
return;
}
try {
await this.saveSubmission();
this.leaveWithoutCheck();
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'Error saving submission.');
}
}
/**
* Save the submission.
*
* @return Promise resolved when done.
*/
protected async saveSubmission(): Promise<void> {
const inputData = this.getInputData();
if (this.submissionStatement && (!inputData.submissionstatement || inputData.submissionstatement === 'false')) {
throw Translate.instant('addon.mod_assign.acceptsubmissionstatement');
}
let modal = await CoreDomUtils.showModalLoading();
let size = -1;
// Get size to ask for confirmation.
try {
size = await AddonModAssignHelper.getSubmissionSizeForEdit(this.assign!, this.userSubmission!, inputData);
} catch (error) {
// Error calculating size, return -1.
size = -1;
}
modal.dismiss();
try {
// Confirm action.
await CoreFileUploaderHelper.confirmUploadFile(size, true, this.allowOffline);
modal = await CoreDomUtils.showModalLoading('core.sending', true);
const pluginData = await this.prepareSubmissionData(inputData);
if (!Object.keys(pluginData).length) {
// Nothing to save.
return;
}
let sent: boolean;
if (this.saveOffline) {
// Save submission in offline.
sent = false;
await AddonModAssignOffline.saveSubmission(
this.assign!.id,
this.courseId,
pluginData,
this.userSubmission!.timemodified,
!this.assign!.submissiondrafts,
this.userId,
);
} else {
// Try to send it to server.
sent = await AddonModAssign.saveSubmission(
this.assign!.id,
this.courseId,
pluginData,
this.allowOffline,
this.userSubmission!.timemodified,
!!this.assign!.submissiondrafts,
this.userId,
);
}
// Clear temporary data from plugins.
AddonModAssignHelper.clearSubmissionPluginTmpData(this.assign!, this.userSubmission, inputData);
if (sent) {
CoreEvents.trigger(CoreEvents.ACTIVITY_DATA_SENT, { module: 'assign' });
}
// Submission saved, trigger events.
CoreForms.triggerFormSubmittedEvent(this.formElement, sent, CoreSites.getCurrentSiteId());
CoreEvents.trigger(
AddonModAssignProvider.SUBMISSION_SAVED_EVENT,
{
assignmentId: this.assign!.id,
submissionId: this.userSubmission!.id,
userId: this.userId,
},
CoreSites.getCurrentSiteId(),
);
if (!this.assign!.submissiondrafts) {
// No drafts allowed, so it was submitted. Trigger event.
CoreEvents.trigger(
AddonModAssignProvider.SUBMITTED_FOR_GRADING_EVENT,
{
assignmentId: this.assign!.id,
submissionId: this.userSubmission!.id,
userId: this.userId,
},
CoreSites.getCurrentSiteId(),
);
}
} finally {
modal.dismiss();
}
}
/**
* Component being destroyed.
*/
ngOnDestroy(): void {
this.isDestroyed = true;
// Unblock the assignment.
if (this.assign) {
CoreSync.unblockOperation(AddonModAssignProvider.COMPONENT, this.assign.id);
}
}
} | the_stack |
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NgbCollapse, NgbPopoverModule } from '@ng-bootstrap/ng-bootstrap';
import { AngularFittextModule } from 'angular-fittext';
import { DragAndDropMapping } from 'app/entities/quiz/drag-and-drop-mapping.model';
import { DragAndDropQuestion } from 'app/entities/quiz/drag-and-drop-question.model';
import { DragItem } from 'app/entities/quiz/drag-item.model';
import { DropLocation } from 'app/entities/quiz/drop-location.model';
import { DragAndDropQuestionUtil } from 'app/exercises/quiz/shared/drag-and-drop-question-util.service';
import { DragAndDropQuestionComponent } from 'app/exercises/quiz/shared/questions/drag-and-drop-question/drag-and-drop-question.component';
import { DragItemComponent } from 'app/exercises/quiz/shared/questions/drag-and-drop-question/drag-item.component';
import { QuizScoringInfoStudentModalComponent } from 'app/exercises/quiz/shared/questions/quiz-scoring-infostudent-modal/quiz-scoring-info-student-modal.component';
import { SecuredImageComponent } from 'app/shared/image/secured-image.component';
import { MarkdownEditorComponent } from 'app/shared/markdown-editor/markdown-editor.component';
import { ArtemisMarkdownService } from 'app/shared/markdown.service';
import { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe';
import * as chai from 'chai';
import { MockComponent, MockDirective, MockPipe, MockProvider } from 'ng-mocks';
import { DndModule } from 'ng2-dnd';
import * as sinon from 'sinon';
import { stub } from 'sinon';
import sinonChai from 'sinon-chai';
import { ArtemisTestModule } from '../../test.module';
chai.use(sinonChai);
const expect = chai.expect;
describe('DragAndDropQuestionComponent', () => {
let fixture: ComponentFixture<DragAndDropQuestionComponent>;
let comp: DragAndDropQuestionComponent;
let markdownService: ArtemisMarkdownService;
let dragAndDropQuestionUtil: DragAndDropQuestionUtil;
const reset = () => {
const question = new DragAndDropQuestion();
question.id = 1;
question.backgroundFilePath = '';
comp.question = question;
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [NgbPopoverModule, ArtemisTestModule, DndModule.forRoot(), AngularFittextModule],
declarations: [
DragAndDropQuestionComponent,
MockPipe(ArtemisTranslatePipe),
MockComponent(MarkdownEditorComponent),
MockComponent(SecuredImageComponent),
MockComponent(DragAndDropQuestionComponent),
MockDirective(NgbCollapse),
MockComponent(QuizScoringInfoStudentModalComponent),
DragItemComponent,
],
providers: [MockProvider(DragAndDropQuestionUtil)],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(DragAndDropQuestionComponent);
comp = fixture.componentInstance;
reset();
markdownService = TestBed.inject(ArtemisMarkdownService);
dragAndDropQuestionUtil = fixture.debugElement.injector.get(DragAndDropQuestionUtil);
});
});
afterEach(() => {
sinon.restore();
});
it('should update html when question changes', () => {
const question = new DragAndDropQuestion();
question.text = 'Test text';
question.hint = 'Test hint';
question.explanation = 'Test explanation';
const markdownStub = stub(markdownService, 'safeHtmlForMarkdown').callsFake((arg) => `${arg}markdown`);
comp.question = question;
expect(markdownStub).to.have.been.calledWith(question.text);
expect(markdownStub).to.have.been.calledWith(question.text);
expect(markdownStub).to.have.been.calledWith(question.text);
expect(comp.renderedQuestion).to.exist;
expect(comp.renderedQuestion.text).to.equal(`${question.text}markdown`);
expect(comp.renderedQuestion.hint).to.equal(`${question.hint}markdown`);
expect(comp.renderedQuestion.explanation).to.equal(`${question.explanation}markdown`);
});
it('should count correct mappings as zero if no correct mappings', () => {
const { dropLocation } = getDropLocationMappingAndItem();
comp.question.dropLocations = [dropLocation];
comp.ngOnChanges();
expect(comp.correctAnswer).to.equal(0);
});
it('should count correct mappings on changes', () => {
const { dropLocation: dropLocation1, mapping: correctMapping1 } = getDropLocationMappingAndItem();
const { dropLocation: dropLocation2, mapping: correctMapping2 } = getDropLocationMappingAndItem();
const { dropLocation: dropLocation3, mapping: correctMapping3 } = getDropLocationMappingAndItem();
const { mapping: correctMapping4 } = getDropLocationMappingAndItem();
const { dropLocation: dropLocation5 } = getDropLocationMappingAndItem();
comp.question.dropLocations = [dropLocation1, dropLocation2, dropLocation3];
// Mappings do not have any of drop locations so no selected item
comp.mappings = [correctMapping4];
comp.question.correctMappings = [correctMapping1, correctMapping2, correctMapping4];
comp.ngOnChanges();
/*
* without selected items it should not set correct answers to drop locations without valid drag item
* as they are excluded from the score calculation as well
*/
expect(comp.correctAnswer).to.equal(0);
// if there is a selected item should count drop locations that has the selected items drag item
// dropLocation1 and dropLocation3 is selected
// dropLocation1 is both correct and selected
// dropLocation2 is correct but not selected
// dropLocation3 is not correct but selected
// dropLocation4 is not one of the drop locations
// dropLocation5 is neither correct nor selected
// Hence 1 because of dropLocation1 (dropLocation5 must be excluded)
comp.mappings = [correctMapping1, correctMapping3];
comp.question.dropLocations = [dropLocation1, dropLocation2, dropLocation3, dropLocation5];
comp.ngOnChanges();
expect(comp.correctAnswer).to.equal(1);
});
it('should return correct drag item for drop location', () => {
const { dropLocation, mapping, dragItem } = getDropLocationMappingAndItem();
const { dropLocation: falseDropLocation } = getDropLocationMappingAndItem();
comp.sampleSolutionMappings = [mapping];
expect(comp.correctDragItemForDropLocation(dropLocation)).to.deep.equal(dragItem);
expect(comp.correctDragItemForDropLocation(falseDropLocation)).to.undefined;
});
it('should show sample solution if force sample solution is set to true', () => {
const { mapping } = getDropLocationMappingAndItem();
const solveStub = stub(dragAndDropQuestionUtil, 'solve').returnsArg(1);
const mappings = [mapping];
comp.mappings = mappings;
comp.forceSampleSolution = true;
expect(comp.forceSampleSolution).to.equal(true);
expect(solveStub).to.have.been.calledWithExactly(comp.question, mappings);
expect(comp.sampleSolutionMappings).to.deep.equal(mappings);
expect(comp.showingSampleSolution).to.equal(true);
});
it('should hide sample solutions', () => {
comp.showingSampleSolution = true;
comp.hideSampleSolution();
expect(comp.showingSampleSolution).to.equal(false);
});
it('should return unassigned drag items', () => {
const { mapping: mapping1, dragItem: dragItem1 } = getDropLocationMappingAndItem();
const { dragItem: dragItem2 } = getDropLocationMappingAndItem();
comp.mappings = [mapping1];
comp.question.dragItems = [dragItem1, dragItem2];
expect(comp.getUnassignedDragItems()).to.deep.equal([dragItem2]);
});
it('should return invalid dragItem for location', () => {
const { dropLocation: dropLocation1, mapping: mapping1 } = getDropLocationMappingAndItem();
const { dropLocation: dropLocation2, mapping: mapping2, dragItem: dragItem2 } = getDropLocationMappingAndItem();
comp.mappings = [mapping1, mapping2];
expect(comp.invalidDragItemForDropLocation(dropLocation1)).to.equal(false);
dragItem2.invalid = true;
expect(comp.invalidDragItemForDropLocation(dropLocation2)).to.equal(true);
});
it('should return no drag item if there is no mapping', () => {
const { dropLocation } = getDropLocationMappingAndItem();
expect(comp.dragItemForDropLocation(dropLocation)).to.null;
});
it('should remove existing mappings when there is no drop location', () => {
const { mapping, dragItem } = getDropLocationMappingAndItem();
const { mapping: mapping1 } = getDropLocationMappingAndItem();
const { mapping: mapping2 } = getDropLocationMappingAndItem();
checkDragDrop(undefined, dragItem, [mapping, mapping1], [mapping1], 1);
// should not call update if mappings did not change
checkDragDrop(undefined, dragItem, [mapping1, mapping2], [mapping1, mapping2], 0);
});
it('should not do anything if given droplocation and dragEvent dragData is mapped', () => {
const { dropLocation, mapping, dragItem } = getDropLocationMappingAndItem();
checkDragDrop(dropLocation, dragItem, [mapping], [mapping], 0);
});
it('should map dragItem to new drop location', () => {
const { dropLocation, mapping, dragItem } = getDropLocationMappingAndItem();
const { dropLocation: dropLocation1, mapping: mapping1, dragItem: dragItem1 } = getDropLocationMappingAndItem();
const { mapping: mapping2 } = getDropLocationMappingAndItem();
const newMappings = [mapping2, new DragAndDropMapping(dragItem1, dropLocation), new DragAndDropMapping(dragItem, dropLocation1)];
checkDragDrop(dropLocation, dragItem1, [mapping, mapping1, mapping2], newMappings, 1);
});
const checkDragDrop = (
dropLocation: DropLocation | undefined,
dragItem: DragItem,
mappings: DragAndDropMapping[],
expectedMappings: DragAndDropMapping[],
callCount: number,
) => {
comp.mappings = mappings;
const dragEvent = { dragData: dragItem };
const fnOnMappingUpdate = sinon.fake();
comp.fnOnMappingUpdate = fnOnMappingUpdate;
comp.onDragDrop(dropLocation, dragEvent);
expect(comp.mappings).to.deep.equal(expectedMappings);
expect(fnOnMappingUpdate.callCount).to.equal(callCount);
};
it('should change loading with given value', () => {
comp.changeLoading('loading');
expect(comp.loadingState).to.equal('loading');
});
it('should set drop allowed to true when dragged', () => {
comp.dropAllowed = false;
comp.drag();
expect(comp.dropAllowed).to.equal(true);
});
const getDropLocationMappingAndItem = () => {
const dropLocation = new DropLocation();
const dragItem = new DragItem();
const mapping = new DragAndDropMapping(dragItem, dropLocation);
return { dropLocation, mapping, dragItem };
};
}); | the_stack |
import { Glue42Core } from "@glue42/core";
import { Glue42Web } from "@glue42/web";
import { ApplicationStartConfig, BridgeOperation, LibController } from "../../common/types";
import { GlueController } from "../../controllers/glue";
import { IoC } from "../../shared/ioc";
import { PromisePlus } from "../../shared/promisePlus";
import { intentsOperationTypesDecoder, wrappedIntentsDecoder, wrappedIntentFilterDecoder, intentRequestDecoder, intentResultDecoder } from "./decoders";
import { IntentsOperationTypes, AppDefinitionWithIntents, IntentInfo, IntentStore, WrappedIntentFilter, WrappedIntents } from "./types";
import logger from "../../shared/logger";
import { GlueWebIntentsPrefix } from "../../common/constants";
import { AppDirectory } from "../applications/appStore/directory";
export class IntentsController implements LibController {
private operations: { [key in IntentsOperationTypes]: BridgeOperation } = {
getIntents: { name: "getIntents", resultDecoder: wrappedIntentsDecoder, execute: this.getWrappedIntents.bind(this) },
findIntent: { name: "findIntent", dataDecoder: wrappedIntentFilterDecoder, resultDecoder: wrappedIntentsDecoder, execute: this.findIntent.bind(this) },
raiseIntent: { name: "raiseIntent", dataDecoder: intentRequestDecoder, resultDecoder: intentResultDecoder, execute: this.raiseIntent.bind(this) }
};
private started = false;
constructor(
private readonly glueController: GlueController,
private readonly appDirectory: AppDirectory,
private readonly ioc: IoC
) { }
private get logger(): Glue42Core.Logger.API | undefined {
return logger.get("intents.controller");
}
public async start(): Promise<void> {
this.started = true;
}
public async handleControl(args: any): Promise<any> {
if (!this.started) {
new Error("Cannot handle this intents control message, because the controller has not been started");
}
const intentsData = args.data;
const commandId = args.commandId;
const operationValidation = intentsOperationTypesDecoder.run(args.operation);
if (!operationValidation.ok) {
throw new Error(`This intents request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(operationValidation.error)}`);
}
const operationName = operationValidation.result;
const incomingValidation = this.operations[operationName].dataDecoder?.run(intentsData);
if (incomingValidation && !incomingValidation.ok) {
throw new Error(`Intents 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(intentsData)}`);
const result = await this.operations[operationName].execute(intentsData, commandId);
const resultValidation = this.operations[operationName].resultDecoder?.run(result);
if (resultValidation && !resultValidation.ok) {
throw new Error(`Intents 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;
}
private extractAppIntents(apps: AppDefinitionWithIntents[]): IntentStore {
const intents: IntentStore = {};
const appsWithIntents = apps.filter((app) => app.intents.length > 0);
// Gather app handlers from application definitions.
for (const app of appsWithIntents) {
for (const intentDef of app.intents) {
if (!intents[intentDef.name]) {
intents[intentDef.name] = [];
}
const handler: Glue42Web.Intents.IntentHandler = {
applicationName: app.name,
applicationTitle: app.title,
applicationDescription: app.caption,
displayName: intentDef.displayName,
contextTypes: intentDef.contexts,
applicationIcon: app.icon,
type: "app"
};
intents[intentDef.name].push(handler);
}
}
return intents;
}
private async getInstanceIntents(apps: AppDefinitionWithIntents[], commandId: string): Promise<IntentStore> {
const intents: IntentStore = {};
// Discover all running instances that provide intents, and add them to the corresponding intent.
for (const server of this.glueController.getServers()) {
const serverIntentsMethods = (server.getMethods?.() || []).filter((method) => method.name.startsWith(GlueWebIntentsPrefix));
await Promise.all(serverIntentsMethods.map(async (method) => {
const intentName = method.name.replace(GlueWebIntentsPrefix, "");
if (!intents[intentName]) {
intents[intentName] = [];
}
const info = method.flags.intent as Omit<Glue42Web.Intents.AddIntentListenerRequest, "intent">;
const app = apps.find((appDef) => appDef.name === server.application);
let appIntent: IntentInfo | undefined;
// app can be undefined in the case of a dynamic intent.
if (app && app.intents) {
appIntent = app.intents.find((appDefIntent) => appDefIntent.name === intentName);
}
let title: string | undefined;
if (server.windowId) {
title = await this.ioc.windowsController.getWindowTitle(server.windowId, commandId);
}
const handler: Glue42Web.Intents.IntentHandler = {
// IFrames do not have windowIds but can still register intents.
instanceId: server.windowId || server.instance,
applicationName: server.application || "",
applicationIcon: info.icon || app?.icon,
applicationTitle: app?.title || "",
applicationDescription: info.description || app?.caption,
displayName: info.displayName || appIntent?.displayName,
contextTypes: info.contextTypes || appIntent?.contexts,
instanceTitle: title,
type: "instance"
};
intents[intentName].push(handler);
}));
}
return intents;
}
private mergeIntentStores(storeOne: IntentStore, storeTwo: IntentStore): IntentStore {
const intents: IntentStore = {};
for (const name of new Set([...Object.keys(storeOne), ...Object.keys(storeTwo)])) {
intents[name] = [...(storeOne[name] || []), ...(storeTwo[name] || [])];
}
return intents;
}
private wrapIntents(intents: Glue42Web.Intents.Intent[]): WrappedIntents {
return {
intents
};
}
private async getIntents(commandId: string): Promise<Glue42Web.Intents.Intent[]> {
/*
Gathers all intents from:
1. Application definitions
2. Running instances (application can register dynamic intents by calling `addIntentListener()` that aren't predefined inside of their application definitions)
It also populates intent handlers (actual entities that can handle the intent).
*/
const apps: AppDefinitionWithIntents[] = (await this.appDirectory.getAll()).map((app) => {
return {
name: app.name,
title: app.title || "",
icon: app.icon,
caption: app.caption,
intents: app.userProperties.intents || []
};
});
const appIntentsStore = this.extractAppIntents(apps);
this.logger?.trace(`[${commandId}] got app intents`);
const instanceIntentsStore = await this.getInstanceIntents(apps, commandId);
this.logger?.trace(`[${commandId}] got instance intents`);
const allIntentsStore = this.mergeIntentStores(appIntentsStore, instanceIntentsStore);
const intents = Object.keys(allIntentsStore).map((name) => ({ name, handlers: allIntentsStore[name] }));
return intents;
}
private async getWrappedIntents(commandId: string): Promise<WrappedIntents> {
this.logger?.trace(`[${commandId}] handling getIntents command`);
const intents = await this.getIntents(commandId);
this.logger?.trace(`[${commandId}] getIntents command completed`);
return this.wrapIntents(intents);
}
private async findIntent(wrappedIntentFilter: WrappedIntentFilter, commandId: string): Promise<WrappedIntents> {
this.logger?.trace(`[${commandId}] handling findIntent command`);
const intentFilter = wrappedIntentFilter.filter;
let intents = await this.getIntents(commandId);
if (!intentFilter) {
return this.wrapIntents(intents);
}
if (typeof intentFilter === "string") {
return this.wrapIntents(intents.filter((intent) => intent.name === intentFilter));
}
if (intentFilter.contextType) {
const ctToLower = intentFilter.contextType.toLowerCase();
intents = intents.filter((intent) => intent.handlers.some((handler) => handler.contextTypes?.some((ct) => ct.toLowerCase() === ctToLower)));
}
if (intentFilter.name) {
intents = intents.filter((intent) => intent.name === intentFilter.name);
}
this.logger?.trace(`[${commandId}] findIntent command completed`);
return this.wrapIntents(intents);
}
private async getIntent(intent: string, commandId: string): Promise<Glue42Web.Intents.Intent | undefined> {
return (await this.getIntents(commandId)).find((registeredIntent) => registeredIntent.name === intent);
}
private async startApp(config: ApplicationStartConfig, commandId: string): Promise<string> {
const instance = await this.ioc.applicationsController.handleApplicationStart(config, commandId);
return instance.id;
}
private async waitForServer(instanceId: string): Promise<Glue42Web.Interop.Instance> {
let unsub: () => void;
const executor = (resolve: (value: Glue42Web.Interop.Instance) => void): void => {
unsub = this.glueController.subscribeForServerAdded((server) => {
if (server.windowId === instanceId || server.instance === instanceId) {
resolve(server);
}
});
};
return PromisePlus(executor, 30 * 1000, `Can not find interop server for instance ${instanceId}`).finally(() => unsub());
}
private async waitForMethod(methodName: string, instanceId: string): Promise<Glue42Web.Interop.MethodDefinition> {
let unsub: () => void;
const executor = (resolve: (value: Glue42Web.Interop.MethodDefinition) => void): void => {
unsub = this.glueController.subscribeForMethodAdded((addedMethod) => {
if (addedMethod.name === methodName) {
resolve(addedMethod);
}
});
};
return PromisePlus(executor, 10 * 1000, `Can not find interop method ${methodName} for instance ${instanceId}`).finally(() => unsub());
}
private instanceIdToInteropInstance(instanceId: string): string | undefined {
const servers = this.glueController.getServers();
return servers.find((server) => server.windowId === instanceId || server.instance === instanceId)?.instance;
}
private async raiseIntentToInstance(instanceId: string, intent: string, context?: Glue42Web.Intents.IntentContext): Promise<any> {
const methodName = `${GlueWebIntentsPrefix}${intent}`;
let interopServer = this.glueController.getServers().find((server) => server.windowId === instanceId || server.instance === instanceId);
if (!interopServer) {
interopServer = await this.waitForServer(instanceId);
}
const method = interopServer.getMethods?.().find((registeredMethod) => registeredMethod.name === methodName);
if (!method) {
await this.waitForMethod(methodName, instanceId);
}
const result = await this.glueController.invokeMethod<any>(methodName, context, { instance: this.instanceIdToInteropInstance(instanceId) });
return result.returned;
}
private async raiseIntent(intentRequest: Glue42Web.Intents.IntentRequest, commandId: string): Promise<Glue42Web.Intents.IntentResult> {
this.logger?.trace(`[${commandId}] handling raiseIntent command`);
const intentName = intentRequest.intent;
const intentDef = await this.getIntent(intentName, commandId);
if (!intentDef) {
throw new Error(`Intent ${intentName} not found!`);
}
const isDynamicIntent = !intentDef.handlers.some((intentDefHandler) => intentDefHandler.type === "app");
// Default to "reuse" in the case of a dynamic intent and to "startNew" if target isn't provided.
const target = intentRequest.target || (isDynamicIntent ? "reuse" : "startNew");
// The handler that will execute the intent.
let handler: Glue42Web.Intents.IntentHandler | undefined;
const anAppHandler = intentDef.handlers.find((intentHandler) => intentHandler.type === "app");
if (target === "startNew") {
handler = anAppHandler;
} else if (target === "reuse") {
const anInstanceHandler = intentDef.handlers.find((intentHandler) => intentHandler.type === "instance");
handler = anInstanceHandler || anAppHandler;
} else if (target.instance) {
handler = intentDef.handlers.find((intentHandler) => intentHandler.type === "instance" && intentHandler.instanceId === target.instance);
} else if (target.app) {
handler = intentDef.handlers.find((intentHandler) => intentHandler.type === "app" && intentHandler.applicationName === target.app);
} else {
throw new Error(`Invalid intent target: ${JSON.stringify(target)}`);
}
if (!handler) {
throw new Error(`Can not raise intent for request ${JSON.stringify(intentRequest)} - can not find intent handler!`);
}
handler.instanceId;
if (handler.type === "app") {
handler.instanceId = await this.startApp({ name: handler.applicationName, ...intentRequest.options }, commandId);
}
if (!handler.instanceId) {
throw new Error(`Can not raise intent for request ${JSON.stringify(intentRequest)} - handler is missing instanceId!`);
}
const result = await this.raiseIntentToInstance(handler.instanceId, intentName, intentRequest.context);
this.logger?.trace(`[${commandId}] raiseIntent command completed`);
return {
request: intentRequest,
handler,
result
};
}
} | the_stack |
import {
Alternative,
Backreference,
CapturingGroup,
CharacterClass,
CharacterClassElement,
CharacterClassRange,
Flags,
Group,
RegExpLiteral,
LookaroundAssertion,
Pattern,
Quantifier,
} from "./ast"
import { EcmaVersion } from "./ecma-versions"
import { HyphenMinus } from "./unicode"
import { RegExpValidator } from "./validator"
type AppendableNode =
| Pattern
| Alternative
| Group
| CapturingGroup
| CharacterClass
| LookaroundAssertion
const DummyPattern: Pattern = {} as any
const DummyFlags: Flags = {} as any
const DummyCapturingGroup: CapturingGroup = {} as any
class RegExpParserState {
public readonly strict: boolean
public readonly ecmaVersion: EcmaVersion
private _node: AppendableNode = DummyPattern
private _flags: Flags = DummyFlags
private _backreferences: Backreference[] = []
private _capturingGroups: CapturingGroup[] = []
public source = ""
public constructor(options?: RegExpParser.Options) {
this.strict = Boolean(options && options.strict)
this.ecmaVersion = (options && options.ecmaVersion) || 2022
}
public get pattern(): Pattern {
if (this._node.type !== "Pattern") {
throw new Error("UnknownError")
}
return this._node
}
public get flags(): Flags {
if (this._flags.type !== "Flags") {
throw new Error("UnknownError")
}
return this._flags
}
public onFlags(
start: number,
end: number,
global: boolean,
ignoreCase: boolean,
multiline: boolean,
unicode: boolean,
sticky: boolean,
dotAll: boolean,
hasIndices: boolean,
): void {
this._flags = {
type: "Flags",
parent: null,
start,
end,
raw: this.source.slice(start, end),
global,
ignoreCase,
multiline,
unicode,
sticky,
dotAll,
hasIndices,
}
}
public onPatternEnter(start: number): void {
this._node = {
type: "Pattern",
parent: null,
start,
end: start,
raw: "",
alternatives: [],
}
this._backreferences.length = 0
this._capturingGroups.length = 0
}
public onPatternLeave(start: number, end: number): void {
this._node.end = end
this._node.raw = this.source.slice(start, end)
for (const reference of this._backreferences) {
const ref = reference.ref
const group =
typeof ref === "number"
? this._capturingGroups[ref - 1]
: this._capturingGroups.find(g => g.name === ref)!
reference.resolved = group
group.references.push(reference)
}
}
public onAlternativeEnter(start: number): void {
const parent = this._node
if (
parent.type !== "Assertion" &&
parent.type !== "CapturingGroup" &&
parent.type !== "Group" &&
parent.type !== "Pattern"
) {
throw new Error("UnknownError")
}
this._node = {
type: "Alternative",
parent,
start,
end: start,
raw: "",
elements: [],
}
parent.alternatives.push(this._node)
}
public onAlternativeLeave(start: number, end: number): void {
const node = this._node
if (node.type !== "Alternative") {
throw new Error("UnknownError")
}
node.end = end
node.raw = this.source.slice(start, end)
this._node = node.parent
}
public onGroupEnter(start: number): void {
const parent = this._node
if (parent.type !== "Alternative") {
throw new Error("UnknownError")
}
this._node = {
type: "Group",
parent,
start,
end: start,
raw: "",
alternatives: [],
}
parent.elements.push(this._node)
}
public onGroupLeave(start: number, end: number): void {
const node = this._node
if (node.type !== "Group" || node.parent.type !== "Alternative") {
throw new Error("UnknownError")
}
node.end = end
node.raw = this.source.slice(start, end)
this._node = node.parent
}
public onCapturingGroupEnter(start: number, name: string | null): void {
const parent = this._node
if (parent.type !== "Alternative") {
throw new Error("UnknownError")
}
this._node = {
type: "CapturingGroup",
parent,
start,
end: start,
raw: "",
name,
alternatives: [],
references: [],
}
parent.elements.push(this._node)
this._capturingGroups.push(this._node)
}
public onCapturingGroupLeave(start: number, end: number): void {
const node = this._node
if (
node.type !== "CapturingGroup" ||
node.parent.type !== "Alternative"
) {
throw new Error("UnknownError")
}
node.end = end
node.raw = this.source.slice(start, end)
this._node = node.parent
}
public onQuantifier(
start: number,
end: number,
min: number,
max: number,
greedy: boolean,
): void {
const parent = this._node
if (parent.type !== "Alternative") {
throw new Error("UnknownError")
}
// Replace the last element.
const element = parent.elements.pop()
if (
element == null ||
element.type === "Quantifier" ||
(element.type === "Assertion" && element.kind !== "lookahead")
) {
throw new Error("UnknownError")
}
const node: Quantifier = {
type: "Quantifier",
parent,
start: element.start,
end,
raw: this.source.slice(element.start, end),
min,
max,
greedy,
element,
}
parent.elements.push(node)
element.parent = node
}
public onLookaroundAssertionEnter(
start: number,
kind: "lookahead" | "lookbehind",
negate: boolean,
): void {
const parent = this._node
if (parent.type !== "Alternative") {
throw new Error("UnknownError")
}
const node: LookaroundAssertion = (this._node = {
type: "Assertion",
parent,
start,
end: start,
raw: "",
kind,
negate,
alternatives: [],
})
parent.elements.push(node)
}
public onLookaroundAssertionLeave(start: number, end: number): void {
const node = this._node
if (node.type !== "Assertion" || node.parent.type !== "Alternative") {
throw new Error("UnknownError")
}
node.end = end
node.raw = this.source.slice(start, end)
this._node = node.parent
}
public onEdgeAssertion(
start: number,
end: number,
kind: "start" | "end",
): void {
const parent = this._node
if (parent.type !== "Alternative") {
throw new Error("UnknownError")
}
parent.elements.push({
type: "Assertion",
parent,
start,
end,
raw: this.source.slice(start, end),
kind,
})
}
public onWordBoundaryAssertion(
start: number,
end: number,
kind: "word",
negate: boolean,
): void {
const parent = this._node
if (parent.type !== "Alternative") {
throw new Error("UnknownError")
}
parent.elements.push({
type: "Assertion",
parent,
start,
end,
raw: this.source.slice(start, end),
kind,
negate,
})
}
public onAnyCharacterSet(start: number, end: number, kind: "any"): void {
const parent = this._node
if (parent.type !== "Alternative") {
throw new Error("UnknownError")
}
parent.elements.push({
type: "CharacterSet",
parent,
start,
end,
raw: this.source.slice(start, end),
kind,
})
}
public onEscapeCharacterSet(
start: number,
end: number,
kind: "digit" | "space" | "word",
negate: boolean,
): void {
const parent = this._node
if (parent.type !== "Alternative" && parent.type !== "CharacterClass") {
throw new Error("UnknownError")
}
;(parent.elements as CharacterClassElement[]).push({
type: "CharacterSet",
parent,
start,
end,
raw: this.source.slice(start, end),
kind,
negate,
})
}
public onUnicodePropertyCharacterSet(
start: number,
end: number,
kind: "property",
key: string,
value: string | null,
negate: boolean,
): void {
const parent = this._node
if (parent.type !== "Alternative" && parent.type !== "CharacterClass") {
throw new Error("UnknownError")
}
;(parent.elements as CharacterClassElement[]).push({
type: "CharacterSet",
parent,
start,
end,
raw: this.source.slice(start, end),
kind,
key,
value,
negate,
})
}
public onCharacter(start: number, end: number, value: number): void {
const parent = this._node
if (parent.type !== "Alternative" && parent.type !== "CharacterClass") {
throw new Error("UnknownError")
}
;(parent.elements as CharacterClassElement[]).push({
type: "Character",
parent,
start,
end,
raw: this.source.slice(start, end),
value,
})
}
public onBackreference(
start: number,
end: number,
ref: number | string,
): void {
const parent = this._node
if (parent.type !== "Alternative") {
throw new Error("UnknownError")
}
const node: Backreference = {
type: "Backreference",
parent,
start,
end,
raw: this.source.slice(start, end),
ref,
resolved: DummyCapturingGroup,
}
parent.elements.push(node)
this._backreferences.push(node)
}
public onCharacterClassEnter(start: number, negate: boolean): void {
const parent = this._node
if (parent.type !== "Alternative") {
throw new Error("UnknownError")
}
this._node = {
type: "CharacterClass",
parent,
start,
end: start,
raw: "",
negate,
elements: [],
}
parent.elements.push(this._node)
}
public onCharacterClassLeave(start: number, end: number): void {
const node = this._node
if (
node.type !== "CharacterClass" ||
node.parent.type !== "Alternative"
) {
throw new Error("UnknownError")
}
node.end = end
node.raw = this.source.slice(start, end)
this._node = node.parent
}
public onCharacterClassRange(start: number, end: number): void {
const parent = this._node
if (parent.type !== "CharacterClass") {
throw new Error("UnknownError")
}
// Replace the last three elements.
const elements = parent.elements
const max = elements.pop()
const hyphen = elements.pop()
const min = elements.pop()
if (
!min ||
!max ||
!hyphen ||
min.type !== "Character" ||
max.type !== "Character" ||
hyphen.type !== "Character" ||
hyphen.value !== HyphenMinus
) {
throw new Error("UnknownError")
}
const node: CharacterClassRange = {
type: "CharacterClassRange",
parent,
start,
end,
raw: this.source.slice(start, end),
min,
max,
}
min.parent = node
max.parent = node
elements.push(node)
}
}
export namespace RegExpParser {
/**
* The options for RegExpParser construction.
*/
export interface Options {
/**
* The flag to disable Annex B syntax. Default is `false`.
*/
strict?: boolean
/**
* ECMAScript version. Default is `2022`.
* - `2015` added `u` and `y` flags.
* - `2018` added `s` flag, Named Capturing Group, Lookbehind Assertion,
* and Unicode Property Escape.
* - `2019`, `2020`, and `2021` added more valid Unicode Property Escapes.
* - `2022` added `d` flag.
*/
ecmaVersion?: EcmaVersion
}
}
export class RegExpParser {
private _state: RegExpParserState
private _validator: RegExpValidator
/**
* Initialize this parser.
* @param options The options of parser.
*/
public constructor(options?: RegExpParser.Options) {
this._state = new RegExpParserState(options)
this._validator = new RegExpValidator(this._state)
}
/**
* Parse a regular expression literal. E.g. "/abc/g"
* @param source The source code to parse.
* @param start The start index in the source code.
* @param end The end index in the source code.
* @returns The AST of the given regular expression.
*/
public parseLiteral(
source: string,
start = 0,
end: number = source.length,
): RegExpLiteral {
this._state.source = source
this._validator.validateLiteral(source, start, end)
const pattern = this._state.pattern
const flags = this._state.flags
const literal: RegExpLiteral = {
type: "RegExpLiteral",
parent: null,
start,
end,
raw: source,
pattern,
flags,
}
pattern.parent = literal
flags.parent = literal
return literal
}
/**
* Parse a regular expression flags. E.g. "gim"
* @param source The source code to parse.
* @param start The start index in the source code.
* @param end The end index in the source code.
* @returns The AST of the given flags.
*/
public parseFlags(
source: string,
start = 0,
end: number = source.length,
): Flags {
this._state.source = source
this._validator.validateFlags(source, start, end)
return this._state.flags
}
/**
* Parse a regular expression pattern. E.g. "abc"
* @param source The source code to parse.
* @param start The start index in the source code.
* @param end The end index in the source code.
* @param uFlag The flag to set unicode mode.
* @returns The AST of the given pattern.
*/
public parsePattern(
source: string,
start = 0,
end: number = source.length,
uFlag = false,
): Pattern {
this._state.source = source
this._validator.validatePattern(source, start, end, uFlag)
return this._state.pattern
}
} | the_stack |
import { Yok } from "../../../lib/common/yok";
import { assert } from "chai";
import { NodeModulesDependenciesBuilder } from "../../../lib/tools/node-modules/node-modules-dependencies-builder";
import * as path from "path";
import * as _ from "lodash";
import * as constants from "../../../lib/constants";
import { IDependencyData } from "../../../lib/declarations";
import { INodeModulesDependenciesBuilder } from "../../../lib/definitions/platform";
import { IInjector } from "../../../lib/common/definitions/yok";
import { IFileSystem, IStringDictionary, } from "../../../lib/common/declarations";
import * as temp from 'temp'
import * as fs from 'fs';
import { FileSystem } from "../../../lib/common/file-system";
interface IDependencyInfo {
name: string;
version: string;
depth: number;
dependencies?: IDependencyInfo[];
nativescript?: any;
isDevDependency?: boolean;
}
// TODO: Add integration tests.
// The tests assumes npm 3 or later is used, so all dependencies (and their dependencies) will be installed at the root node_modules
describe("nodeModulesDependenciesBuilder", () => {
let pathToProject: string = 'test-project';
beforeEach(() => {
// we use realpath because os.tmpdir points to a symlink on macos
// and require.resolve resolves the symlink causing test failures
pathToProject = fs.realpathSync(
temp.mkdirSync("test-project")
);
})
const getTestInjector = (): IInjector => {
const testInjector = new Yok();
testInjector.register("fs", FileSystem);
return testInjector;
};
describe("getProductionDependencies", () => {
describe("returns empty array", () => {
const validateResultIsEmpty = async (resultOfReadJson: any) => {
const testInjector = getTestInjector();
const fs = testInjector.resolve<IFileSystem>("fs");
fs.readJson = (filename: string, encoding?: string): any => {
return resultOfReadJson;
};
const nodeModulesDependenciesBuilder = testInjector.resolve<INodeModulesDependenciesBuilder>(NodeModulesDependenciesBuilder);
const result = await nodeModulesDependenciesBuilder.getProductionDependencies(
pathToProject
);
assert.deepStrictEqual(result, []);
};
it("when package.json does not have any data", async () => {
await validateResultIsEmpty(null);
});
it("when package.json does not have dependencies section", async () => {
await validateResultIsEmpty({
name: "some name",
devDependencies: { a: "1.0.0" },
});
});
});
describe("returns correct dependencies", () => {
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Helper functions for easier writing of consecutive tests in the suite. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
const getPathToDependencyInNodeModules = (
dependencyName: string,
parentDir?: string
): string => {
return path.join(
parentDir ?? pathToProject,
constants.NODE_MODULES_FOLDER_NAME,
dependencyName
);
};
const getNodeModuleInfoForExpectedDependency = (
dir: string,
depth: number,
nativescript?: any,
dependencies?: string[],
name?: string,
version?: string
): IDependencyData => {
const packageName = name ?? path.basename(dir);
const result: IDependencyData = {
name: packageName,
directory: getPathToDependencyInNodeModules(dir),
depth,
dependencies: dependencies || [],
version: version,
};
if (nativescript) {
result.nativescript = nativescript;
}
return result;
};
const getPathToPackageJsonOfDependency = (
dependencyName: string,
parentDir?: string
): string => {
return path.join(
getPathToDependencyInNodeModules(dependencyName, parentDir),
constants.PACKAGE_JSON_FILE_NAME
);
};
const getDependenciesObjectFromDependencyInfo = (
depInfos: IDependencyInfo[],
nativescript: any,
version: string
): {
dependencies: IStringDictionary;
nativescript?: any;
devDependencies: IStringDictionary;
version: string;
} => {
const dependencies: any = {};
const devDependencies: any = {};
_.each(depInfos, (innerDependency) => {
if (innerDependency.isDevDependency) {
devDependencies[innerDependency.name] = innerDependency.version;
} else {
dependencies[innerDependency.name] = innerDependency.version;
}
});
const result: any = {
dependencies,
devDependencies,
};
if (nativescript) {
result.nativescript = nativescript;
}
if (version) {
result.version = version;
}
return result;
};
const getDependenciesObject = (
filename: string,
deps: IDependencyInfo[],
parentDir: string
): {
dependencies: IStringDictionary;
nativescript?: any;
devDependencies: IStringDictionary;
} => {
let result: {
dependencies: IStringDictionary;
nativescript?: any;
devDependencies: IStringDictionary;
} = null;
for (const dependencyInfo of deps) {
const pathToPackageJson = getPathToPackageJsonOfDependency(
dependencyInfo.name,
parentDir
);
if (filename === pathToPackageJson) {
return getDependenciesObjectFromDependencyInfo(
dependencyInfo.dependencies,
dependencyInfo.nativescript,
dependencyInfo.version
);
}
if (dependencyInfo.dependencies) {
result = getDependenciesObject(
filename,
dependencyInfo.dependencies,
path.join(
parentDir,
constants.NODE_MODULES_FOLDER_NAME,
dependencyInfo.name
)
);
if (result) {
break;
}
}
}
return result;
};
const generatePackageJsonData = (
dep: IDependencyInfo
) => {
const data: any = {
name: dep.name,
version: dep.version,
dependencies: dep.dependencies?.reduce((deps, dep) => {
if (!dep.isDevDependency) {
deps[dep.name] = dep.version
}
return deps;
}, {} as { [name: string]: string }),
devDependencies: dep.dependencies?.reduce((deps, dep) => {
if (dep.isDevDependency) {
deps[dep.name] = dep.version
}
return deps;
}, {} as { [name: string]: string })
}
if(dep.nativescript) {
data.nativescript = dep.nativescript;
}
return data;
}
const generateNodeModules = (
dep: IDependencyInfo,
rootPath: string) => {
// ensure dep directory
fs.mkdirSync(rootPath, { recursive: true });
// generate package.json contents
const packageJsonData = generatePackageJsonData(dep);
// write package.json
fs.writeFileSync(
path.join(rootPath, 'package.json'),
JSON.stringify(packageJsonData)
)
// recurse into sub-dependencies if any
if (dep.dependencies) {
for (const subDep of dep.dependencies) {
generateNodeModules(
subDep,
path.join(rootPath, 'node_modules', subDep.name)
);
}
}
}
const generateTest = (
rootDeps: IDependencyInfo[]
): INodeModulesDependenciesBuilder => {
const testInjector = getTestInjector();
const nodeModulesDependenciesBuilder = testInjector.resolve<INodeModulesDependenciesBuilder>(NodeModulesDependenciesBuilder);
generateNodeModules(
{
name: 'test-project',
version: '1.0.0',
depth: 0,
dependencies: rootDeps
},
pathToProject
);
return nodeModulesDependenciesBuilder;
};
const generateDependency = (
name: string,
version: string,
depth: number,
dependencies: IDependencyInfo[],
nativescript?: any,
opts?: { isDevDependency: boolean }
): IDependencyInfo => {
return {
name,
version,
depth,
dependencies,
nativescript,
isDevDependency: !!(opts && opts.isDevDependency),
};
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* END of helper functions for easier writing of consecutive tests in the suite. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
const firstPackage = "firstPackage";
const secondPackage = "secondPackage";
const thirdPackage = "thirdPackage";
it("when there are both dependencies and devDependencies installed", async () => {
// The test validates the following dependency tree, when npm 3+ is used.
// <project dir>
// ├── firstPackage@1.0.0
// ├── secondPackage@1.1.0
// └── thirdPackage@1.2.0 // this is devDependency
const rootDeps: IDependencyInfo[] = [
generateDependency(firstPackage, "1.0.0", 0, null),
generateDependency(secondPackage, "1.1.0", 0, null),
generateDependency(thirdPackage, "1.2.0", 0, null, null, {
isDevDependency: true,
}),
];
const nodeModulesDependenciesBuilder = generateTest(rootDeps);
const actualResult = await nodeModulesDependenciesBuilder.getProductionDependencies(
pathToProject
);
const expectedResult: IDependencyData[] = [
getNodeModuleInfoForExpectedDependency(
firstPackage,
0,
null,
null,
null,
"1.0.0"
),
getNodeModuleInfoForExpectedDependency(
secondPackage,
0,
null,
null,
null,
"1.1.0"
),
];
assert.deepStrictEqual(actualResult, expectedResult);
});
it("when there are both dependencies and devDependencies installed, does not handle dependencies of devDependencies", async () => {
// The test validates the following dependency tree, when npm 3+ is used.
// <project dir>
// ├─┬ firstPackage@1.0.0 // this is devDependency
// │ └── secondPackage@1.2.0
// └── secondPackage@1.1.0
const rootDeps: IDependencyInfo[] = [
generateDependency(
firstPackage,
"1.0.0",
0,
[generateDependency(secondPackage, "1.2.0", 1, null)],
null,
{ isDevDependency: true }
),
generateDependency(secondPackage, "1.1.0", 0, null),
];
const expectedResult: IDependencyData[] = [
getNodeModuleInfoForExpectedDependency(
secondPackage,
0,
null,
null,
null,
"1.1.0"
),
];
const nodeModulesDependenciesBuilder = generateTest(rootDeps);
const actualResult = await nodeModulesDependenciesBuilder.getProductionDependencies(
pathToProject
);
assert.deepStrictEqual(actualResult, expectedResult);
});
it("when there are scoped dependencies", async () => {
// The test validates the following dependency tree, when npm 3+ is used.
// <project dir>
// ├─┬ @scope/firstPackage@1.0.0
// │ └── secondPackage@1.2.0
// └── secondPackage@1.1.0
const scopedPackageName = `@scope/${firstPackage}`;
const rootDeps: IDependencyInfo[] = [
generateDependency(scopedPackageName, "1.0.0", 0, [
generateDependency(secondPackage, "1.2.0", 1, null),
]),
generateDependency(secondPackage, "1.1.0", 0, null),
];
const expectedResult: IDependencyData[] = [
getNodeModuleInfoForExpectedDependency(
scopedPackageName,
0,
null,
[secondPackage],
scopedPackageName,
"1.0.0"
),
getNodeModuleInfoForExpectedDependency(
secondPackage,
0,
null,
null,
null,
"1.1.0"
),
getNodeModuleInfoForExpectedDependency(
path.join(
scopedPackageName,
constants.NODE_MODULES_FOLDER_NAME,
secondPackage
),
1,
null,
null,
null,
"1.2.0"
),
];
const nodeModulesDependenciesBuilder = generateTest(rootDeps);
const actualResult = await nodeModulesDependenciesBuilder.getProductionDependencies(
pathToProject
);
assert.deepStrictEqual(actualResult, expectedResult);
});
it("when there are scoped dependencies as dependency of other non-scoped dependency", async () => {
// The test validates the following dependency tree, when npm 3+ is used.
// <project dir>
// ├─┬ firstPackage@1.0.0
// │ └── @scope/secondPackage@1.2.0
// └── thirdPackage@1.1.0
const scopedPackageName = `@scope/${secondPackage}`;
const rootDeps: IDependencyInfo[] = [
generateDependency(firstPackage, "1.0.0", 0, [
generateDependency(scopedPackageName, "1.2.0", 1, null),
]),
generateDependency(thirdPackage, "1.1.0", 0, null),
];
const expectedResult: IDependencyData[] = [
getNodeModuleInfoForExpectedDependency(
firstPackage,
0,
null,
[scopedPackageName],
null,
"1.0.0"
),
getNodeModuleInfoForExpectedDependency(
thirdPackage,
0,
null,
null,
null,
"1.1.0"
),
getNodeModuleInfoForExpectedDependency(
path.join(
firstPackage,
constants.NODE_MODULES_FOLDER_NAME,
scopedPackageName
),
1,
null,
null,
scopedPackageName,
"1.2.0"
),
];
const nodeModulesDependenciesBuilder = generateTest(rootDeps);
const actualResult = await nodeModulesDependenciesBuilder.getProductionDependencies(
pathToProject
);
assert.deepStrictEqual(actualResult, expectedResult);
});
it("when all dependencies are installed at the root level of the project", async () => {
// The test validates the following dependency tree, when npm 3+ is used.
// <project dir>
// ├── firstPackage@1.0.0
// ├── secondPackage@1.1.0
// └── thirdPackage@1.2.0
const rootDeps: IDependencyInfo[] = [
generateDependency(firstPackage, "1.0.0", 0, null),
generateDependency(secondPackage, "1.1.0", 0, null),
generateDependency(thirdPackage, "1.2.0", 0, null),
];
const nodeModulesDependenciesBuilder = generateTest(rootDeps);
const actualResult = await nodeModulesDependenciesBuilder.getProductionDependencies(
pathToProject
);
const expectedResult: IDependencyData[] = [
getNodeModuleInfoForExpectedDependency(
firstPackage,
0,
null,
null,
null,
"1.0.0"
),
getNodeModuleInfoForExpectedDependency(
secondPackage,
0,
null,
null,
null,
"1.1.0"
),
getNodeModuleInfoForExpectedDependency(
thirdPackage,
0,
null,
null,
null,
"1.2.0"
),
];
assert.deepStrictEqual(actualResult, expectedResult);
});
it("when the project has a dependency to a package and one of the other packages has dependency to other version of this package", async () => {
// The test validates the following dependency tree, when npm 3+ is used.
// <project dir>
// ├─┬ firstPackage@1.0.0
// │ └── secondPackage@1.2.0
// └── secondPackage@1.1.0
const rootDeps: IDependencyInfo[] = [
generateDependency(firstPackage, "1.0.0", 0, [
generateDependency(secondPackage, "1.2.0", 1, null),
]),
generateDependency(secondPackage, "1.1.0", 0, null),
];
const expectedResult: IDependencyData[] = [
getNodeModuleInfoForExpectedDependency(
firstPackage,
0,
null,
[secondPackage],
null,
"1.0.0"
),
getNodeModuleInfoForExpectedDependency(
secondPackage,
0,
null,
null,
null,
"1.1.0"
),
getNodeModuleInfoForExpectedDependency(
path.join(
firstPackage,
constants.NODE_MODULES_FOLDER_NAME,
secondPackage
),
1,
null,
null,
null,
"1.2.0"
),
];
const nodeModulesDependenciesBuilder = generateTest(rootDeps);
const actualResult = await nodeModulesDependenciesBuilder.getProductionDependencies(
pathToProject
);
assert.deepStrictEqual(actualResult, expectedResult);
});
it("when several package depend on different versions of other packages", async () => {
// The test validates the following dependency tree, when npm 3+ is used.
// <project dir>
// ├─┬ firstPackage@1.0.0
// │ ├─┬ secondPackage@1.1.0
// │ │ └── thirdPackage@1.2.0
// │ └── thirdPackage@1.1.0
// ├── secondPackage@1.0.0
// └── thirdPackage@1.0.0
const rootDeps: IDependencyInfo[] = [
generateDependency(firstPackage, "1.0.0", 0, [
generateDependency(secondPackage, "1.1.0", 1, [
generateDependency(thirdPackage, "1.2.0", 2, null),
]),
generateDependency(thirdPackage, "1.1.0", 1, null),
]),
generateDependency(secondPackage, "1.0.0", 0, null),
generateDependency(thirdPackage, "1.0.0", 0, null),
];
const pathToSecondPackageInsideFirstPackage = path.join(
firstPackage,
constants.NODE_MODULES_FOLDER_NAME,
secondPackage
);
const expectedResult: IDependencyData[] = [
getNodeModuleInfoForExpectedDependency(
firstPackage,
0,
null,
[secondPackage, thirdPackage],
null,
"1.0.0"
),
getNodeModuleInfoForExpectedDependency(
secondPackage,
0,
null,
null,
null,
"1.0.0"
),
getNodeModuleInfoForExpectedDependency(
thirdPackage,
0,
null,
null,
null,
"1.0.0"
),
getNodeModuleInfoForExpectedDependency(
pathToSecondPackageInsideFirstPackage,
1,
null,
[thirdPackage],
null,
"1.1.0"
),
getNodeModuleInfoForExpectedDependency(
path.join(
firstPackage,
constants.NODE_MODULES_FOLDER_NAME,
thirdPackage
),
1,
null,
null,
null,
"1.1.0"
),
getNodeModuleInfoForExpectedDependency(
path.join(
pathToSecondPackageInsideFirstPackage,
constants.NODE_MODULES_FOLDER_NAME,
thirdPackage
),
2,
null,
null,
null,
"1.2.0"
),
];
const nodeModulesDependenciesBuilder = generateTest(rootDeps);
const actualResult = await nodeModulesDependenciesBuilder.getProductionDependencies(
pathToProject
);
assert.deepStrictEqual(actualResult, expectedResult);
});
it("when the installed packages have nativescript data in their package.json", async () => {
// The test validates the following dependency tree, when npm 3+ is used.
// <project dir>
// ├── firstPackage@1.0.0
// ├── secondPackage@1.1.0
// └── thirdPackage@1.2.0
const getNativeScriptDataForPlugin = (pluginName: string): any => {
return {
platforms: {
"tns-android": "x.x.x",
"tns-ios": "x.x.x",
},
customPropertyUsedForThisTestOnly: pluginName,
};
};
const rootDeps: IDependencyInfo[] = [
generateDependency(
firstPackage,
"1.0.0",
0,
null,
getNativeScriptDataForPlugin(firstPackage)
),
generateDependency(
secondPackage,
"1.1.0",
0,
null,
getNativeScriptDataForPlugin(secondPackage)
),
generateDependency(
thirdPackage,
"1.2.0",
0,
null,
getNativeScriptDataForPlugin(thirdPackage)
),
];
const nodeModulesDependenciesBuilder = generateTest(rootDeps);
const actualResult = await nodeModulesDependenciesBuilder.getProductionDependencies(
pathToProject
);
const expectedResult: IDependencyData[] = [
getNodeModuleInfoForExpectedDependency(
firstPackage,
0,
getNativeScriptDataForPlugin(firstPackage),
null,
null,
"1.0.0"
),
getNodeModuleInfoForExpectedDependency(
secondPackage,
0,
getNativeScriptDataForPlugin(secondPackage),
null,
null,
"1.1.0"
),
getNodeModuleInfoForExpectedDependency(
thirdPackage,
0,
getNativeScriptDataForPlugin(thirdPackage),
null,
null,
"1.2.0"
),
];
assert.deepStrictEqual(actualResult, expectedResult);
});
it("ignoring dependencies", async () => {
// The test validates the following dependency tree, when npm 3+ is used.
// <project dir>
// ├── firstPackage@1.0.0
// ├── secondPackage@1.1.0
// └── thirdPackage@1.2.0
const rootDeps: IDependencyInfo[] = [
generateDependency(firstPackage, "1.0.0", 0, null),
generateDependency(secondPackage, "1.1.0", 0, null),
generateDependency(thirdPackage, "1.2.0", 0, null),
];
const nodeModulesDependenciesBuilder = generateTest(rootDeps);
const actualResult = await nodeModulesDependenciesBuilder.getProductionDependencies(
pathToProject, [firstPackage]
);
const expectedResult: IDependencyData[] = [
getNodeModuleInfoForExpectedDependency(
secondPackage,
0,
null,
null,
null,
"1.1.0"
),
getNodeModuleInfoForExpectedDependency(
thirdPackage,
0,
null,
null,
null,
"1.2.0"
),
];
assert.deepStrictEqual(actualResult, expectedResult);
});
});
})
;
})
; | the_stack |
import * as GLib from "@gi-types/glib";
import * as GModule from "@gi-types/gmodule";
import * as GObject from "@gi-types/gobject";
export const ALLOCATOR_SYSMEM: string;
export const BUFFER_COPY_ALL: BufferCopyFlags;
export const BUFFER_COPY_METADATA: BufferCopyFlags;
export const BUFFER_OFFSET_NONE: number;
export const CAN_INLINE: number;
export const CAPS_FEATURE_MEMORY_SYSTEM_MEMORY: string;
export const CLOCK_TIME_NONE: ClockTime;
export const DEBUG_BG_MASK: number;
export const DEBUG_FG_MASK: number;
export const DEBUG_FORMAT_MASK: number;
export const ELEMENT_FACTORY_KLASS_DECODER: string;
export const ELEMENT_FACTORY_KLASS_DECRYPTOR: string;
export const ELEMENT_FACTORY_KLASS_DEMUXER: string;
export const ELEMENT_FACTORY_KLASS_DEPAYLOADER: string;
export const ELEMENT_FACTORY_KLASS_ENCODER: string;
export const ELEMENT_FACTORY_KLASS_ENCRYPTOR: string;
export const ELEMENT_FACTORY_KLASS_FORMATTER: string;
export const ELEMENT_FACTORY_KLASS_HARDWARE: string;
export const ELEMENT_FACTORY_KLASS_MEDIA_AUDIO: string;
export const ELEMENT_FACTORY_KLASS_MEDIA_IMAGE: string;
export const ELEMENT_FACTORY_KLASS_MEDIA_METADATA: string;
export const ELEMENT_FACTORY_KLASS_MEDIA_SUBTITLE: string;
export const ELEMENT_FACTORY_KLASS_MEDIA_VIDEO: string;
export const ELEMENT_FACTORY_KLASS_MUXER: string;
export const ELEMENT_FACTORY_KLASS_PARSER: string;
export const ELEMENT_FACTORY_KLASS_PAYLOADER: string;
export const ELEMENT_FACTORY_KLASS_SINK: string;
export const ELEMENT_FACTORY_KLASS_SRC: string;
export const ELEMENT_FACTORY_TYPE_ANY: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_AUDIOVIDEO_SINKS: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_AUDIO_ENCODER: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_DECODABLE: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_DECODER: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_DECRYPTOR: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_DEMUXER: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_DEPAYLOADER: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_ENCODER: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_ENCRYPTOR: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_FORMATTER: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_HARDWARE: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_MAX_ELEMENTS: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_MEDIA_ANY: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_MEDIA_AUDIO: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_MEDIA_IMAGE: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_MEDIA_METADATA: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_MEDIA_SUBTITLE: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_MEDIA_VIDEO: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_MUXER: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_PARSER: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_PAYLOADER: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_SINK: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_SRC: ElementFactoryListType;
export const ELEMENT_FACTORY_TYPE_VIDEO_ENCODER: ElementFactoryListType;
export const ELEMENT_METADATA_AUTHOR: string;
export const ELEMENT_METADATA_DESCRIPTION: string;
export const ELEMENT_METADATA_DOC_URI: string;
export const ELEMENT_METADATA_ICON_NAME: string;
export const ELEMENT_METADATA_KLASS: string;
export const ELEMENT_METADATA_LONGNAME: string;
export const EVENT_NUM_SHIFT: number;
export const EVENT_TYPE_BOTH: EventTypeFlags;
export const FLAG_SET_MASK_EXACT: number;
export const FORMAT_PERCENT_MAX: number;
export const FORMAT_PERCENT_SCALE: number;
export const GROUP_ID_INVALID: number;
export const LICENSE_UNKNOWN: string;
export const LOCK_FLAG_READWRITE: LockFlags;
export const MAP_READWRITE: MapFlags;
export const META_TAG_MEMORY_STR: string;
export const MSECOND: ClockTimeDiff;
export const NSECOND: ClockTimeDiff;
export const PARAM_CONDITIONALLY_AVAILABLE: number;
export const PARAM_CONTROLLABLE: number;
export const PARAM_DOC_SHOW_DEFAULT: number;
export const PARAM_MUTABLE_PAUSED: number;
export const PARAM_MUTABLE_PLAYING: number;
export const PARAM_MUTABLE_READY: number;
export const PARAM_USER_SHIFT: number;
export const PROTECTION_SYSTEM_ID_CAPS_FIELD: string;
export const PROTECTION_UNSPECIFIED_SYSTEM_ID: string;
export const QUERY_NUM_SHIFT: number;
export const QUERY_TYPE_BOTH: QueryTypeFlags;
export const SECOND: ClockTimeDiff;
export const SEGMENT_INSTANT_FLAGS: number;
export const SEQNUM_INVALID: number;
export const TAG_ALBUM: string;
export const TAG_ALBUM_ARTIST: string;
export const TAG_ALBUM_ARTIST_SORTNAME: string;
export const TAG_ALBUM_GAIN: string;
export const TAG_ALBUM_PEAK: string;
export const TAG_ALBUM_SORTNAME: string;
export const TAG_ALBUM_VOLUME_COUNT: string;
export const TAG_ALBUM_VOLUME_NUMBER: string;
export const TAG_APPLICATION_DATA: string;
export const TAG_APPLICATION_NAME: string;
export const TAG_ARTIST: string;
export const TAG_ARTIST_SORTNAME: string;
export const TAG_ATTACHMENT: string;
export const TAG_AUDIO_CODEC: string;
export const TAG_BEATS_PER_MINUTE: string;
export const TAG_BITRATE: string;
export const TAG_CODEC: string;
export const TAG_COMMENT: string;
export const TAG_COMPOSER: string;
export const TAG_COMPOSER_SORTNAME: string;
export const TAG_CONDUCTOR: string;
export const TAG_CONTACT: string;
export const TAG_CONTAINER_FORMAT: string;
export const TAG_COPYRIGHT: string;
export const TAG_COPYRIGHT_URI: string;
export const TAG_DATE: string;
export const TAG_DATE_TIME: string;
export const TAG_DESCRIPTION: string;
export const TAG_DEVICE_MANUFACTURER: string;
export const TAG_DEVICE_MODEL: string;
export const TAG_DURATION: string;
export const TAG_ENCODED_BY: string;
export const TAG_ENCODER: string;
export const TAG_ENCODER_VERSION: string;
export const TAG_EXTENDED_COMMENT: string;
export const TAG_GENRE: string;
export const TAG_GEO_LOCATION_CAPTURE_DIRECTION: string;
export const TAG_GEO_LOCATION_CITY: string;
export const TAG_GEO_LOCATION_COUNTRY: string;
export const TAG_GEO_LOCATION_ELEVATION: string;
export const TAG_GEO_LOCATION_HORIZONTAL_ERROR: string;
export const TAG_GEO_LOCATION_LATITUDE: string;
export const TAG_GEO_LOCATION_LONGITUDE: string;
export const TAG_GEO_LOCATION_MOVEMENT_DIRECTION: string;
export const TAG_GEO_LOCATION_MOVEMENT_SPEED: string;
export const TAG_GEO_LOCATION_NAME: string;
export const TAG_GEO_LOCATION_SUBLOCATION: string;
export const TAG_GROUPING: string;
export const TAG_HOMEPAGE: string;
export const TAG_IMAGE: string;
export const TAG_IMAGE_ORIENTATION: string;
export const TAG_INTERPRETED_BY: string;
export const TAG_ISRC: string;
export const TAG_KEYWORDS: string;
export const TAG_LANGUAGE_CODE: string;
export const TAG_LANGUAGE_NAME: string;
export const TAG_LICENSE: string;
export const TAG_LICENSE_URI: string;
export const TAG_LOCATION: string;
export const TAG_LYRICS: string;
export const TAG_MAXIMUM_BITRATE: string;
export const TAG_MIDI_BASE_NOTE: string;
export const TAG_MINIMUM_BITRATE: string;
export const TAG_NOMINAL_BITRATE: string;
export const TAG_ORGANIZATION: string;
export const TAG_PERFORMER: string;
export const TAG_PREVIEW_IMAGE: string;
export const TAG_PRIVATE_DATA: string;
export const TAG_PUBLISHER: string;
export const TAG_REFERENCE_LEVEL: string;
export const TAG_SERIAL: string;
export const TAG_SHOW_EPISODE_NUMBER: string;
export const TAG_SHOW_NAME: string;
export const TAG_SHOW_SEASON_NUMBER: string;
export const TAG_SHOW_SORTNAME: string;
export const TAG_SUBTITLE_CODEC: string;
export const TAG_TITLE: string;
export const TAG_TITLE_SORTNAME: string;
export const TAG_TRACK_COUNT: string;
export const TAG_TRACK_GAIN: string;
export const TAG_TRACK_NUMBER: string;
export const TAG_TRACK_PEAK: string;
export const TAG_USER_RATING: string;
export const TAG_VERSION: string;
export const TAG_VIDEO_CODEC: string;
export const TOC_REPEAT_COUNT_INFINITE: number;
export const URI_NO_PORT: number;
export const USECOND: ClockTimeDiff;
export const VALUE_EQUAL: number;
export const VALUE_GREATER_THAN: number;
export const VALUE_LESS_THAN: number;
export const VALUE_UNORDERED: number;
export const VERSION_MAJOR: number;
export const VERSION_MICRO: number;
export const VERSION_MINOR: number;
export const VERSION_NANO: number;
export function buffer_get_max_memory(): number;
export function caps_features_from_string(features: string): CapsFeatures | null;
export function caps_from_string(string: string): Caps | null;
export function core_error_quark(): GLib.Quark;
export function debug_add_log_function(func: LogFunction): void;
export function debug_add_ring_buffer_logger(max_size_per_thread: number, thread_timeout: number): void;
export function debug_bin_to_dot_data(bin: Bin, details: DebugGraphDetails): string;
export function debug_bin_to_dot_file(bin: Bin, details: DebugGraphDetails, file_name: string): void;
export function debug_bin_to_dot_file_with_ts(bin: Bin, details: DebugGraphDetails, file_name: string): void;
export function debug_construct_term_color(colorinfo: number): string;
export function debug_construct_win_color(colorinfo: number): number;
export function debug_get_all_categories(): DebugCategory[];
export function debug_get_color_mode(): DebugColorMode;
export function debug_get_default_threshold(): DebugLevel;
export function debug_get_stack_trace(flags: StackTraceFlags): string | null;
export function debug_is_active(): boolean;
export function debug_is_colored(): boolean;
export function debug_level_get_name(level: DebugLevel): string;
export function debug_log_default(
category: DebugCategory,
level: DebugLevel,
file: string,
_function: string,
line: number,
object: GObject.Object | null,
message: DebugMessage,
user_data?: any | null
): void;
export function debug_log_get_line(
category: DebugCategory,
level: DebugLevel,
file: string,
_function: string,
line: number,
object: GObject.Object | null,
message: DebugMessage
): string;
export function debug_print_stack_trace(): void;
export function debug_remove_log_function(func?: LogFunction | null): number;
export function debug_remove_log_function_by_data(data?: any | null): number;
export function debug_remove_ring_buffer_logger(): void;
export function debug_ring_buffer_logger_get_logs(): string[];
export function debug_set_active(active: boolean): void;
export function debug_set_color_mode(mode: DebugColorMode): void;
export function debug_set_color_mode_from_string(mode: string): void;
export function debug_set_colored(colored: boolean): void;
export function debug_set_default_threshold(level: DebugLevel): void;
export function debug_set_threshold_for_name(name: string, level: DebugLevel): void;
export function debug_set_threshold_from_string(list: string, reset: boolean): void;
export function debug_unset_threshold_for_name(name: string): void;
export function deinit(): void;
export function dynamic_type_register(plugin: Plugin, type: GObject.GType): boolean;
export function error_get_message(domain: GLib.Quark, code: number): string;
export function event_type_get_flags(type: EventType): EventTypeFlags;
export function event_type_get_name(type: EventType): string;
export function event_type_to_quark(type: EventType): GLib.Quark;
export function filename_to_uri(filename: string): string;
export function flow_get_name(ret: FlowReturn): string;
export function flow_to_quark(ret: FlowReturn): GLib.Quark;
export function format_get_by_nick(nick: string): Format;
export function format_get_details(format: Format): FormatDefinition | null;
export function format_get_name(format: Format): string | null;
export function format_iterate_definitions(): Iterator;
export function format_register(nick: string, description: string): Format;
export function format_to_quark(format: Format): GLib.Quark;
export function formats_contains(formats: Format[], format: Format): boolean;
export function get_main_executable_path(): string | null;
export function init(argv?: string[] | null): string[] | null;
export function init_check(argv?: string[] | null): [boolean, string[] | null];
export function is_caps_features(obj?: any | null): boolean;
export function is_initialized(): boolean;
export function library_error_quark(): GLib.Quark;
export function message_type_get_name(type: MessageType): string;
export function message_type_to_quark(type: MessageType): GLib.Quark;
export function meta_api_type_get_tags(api: GObject.GType): string[];
export function meta_api_type_has_tag(api: GObject.GType, tag: GLib.Quark): boolean;
export function meta_api_type_register(api: string, tags: string[]): GObject.GType;
export function meta_get_info(impl: string): MetaInfo | null;
export function meta_register(
api: GObject.GType,
impl: string,
size: number,
init_func: MetaInitFunction,
free_func: MetaFreeFunction,
transform_func: MetaTransformFunction
): MetaInfo | null;
export function mini_object_replace(
olddata?: MiniObject | null,
newdata?: MiniObject | null
): [boolean, MiniObject | null];
export function mini_object_take(olddata: MiniObject, newdata: MiniObject): [boolean, MiniObject];
export function pad_mode_get_name(mode: PadMode): string;
export function param_spec_array(
name: string,
nick: string,
blurb: string,
element_spec: GObject.ParamSpec,
flags: GObject.ParamFlags
): GObject.ParamSpec;
export function param_spec_fraction(
name: string,
nick: string,
blurb: string,
min_num: number,
min_denom: number,
max_num: number,
max_denom: number,
default_num: number,
default_denom: number,
flags: GObject.ParamFlags
): GObject.ParamSpec | null;
export function parent_buffer_meta_api_get_type(): GObject.GType;
export function parent_buffer_meta_get_info(): MetaInfo;
export function parse_bin_from_description(bin_description: string, ghost_unlinked_pads: boolean): Bin;
export function parse_bin_from_description_full(
bin_description: string,
ghost_unlinked_pads: boolean,
context: ParseContext | null,
flags: ParseFlags
): Element;
export function parse_error_quark(): GLib.Quark;
export function parse_launch(pipeline_description: string): Element;
export function parse_launch_full(
pipeline_description: string,
context: ParseContext | null,
flags: ParseFlags
): Element;
export function parse_launchv(argv: string[]): Element;
export function parse_launchv_full(argv: string[], context: ParseContext | null, flags: ParseFlags): Element;
export function plugin_error_quark(): GLib.Quark;
export function preset_get_app_dir(): string | null;
export function preset_set_app_dir(app_dir: string): boolean;
export function protection_filter_systems_by_available_decryptors(system_identifiers: string[]): string[] | null;
export function protection_meta_api_get_type(): GObject.GType;
export function protection_meta_get_info(): MetaInfo;
export function protection_select_system(system_identifiers: string[]): string | null;
export function query_type_get_flags(type: QueryType): QueryTypeFlags;
export function query_type_get_name(type: QueryType): string;
export function query_type_to_quark(type: QueryType): GLib.Quark;
export function reference_timestamp_meta_api_get_type(): GObject.GType;
export function reference_timestamp_meta_get_info(): MetaInfo;
export function resource_error_quark(): GLib.Quark;
export function segtrap_is_enabled(): boolean;
export function segtrap_set_enabled(enabled: boolean): void;
export function state_change_get_name(transition: StateChange): string;
export function static_caps_get_type(): GObject.GType;
export function static_pad_template_get_type(): GObject.GType;
export function stream_error_quark(): GLib.Quark;
export function stream_type_get_name(stype: StreamType): string;
export function structure_take(oldstr_ptr?: Structure | null, newstr?: Structure | null): [boolean, Structure | null];
export function tag_exists(tag: string): boolean;
export function tag_get_description(tag: string): string | null;
export function tag_get_flag(tag: string): TagFlag;
export function tag_get_nick(tag: string): string | null;
export function tag_get_type(tag: string): GObject.GType;
export function tag_is_fixed(tag: string): boolean;
export function tag_list_copy_value(list: TagList, tag: string): [boolean, unknown];
export function tag_merge_strings_with_comma(src: any): unknown;
export function tag_merge_use_first(src: any): unknown;
export function toc_entry_type_get_nick(type: TocEntryType): string;
export function tracing_get_active_tracers(): Tracer[];
export function tracing_register_hook(tracer: Tracer, detail: string, func: GObject.Callback): void;
export function type_find_get_type(): GObject.GType;
export function type_find_register(
plugin: Plugin | null,
name: string,
rank: number,
func: TypeFindFunction,
extensions?: string | null,
possible_caps?: Caps | null
): boolean;
export function type_is_plugin_api(type: GObject.GType): [boolean, PluginAPIFlags | null];
export function type_mark_as_plugin_api(type: GObject.GType, flags: PluginAPIFlags): void;
export function update_registry(): boolean;
export function uri_construct(protocol: string, location: string): string;
export function uri_error_quark(): GLib.Quark;
export function uri_from_string(uri: string): Uri | null;
export function uri_from_string_escaped(uri: string): Uri | null;
export function uri_get_location(uri: string): string | null;
export function uri_get_protocol(uri: string): string | null;
export function uri_has_protocol(uri: string, protocol: string): boolean;
export function uri_is_valid(uri: string): boolean;
export function uri_join_strings(base_uri: string, ref_uri: string): string;
export function uri_protocol_is_supported(type: URIType, protocol: string): boolean;
export function uri_protocol_is_valid(protocol: string): boolean;
export function util_array_binary_search(
array: any | null,
num_elements: number,
element_size: number,
search_func: GLib.CompareDataFunc,
mode: SearchMode,
search_data?: any | null
): any | null;
export function util_double_to_fraction(src: number): [number, number];
export function util_dump_buffer(buf: Buffer): void;
export function util_dump_mem(mem: Uint8Array | string): void;
export function util_fraction_add(a_n: number, a_d: number, b_n: number, b_d: number): [boolean, number, number];
export function util_fraction_compare(a_n: number, a_d: number, b_n: number, b_d: number): number;
export function util_fraction_multiply(a_n: number, a_d: number, b_n: number, b_d: number): [boolean, number, number];
export function util_fraction_to_double(src_n: number, src_d: number): number;
export function util_gdouble_to_guint64(value: number): number;
export function util_get_object_array(object: GObject.Object, name: string): [boolean, GObject.ValueArray];
export function util_get_timestamp(): ClockTime;
export function util_greatest_common_divisor(a: number, b: number): number;
export function util_greatest_common_divisor_int64(a: number, b: number): number;
export function util_group_id_next(): number;
export function util_guint64_to_gdouble(value: number): number;
export function util_seqnum_compare(s1: number, s2: number): number;
export function util_seqnum_next(): number;
export function util_set_object_arg(object: GObject.Object, name: string, value: string): void;
export function util_set_object_array(object: GObject.Object, name: string, array: GObject.ValueArray): boolean;
export function util_set_value_from_string(value_str: string): unknown;
export function util_uint64_scale(val: number, num: number, denom: number): number;
export function util_uint64_scale_ceil(val: number, num: number, denom: number): number;
export function util_uint64_scale_int(val: number, num: number, denom: number): number;
export function util_uint64_scale_int_ceil(val: number, num: number, denom: number): number;
export function util_uint64_scale_int_round(val: number, num: number, denom: number): number;
export function util_uint64_scale_round(val: number, num: number, denom: number): number;
export function value_can_compare(value1: any, value2: any): boolean;
export function value_can_intersect(value1: any, value2: any): boolean;
export function value_can_subtract(minuend: any, subtrahend: any): boolean;
export function value_can_union(value1: any, value2: any): boolean;
export function value_compare(value1: any, value2: any): number;
export function value_deserialize(src: string): [boolean, unknown];
export function value_fixate(dest: any, src: any): boolean;
export function value_fraction_multiply(product: any, factor1: any, factor2: any): boolean;
export function value_fraction_subtract(dest: any, minuend: any, subtrahend: any): boolean;
export function value_get_bitmask(value: any): number;
export function value_get_caps(value: any): Caps;
export function value_get_caps_features(value: any): CapsFeatures;
export function value_get_double_range_max(value: any): number;
export function value_get_double_range_min(value: any): number;
export function value_get_flagset_flags(value: any): number;
export function value_get_flagset_mask(value: any): number;
export function value_get_fraction_denominator(value: any): number;
export function value_get_fraction_numerator(value: any): number;
export function value_get_fraction_range_max(value: any): GObject.Value | null;
export function value_get_fraction_range_min(value: any): GObject.Value | null;
export function value_get_int64_range_max(value: any): number;
export function value_get_int64_range_min(value: any): number;
export function value_get_int64_range_step(value: any): number;
export function value_get_int_range_max(value: any): number;
export function value_get_int_range_min(value: any): number;
export function value_get_int_range_step(value: any): number;
export function value_get_structure(value: any): Structure;
export function value_init_and_copy(src: any): unknown;
export function value_intersect(value1: any, value2: any): [boolean, GObject.Value | null];
export function value_is_fixed(value: any): boolean;
export function value_is_subset(value1: any, value2: any): boolean;
export function value_register(table: ValueTable): void;
export function value_serialize(value: any): string | null;
export function value_set_bitmask(value: any, bitmask: number): void;
export function value_set_caps(value: any, caps: Caps): void;
export function value_set_caps_features(value: any, features: CapsFeatures): void;
export function value_set_double_range(value: any, start: number, end: number): void;
export function value_set_flagset(value: any, flags: number, mask: number): void;
export function value_set_fraction(value: any, numerator: number, denominator: number): void;
export function value_set_fraction_range(value: any, start: any, end: any): void;
export function value_set_fraction_range_full(
value: any,
numerator_start: number,
denominator_start: number,
numerator_end: number,
denominator_end: number
): void;
export function value_set_int64_range(value: any, start: number, end: number): void;
export function value_set_int64_range_step(value: any, start: number, end: number, step: number): void;
export function value_set_int_range(value: any, start: number, end: number): void;
export function value_set_int_range_step(value: any, start: number, end: number, step: number): void;
export function value_set_structure(value: any, structure: Structure): void;
export function value_subtract(minuend: any, subtrahend: any): [boolean, GObject.Value | null];
export function value_union(value1: any, value2: any): [boolean, unknown];
export function version(): [number, number, number, number];
export function version_string(): string;
export type BufferForeachMetaFunc = (buffer: Buffer) => boolean;
export type BufferListFunc = (idx: number) => boolean;
export type BusFunc = (bus: Bus, message: Message) => boolean;
export type BusSyncHandler = (bus: Bus, message: Message) => BusSyncReply;
export type CapsFilterMapFunc = (features: CapsFeatures, structure: Structure) => boolean;
export type CapsForeachFunc = (features: CapsFeatures, structure: Structure) => boolean;
export type CapsMapFunc = (features: CapsFeatures, structure: Structure) => boolean;
export type ClockCallback = (clock: Clock, time: ClockTime, id: ClockID) => boolean;
export type ControlBindingConvert = (binding: ControlBinding, src_value: number, dest_value: any) => void;
export type ControlSourceGetValue = (self: ControlSource, timestamp: ClockTime, value: number) => boolean;
export type ControlSourceGetValueArray = (
self: ControlSource,
timestamp: ClockTime,
interval: ClockTime,
n_values: number,
values: number
) => boolean;
export type DebugFuncPtr = () => void;
export type ElementCallAsyncFunc = (element: Element) => void;
export type ElementForeachPadFunc = (element: Element, pad: Pad) => boolean;
export type IteratorCopyFunction = (it: Iterator, copy: Iterator) => void;
export type IteratorFoldFunction = (item: any, ret: any) => boolean;
export type IteratorForeachFunction = (item: any) => void;
export type IteratorFreeFunction = (it: Iterator) => void;
export type IteratorItemFunction = (it: Iterator, item: any) => IteratorItem;
export type IteratorNextFunction = (it: Iterator, result: any) => IteratorResult;
export type IteratorResyncFunction = (it: Iterator) => void;
export type LogFunction<A = GObject.Object> = (
category: DebugCategory,
level: DebugLevel,
file: string,
_function: string,
line: number,
object: A,
message: DebugMessage
) => void;
export type MemoryCopyFunction = (mem: Memory, offset: number, size: number) => Memory;
export type MemoryIsSpanFunction = (mem1: Memory, mem2: Memory, offset: number) => boolean;
export type MemoryMapFullFunction = (mem: Memory, info: MapInfo, maxsize: number) => any | null;
export type MemoryMapFunction = (mem: Memory, maxsize: number, flags: MapFlags) => any | null;
export type MemoryShareFunction = (mem: Memory, offset: number, size: number) => Memory;
export type MemoryUnmapFullFunction = (mem: Memory, info: MapInfo) => void;
export type MemoryUnmapFunction = (mem: Memory) => void;
export type MetaFreeFunction = (meta: Meta, buffer: Buffer) => void;
export type MetaInitFunction = (meta: Meta, params: any | null, buffer: Buffer) => boolean;
export type MetaTransformFunction = (
transbuf: Buffer,
meta: Meta,
buffer: Buffer,
type: GLib.Quark,
data?: any | null
) => boolean;
export type MiniObjectDisposeFunction = (obj: MiniObject) => boolean;
export type MiniObjectFreeFunction = (obj: MiniObject) => void;
export type MiniObjectNotify = (obj: MiniObject) => void;
export type PadActivateFunction = (pad: Pad, parent: Object) => boolean;
export type PadActivateModeFunction = (pad: Pad, parent: Object, mode: PadMode, active: boolean) => boolean;
export type PadChainFunction = (pad: Pad, parent: Object | null, buffer: Buffer) => FlowReturn;
export type PadChainListFunction = (pad: Pad, parent: Object | null, list: BufferList) => FlowReturn;
export type PadEventFullFunction = (pad: Pad, parent: Object | null, event: Event) => FlowReturn;
export type PadEventFunction = (pad: Pad, parent: Object | null, event: Event) => boolean;
export type PadForwardFunction = (pad: Pad) => boolean;
export type PadGetRangeFunction = (
pad: Pad,
parent: Object | null,
offset: number,
length: number,
buffer: Buffer
) => FlowReturn;
export type PadIterIntLinkFunction = (pad: Pad, parent?: Object | null) => Iterator;
export type PadLinkFunction = (pad: Pad, parent: Object | null, peer: Pad) => PadLinkReturn;
export type PadProbeCallback = (pad: Pad, info: PadProbeInfo) => PadProbeReturn;
export type PadQueryFunction = (pad: Pad, parent: Object | null, query: Query) => boolean;
export type PadStickyEventsForeachFunction = (pad: Pad, event?: Event | null) => boolean;
export type PadUnlinkFunction = (pad: Pad, parent?: Object | null) => void;
export type PluginFeatureFilter = (feature: PluginFeature) => boolean;
export type PluginFilter = (plugin: Plugin) => boolean;
export type PluginInitFullFunc = (plugin: Plugin) => boolean;
export type PluginInitFunc = (plugin: Plugin) => boolean;
export type PromiseChangeFunc = (promise: Promise) => void;
export type StructureFilterMapFunc = (field_id: GLib.Quark, value: any) => boolean;
export type StructureForeachFunc = (field_id: GLib.Quark, value: any) => boolean;
export type StructureMapFunc = (field_id: GLib.Quark, value: any) => boolean;
export type TagForeachFunc = (list: TagList, tag: string) => void;
export type TagMergeFunc = (dest: any, src: any) => void;
export type TaskFunction = () => void;
export type TaskPoolFunction = () => void;
export type TaskThreadFunc = (task: Task, thread: GLib.Thread) => void;
export type TypeFindFunction = (find: TypeFind) => void;
export type ValueCompareFunc = (value1: any, value2: any) => number;
export type ValueDeserializeFunc = (dest: any, s: string) => boolean;
export type ValueSerializeFunc = (value1: any) => string;
export namespace BufferingMode {
export const $gtype: GObject.GType<BufferingMode>;
}
export enum BufferingMode {
STREAM = 0,
DOWNLOAD = 1,
TIMESHIFT = 2,
LIVE = 3,
}
export namespace BusSyncReply {
export const $gtype: GObject.GType<BusSyncReply>;
}
export enum BusSyncReply {
DROP = 0,
PASS = 1,
ASYNC = 2,
}
export namespace CapsIntersectMode {
export const $gtype: GObject.GType<CapsIntersectMode>;
}
export enum CapsIntersectMode {
ZIG_ZAG = 0,
FIRST = 1,
}
export namespace ClockEntryType {
export const $gtype: GObject.GType<ClockEntryType>;
}
export enum ClockEntryType {
SINGLE = 0,
PERIODIC = 1,
}
export namespace ClockReturn {
export const $gtype: GObject.GType<ClockReturn>;
}
export enum ClockReturn {
OK = 0,
EARLY = 1,
UNSCHEDULED = 2,
BUSY = 3,
BADTIME = 4,
ERROR = 5,
UNSUPPORTED = 6,
DONE = 7,
}
export namespace ClockType {
export const $gtype: GObject.GType<ClockType>;
}
export enum ClockType {
REALTIME = 0,
MONOTONIC = 1,
OTHER = 2,
TAI = 3,
}
export class CoreError extends GLib.Error {
static $gtype: GObject.GType<CoreError>;
constructor(options: { message: string; code: number });
constructor(copy: CoreError);
// Properties
static FAILED: number;
static TOO_LAZY: number;
static NOT_IMPLEMENTED: number;
static STATE_CHANGE: number;
static PAD: number;
static THREAD: number;
static NEGOTIATION: number;
static EVENT: number;
static SEEK: number;
static CAPS: number;
static TAG: number;
static MISSING_PLUGIN: number;
static CLOCK: number;
static DISABLED: number;
static NUM_ERRORS: number;
// Members
static quark(): GLib.Quark;
}
export namespace DebugColorMode {
export const $gtype: GObject.GType<DebugColorMode>;
}
export enum DebugColorMode {
OFF = 0,
ON = 1,
UNIX = 2,
}
export namespace DebugLevel {
export const $gtype: GObject.GType<DebugLevel>;
}
export enum DebugLevel {
NONE = 0,
ERROR = 1,
WARNING = 2,
FIXME = 3,
INFO = 4,
DEBUG = 5,
LOG = 6,
TRACE = 7,
MEMDUMP = 9,
COUNT = 10,
}
export namespace EventType {
export const $gtype: GObject.GType<EventType>;
}
export enum EventType {
UNKNOWN = 0,
FLUSH_START = 2563,
FLUSH_STOP = 5127,
STREAM_START = 10254,
CAPS = 12814,
SEGMENT = 17934,
STREAM_COLLECTION = 19230,
TAG = 20510,
BUFFERSIZE = 23054,
SINK_MESSAGE = 25630,
STREAM_GROUP_DONE = 26894,
EOS = 28174,
TOC = 30750,
PROTECTION = 33310,
SEGMENT_DONE = 38406,
GAP = 40966,
INSTANT_RATE_CHANGE = 46090,
QOS = 48641,
SEEK = 51201,
NAVIGATION = 53761,
LATENCY = 56321,
STEP = 58881,
RECONFIGURE = 61441,
TOC_SELECT = 64001,
SELECT_STREAMS = 66561,
INSTANT_RATE_SYNC_TIME = 66817,
CUSTOM_UPSTREAM = 69121,
CUSTOM_DOWNSTREAM = 71686,
CUSTOM_DOWNSTREAM_OOB = 74242,
CUSTOM_DOWNSTREAM_STICKY = 76830,
CUSTOM_BOTH = 79367,
CUSTOM_BOTH_OOB = 81923,
}
export namespace FlowReturn {
export const $gtype: GObject.GType<FlowReturn>;
}
export enum FlowReturn {
CUSTOM_SUCCESS_2 = 102,
CUSTOM_SUCCESS_1 = 101,
CUSTOM_SUCCESS = 100,
OK = 0,
NOT_LINKED = -1,
FLUSHING = -2,
EOS = -3,
NOT_NEGOTIATED = -4,
ERROR = -5,
NOT_SUPPORTED = -6,
CUSTOM_ERROR = -100,
CUSTOM_ERROR_1 = -101,
CUSTOM_ERROR_2 = -102,
}
export namespace Format {
export const $gtype: GObject.GType<Format>;
}
export enum Format {
UNDEFINED = 0,
DEFAULT = 1,
BYTES = 2,
TIME = 3,
BUFFERS = 4,
PERCENT = 5,
}
export namespace IteratorItem {
export const $gtype: GObject.GType<IteratorItem>;
}
export enum IteratorItem {
SKIP = 0,
PASS = 1,
END = 2,
}
export namespace IteratorResult {
export const $gtype: GObject.GType<IteratorResult>;
}
export enum IteratorResult {
DONE = 0,
OK = 1,
RESYNC = 2,
ERROR = 3,
}
export class LibraryError extends GLib.Error {
static $gtype: GObject.GType<LibraryError>;
constructor(options: { message: string; code: number });
constructor(copy: LibraryError);
// Properties
static FAILED: number;
static TOO_LAZY: number;
static INIT: number;
static SHUTDOWN: number;
static SETTINGS: number;
static ENCODE: number;
static NUM_ERRORS: number;
// Members
static quark(): GLib.Quark;
}
export namespace PadDirection {
export const $gtype: GObject.GType<PadDirection>;
}
export enum PadDirection {
UNKNOWN = 0,
SRC = 1,
SINK = 2,
}
export namespace PadLinkReturn {
export const $gtype: GObject.GType<PadLinkReturn>;
}
export enum PadLinkReturn {
OK = 0,
WRONG_HIERARCHY = -1,
WAS_LINKED = -2,
WRONG_DIRECTION = -3,
NOFORMAT = -4,
NOSCHED = -5,
REFUSED = -6,
}
export namespace PadMode {
export const $gtype: GObject.GType<PadMode>;
}
export enum PadMode {
NONE = 0,
PUSH = 1,
PULL = 2,
}
export namespace PadPresence {
export const $gtype: GObject.GType<PadPresence>;
}
export enum PadPresence {
ALWAYS = 0,
SOMETIMES = 1,
REQUEST = 2,
}
export namespace PadProbeReturn {
export const $gtype: GObject.GType<PadProbeReturn>;
}
export enum PadProbeReturn {
DROP = 0,
OK = 1,
REMOVE = 2,
PASS = 3,
HANDLED = 4,
}
export class ParseError extends GLib.Error {
static $gtype: GObject.GType<ParseError>;
constructor(options: { message: string; code: number });
constructor(copy: ParseError);
// Properties
static SYNTAX: number;
static NO_SUCH_ELEMENT: number;
static NO_SUCH_PROPERTY: number;
static LINK: number;
static COULD_NOT_SET_PROPERTY: number;
static EMPTY_BIN: number;
static EMPTY: number;
static DELAYED_LINK: number;
// Members
static quark(): GLib.Quark;
}
export class PluginError extends GLib.Error {
static $gtype: GObject.GType<PluginError>;
constructor(options: { message: string; code: number });
constructor(copy: PluginError);
// Properties
static MODULE: number;
static DEPENDENCIES: number;
static NAME_MISMATCH: number;
// Members
static quark(): GLib.Quark;
}
export namespace ProgressType {
export const $gtype: GObject.GType<ProgressType>;
}
export enum ProgressType {
START = 0,
CONTINUE = 1,
COMPLETE = 2,
CANCELED = 3,
ERROR = 4,
}
export namespace PromiseResult {
export const $gtype: GObject.GType<PromiseResult>;
}
export enum PromiseResult {
PENDING = 0,
INTERRUPTED = 1,
REPLIED = 2,
EXPIRED = 3,
}
export namespace QOSType {
export const $gtype: GObject.GType<QOSType>;
}
export enum QOSType {
OVERFLOW = 0,
UNDERFLOW = 1,
THROTTLE = 2,
}
export namespace QueryType {
export const $gtype: GObject.GType<QueryType>;
}
export enum QueryType {
UNKNOWN = 0,
POSITION = 2563,
DURATION = 5123,
LATENCY = 7683,
JITTER = 10243,
RATE = 12803,
SEEKING = 15363,
SEGMENT = 17923,
CONVERT = 20483,
FORMATS = 23043,
BUFFERING = 28163,
CUSTOM = 30723,
URI = 33283,
ALLOCATION = 35846,
SCHEDULING = 38401,
ACCEPT_CAPS = 40963,
CAPS = 43523,
DRAIN = 46086,
CONTEXT = 48643,
BITRATE = 51202,
}
export namespace Rank {
export const $gtype: GObject.GType<Rank>;
}
export enum Rank {
NONE = 0,
MARGINAL = 64,
SECONDARY = 128,
PRIMARY = 256,
}
export class ResourceError extends GLib.Error {
static $gtype: GObject.GType<ResourceError>;
constructor(options: { message: string; code: number });
constructor(copy: ResourceError);
// Properties
static FAILED: number;
static TOO_LAZY: number;
static NOT_FOUND: number;
static BUSY: number;
static OPEN_READ: number;
static OPEN_WRITE: number;
static OPEN_READ_WRITE: number;
static CLOSE: number;
static READ: number;
static WRITE: number;
static SEEK: number;
static SYNC: number;
static SETTINGS: number;
static NO_SPACE_LEFT: number;
static NOT_AUTHORIZED: number;
static NUM_ERRORS: number;
// Members
static quark(): GLib.Quark;
}
export namespace SearchMode {
export const $gtype: GObject.GType<SearchMode>;
}
export enum SearchMode {
EXACT = 0,
BEFORE = 1,
AFTER = 2,
}
export namespace SeekType {
export const $gtype: GObject.GType<SeekType>;
}
export enum SeekType {
NONE = 0,
SET = 1,
END = 2,
}
export namespace State {
export const $gtype: GObject.GType<State>;
}
export enum State {
VOID_PENDING = 0,
NULL = 1,
READY = 2,
PAUSED = 3,
PLAYING = 4,
}
export namespace StateChange {
export const $gtype: GObject.GType<StateChange>;
}
export enum StateChange {
NULL_TO_READY = 10,
READY_TO_PAUSED = 19,
PAUSED_TO_PLAYING = 28,
PLAYING_TO_PAUSED = 35,
PAUSED_TO_READY = 26,
READY_TO_NULL = 17,
NULL_TO_NULL = 9,
READY_TO_READY = 18,
PAUSED_TO_PAUSED = 27,
PLAYING_TO_PLAYING = 36,
}
export namespace StateChangeReturn {
export const $gtype: GObject.GType<StateChangeReturn>;
}
export enum StateChangeReturn {
FAILURE = 0,
SUCCESS = 1,
ASYNC = 2,
NO_PREROLL = 3,
}
export class StreamError extends GLib.Error {
static $gtype: GObject.GType<StreamError>;
constructor(options: { message: string; code: number });
constructor(copy: StreamError);
// Properties
static FAILED: number;
static TOO_LAZY: number;
static NOT_IMPLEMENTED: number;
static TYPE_NOT_FOUND: number;
static WRONG_TYPE: number;
static CODEC_NOT_FOUND: number;
static DECODE: number;
static ENCODE: number;
static DEMUX: number;
static MUX: number;
static FORMAT: number;
static DECRYPT: number;
static DECRYPT_NOKEY: number;
static NUM_ERRORS: number;
// Members
static quark(): GLib.Quark;
}
export namespace StreamStatusType {
export const $gtype: GObject.GType<StreamStatusType>;
}
export enum StreamStatusType {
CREATE = 0,
ENTER = 1,
LEAVE = 2,
DESTROY = 3,
START = 8,
PAUSE = 9,
STOP = 10,
}
export namespace StructureChangeType {
export const $gtype: GObject.GType<StructureChangeType>;
}
export enum StructureChangeType {
LINK = 0,
UNLINK = 1,
}
export namespace TagFlag {
export const $gtype: GObject.GType<TagFlag>;
}
export enum TagFlag {
UNDEFINED = 0,
META = 1,
ENCODED = 2,
DECODED = 3,
COUNT = 4,
}
export namespace TagMergeMode {
export const $gtype: GObject.GType<TagMergeMode>;
}
export enum TagMergeMode {
UNDEFINED = 0,
REPLACE_ALL = 1,
REPLACE = 2,
APPEND = 3,
PREPEND = 4,
KEEP = 5,
KEEP_ALL = 6,
COUNT = 7,
}
export namespace TagScope {
export const $gtype: GObject.GType<TagScope>;
}
export enum TagScope {
STREAM = 0,
GLOBAL = 1,
}
export namespace TaskState {
export const $gtype: GObject.GType<TaskState>;
}
export enum TaskState {
STARTED = 0,
STOPPED = 1,
PAUSED = 2,
}
export namespace TocEntryType {
export const $gtype: GObject.GType<TocEntryType>;
}
export enum TocEntryType {
ANGLE = -3,
VERSION = -2,
EDITION = -1,
INVALID = 0,
TITLE = 1,
TRACK = 2,
CHAPTER = 3,
}
export namespace TocLoopType {
export const $gtype: GObject.GType<TocLoopType>;
}
export enum TocLoopType {
NONE = 0,
FORWARD = 1,
REVERSE = 2,
PING_PONG = 3,
}
export namespace TocScope {
export const $gtype: GObject.GType<TocScope>;
}
export enum TocScope {
GLOBAL = 1,
CURRENT = 2,
}
export namespace TracerValueScope {
export const $gtype: GObject.GType<TracerValueScope>;
}
export enum TracerValueScope {
PROCESS = 0,
THREAD = 1,
ELEMENT = 2,
PAD = 3,
}
export namespace TypeFindProbability {
export const $gtype: GObject.GType<TypeFindProbability>;
}
export enum TypeFindProbability {
NONE = 0,
MINIMUM = 1,
POSSIBLE = 50,
LIKELY = 80,
NEARLY_CERTAIN = 99,
MAXIMUM = 100,
}
export class URIError extends GLib.Error {
static $gtype: GObject.GType<URIError>;
constructor(options: { message: string; code: number });
constructor(copy: URIError);
// Properties
static UNSUPPORTED_PROTOCOL: number;
static BAD_URI: number;
static BAD_STATE: number;
static BAD_REFERENCE: number;
// Members
static quark(): GLib.Quark;
}
export namespace URIType {
export const $gtype: GObject.GType<URIType>;
}
export enum URIType {
UNKNOWN = 0,
SINK = 1,
SRC = 2,
}
export namespace AllocatorFlags {
export const $gtype: GObject.GType<AllocatorFlags>;
}
export enum AllocatorFlags {
CUSTOM_ALLOC = 16,
LAST = 1048576,
}
export namespace BinFlags {
export const $gtype: GObject.GType<BinFlags>;
}
export enum BinFlags {
NO_RESYNC = 16384,
STREAMS_AWARE = 32768,
LAST = 524288,
}
export namespace BufferCopyFlags {
export const $gtype: GObject.GType<BufferCopyFlags>;
}
export enum BufferCopyFlags {
NONE = 0,
FLAGS = 1,
TIMESTAMPS = 2,
META = 4,
MEMORY = 8,
MERGE = 16,
DEEP = 32,
}
export namespace BufferFlags {
export const $gtype: GObject.GType<BufferFlags>;
}
export enum BufferFlags {
LIVE = 16,
DECODE_ONLY = 32,
DISCONT = 64,
RESYNC = 128,
CORRUPTED = 256,
MARKER = 512,
HEADER = 1024,
GAP = 2048,
DROPPABLE = 4096,
DELTA_UNIT = 8192,
TAG_MEMORY = 16384,
SYNC_AFTER = 32768,
NON_DROPPABLE = 65536,
LAST = 1048576,
}
export namespace BufferPoolAcquireFlags {
export const $gtype: GObject.GType<BufferPoolAcquireFlags>;
}
export enum BufferPoolAcquireFlags {
NONE = 0,
KEY_UNIT = 1,
DONTWAIT = 2,
DISCONT = 4,
LAST = 65536,
}
export namespace BusFlags {
export const $gtype: GObject.GType<BusFlags>;
}
export enum BusFlags {
FLUSHING = 16,
FLAG_LAST = 32,
}
export namespace CapsFlags {
export const $gtype: GObject.GType<CapsFlags>;
}
export enum CapsFlags {
ANY = 16,
}
export namespace ClockFlags {
export const $gtype: GObject.GType<ClockFlags>;
}
export enum ClockFlags {
CAN_DO_SINGLE_SYNC = 16,
CAN_DO_SINGLE_ASYNC = 32,
CAN_DO_PERIODIC_SYNC = 64,
CAN_DO_PERIODIC_ASYNC = 128,
CAN_SET_RESOLUTION = 256,
CAN_SET_MASTER = 512,
NEEDS_STARTUP_SYNC = 1024,
LAST = 4096,
}
export namespace DebugColorFlags {
export const $gtype: GObject.GType<DebugColorFlags>;
}
export enum DebugColorFlags {
FG_BLACK = 0,
FG_RED = 1,
FG_GREEN = 2,
FG_YELLOW = 3,
FG_BLUE = 4,
FG_MAGENTA = 5,
FG_CYAN = 6,
FG_WHITE = 7,
BG_BLACK = 0,
BG_RED = 16,
BG_GREEN = 32,
BG_YELLOW = 48,
BG_BLUE = 64,
BG_MAGENTA = 80,
BG_CYAN = 96,
BG_WHITE = 112,
BOLD = 256,
UNDERLINE = 512,
}
export namespace DebugGraphDetails {
export const $gtype: GObject.GType<DebugGraphDetails>;
}
export enum DebugGraphDetails {
MEDIA_TYPE = 1,
CAPS_DETAILS = 2,
NON_DEFAULT_PARAMS = 4,
STATES = 8,
FULL_PARAMS = 16,
ALL = 15,
VERBOSE = 4294967295,
}
export namespace ElementFlags {
export const $gtype: GObject.GType<ElementFlags>;
}
export enum ElementFlags {
LOCKED_STATE = 16,
SINK = 32,
SOURCE = 64,
PROVIDE_CLOCK = 128,
REQUIRE_CLOCK = 256,
INDEXABLE = 512,
LAST = 16384,
}
export namespace EventTypeFlags {
export const $gtype: GObject.GType<EventTypeFlags>;
}
export enum EventTypeFlags {
UPSTREAM = 1,
DOWNSTREAM = 2,
SERIALIZED = 4,
STICKY = 8,
STICKY_MULTI = 16,
}
export namespace LockFlags {
export const $gtype: GObject.GType<LockFlags>;
}
export enum LockFlags {
READ = 1,
WRITE = 2,
EXCLUSIVE = 4,
LAST = 256,
}
export namespace MapFlags {
export const $gtype: GObject.GType<MapFlags>;
}
export enum MapFlags {
READ = 1,
WRITE = 2,
FLAG_LAST = 65536,
}
export namespace MemoryFlags {
export const $gtype: GObject.GType<MemoryFlags>;
}
export enum MemoryFlags {
READONLY = 2,
NO_SHARE = 16,
ZERO_PREFIXED = 32,
ZERO_PADDED = 64,
PHYSICALLY_CONTIGUOUS = 128,
NOT_MAPPABLE = 256,
LAST = 1048576,
}
export namespace MessageType {
export const $gtype: GObject.GType<MessageType>;
}
export enum MessageType {
UNKNOWN = 0,
EOS = 1,
ERROR = 2,
WARNING = 4,
INFO = 8,
TAG = 16,
BUFFERING = 32,
STATE_CHANGED = 64,
STATE_DIRTY = 128,
STEP_DONE = 256,
CLOCK_PROVIDE = 512,
CLOCK_LOST = 1024,
NEW_CLOCK = 2048,
STRUCTURE_CHANGE = 4096,
STREAM_STATUS = 8192,
APPLICATION = 16384,
ELEMENT = 32768,
SEGMENT_START = 65536,
SEGMENT_DONE = 131072,
DURATION_CHANGED = 262144,
LATENCY = 524288,
ASYNC_START = 1048576,
ASYNC_DONE = 2097152,
REQUEST_STATE = 4194304,
STEP_START = 8388608,
QOS = 16777216,
PROGRESS = 33554432,
TOC = 67108864,
RESET_TIME = 134217728,
STREAM_START = 268435456,
NEED_CONTEXT = 536870912,
HAVE_CONTEXT = 1073741824,
EXTENDED = 2147483648,
DEVICE_ADDED = 2147483649,
DEVICE_REMOVED = 2147483650,
PROPERTY_NOTIFY = 2147483651,
STREAM_COLLECTION = 2147483652,
STREAMS_SELECTED = 2147483653,
REDIRECT = 2147483654,
DEVICE_CHANGED = 2147483655,
INSTANT_RATE_REQUEST = 2147483656,
ANY = 4294967295,
}
export namespace MetaFlags {
export const $gtype: GObject.GType<MetaFlags>;
}
export enum MetaFlags {
NONE = 0,
READONLY = 1,
POOLED = 2,
LOCKED = 4,
LAST = 65536,
}
export namespace MiniObjectFlags {
export const $gtype: GObject.GType<MiniObjectFlags>;
}
export enum MiniObjectFlags {
LOCKABLE = 1,
LOCK_READONLY = 2,
MAY_BE_LEAKED = 4,
LAST = 16,
}
export namespace ObjectFlags {
export const $gtype: GObject.GType<ObjectFlags>;
}
export enum ObjectFlags {
MAY_BE_LEAKED = 1,
LAST = 16,
}
export namespace PadFlags {
export const $gtype: GObject.GType<PadFlags>;
}
export enum PadFlags {
BLOCKED = 16,
FLUSHING = 32,
EOS = 64,
BLOCKING = 128,
NEED_PARENT = 256,
NEED_RECONFIGURE = 512,
PENDING_EVENTS = 1024,
FIXED_CAPS = 2048,
PROXY_CAPS = 4096,
PROXY_ALLOCATION = 8192,
PROXY_SCHEDULING = 16384,
ACCEPT_INTERSECT = 32768,
ACCEPT_TEMPLATE = 65536,
LAST = 1048576,
}
export namespace PadLinkCheck {
export const $gtype: GObject.GType<PadLinkCheck>;
}
export enum PadLinkCheck {
NOTHING = 0,
HIERARCHY = 1,
TEMPLATE_CAPS = 2,
CAPS = 4,
NO_RECONFIGURE = 8,
DEFAULT = 5,
}
export namespace PadProbeType {
export const $gtype: GObject.GType<PadProbeType>;
}
export enum PadProbeType {
INVALID = 0,
IDLE = 1,
BLOCK = 2,
BUFFER = 16,
BUFFER_LIST = 32,
EVENT_DOWNSTREAM = 64,
EVENT_UPSTREAM = 128,
EVENT_FLUSH = 256,
QUERY_DOWNSTREAM = 512,
QUERY_UPSTREAM = 1024,
PUSH = 4096,
PULL = 8192,
BLOCKING = 3,
DATA_DOWNSTREAM = 112,
DATA_UPSTREAM = 128,
DATA_BOTH = 240,
BLOCK_DOWNSTREAM = 114,
BLOCK_UPSTREAM = 130,
EVENT_BOTH = 192,
QUERY_BOTH = 1536,
ALL_BOTH = 1776,
SCHEDULING = 12288,
}
export namespace PadTemplateFlags {
export const $gtype: GObject.GType<PadTemplateFlags>;
}
export enum PadTemplateFlags {
LAST = 256,
}
export namespace ParseFlags {
export const $gtype: GObject.GType<ParseFlags>;
}
export enum ParseFlags {
NONE = 0,
FATAL_ERRORS = 1,
NO_SINGLE_ELEMENT_BINS = 2,
PLACE_IN_BIN = 4,
}
export namespace PipelineFlags {
export const $gtype: GObject.GType<PipelineFlags>;
}
export enum PipelineFlags {
FIXED_CLOCK = 524288,
LAST = 8388608,
}
export namespace PluginAPIFlags {
export const $gtype: GObject.GType<PluginAPIFlags>;
}
export enum PluginAPIFlags {
MEMBERS = 1,
}
export namespace PluginDependencyFlags {
export const $gtype: GObject.GType<PluginDependencyFlags>;
}
export enum PluginDependencyFlags {
NONE = 0,
RECURSE = 1,
PATHS_ARE_DEFAULT_ONLY = 2,
FILE_NAME_IS_SUFFIX = 4,
FILE_NAME_IS_PREFIX = 8,
PATHS_ARE_RELATIVE_TO_EXE = 16,
}
export namespace PluginFlags {
export const $gtype: GObject.GType<PluginFlags>;
}
export enum PluginFlags {
CACHED = 16,
BLACKLISTED = 32,
}
export namespace QueryTypeFlags {
export const $gtype: GObject.GType<QueryTypeFlags>;
}
export enum QueryTypeFlags {
UPSTREAM = 1,
DOWNSTREAM = 2,
SERIALIZED = 4,
}
export namespace SchedulingFlags {
export const $gtype: GObject.GType<SchedulingFlags>;
}
export enum SchedulingFlags {
SEEKABLE = 1,
SEQUENTIAL = 2,
BANDWIDTH_LIMITED = 4,
}
export namespace SeekFlags {
export const $gtype: GObject.GType<SeekFlags>;
}
export enum SeekFlags {
NONE = 0,
FLUSH = 1,
ACCURATE = 2,
KEY_UNIT = 4,
SEGMENT = 8,
TRICKMODE = 16,
SKIP = 16,
SNAP_BEFORE = 32,
SNAP_AFTER = 64,
SNAP_NEAREST = 96,
TRICKMODE_KEY_UNITS = 128,
TRICKMODE_NO_AUDIO = 256,
TRICKMODE_FORWARD_PREDICTED = 512,
INSTANT_RATE_CHANGE = 1024,
}
export namespace SegmentFlags {
export const $gtype: GObject.GType<SegmentFlags>;
}
export enum SegmentFlags {
NONE = 0,
RESET = 1,
TRICKMODE = 16,
SKIP = 16,
SEGMENT = 8,
TRICKMODE_KEY_UNITS = 128,
TRICKMODE_FORWARD_PREDICTED = 512,
TRICKMODE_NO_AUDIO = 256,
}
export namespace StackTraceFlags {
export const $gtype: GObject.GType<StackTraceFlags>;
}
export enum StackTraceFlags {
NONE = 0,
FULL = 1,
}
export namespace StreamFlags {
export const $gtype: GObject.GType<StreamFlags>;
}
export enum StreamFlags {
NONE = 0,
SPARSE = 1,
SELECT = 2,
UNSELECT = 4,
}
export namespace StreamType {
export const $gtype: GObject.GType<StreamType>;
}
export enum StreamType {
UNKNOWN = 1,
AUDIO = 2,
VIDEO = 4,
CONTAINER = 8,
TEXT = 16,
}
export namespace TracerValueFlags {
export const $gtype: GObject.GType<TracerValueFlags>;
}
export enum TracerValueFlags {
NONE = 0,
OPTIONAL = 1,
AGGREGATED = 2,
}
export module Allocator {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
}
}
export abstract class Allocator extends Object {
static $gtype: GObject.GType<Allocator>;
constructor(properties?: Partial<Allocator.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Allocator.ConstructorProperties>, ...args: any[]): void;
// Fields
object: Object | any;
mem_type: string;
mem_map: MemoryMapFunction;
mem_unmap: MemoryUnmapFunction;
mem_copy: MemoryCopyFunction;
mem_share: MemoryShareFunction;
mem_is_span: MemoryIsSpanFunction;
mem_map_full: MemoryMapFullFunction;
mem_unmap_full: MemoryUnmapFullFunction;
// Members
alloc(size: number, params?: AllocationParams | null): Memory | null;
free(memory: Memory): void;
set_default(): void;
vfunc_alloc(size: number, params?: AllocationParams | null): Memory | null;
vfunc_free(memory: Memory): void;
static find(name?: string | null): Allocator | null;
static register(name: string, allocator: Allocator): void;
}
export module Bin {
export interface ConstructorProperties extends Element.ConstructorProperties {
[key: string]: any;
async_handling: boolean;
asyncHandling: boolean;
message_forward: boolean;
messageForward: boolean;
}
}
export class Bin extends Element implements ChildProxy {
static $gtype: GObject.GType<Bin>;
constructor(properties?: Partial<Bin.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Bin.ConstructorProperties>, ...args: any[]): void;
// Properties
async_handling: boolean;
asyncHandling: boolean;
message_forward: boolean;
messageForward: boolean;
// Fields
element: Element;
numchildren: number;
children: Element[];
children_cookie: number;
child_bus: Bus;
messages: Message[];
polling: boolean;
state_dirty: boolean;
clock_dirty: boolean;
provided_clock: Clock;
clock_provider: Element;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(signal: "deep-element-added", callback: (_source: this, sub_bin: Bin, element: Element) => void): number;
connect_after(
signal: "deep-element-added",
callback: (_source: this, sub_bin: Bin, element: Element) => void
): number;
emit(signal: "deep-element-added", sub_bin: Bin, element: Element): void;
connect(signal: "deep-element-removed", callback: (_source: this, sub_bin: Bin, element: Element) => void): number;
connect_after(
signal: "deep-element-removed",
callback: (_source: this, sub_bin: Bin, element: Element) => void
): number;
emit(signal: "deep-element-removed", sub_bin: Bin, element: Element): void;
connect(signal: "do-latency", callback: (_source: this) => boolean): number;
connect_after(signal: "do-latency", callback: (_source: this) => boolean): number;
emit(signal: "do-latency"): void;
connect(signal: "element-added", callback: (_source: this, element: Element) => void): number;
connect_after(signal: "element-added", callback: (_source: this, element: Element) => void): number;
emit(signal: "element-added", element: Element): void;
connect(signal: "element-removed", callback: (_source: this, element: Element) => void): number;
connect_after(signal: "element-removed", callback: (_source: this, element: Element) => void): number;
emit(signal: "element-removed", element: Element): void;
// Constructors
static ["new"](name?: string | null): Bin;
// Members
add(element: Element): boolean;
find_unlinked_pad(direction: PadDirection): Pad | null;
get_by_interface(iface: GObject.GType): Element | null;
get_by_name(name: string): Element | null;
get_by_name_recurse_up(name: string): Element | null;
get_suppressed_flags(): ElementFlags;
iterate_all_by_element_factory_name(factory_name: string): Iterator | null;
iterate_all_by_interface(iface: GObject.GType): Iterator | null;
iterate_elements(): Iterator | null;
iterate_recurse(): Iterator | null;
iterate_sinks(): Iterator | null;
iterate_sorted(): Iterator | null;
iterate_sources(): Iterator | null;
recalculate_latency(): boolean;
remove(element: Element): boolean;
set_suppressed_flags(flags: ElementFlags): void;
sync_children_states(): boolean;
vfunc_add_element(element: Element): boolean;
vfunc_deep_element_added(sub_bin: Bin, child: Element): void;
vfunc_deep_element_removed(sub_bin: Bin, child: Element): void;
vfunc_do_latency(): boolean;
vfunc_element_added(child: Element): void;
vfunc_element_removed(child: Element): void;
vfunc_handle_message(message: Message): void;
vfunc_remove_element(element: Element): boolean;
// Implemented Members
child_added(child: GObject.Object, name: string): void;
child_removed(child: GObject.Object, name: string): void;
get_child_by_index<T = GObject.Object>(index: number): T;
get_child_by_name<T = GObject.Object>(name: string): T;
get_children_count(): number;
get_property(name: string): unknown;
get_property(...args: never[]): never;
lookup(name: string): [boolean, GObject.Object | null, GObject.ParamSpec | null];
set_property(name: string, value: any): void;
set_property(...args: never[]): never;
vfunc_child_added(child: GObject.Object, name: string): void;
vfunc_child_removed(child: GObject.Object, name: string): void;
vfunc_get_child_by_index<T = GObject.Object>(index: number): T;
vfunc_get_child_by_name<T = GObject.Object>(name: string): T;
vfunc_get_children_count(): number;
}
export module Bitmask {
export interface ConstructorProperties {
[key: string]: any;
}
}
export class Bitmask {
static $gtype: GObject.GType<Bitmask>;
constructor(properties?: Partial<Bitmask.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Bitmask.ConstructorProperties>, ...args: any[]): void;
}
export module BufferPool {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
}
}
export class BufferPool extends Object {
static $gtype: GObject.GType<BufferPool>;
constructor(properties?: Partial<BufferPool.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<BufferPool.ConstructorProperties>, ...args: any[]): void;
// Fields
object: Object | any;
flushing: number;
// Constructors
static ["new"](): BufferPool;
// Members
acquire_buffer(params?: BufferPoolAcquireParams | null): [FlowReturn, Buffer];
get_config(): Structure;
get_options(): string[];
has_option(option: string): boolean;
is_active(): boolean;
release_buffer(buffer: Buffer): void;
set_active(active: boolean): boolean;
set_config(config: Structure): boolean;
set_flushing(flushing: boolean): void;
vfunc_acquire_buffer(params?: BufferPoolAcquireParams | null): [FlowReturn, Buffer];
vfunc_alloc_buffer(buffer: Buffer, params: BufferPoolAcquireParams): FlowReturn;
vfunc_flush_start(): void;
vfunc_flush_stop(): void;
vfunc_free_buffer(buffer: Buffer): void;
vfunc_get_options(): string[];
vfunc_release_buffer(buffer: Buffer): void;
vfunc_reset_buffer(buffer: Buffer): void;
vfunc_set_config(config: Structure): boolean;
vfunc_start(): boolean;
vfunc_stop(): boolean;
static config_add_option(config: Structure, option: string): void;
static config_get_allocator(config: Structure): [boolean, Allocator | null, AllocationParams | null];
static config_get_option(config: Structure, index: number): string | null;
static config_get_params(config: Structure): [boolean, Caps | null, number | null, number | null, number | null];
static config_has_option(config: Structure, option: string): boolean;
static config_n_options(config: Structure): number;
static config_set_allocator(
config: Structure,
allocator?: Allocator | null,
params?: AllocationParams | null
): void;
static config_set_params(
config: Structure,
caps: Caps | null,
size: number,
min_buffers: number,
max_buffers: number
): void;
static config_validate_params(
config: Structure,
caps: Caps | null,
size: number,
min_buffers: number,
max_buffers: number
): boolean;
}
export module Bus {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
enable_async: boolean;
enableAsync: boolean;
}
}
export class Bus extends Object {
static $gtype: GObject.GType<Bus>;
constructor(properties?: Partial<Bus.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Bus.ConstructorProperties>, ...args: any[]): void;
// Properties
enable_async: boolean;
enableAsync: boolean;
// Fields
object: Object | any;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(signal: "message", callback: (_source: this, message: Message) => void): number;
connect_after(signal: "message", callback: (_source: this, message: Message) => void): number;
emit(signal: "message", message: Message): void;
connect(signal: "sync-message", callback: (_source: this, message: Message) => void): number;
connect_after(signal: "sync-message", callback: (_source: this, message: Message) => void): number;
emit(signal: "sync-message", message: Message): void;
// Constructors
static ["new"](): Bus;
// Members
add_signal_watch(): void;
add_signal_watch_full(priority: number): void;
add_watch(priority: number, func: BusFunc): number;
async_signal_func(message: Message, data?: any | null): boolean;
create_watch(): GLib.Source | null;
disable_sync_message_emission(): void;
enable_sync_message_emission(): void;
get_pollfd(): GLib.PollFD;
have_pending(): boolean;
peek(): Message | null;
poll(events: MessageType, timeout: ClockTime): Message | null;
pop(): Message | null;
pop_filtered(types: MessageType): Message | null;
post(message: Message): boolean;
remove_signal_watch(): void;
remove_watch(): boolean;
set_flushing(flushing: boolean): void;
set_sync_handler(func?: BusSyncHandler | null): void;
sync_signal_handler(message: Message, data?: any | null): BusSyncReply;
timed_pop(timeout: ClockTime): Message | null;
timed_pop_filtered(timeout: ClockTime, types: MessageType): Message | null;
vfunc_message(message: Message): void;
vfunc_sync_message(message: Message): void;
}
export module Clock {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
timeout: number;
window_size: number;
windowSize: number;
window_threshold: number;
windowThreshold: number;
}
}
export abstract class Clock extends Object {
static $gtype: GObject.GType<Clock>;
constructor(properties?: Partial<Clock.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Clock.ConstructorProperties>, ...args: any[]): void;
// Properties
timeout: number;
window_size: number;
windowSize: number;
window_threshold: number;
windowThreshold: number;
// Fields
object: Object | any;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(signal: "synced", callback: (_source: this, synced: boolean) => void): number;
connect_after(signal: "synced", callback: (_source: this, synced: boolean) => void): number;
emit(signal: "synced", synced: boolean): void;
// Members
add_observation(slave: ClockTime, master: ClockTime): [boolean, number];
add_observation_unapplied(
slave: ClockTime,
master: ClockTime
): [boolean, number, ClockTime | null, ClockTime | null, ClockTime | null, ClockTime | null];
adjust_unlocked(internal: ClockTime): ClockTime;
adjust_with_calibration(
internal_target: ClockTime,
cinternal: ClockTime,
cexternal: ClockTime,
cnum: ClockTime,
cdenom: ClockTime
): ClockTime;
get_calibration(): [ClockTime | null, ClockTime | null, ClockTime | null, ClockTime | null];
get_internal_time(): ClockTime;
get_master(): Clock | null;
get_resolution(): ClockTime;
get_time(): ClockTime;
get_timeout(): ClockTime;
is_synced(): boolean;
new_periodic_id(start_time: ClockTime, interval: ClockTime): ClockID;
new_single_shot_id(time: ClockTime): ClockID;
periodic_id_reinit(id: ClockID, start_time: ClockTime, interval: ClockTime): boolean;
set_calibration(internal: ClockTime, external: ClockTime, rate_num: ClockTime, rate_denom: ClockTime): void;
set_master(master?: Clock | null): boolean;
set_resolution(resolution: ClockTime): ClockTime;
set_synced(synced: boolean): void;
set_timeout(timeout: ClockTime): void;
single_shot_id_reinit(id: ClockID, time: ClockTime): boolean;
unadjust_unlocked(external: ClockTime): ClockTime;
unadjust_with_calibration(
external_target: ClockTime,
cinternal: ClockTime,
cexternal: ClockTime,
cnum: ClockTime,
cdenom: ClockTime
): ClockTime;
wait_for_sync(timeout: ClockTime): boolean;
vfunc_change_resolution(old_resolution: ClockTime, new_resolution: ClockTime): ClockTime;
vfunc_get_internal_time(): ClockTime;
vfunc_get_resolution(): ClockTime;
vfunc_unschedule(entry: ClockEntry): void;
vfunc_wait(entry: ClockEntry, jitter: ClockTimeDiff): ClockReturn;
vfunc_wait_async(entry: ClockEntry): ClockReturn;
static id_compare_func(id1?: any | null, id2?: any | null): number;
static id_get_clock(id: ClockID): Clock | null;
static id_get_time(id: ClockID): ClockTime;
static id_ref(id: ClockID): ClockID;
static id_unref(id: ClockID): void;
static id_unschedule(id: ClockID): void;
static id_uses_clock(id: ClockID, clock: Clock): boolean;
static id_wait(id: ClockID): [ClockReturn, ClockTimeDiff | null];
static id_wait_async(id: ClockID, func: ClockCallback): ClockReturn;
}
export module ControlBinding {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
name: string;
object: Object | any;
}
}
export abstract class ControlBinding extends Object {
static $gtype: GObject.GType<ControlBinding>;
constructor(properties?: Partial<ControlBinding.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<ControlBinding.ConstructorProperties>, ...args: any[]): void;
// Properties
name: string;
object: Object | any;
// Fields
pspec: GObject.ParamSpec;
// Members
get_g_value_array(timestamp: ClockTime, interval: ClockTime, values: GObject.Value[]): boolean;
get_g_value_array(...args: never[]): never;
get_value(timestamp: ClockTime): GObject.Value | null;
get_value(...args: never[]): never;
is_disabled(): boolean;
set_disabled(disabled: boolean): void;
sync_values(object: Object, timestamp: ClockTime, last_sync: ClockTime): boolean;
sync_values(...args: never[]): never;
vfunc_get_g_value_array(timestamp: ClockTime, interval: ClockTime, values: GObject.Value[]): boolean;
vfunc_get_value(timestamp: ClockTime): GObject.Value | null;
vfunc_sync_values(object: Object, timestamp: ClockTime, last_sync: ClockTime): boolean;
}
export module ControlSource {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
}
}
export abstract class ControlSource extends Object {
static $gtype: GObject.GType<ControlSource>;
constructor(properties?: Partial<ControlSource.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<ControlSource.ConstructorProperties>, ...args: any[]): void;
// Fields
get_value: ControlSourceGetValue | any;
get_value_array: ControlSourceGetValueArray;
// Members
control_source_get_value(timestamp: ClockTime): [boolean, number];
control_source_get_value_array(timestamp: ClockTime, interval: ClockTime, values: number[]): boolean;
}
export module Device {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
caps: Caps;
device_class: string;
deviceClass: string;
display_name: string;
displayName: string;
properties: Structure;
}
}
export abstract class Device extends Object {
static $gtype: GObject.GType<Device>;
constructor(properties?: Partial<Device.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Device.ConstructorProperties>, ...args: any[]): void;
// Properties
caps: Caps;
device_class: string;
deviceClass: string;
display_name: string;
displayName: string;
properties: Structure;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(signal: "removed", callback: (_source: this) => void): number;
connect_after(signal: "removed", callback: (_source: this) => void): number;
emit(signal: "removed"): void;
// Members
create_element(name?: string | null): Element | null;
get_caps(): Caps | null;
get_device_class(): string;
get_display_name(): string;
get_properties(): Structure | null;
has_classes(classes: string): boolean;
has_classesv(classes: string[]): boolean;
reconfigure_element(element: Element): boolean;
vfunc_create_element(name?: string | null): Element | null;
vfunc_reconfigure_element(element: Element): boolean;
}
export module DeviceMonitor {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
}
}
export class DeviceMonitor extends Object {
static $gtype: GObject.GType<DeviceMonitor>;
constructor(properties?: Partial<DeviceMonitor.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<DeviceMonitor.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](): DeviceMonitor;
// Members
add_filter(classes?: string | null, caps?: Caps | null): number;
get_bus(): Bus;
get_devices(): Device[] | null;
get_providers(): string[];
get_show_all_devices(): boolean;
remove_filter(filter_id: number): boolean;
set_show_all_devices(show_all: boolean): void;
start(): boolean;
stop(): void;
}
export module DeviceProvider {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
}
}
export abstract class DeviceProvider extends Object {
static $gtype: GObject.GType<DeviceProvider>;
constructor(properties?: Partial<DeviceProvider.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<DeviceProvider.ConstructorProperties>, ...args: any[]): void;
// Fields
devices: any[];
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(signal: "provider-hidden", callback: (_source: this, object: string) => void): number;
connect_after(signal: "provider-hidden", callback: (_source: this, object: string) => void): number;
emit(signal: "provider-hidden", object: string): void;
connect(signal: "provider-unhidden", callback: (_source: this, object: string) => void): number;
connect_after(signal: "provider-unhidden", callback: (_source: this, object: string) => void): number;
emit(signal: "provider-unhidden", object: string): void;
// Members
can_monitor(): boolean;
device_add(device: Device): void;
device_changed(device: Device, changed_device: Device): void;
device_remove(device: Device): void;
get_bus(): Bus;
get_devices(): Device[];
get_factory(): DeviceProviderFactory | null;
get_hidden_providers(): string[];
get_metadata(key: string): string;
hide_provider(name: string): void;
start(): boolean;
stop(): void;
unhide_provider(name: string): void;
vfunc_start(): boolean;
vfunc_stop(): void;
static register(plugin: Plugin | null, name: string, rank: number, type: GObject.GType): boolean;
}
export module DeviceProviderFactory {
export interface ConstructorProperties extends PluginFeature.ConstructorProperties {
[key: string]: any;
}
}
export class DeviceProviderFactory extends PluginFeature {
static $gtype: GObject.GType<DeviceProviderFactory>;
constructor(properties?: Partial<DeviceProviderFactory.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<DeviceProviderFactory.ConstructorProperties>, ...args: any[]): void;
// Members
get(): DeviceProvider | null;
get_device_provider_type(): GObject.GType;
get_metadata(key: string): string | null;
get_metadata_keys(): string[] | null;
has_classes(classes?: string | null): boolean;
has_classesv(classes?: string[] | null): boolean;
static find(name: string): DeviceProviderFactory | null;
static get_by_name(factoryname: string): DeviceProvider | null;
static list_get_device_providers(minrank: Rank): DeviceProviderFactory[];
}
export module DoubleRange {
export interface ConstructorProperties {
[key: string]: any;
}
}
export class DoubleRange {
static $gtype: GObject.GType<DoubleRange>;
constructor(properties?: Partial<DoubleRange.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<DoubleRange.ConstructorProperties>, ...args: any[]): void;
}
export module DynamicTypeFactory {
export interface ConstructorProperties extends PluginFeature.ConstructorProperties {
[key: string]: any;
}
}
export class DynamicTypeFactory extends PluginFeature {
static $gtype: GObject.GType<DynamicTypeFactory>;
constructor(properties?: Partial<DynamicTypeFactory.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<DynamicTypeFactory.ConstructorProperties>, ...args: any[]): void;
// Members
static load(factoryname: string): GObject.GType;
static load(...args: never[]): never;
}
export module Element {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
}
}
export abstract class Element extends Object {
static $gtype: GObject.GType<Element>;
constructor(properties?: Partial<Element.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Element.ConstructorProperties>, ...args: any[]): void;
// Fields
object: Object | any;
state_lock: GLib.RecMutex;
state_cond: GLib.Cond;
state_cookie: number;
target_state: State;
current_state: State;
next_state: State;
pending_state: State;
last_return: StateChangeReturn;
bus: Bus;
clock: Clock;
base_time: ClockTimeDiff;
start_time: ClockTime;
numpads: number;
pads: Pad[];
numsrcpads: number;
srcpads: Pad[];
numsinkpads: number;
sinkpads: Pad[];
pads_cookie: number;
contexts: Context[];
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(signal: "no-more-pads", callback: (_source: this) => void): number;
connect_after(signal: "no-more-pads", callback: (_source: this) => void): number;
emit(signal: "no-more-pads"): void;
connect(signal: "pad-added", callback: (_source: this, new_pad: Pad) => void): number;
connect_after(signal: "pad-added", callback: (_source: this, new_pad: Pad) => void): number;
emit(signal: "pad-added", new_pad: Pad): void;
connect(signal: "pad-removed", callback: (_source: this, old_pad: Pad) => void): number;
connect_after(signal: "pad-removed", callback: (_source: this, old_pad: Pad) => void): number;
emit(signal: "pad-removed", old_pad: Pad): void;
// Members
abort_state(): void;
add_pad(pad: Pad): boolean;
add_property_deep_notify_watch(property_name: string | null, include_value: boolean): number;
add_property_notify_watch(property_name: string | null, include_value: boolean): number;
call_async(func: ElementCallAsyncFunc): void;
change_state(transition: StateChange): StateChangeReturn;
continue_state(ret: StateChangeReturn): StateChangeReturn;
create_all_pads(): void;
foreach_pad(func: ElementForeachPadFunc): boolean;
foreach_sink_pad(func: ElementForeachPadFunc): boolean;
foreach_src_pad(func: ElementForeachPadFunc): boolean;
get_base_time(): ClockTime;
get_bus(): Bus | null;
get_clock(): Clock | null;
get_compatible_pad(pad: Pad, caps?: Caps | null): Pad | null;
get_compatible_pad_template(compattempl: PadTemplate): PadTemplate | null;
get_context(context_type: string): Context | null;
get_context_unlocked(context_type: string): Context | null;
get_contexts(): Context[];
get_current_clock_time(): ClockTime;
get_current_running_time(): ClockTime;
get_factory(): ElementFactory | null;
get_metadata(key: string): string;
get_pad_template(name: string): PadTemplate | null;
get_pad_template_list(): PadTemplate[];
get_request_pad(name: string): Pad | null;
get_start_time(): ClockTime;
get_state(timeout: ClockTime): [StateChangeReturn, State | null, State | null];
get_static_pad(name: string): Pad | null;
is_locked_state(): boolean;
iterate_pads(): Iterator;
iterate_sink_pads(): Iterator;
iterate_src_pads(): Iterator;
link(dest: Element): boolean;
link_filtered(dest: Element, filter?: Caps | null): boolean;
link_pads(srcpadname: string | null, dest: Element, destpadname?: string | null): boolean;
link_pads_filtered(
srcpadname: string | null,
dest: Element,
destpadname?: string | null,
filter?: Caps | null
): boolean;
link_pads_full(srcpadname: string | null, dest: Element, destpadname: string | null, flags: PadLinkCheck): boolean;
lost_state(): void;
message_full(
type: MessageType,
domain: GLib.Quark,
code: number,
text: string | null,
debug: string | null,
file: string,
_function: string,
line: number
): void;
message_full_with_details(
type: MessageType,
domain: GLib.Quark,
code: number,
text: string | null,
debug: string | null,
file: string,
_function: string,
line: number,
structure: Structure
): void;
no_more_pads(): void;
post_message(message: Message): boolean;
provide_clock(): Clock | null;
query(query: Query): boolean;
query_convert(src_format: Format, src_val: number, dest_format: Format): [boolean, number];
query_duration(format: Format): [boolean, number | null];
query_position(format: Format): [boolean, number | null];
release_request_pad(pad: Pad): void;
remove_pad(pad: Pad): boolean;
remove_property_notify_watch(watch_id: number): void;
request_pad(templ: PadTemplate, name?: string | null, caps?: Caps | null): Pad | null;
seek(
rate: number,
format: Format,
flags: SeekFlags,
start_type: SeekType,
start: number,
stop_type: SeekType,
stop: number
): boolean;
seek_simple(format: Format, seek_flags: SeekFlags, seek_pos: number): boolean;
send_event(event: Event): boolean;
set_base_time(time: ClockTime): void;
set_bus(bus?: Bus | null): void;
set_clock(clock?: Clock | null): boolean;
set_context(context: Context): void;
set_locked_state(locked_state: boolean): boolean;
set_start_time(time: ClockTime): void;
set_state(state: State): StateChangeReturn;
sync_state_with_parent(): boolean;
unlink(dest: Element): void;
unlink_pads(srcpadname: string, dest: Element, destpadname: string): void;
vfunc_change_state(transition: StateChange): StateChangeReturn;
vfunc_get_state(timeout: ClockTime): [StateChangeReturn, State | null, State | null];
vfunc_no_more_pads(): void;
vfunc_pad_added(pad: Pad): void;
vfunc_pad_removed(pad: Pad): void;
vfunc_post_message(message: Message): boolean;
vfunc_provide_clock(): Clock | null;
vfunc_query(query: Query): boolean;
vfunc_release_pad(pad: Pad): void;
vfunc_request_new_pad(templ: PadTemplate, name?: string | null, caps?: Caps | null): Pad | null;
vfunc_send_event(event: Event): boolean;
vfunc_set_bus(bus?: Bus | null): void;
vfunc_set_clock(clock?: Clock | null): boolean;
vfunc_set_context(context: Context): void;
vfunc_set_state(state: State): StateChangeReturn;
vfunc_state_changed(oldstate: State, newstate: State, pending: State): void;
static make_from_uri(type: URIType, uri: string, elementname?: string | null): Element;
static register(plugin: Plugin | null, name: string, rank: number, type: GObject.GType): boolean;
static state_change_return_get_name(state_ret: StateChangeReturn): string;
static state_get_name(state: State): string;
}
export module ElementFactory {
export interface ConstructorProperties extends PluginFeature.ConstructorProperties {
[key: string]: any;
}
}
export class ElementFactory extends PluginFeature {
static $gtype: GObject.GType<ElementFactory>;
constructor(properties?: Partial<ElementFactory.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<ElementFactory.ConstructorProperties>, ...args: any[]): void;
// Members
can_sink_all_caps(caps: Caps): boolean;
can_sink_any_caps(caps: Caps): boolean;
can_src_all_caps(caps: Caps): boolean;
can_src_any_caps(caps: Caps): boolean;
create(name?: string | null): Element | null;
get_element_type(): GObject.GType;
get_metadata(key: string): string | null;
get_metadata_keys(): string[] | null;
get_num_pad_templates(): number;
get_static_pad_templates(): StaticPadTemplate[];
get_uri_protocols(): string[];
get_uri_type(): URIType;
has_interface(interfacename: string): boolean;
list_is_type(type: ElementFactoryListType): boolean;
static find(name: string): ElementFactory | null;
static list_filter(
list: ElementFactory[],
caps: Caps,
direction: PadDirection,
subsetonly: boolean
): ElementFactory[];
static list_get_elements(type: ElementFactoryListType, minrank: Rank): ElementFactory[];
static make(factoryname: string, name?: string | null): Element | null;
}
export module FlagSet {
export interface ConstructorProperties {
[key: string]: any;
}
}
export class FlagSet {
static $gtype: GObject.GType<FlagSet>;
constructor(properties?: Partial<FlagSet.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<FlagSet.ConstructorProperties>, ...args: any[]): void;
// Members
static register(flags_type: GObject.GType): GObject.GType;
}
export module Fraction {
export interface ConstructorProperties {
[key: string]: any;
}
}
export class Fraction {
static $gtype: GObject.GType<Fraction>;
constructor(properties?: Partial<Fraction.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Fraction.ConstructorProperties>, ...args: any[]): void;
}
export module FractionRange {
export interface ConstructorProperties {
[key: string]: any;
}
}
export class FractionRange {
static $gtype: GObject.GType<FractionRange>;
constructor(properties?: Partial<FractionRange.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<FractionRange.ConstructorProperties>, ...args: any[]): void;
}
export module GhostPad {
export interface ConstructorProperties extends ProxyPad.ConstructorProperties {
[key: string]: any;
}
}
export class GhostPad extends ProxyPad {
static $gtype: GObject.GType<GhostPad>;
constructor(properties?: Partial<GhostPad.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<GhostPad.ConstructorProperties>, ...args: any[]): void;
// Fields
pad: ProxyPad | any;
// Constructors
static ["new"](name: string | null, target: Pad): GhostPad;
static ["new"](...args: never[]): never;
static new_from_template(name: string | null, target: Pad, templ: PadTemplate): GhostPad;
static new_from_template(...args: never[]): never;
static new_no_target(name: string | null, dir: PadDirection): GhostPad;
static new_no_target_from_template(name: string | null, templ: PadTemplate): GhostPad;
// Members
construct(): boolean;
get_target(): Pad | null;
set_target(newtarget?: Pad | null): boolean;
static activate_mode_default(pad: Pad, parent: Object | null, mode: PadMode, active: boolean): boolean;
static internal_activate_mode_default(pad: Pad, parent: Object | null, mode: PadMode, active: boolean): boolean;
}
export module Int64Range {
export interface ConstructorProperties {
[key: string]: any;
}
}
export class Int64Range {
static $gtype: GObject.GType<Int64Range>;
constructor(properties?: Partial<Int64Range.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Int64Range.ConstructorProperties>, ...args: any[]): void;
}
export module IntRange {
export interface ConstructorProperties {
[key: string]: any;
}
}
export class IntRange {
static $gtype: GObject.GType<IntRange>;
constructor(properties?: Partial<IntRange.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<IntRange.ConstructorProperties>, ...args: any[]): void;
}
export module Object {
export interface ConstructorProperties extends GObject.InitiallyUnowned.ConstructorProperties {
[key: string]: any;
name: string;
}
}
export abstract class Object extends GObject.InitiallyUnowned {
static $gtype: GObject.GType<Object>;
constructor(properties?: Partial<Object.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Object.ConstructorProperties>, ...args: any[]): void;
// Properties
name: string;
// Fields
object: GObject.InitiallyUnowned;
lock: GLib.Mutex;
flags: number;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(
signal: "deep-notify",
callback: (_source: this, prop_object: Object, prop: GObject.ParamSpec) => void
): number;
connect_after(
signal: "deep-notify",
callback: (_source: this, prop_object: Object, prop: GObject.ParamSpec) => void
): number;
emit(signal: "deep-notify", prop_object: Object, prop: GObject.ParamSpec): void;
// Members
add_control_binding(binding: ControlBinding): boolean;
default_error(error: GLib.Error, debug?: string | null): void;
get_control_binding(property_name: string): ControlBinding | null;
get_control_rate(): ClockTime;
get_g_value_array(
property_name: string,
timestamp: ClockTime,
interval: ClockTime,
values: GObject.Value[]
): boolean;
get_name(): string | null;
get_parent(): Object | null;
get_path_string(): string;
get_value(property_name: string, timestamp: ClockTime): GObject.Value | null;
has_active_control_bindings(): boolean;
has_ancestor(ancestor: Object): boolean;
has_as_ancestor(ancestor: Object): boolean;
has_as_parent(parent: Object): boolean;
ref(): Object;
ref(...args: never[]): never;
remove_control_binding(binding: ControlBinding): boolean;
set_control_binding_disabled(property_name: string, disabled: boolean): void;
set_control_bindings_disabled(disabled: boolean): void;
set_control_rate(control_rate: ClockTime): void;
set_name(name?: string | null): boolean;
set_parent(parent: Object): boolean;
suggest_next_sync(): ClockTime;
sync_values(timestamp: ClockTime): boolean;
unparent(): void;
unref(): void;
vfunc_deep_notify(orig: Object, pspec: GObject.ParamSpec): void;
static check_uniqueness(list: Object[], name: string): boolean;
static default_deep_notify(
object: GObject.Object,
orig: Object,
pspec: GObject.ParamSpec,
excluded_props?: string[] | null
): void;
static replace(oldobj?: Object | null, newobj?: Object | null): [boolean, Object | null];
}
export module Pad {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
caps: Caps;
direction: PadDirection;
offset: number;
template: PadTemplate;
}
}
export class Pad extends Object {
static $gtype: GObject.GType<Pad>;
constructor(properties?: Partial<Pad.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Pad.ConstructorProperties>, ...args: any[]): void;
// Properties
caps: Caps;
direction: PadDirection;
offset: number;
template: PadTemplate;
// Fields
object: Object | any;
element_private: any;
padtemplate: PadTemplate;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(signal: "linked", callback: (_source: this, peer: Pad) => void): number;
connect_after(signal: "linked", callback: (_source: this, peer: Pad) => void): number;
emit(signal: "linked", peer: Pad): void;
connect(signal: "unlinked", callback: (_source: this, peer: Pad) => void): number;
connect_after(signal: "unlinked", callback: (_source: this, peer: Pad) => void): number;
emit(signal: "unlinked", peer: Pad): void;
// Constructors
static ["new"](name: string | null, direction: PadDirection): Pad;
static new_from_static_template(templ: StaticPadTemplate, name: string): Pad;
static new_from_template(templ: PadTemplate, name?: string | null): Pad;
// Members
activate_mode(mode: PadMode, active: boolean): boolean;
add_probe(mask: PadProbeType, callback: PadProbeCallback): number;
can_link(sinkpad: Pad): boolean;
chain(buffer: Buffer): FlowReturn;
chain_list(list: BufferList): FlowReturn;
check_reconfigure(): boolean;
create_stream_id(parent: Element, stream_id?: string | null): string;
event_default(parent: Object | null, event: Event): boolean;
forward(forward: PadForwardFunction): boolean;
get_allowed_caps(): Caps | null;
get_current_caps(): Caps | null;
get_direction(): PadDirection;
get_element_private(): any | null;
get_last_flow_return(): FlowReturn;
get_offset(): number;
get_pad_template(): PadTemplate | null;
get_pad_template_caps(): Caps;
get_parent_element(): Element | null;
get_peer(): Pad | null;
get_range(offset: number, size: number): [FlowReturn, Buffer];
get_single_internal_link(): Pad | null;
get_sticky_event(event_type: EventType, idx: number): Event | null;
get_stream(): Stream | null;
get_stream_id(): string | null;
get_task_state(): TaskState;
has_current_caps(): boolean;
is_active(): boolean;
is_blocked(): boolean;
is_blocking(): boolean;
is_linked(): boolean;
iterate_internal_links(): Iterator | null;
iterate_internal_links_default(parent?: Object | null): Iterator | null;
link(sinkpad: Pad): PadLinkReturn;
link_full(sinkpad: Pad, flags: PadLinkCheck): PadLinkReturn;
link_maybe_ghosting(sink: Pad): boolean;
link_maybe_ghosting_full(sink: Pad, flags: PadLinkCheck): boolean;
mark_reconfigure(): void;
needs_reconfigure(): boolean;
pause_task(): boolean;
peer_query(query: Query): boolean;
peer_query_accept_caps(caps: Caps): boolean;
peer_query_caps(filter?: Caps | null): Caps;
peer_query_convert(src_format: Format, src_val: number, dest_format: Format): [boolean, number];
peer_query_duration(format: Format): [boolean, number | null];
peer_query_position(format: Format): [boolean, number | null];
proxy_query_accept_caps(query: Query): boolean;
proxy_query_caps(query: Query): boolean;
pull_range(offset: number, size: number): [FlowReturn, Buffer];
push(buffer: Buffer): FlowReturn;
push_event(event: Event): boolean;
push_list(list: BufferList): FlowReturn;
query(query: Query): boolean;
query_accept_caps(caps: Caps): boolean;
query_caps(filter?: Caps | null): Caps;
query_convert(src_format: Format, src_val: number, dest_format: Format): [boolean, number];
query_default(parent: Object | null, query: Query): boolean;
query_duration(format: Format): [boolean, number | null];
query_position(format: Format): [boolean, number | null];
remove_probe(id: number): void;
send_event(event: Event): boolean;
set_activate_function_full(activate: PadActivateFunction): void;
set_activatemode_function_full(activatemode: PadActivateModeFunction): void;
set_active(active: boolean): boolean;
set_chain_function_full(chain: PadChainFunction): void;
set_chain_list_function_full(chainlist: PadChainListFunction): void;
set_element_private(priv?: any | null): void;
set_event_full_function_full(event: PadEventFullFunction): void;
set_event_function_full(event: PadEventFunction): void;
set_getrange_function_full(get: PadGetRangeFunction): void;
set_iterate_internal_links_function_full(iterintlink: PadIterIntLinkFunction): void;
set_link_function_full(link: PadLinkFunction): void;
set_offset(offset: number): void;
set_query_function_full(query: PadQueryFunction): void;
set_unlink_function_full(unlink: PadUnlinkFunction): void;
start_task(func: TaskFunction): boolean;
sticky_events_foreach(foreach_func: PadStickyEventsForeachFunction): void;
stop_task(): boolean;
store_sticky_event(event: Event): FlowReturn;
unlink(sinkpad: Pad): boolean;
use_fixed_caps(): void;
vfunc_linked(peer: Pad): void;
vfunc_unlinked(peer: Pad): void;
static link_get_name(ret: PadLinkReturn): string;
}
export module PadTemplate {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
caps: Caps;
direction: PadDirection;
gtype: GObject.GType;
name_template: string;
nameTemplate: string;
presence: PadPresence;
}
}
export class PadTemplate extends Object {
static $gtype: GObject.GType<PadTemplate>;
constructor(properties?: Partial<PadTemplate.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<PadTemplate.ConstructorProperties>, ...args: any[]): void;
// Properties
caps: Caps;
direction: PadDirection;
gtype: GObject.GType;
name_template: string;
nameTemplate: string;
presence: PadPresence;
// Fields
object: Object | any;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(signal: "pad-created", callback: (_source: this, pad: Pad) => void): number;
connect_after(signal: "pad-created", callback: (_source: this, pad: Pad) => void): number;
emit(signal: "pad-created", pad: Pad): void;
// Constructors
static ["new"](name_template: string, direction: PadDirection, presence: PadPresence, caps: Caps): PadTemplate;
static new_from_static_pad_template_with_gtype(
pad_template: StaticPadTemplate,
pad_type: GObject.GType
): PadTemplate;
static new_with_gtype(
name_template: string,
direction: PadDirection,
presence: PadPresence,
caps: Caps,
pad_type: GObject.GType
): PadTemplate;
// Members
get_caps(): Caps;
get_documentation_caps(): Caps;
pad_created(pad: Pad): void;
set_documentation_caps(caps: Caps): void;
vfunc_pad_created(pad: Pad): void;
}
export module ParamArray {
export interface ConstructorProperties extends GObject.ParamSpec.ConstructorProperties {
[key: string]: any;
}
}
export class ParamArray extends GObject.ParamSpec {
static $gtype: GObject.GType<ParamArray>;
constructor(properties?: Partial<ParamArray.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<ParamArray.ConstructorProperties>, ...args: any[]): void;
}
export module ParamFraction {
export interface ConstructorProperties extends GObject.ParamSpec.ConstructorProperties {
[key: string]: any;
}
}
export class ParamFraction extends GObject.ParamSpec {
static $gtype: GObject.GType<ParamFraction>;
constructor(properties?: Partial<ParamFraction.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<ParamFraction.ConstructorProperties>, ...args: any[]): void;
}
export module Pipeline {
export interface ConstructorProperties extends Bin.ConstructorProperties {
[key: string]: any;
auto_flush_bus: boolean;
autoFlushBus: boolean;
delay: number;
latency: number;
}
}
export class Pipeline extends Bin implements ChildProxy {
static $gtype: GObject.GType<Pipeline>;
constructor(properties?: Partial<Pipeline.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Pipeline.ConstructorProperties>, ...args: any[]): void;
// Properties
auto_flush_bus: boolean;
autoFlushBus: boolean;
delay: number;
latency: number;
// Fields
bin: Bin;
fixed_clock: Clock;
stream_time: ClockTime;
// Constructors
static ["new"](name?: string | null): Pipeline;
// Members
auto_clock(): void;
get_auto_flush_bus(): boolean;
get_bus(): Bus;
get_bus(...args: never[]): never;
get_delay(): ClockTime;
get_latency(): ClockTime;
get_pipeline_clock(): Clock;
set_auto_flush_bus(auto_flush: boolean): void;
set_delay(delay: ClockTime): void;
set_latency(latency: ClockTime): void;
use_clock(clock?: Clock | null): void;
// Implemented Members
child_added(child: GObject.Object, name: string): void;
child_removed(child: GObject.Object, name: string): void;
get_child_by_index<T = GObject.Object>(index: number): T;
get_child_by_name<T = GObject.Object>(name: string): T;
get_children_count(): number;
get_property(name: string): unknown;
get_property(...args: never[]): never;
lookup(name: string): [boolean, GObject.Object | null, GObject.ParamSpec | null];
set_property(name: string, value: any): void;
set_property(...args: never[]): never;
vfunc_child_added(child: GObject.Object, name: string): void;
vfunc_child_removed(child: GObject.Object, name: string): void;
vfunc_get_child_by_index<T = GObject.Object>(index: number): T;
vfunc_get_child_by_name<T = GObject.Object>(name: string): T;
vfunc_get_children_count(): number;
}
export module Plugin {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
}
}
export class Plugin extends Object {
static $gtype: GObject.GType<Plugin>;
constructor(properties?: Partial<Plugin.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Plugin.ConstructorProperties>, ...args: any[]): void;
// Members
add_dependency(
env_vars: string[] | null,
paths: string[] | null,
names: string[] | null,
flags: PluginDependencyFlags
): void;
add_dependency_simple(
env_vars: string | null,
paths: string | null,
names: string | null,
flags: PluginDependencyFlags
): void;
get_cache_data(): Structure | null;
get_description(): string;
get_filename(): string | null;
get_license(): string;
get_name(): string;
get_name(...args: never[]): never;
get_origin(): string;
get_package(): string;
get_release_date_string(): string | null;
get_source(): string;
get_version(): string;
is_loaded(): boolean;
load(): Plugin | null;
set_cache_data(cache_data: Structure): void;
static list_free(list: Plugin[]): void;
static load_by_name(name: string): Plugin | null;
static load_file(filename: string): Plugin;
static register_static(
major_version: number,
minor_version: number,
name: string,
description: string,
init_func: PluginInitFunc,
version: string,
license: string,
source: string,
_package: string,
origin: string
): boolean;
static register_static_full(
major_version: number,
minor_version: number,
name: string,
description: string,
init_full_func: PluginInitFullFunc,
version: string,
license: string,
source: string,
_package: string,
origin: string
): boolean;
}
export module PluginFeature {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
}
}
export abstract class PluginFeature extends Object {
static $gtype: GObject.GType<PluginFeature>;
constructor(properties?: Partial<PluginFeature.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<PluginFeature.ConstructorProperties>, ...args: any[]): void;
// Members
check_version(min_major: number, min_minor: number, min_micro: number): boolean;
get_plugin(): Plugin | null;
get_plugin_name(): string | null;
get_rank(): number;
load(): PluginFeature | null;
set_rank(rank: number): void;
static list_copy(list: PluginFeature[]): PluginFeature[];
static list_debug(list: PluginFeature[]): void;
static list_free(list: PluginFeature[]): void;
static rank_compare_func(p1?: any | null, p2?: any | null): number;
}
export module ProxyPad {
export interface ConstructorProperties extends Pad.ConstructorProperties {
[key: string]: any;
}
}
export class ProxyPad extends Pad {
static $gtype: GObject.GType<ProxyPad>;
constructor(properties?: Partial<ProxyPad.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<ProxyPad.ConstructorProperties>, ...args: any[]): void;
// Fields
pad: Pad;
// Members
get_internal(): ProxyPad | null;
static chain_default(pad: Pad, parent: Object | null, buffer: Buffer): FlowReturn;
static chain_list_default(pad: Pad, parent: Object | null, list: BufferList): FlowReturn;
static getrange_default(pad: Pad, parent: Object, offset: number, size: number): [FlowReturn, Buffer];
static iterate_internal_links_default(pad: Pad, parent?: Object | null): Iterator | null;
static iterate_internal_links_default(...args: never[]): never;
}
export module Registry {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
}
}
export class Registry extends Object {
static $gtype: GObject.GType<Registry>;
constructor(properties?: Partial<Registry.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Registry.ConstructorProperties>, ...args: any[]): void;
// Fields
object: Object | any;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(signal: "feature-added", callback: (_source: this, feature: PluginFeature) => void): number;
connect_after(signal: "feature-added", callback: (_source: this, feature: PluginFeature) => void): number;
emit(signal: "feature-added", feature: PluginFeature): void;
connect(signal: "plugin-added", callback: (_source: this, plugin: Plugin) => void): number;
connect_after(signal: "plugin-added", callback: (_source: this, plugin: Plugin) => void): number;
emit(signal: "plugin-added", plugin: Plugin): void;
// Members
add_feature(feature: PluginFeature): boolean;
add_plugin(plugin: Plugin): boolean;
check_feature_version(feature_name: string, min_major: number, min_minor: number, min_micro: number): boolean;
feature_filter(filter: PluginFeatureFilter, first: boolean): PluginFeature[];
find_feature(name: string, type: GObject.GType): PluginFeature | null;
find_plugin(name: string): Plugin | null;
get_feature_list(type: GObject.GType): PluginFeature[];
get_feature_list_by_plugin(name: string): PluginFeature[];
get_feature_list_cookie(): number;
get_plugin_list(): Plugin[];
lookup(filename: string): Plugin | null;
lookup_feature(name: string): PluginFeature | null;
plugin_filter(filter: PluginFilter, first: boolean): Plugin[];
remove_feature(feature: PluginFeature): void;
remove_plugin(plugin: Plugin): void;
scan_path(path: string): boolean;
static fork_is_enabled(): boolean;
static fork_set_enabled(enabled: boolean): void;
static get(): Registry;
}
export module Stream {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
caps: Caps;
stream_flags: StreamFlags;
streamFlags: StreamFlags;
stream_id: string;
streamId: string;
stream_type: StreamType;
streamType: StreamType;
tags: TagList;
}
}
export class Stream extends Object {
static $gtype: GObject.GType<Stream>;
constructor(properties?: Partial<Stream.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Stream.ConstructorProperties>, ...args: any[]): void;
// Properties
caps: Caps;
stream_flags: StreamFlags;
streamFlags: StreamFlags;
stream_id: string;
streamId: string;
stream_type: StreamType;
streamType: StreamType;
tags: TagList;
// Constructors
static ["new"](stream_id: string | null, caps: Caps | null, type: StreamType, flags: StreamFlags): Stream;
// Members
get_caps(): Caps | null;
get_stream_flags(): StreamFlags;
get_stream_id(): string | null;
get_stream_type(): StreamType;
get_tags(): TagList | null;
set_caps(caps?: Caps | null): void;
set_stream_flags(flags: StreamFlags): void;
set_stream_type(stream_type: StreamType): void;
set_tags(tags?: TagList | null): void;
}
export module StreamCollection {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
upstream_id: string;
upstreamId: string;
}
}
export class StreamCollection extends Object {
static $gtype: GObject.GType<StreamCollection>;
constructor(properties?: Partial<StreamCollection.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<StreamCollection.ConstructorProperties>, ...args: any[]): void;
// Properties
upstream_id: string;
upstreamId: string;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(signal: "stream-notify", callback: (_source: this, object: Stream, p0: GObject.ParamSpec) => void): number;
connect_after(
signal: "stream-notify",
callback: (_source: this, object: Stream, p0: GObject.ParamSpec) => void
): number;
emit(signal: "stream-notify", object: Stream, p0: GObject.ParamSpec): void;
// Constructors
static ["new"](upstream_id?: string | null): StreamCollection;
// Members
add_stream(stream: Stream): boolean;
get_size(): number;
get_stream(index: number): Stream | null;
get_upstream_id(): string | null;
vfunc_stream_notify(stream: Stream, pspec: GObject.ParamSpec): void;
}
export module SystemClock {
export interface ConstructorProperties extends Clock.ConstructorProperties {
[key: string]: any;
clock_type: ClockType;
clockType: ClockType;
}
}
export class SystemClock extends Clock {
static $gtype: GObject.GType<SystemClock>;
constructor(properties?: Partial<SystemClock.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<SystemClock.ConstructorProperties>, ...args: any[]): void;
// Properties
clock_type: ClockType;
clockType: ClockType;
// Fields
clock: Clock;
// Members
static obtain(): Clock;
static set_default(new_clock?: Clock | null): void;
}
export module Task {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
}
}
export class Task extends Object {
static $gtype: GObject.GType<Task>;
constructor(properties?: Partial<Task.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Task.ConstructorProperties>, ...args: any[]): void;
// Fields
object: Object | any;
state: TaskState;
cond: GLib.Cond;
lock: GLib.RecMutex | any;
func: TaskFunction;
user_data: any;
notify: GLib.DestroyNotify | any;
running: boolean;
// Constructors
static ["new"](func: TaskFunction): Task;
// Members
get_pool(): TaskPool;
get_state(): TaskState;
join(): boolean;
pause(): boolean;
resume(): boolean;
set_enter_callback(enter_func: TaskThreadFunc): void;
set_leave_callback(leave_func: TaskThreadFunc): void;
set_lock(mutex: GLib.RecMutex): void;
set_pool(pool: TaskPool): void;
set_state(state: TaskState): boolean;
start(): boolean;
stop(): boolean;
static cleanup_all(): void;
}
export module TaskPool {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
}
}
export class TaskPool extends Object {
static $gtype: GObject.GType<TaskPool>;
constructor(properties?: Partial<TaskPool.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<TaskPool.ConstructorProperties>, ...args: any[]): void;
// Fields
object: Object | any;
// Constructors
static ["new"](): TaskPool;
// Members
cleanup(): void;
join(id?: any | null): void;
prepare(): void;
push(func: TaskPoolFunction): any | null;
vfunc_cleanup(): void;
vfunc_join(id?: any | null): void;
vfunc_prepare(): void;
vfunc_push(func: TaskPoolFunction): any | null;
}
export module Tracer {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
params: string;
}
}
export abstract class Tracer extends Object {
static $gtype: GObject.GType<Tracer>;
constructor(properties?: Partial<Tracer.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Tracer.ConstructorProperties>, ...args: any[]): void;
// Properties
params: string;
// Members
static register(plugin: Plugin | null, name: string, type: GObject.GType): boolean;
}
export module TracerFactory {
export interface ConstructorProperties extends PluginFeature.ConstructorProperties {
[key: string]: any;
}
}
export class TracerFactory extends PluginFeature {
static $gtype: GObject.GType<TracerFactory>;
constructor(properties?: Partial<TracerFactory.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<TracerFactory.ConstructorProperties>, ...args: any[]): void;
// Members
get_tracer_type(): GObject.GType;
static get_list(): TracerFactory[];
}
export module TracerRecord {
export interface ConstructorProperties extends Object.ConstructorProperties {
[key: string]: any;
}
}
export class TracerRecord extends Object {
static $gtype: GObject.GType<TracerRecord>;
constructor(properties?: Partial<TracerRecord.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<TracerRecord.ConstructorProperties>, ...args: any[]): void;
}
export module TypeFindFactory {
export interface ConstructorProperties extends PluginFeature.ConstructorProperties {
[key: string]: any;
}
}
export class TypeFindFactory extends PluginFeature {
static $gtype: GObject.GType<TypeFindFactory>;
constructor(properties?: Partial<TypeFindFactory.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<TypeFindFactory.ConstructorProperties>, ...args: any[]): void;
// Members
call_function(find: TypeFind): void;
get_caps(): Caps | null;
get_extensions(): string[] | null;
has_function(): boolean;
static get_list(): TypeFindFactory[];
}
export module ValueArray {
export interface ConstructorProperties {
[key: string]: any;
}
}
export class ValueArray {
static $gtype: GObject.GType<ValueArray>;
constructor(properties?: Partial<ValueArray.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<ValueArray.ConstructorProperties>, ...args: any[]): void;
// Members
static append_and_take_value(value: any, append_value: any): void;
static append_value(value: any, append_value: any): void;
static get_size(value: any): number;
static get_value(value: any, index: number): unknown;
static init(value: any, prealloc: number): unknown;
static prepend_value(value: any, prepend_value: any): void;
}
export module ValueList {
export interface ConstructorProperties {
[key: string]: any;
}
}
export class ValueList {
static $gtype: GObject.GType<ValueList>;
constructor(properties?: Partial<ValueList.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<ValueList.ConstructorProperties>, ...args: any[]): void;
// Members
static append_and_take_value(value: any, append_value: any): void;
static append_value(value: any, append_value: any): void;
static concat(value1: any, value2: any): unknown;
static get_size(value: any): number;
static get_value(value: any, index: number): unknown;
static init(value: any, prealloc: number): unknown;
static merge(value1: any, value2: any): unknown;
static prepend_value(value: any, prepend_value: any): void;
}
export class AllocationParams {
static $gtype: GObject.GType<AllocationParams>;
constructor(copy: AllocationParams);
// Fields
flags: MemoryFlags;
align: number;
prefix: number;
padding: number;
// Members
copy(): AllocationParams | null;
free(): void;
init(): void;
}
export class AllocatorPrivate {
static $gtype: GObject.GType<AllocatorPrivate>;
constructor(copy: AllocatorPrivate);
}
export class AtomicQueue {
static $gtype: GObject.GType<AtomicQueue>;
constructor(initial_size: number);
constructor(copy: AtomicQueue);
// Constructors
static ["new"](initial_size: number): AtomicQueue;
// Members
length(): number;
peek(): any | null;
pop(): any | null;
push(data?: any | null): void;
ref(): void;
unref(): void;
}
export class BinPrivate {
static $gtype: GObject.GType<BinPrivate>;
constructor(copy: BinPrivate);
}
export class Buffer {
static $gtype: GObject.GType<Buffer>;
constructor();
constructor(copy: Buffer);
// Fields
mini_object: MiniObject;
pool: BufferPool;
pts: ClockTime;
dts: ClockTime;
duration: ClockTime;
offset: number;
offset_end: number;
// Constructors
static ["new"](): Buffer;
static new_allocate(allocator: Allocator | null, size: number, params?: AllocationParams | null): Buffer;
static new_wrapped(data: Uint8Array | string): Buffer;
static new_wrapped_bytes(bytes: GLib.Bytes | Uint8Array): Buffer;
static new_wrapped_full(
flags: MemoryFlags,
data: Uint8Array | string,
maxsize: number,
offset: number,
notify?: GLib.DestroyNotify | null
): Buffer;
// Members
add_meta(info: MetaInfo, params?: any | null): Meta | null;
add_parent_buffer_meta(ref: Buffer): ParentBufferMeta | null;
add_protection_meta(info: Structure): ProtectionMeta;
add_reference_timestamp_meta(
reference: Caps,
timestamp: ClockTime,
duration: ClockTime
): ReferenceTimestampMeta | null;
append(buf2: Buffer): Buffer;
append_memory(mem: Memory): void;
append_region(buf2: Buffer, offset: number, size: number): Buffer;
copy_deep(): Buffer;
copy_into(src: Buffer, flags: BufferCopyFlags, offset: number, size: number): boolean;
copy_region(flags: BufferCopyFlags, offset: number, size: number): Buffer;
extract(offset: number): [number, Uint8Array];
extract_dup(offset: number, size: number): Uint8Array;
fill(offset: number, src: Uint8Array | string): number;
find_memory(offset: number, size: number): [boolean, number, number, number];
foreach_meta(func: BufferForeachMetaFunc): boolean;
get_all_memory(): Memory | null;
get_flags(): BufferFlags;
get_memory(idx: number): Memory | null;
get_memory_range(idx: number, length: number): Memory | null;
get_meta(api: GObject.GType): Meta | null;
get_n_meta(api_type: GObject.GType): number;
get_reference_timestamp_meta(reference?: Caps | null): ReferenceTimestampMeta | null;
get_size(): number;
get_sizes(): [number, number | null, number | null];
get_sizes_range(idx: number, length: number): [number, number | null, number | null];
has_flags(flags: BufferFlags): boolean;
insert_memory(idx: number, mem: Memory): void;
is_all_memory_writable(): boolean;
is_memory_range_writable(idx: number, length: number): boolean;
map(flags: MapFlags): [boolean, MapInfo];
map_range(idx: number, length: number, flags: MapFlags): [boolean, MapInfo];
memcmp(offset: number, mem: Uint8Array | string): number;
memset(offset: number, val: number, size: number): number;
n_memory(): number;
peek_memory(idx: number): Memory | null;
prepend_memory(mem: Memory): void;
remove_all_memory(): void;
remove_memory(idx: number): void;
remove_memory_range(idx: number, length: number): void;
remove_meta(meta: Meta): boolean;
replace_all_memory(mem: Memory): void;
replace_memory(idx: number, mem: Memory): void;
replace_memory_range(idx: number, length: number, mem: Memory): void;
resize(offset: number, size: number): void;
resize_range(idx: number, length: number, offset: number, size: number): boolean;
set_flags(flags: BufferFlags): boolean;
set_size(size: number): void;
unmap(info: MapInfo): void;
unset_flags(flags: BufferFlags): boolean;
static get_max_memory(): number;
}
export class BufferList {
static $gtype: GObject.GType<BufferList>;
constructor();
constructor(copy: BufferList);
// Constructors
static ["new"](): BufferList;
static new_sized(size: number): BufferList;
// Members
calculate_size(): number;
copy_deep(): BufferList;
foreach(func: BufferListFunc): boolean;
get(idx: number): Buffer | null;
get_writable(idx: number): Buffer | null;
insert(idx: number, buffer: Buffer): void;
length(): number;
remove(idx: number, length: number): void;
}
export class BufferPoolAcquireParams {
static $gtype: GObject.GType<BufferPoolAcquireParams>;
constructor(copy: BufferPoolAcquireParams);
// Fields
format: Format;
start: number;
stop: number;
flags: BufferPoolAcquireFlags;
}
export class BufferPoolPrivate {
static $gtype: GObject.GType<BufferPoolPrivate>;
constructor(copy: BufferPoolPrivate);
}
export class BusPrivate {
static $gtype: GObject.GType<BusPrivate>;
constructor(copy: BusPrivate);
}
export class Caps {
static $gtype: GObject.GType<Caps>;
constructor();
constructor(copy: Caps);
// Fields
mini_object: MiniObject;
// Constructors
static new_any(): Caps;
static new_empty(): Caps;
static new_empty_simple(media_type: string): Caps;
// Members
append(caps2: Caps): void;
append_structure(structure: Structure): void;
append_structure_full(structure: Structure, features?: CapsFeatures | null): void;
can_intersect(caps2: Caps): boolean;
copy(): Caps;
copy_nth(nth: number): Caps;
filter_and_map_in_place(func: CapsFilterMapFunc): void;
fixate(): Caps;
foreach(func: CapsForeachFunc): boolean;
get_features(index: number): CapsFeatures | null;
get_size(): number;
get_structure(index: number): Structure;
intersect(caps2: Caps): Caps;
intersect_full(caps2: Caps, mode: CapsIntersectMode): Caps;
is_always_compatible(caps2: Caps): boolean;
is_any(): boolean;
is_empty(): boolean;
is_equal(caps2: Caps): boolean;
is_equal_fixed(caps2: Caps): boolean;
is_fixed(): boolean;
is_strictly_equal(caps2: Caps): boolean;
is_subset(superset: Caps): boolean;
is_subset_structure(structure: Structure): boolean;
is_subset_structure_full(structure: Structure, features?: CapsFeatures | null): boolean;
map_in_place(func: CapsMapFunc): boolean;
merge(caps2: Caps): Caps;
merge_structure(structure: Structure): Caps;
merge_structure_full(structure: Structure, features?: CapsFeatures | null): Caps;
normalize(): Caps;
remove_structure(idx: number): void;
set_features(index: number, features?: CapsFeatures | null): void;
set_features_simple(features?: CapsFeatures | null): void;
set_value(field: string, value: any): void;
simplify(): Caps;
steal_structure(index: number): Structure | null;
subtract(subtrahend: Caps): Caps;
to_string(): string;
truncate(): Caps;
static from_string(string: string): Caps | null;
}
export class CapsFeatures {
static $gtype: GObject.GType<CapsFeatures>;
constructor();
constructor(copy: CapsFeatures);
// Constructors
static new_any(): CapsFeatures;
static new_empty(): CapsFeatures;
// Members
add(feature: string): void;
add_id(feature: GLib.Quark): void;
contains(feature: string): boolean;
contains_id(feature: GLib.Quark): boolean;
copy(): CapsFeatures;
free(): void;
get_nth(i: number): string | null;
get_nth_id(i: number): GLib.Quark;
get_size(): number;
is_any(): boolean;
is_equal(features2: CapsFeatures): boolean;
remove(feature: string): void;
remove_id(feature: GLib.Quark): void;
set_parent_refcount(refcount: number): boolean;
to_string(): string;
static from_string(features: string): CapsFeatures | null;
}
export class ClockEntry {
static $gtype: GObject.GType<ClockEntry>;
constructor(copy: ClockEntry);
// Fields
refcount: number;
clock: Clock;
type: ClockEntryType;
time: ClockTime;
interval: ClockTime;
status: ClockReturn;
func: ClockCallback;
user_data: any;
destroy_data: GLib.DestroyNotify;
unscheduled: boolean;
woken_up: boolean;
}
export class ClockPrivate {
static $gtype: GObject.GType<ClockPrivate>;
constructor(copy: ClockPrivate);
}
export class Context {
static $gtype: GObject.GType<Context>;
constructor(context_type: string, persistent: boolean);
constructor(copy: Context);
// Constructors
static ["new"](context_type: string, persistent: boolean): Context;
// Members
get_context_type(): string;
get_structure(): Structure;
has_context_type(context_type: string): boolean;
is_persistent(): boolean;
writable_structure(): Structure;
}
export class ControlBindingPrivate {
static $gtype: GObject.GType<ControlBindingPrivate>;
constructor(copy: ControlBindingPrivate);
}
export class DateTime {
static $gtype: GObject.GType<DateTime>;
constructor(
tzoffset: number,
year: number,
month: number,
day: number,
hour: number,
minute: number,
seconds: number
);
constructor(copy: DateTime);
// Constructors
static ["new"](
tzoffset: number,
year: number,
month: number,
day: number,
hour: number,
minute: number,
seconds: number
): DateTime;
static new_from_g_date_time(dt: GLib.DateTime): DateTime;
static new_from_iso8601_string(string: string): DateTime;
static new_from_unix_epoch_local_time(secs: number): DateTime;
static new_from_unix_epoch_local_time_usecs(usecs: number): DateTime;
static new_from_unix_epoch_utc(secs: number): DateTime;
static new_from_unix_epoch_utc_usecs(usecs: number): DateTime;
static new_local_time(
year: number,
month: number,
day: number,
hour: number,
minute: number,
seconds: number
): DateTime;
static new_now_local_time(): DateTime;
static new_now_utc(): DateTime;
static new_y(year: number): DateTime;
static new_ym(year: number, month: number): DateTime;
static new_ymd(year: number, month: number, day: number): DateTime;
// Members
get_day(): number;
get_hour(): number;
get_microsecond(): number;
get_minute(): number;
get_month(): number;
get_second(): number;
get_time_zone_offset(): number;
get_year(): number;
has_day(): boolean;
has_month(): boolean;
has_second(): boolean;
has_time(): boolean;
has_year(): boolean;
ref(): DateTime;
to_g_date_time(): GLib.DateTime | null;
to_iso8601_string(): string | null;
unref(): void;
}
export class DebugCategory {
static $gtype: GObject.GType<DebugCategory>;
constructor(
properties?: Partial<{
threshold?: number;
color?: number;
name?: string;
description?: string;
}>
);
constructor(copy: DebugCategory);
// Fields
threshold: number;
color: number;
name: string;
description: string;
// Members
free(): void;
get_color(): number;
get_description(): string;
get_name(): string;
get_threshold(): DebugLevel;
reset_threshold(): void;
set_threshold(level: DebugLevel): void;
}
export class DebugMessage {
static $gtype: GObject.GType<DebugMessage>;
constructor(copy: DebugMessage);
// Members
get(): string | null;
}
export class DeviceMonitorPrivate {
static $gtype: GObject.GType<DeviceMonitorPrivate>;
constructor(copy: DeviceMonitorPrivate);
}
export class DevicePrivate {
static $gtype: GObject.GType<DevicePrivate>;
constructor(copy: DevicePrivate);
}
export class DeviceProviderPrivate {
static $gtype: GObject.GType<DeviceProviderPrivate>;
constructor(copy: DeviceProviderPrivate);
}
export class Event {
static $gtype: GObject.GType<Event>;
constructor(format: Format, minsize: number, maxsize: number, async: boolean);
constructor(copy: Event);
// Fields
mini_object: MiniObject;
type: EventType;
timestamp: number;
seqnum: number;
// Constructors
static new_buffer_size(format: Format, minsize: number, maxsize: number, async: boolean): Event;
static new_caps(caps: Caps): Event;
static new_custom(type: EventType, structure: Structure): Event;
static new_eos(): Event;
static new_flush_start(): Event;
static new_flush_stop(reset_time: boolean): Event;
static new_gap(timestamp: ClockTime, duration: ClockTime): Event;
static new_instant_rate_change(rate_multiplier: number, new_flags: SegmentFlags): Event;
static new_instant_rate_sync_time(
rate_multiplier: number,
running_time: ClockTime,
upstream_running_time: ClockTime
): Event;
static new_latency(latency: ClockTime): Event;
static new_navigation(structure: Structure): Event;
static new_protection(system_id: string, data: Buffer, origin: string): Event;
static new_qos(type: QOSType, proportion: number, diff: ClockTimeDiff, timestamp: ClockTime): Event;
static new_reconfigure(): Event;
static new_seek(
rate: number,
format: Format,
flags: SeekFlags,
start_type: SeekType,
start: number,
stop_type: SeekType,
stop: number
): Event;
static new_segment(segment: Segment): Event;
static new_segment_done(format: Format, position: number): Event;
static new_select_streams(streams: string[]): Event;
static new_sink_message(name: string, msg: Message): Event;
static new_step(format: Format, amount: number, rate: number, flush: boolean, intermediate: boolean): Event;
static new_stream_collection(collection: StreamCollection): Event;
static new_stream_group_done(group_id: number): Event;
static new_stream_start(stream_id: string): Event;
static new_tag(taglist: TagList): Event;
static new_toc(toc: Toc, updated: boolean): Event;
static new_toc_select(uid: string): Event;
// Members
copy_segment(segment: Segment): void;
get_running_time_offset(): number;
get_seqnum(): number;
get_structure(): Structure | null;
has_name(name: string): boolean;
has_name_id(name: GLib.Quark): boolean;
parse_buffer_size(): [Format, number, number, boolean];
parse_caps(): Caps;
parse_flush_stop(): boolean;
parse_gap(): [ClockTime | null, ClockTime | null];
parse_group_id(): [boolean, number];
parse_instant_rate_change(): [number | null, SegmentFlags | null];
parse_instant_rate_sync_time(): [number | null, ClockTime | null, ClockTime | null];
parse_latency(): ClockTime;
parse_protection(): [string | null, Buffer | null, string | null];
parse_qos(): [QOSType, number, ClockTimeDiff, ClockTime];
parse_seek(): [number, Format, SeekFlags, SeekType, number, SeekType, number];
parse_seek_trickmode_interval(): ClockTime;
parse_segment(): Segment;
parse_segment_done(): [Format | null, number | null];
parse_select_streams(): string[];
parse_sink_message(): Message;
parse_step(): [Format | null, number | null, number | null, boolean | null, boolean | null];
parse_stream(): Stream;
parse_stream_collection(): StreamCollection;
parse_stream_flags(): StreamFlags;
parse_stream_group_done(): number;
parse_stream_start(): string;
parse_tag(): TagList;
parse_toc(): [Toc, boolean];
parse_toc_select(): string | null;
set_group_id(group_id: number): void;
set_running_time_offset(offset: number): void;
set_seek_trickmode_interval(interval: ClockTime): void;
set_seqnum(seqnum: number): void;
set_stream(stream: Stream): void;
set_stream_flags(flags: StreamFlags): void;
writable_structure(): Structure;
}
export class FormatDefinition {
static $gtype: GObject.GType<FormatDefinition>;
constructor(copy: FormatDefinition);
// Fields
value: Format;
nick: string;
description: string;
quark: GLib.Quark;
}
export class GhostPadPrivate {
static $gtype: GObject.GType<GhostPadPrivate>;
constructor(copy: GhostPadPrivate);
}
export class Iterator {
static $gtype: GObject.GType<Iterator>;
constructor(type: GObject.GType, object: any);
constructor(copy: Iterator);
// Fields
item: IteratorItemFunction;
pushed: Iterator;
type: GObject.GType;
lock: GLib.Mutex;
cookie: number;
master_cookie: number;
size: number;
// Constructors
static new_single(type: GObject.GType, object: any): Iterator;
// Members
copy(): Iterator;
filter(func: GLib.CompareFunc, user_data: any): Iterator;
find_custom(func: GLib.CompareFunc): [boolean, unknown];
fold(func: IteratorFoldFunction, ret: any): IteratorResult;
foreach(func: IteratorForeachFunction): IteratorResult;
free(): void;
next(): [IteratorResult, unknown];
push(other: Iterator): void;
resync(): void;
}
export class MapInfo {
static $gtype: GObject.GType<MapInfo>;
constructor(copy: MapInfo);
// Fields
memory: Memory;
flags: MapFlags;
data: Uint8Array;
size: number;
maxsize: number;
user_data: any[];
}
export class Memory {
static $gtype: GObject.GType<Memory>;
constructor(
flags: MemoryFlags,
data: Uint8Array | string,
maxsize: number,
offset: number,
notify?: GLib.DestroyNotify | null
);
constructor(copy: Memory);
// Fields
mini_object: MiniObject;
allocator: Allocator;
maxsize: number;
align: number;
offset: number;
size: number;
// Constructors
static new_wrapped(
flags: MemoryFlags,
data: Uint8Array | string,
maxsize: number,
offset: number,
notify?: GLib.DestroyNotify | null
): Memory;
// Members
copy(offset: number, size: number): Memory;
get_sizes(): [number, number | null, number | null];
is_span(mem2: Memory): [boolean, number];
is_type(mem_type: string): boolean;
make_mapped(flags: MapFlags): [Memory | null, MapInfo];
map(flags: MapFlags): [boolean, MapInfo];
resize(offset: number, size: number): void;
share(offset: number, size: number): Memory;
unmap(info: MapInfo): void;
}
export class Message {
static $gtype: GObject.GType<Message>;
constructor(src: Object | null, structure: Structure);
constructor(copy: Message);
// Fields
mini_object: MiniObject;
type: MessageType;
timestamp: number;
src: Object;
seqnum: number;
lock: GLib.Mutex;
cond: GLib.Cond;
// Constructors
static new_application(src: Object | null, structure: Structure): Message;
static new_async_done(src: Object | null, running_time: ClockTime): Message;
static new_async_start(src?: Object | null): Message;
static new_buffering(src: Object | null, percent: number): Message;
static new_clock_lost(src: Object | null, clock: Clock): Message;
static new_clock_provide(src: Object | null, clock: Clock, ready: boolean): Message;
static new_custom(type: MessageType, src?: Object | null, structure?: Structure | null): Message;
static new_device_added(src: Object, device: Device): Message;
static new_device_changed(src: Object, device: Device, changed_device: Device): Message;
static new_device_removed(src: Object, device: Device): Message;
static new_duration_changed(src?: Object | null): Message;
static new_element(src: Object | null, structure: Structure): Message;
static new_eos(src?: Object | null): Message;
static new_error(src: Object | null, error: GLib.Error, debug: string): Message;
static new_error_with_details(
src: Object | null,
error: GLib.Error,
debug: string,
details?: Structure | null
): Message;
static new_have_context(src: Object | null, context: Context): Message;
static new_info(src: Object | null, error: GLib.Error, debug: string): Message;
static new_info_with_details(
src: Object | null,
error: GLib.Error,
debug: string,
details?: Structure | null
): Message;
static new_instant_rate_request(src: Object, rate_multiplier: number): Message;
static new_latency(src?: Object | null): Message;
static new_need_context(src: Object | null, context_type: string): Message;
static new_new_clock(src: Object | null, clock: Clock): Message;
static new_progress(src: Object, type: ProgressType, code: string, text: string): Message;
static new_property_notify(src: Object, property_name: string, val?: GObject.Value | null): Message;
static new_qos(
src: Object,
live: boolean,
running_time: number,
stream_time: number,
timestamp: number,
duration: number
): Message;
static new_redirect(
src: Object,
location: string,
tag_list?: TagList | null,
entry_struct?: Structure | null
): Message;
static new_request_state(src: Object | null, state: State): Message;
static new_reset_time(src: Object | null, running_time: ClockTime): Message;
static new_segment_done(src: Object | null, format: Format, position: number): Message;
static new_segment_start(src: Object | null, format: Format, position: number): Message;
static new_state_changed(src: Object | null, oldstate: State, newstate: State, pending: State): Message;
static new_state_dirty(src?: Object | null): Message;
static new_step_done(
src: Object,
format: Format,
amount: number,
rate: number,
flush: boolean,
intermediate: boolean,
duration: number,
eos: boolean
): Message;
static new_step_start(
src: Object,
active: boolean,
format: Format,
amount: number,
rate: number,
flush: boolean,
intermediate: boolean
): Message;
static new_stream_collection(src: Object, collection: StreamCollection): Message;
static new_stream_start(src?: Object | null): Message;
static new_stream_status(src: Object, type: StreamStatusType, owner: Element): Message;
static new_streams_selected(src: Object, collection: StreamCollection): Message;
static new_structure_change(src: Object | null, type: StructureChangeType, owner: Element, busy: boolean): Message;
static new_tag(src: Object | null, tag_list: TagList): Message;
static new_toc(src: Object, toc: Toc, updated: boolean): Message;
static new_warning(src: Object | null, error: GLib.Error, debug: string): Message;
static new_warning_with_details(
src: Object | null,
error: GLib.Error,
debug: string,
details?: Structure | null
): Message;
// Members
add_redirect_entry(location: string, tag_list?: TagList | null, entry_struct?: Structure | null): void;
get_num_redirect_entries(): number;
get_seqnum(): number;
get_stream_status_object(): GObject.Value | null;
get_structure(): Structure | null;
has_name(name: string): boolean;
parse_async_done(): ClockTime | null;
parse_buffering(): number | null;
parse_buffering_stats(): [BufferingMode | null, number | null, number | null, number | null];
parse_clock_lost(): Clock | null;
parse_clock_provide(): [Clock | null, boolean | null];
parse_context_type(): [boolean, string | null];
parse_device_added(): Device | null;
parse_device_changed(): [Device | null, Device | null];
parse_device_removed(): Device | null;
parse_error(): [GLib.Error | null, string | null];
parse_error_details(): Structure;
parse_group_id(): [boolean, number | null];
parse_have_context(): Context | null;
parse_info(): [GLib.Error | null, string | null];
parse_info_details(): Structure;
parse_instant_rate_request(): number | null;
parse_new_clock(): Clock | null;
parse_progress(): [ProgressType | null, string | null, string | null];
parse_property_notify(): [Object | null, string | null, GObject.Value | null];
parse_qos(): [boolean | null, number | null, number | null, number | null, number | null];
parse_qos_stats(): [Format | null, number | null, number | null];
parse_qos_values(): [number | null, number | null, number | null];
parse_redirect_entry(entry_index: number): [string | null, TagList | null, Structure | null];
parse_request_state(): State | null;
parse_reset_time(): ClockTime | null;
parse_segment_done(): [Format | null, number | null];
parse_segment_start(): [Format | null, number | null];
parse_state_changed(): [State | null, State | null, State | null];
parse_step_done(): [
Format | null,
number | null,
number | null,
boolean | null,
boolean | null,
number | null,
boolean | null
];
parse_step_start(): [boolean | null, Format | null, number | null, number | null, boolean | null, boolean | null];
parse_stream_collection(): StreamCollection | null;
parse_stream_status(): [StreamStatusType, Element];
parse_streams_selected(): StreamCollection | null;
parse_structure_change(): [StructureChangeType, Element | null, boolean | null];
parse_tag(): TagList;
parse_toc(): [Toc, boolean];
parse_warning(): [GLib.Error | null, string | null];
parse_warning_details(): Structure;
set_buffering_stats(mode: BufferingMode, avg_in: number, avg_out: number, buffering_left: number): void;
set_group_id(group_id: number): void;
set_qos_stats(format: Format, processed: number, dropped: number): void;
set_qos_values(jitter: number, proportion: number, quality: number): void;
set_seqnum(seqnum: number): void;
set_stream_status_object(object: any): void;
streams_selected_add(stream: Stream): void;
streams_selected_get_size(): number;
streams_selected_get_stream(idx: number): Stream | null;
writable_structure(): Structure;
}
export class Meta {
static $gtype: GObject.GType<Meta>;
constructor(copy: Meta);
// Fields
flags: MetaFlags;
info: MetaInfo;
// Members
compare_seqnum(meta2: Meta): number;
get_seqnum(): number;
static api_type_get_tags(api: GObject.GType): string[];
static api_type_has_tag(api: GObject.GType, tag: GLib.Quark): boolean;
static api_type_register(api: string, tags: string[]): GObject.GType;
static get_info(impl: string): MetaInfo | null;
static register(
api: GObject.GType,
impl: string,
size: number,
init_func: MetaInitFunction,
free_func: MetaFreeFunction,
transform_func: MetaTransformFunction
): MetaInfo | null;
}
export class MetaInfo {
static $gtype: GObject.GType<MetaInfo>;
constructor(copy: MetaInfo);
// Fields
api: GObject.GType;
type: GObject.GType;
size: number;
init_func: MetaInitFunction;
free_func: MetaFreeFunction;
transform_func: MetaTransformFunction;
}
export class MetaTransformCopy {
static $gtype: GObject.GType<MetaTransformCopy>;
constructor(
properties?: Partial<{
region?: boolean;
offset?: number;
size?: number;
}>
);
constructor(copy: MetaTransformCopy);
// Fields
region: boolean;
offset: number;
size: number;
}
export class MiniObject {
static $gtype: GObject.GType<MiniObject>;
constructor(copy: MiniObject);
// Fields
type: GObject.GType;
refcount: number;
lockstate: number;
flags: number;
dispose: MiniObjectDisposeFunction;
free: MiniObjectFreeFunction;
priv_uint: number;
priv_pointer: any;
// Members
add_parent(parent: MiniObject): void;
get_qdata(quark: GLib.Quark): any | null;
is_writable(): boolean;
lock(flags: LockFlags): boolean;
remove_parent(parent: MiniObject): void;
set_qdata(quark: GLib.Quark, data?: any | null): void;
steal_qdata(quark: GLib.Quark): any | null;
unlock(flags: LockFlags): void;
static replace(olddata?: MiniObject | null, newdata?: MiniObject | null): [boolean, MiniObject | null];
static take(olddata: MiniObject, newdata: MiniObject): [boolean, MiniObject];
}
export class PadPrivate {
static $gtype: GObject.GType<PadPrivate>;
constructor(copy: PadPrivate);
}
export class PadProbeInfo {
static $gtype: GObject.GType<PadProbeInfo>;
constructor(copy: PadProbeInfo);
// Fields
type: PadProbeType;
id: number;
data: any;
offset: number;
size: number;
// Members
get_buffer(): Buffer | null;
get_buffer_list(): BufferList | null;
get_event(): Event | null;
get_query(): Query | null;
}
export class ParamSpecArray {
static $gtype: GObject.GType<ParamSpecArray>;
constructor(copy: ParamSpecArray);
// Fields
element_spec: GObject.ParamSpec;
}
export class ParamSpecFraction {
static $gtype: GObject.GType<ParamSpecFraction>;
constructor(
properties?: Partial<{
min_num?: number;
min_den?: number;
max_num?: number;
max_den?: number;
def_num?: number;
def_den?: number;
}>
);
constructor(copy: ParamSpecFraction);
// Fields
min_num: number;
min_den: number;
max_num: number;
max_den: number;
def_num: number;
def_den: number;
}
export class ParentBufferMeta {
static $gtype: GObject.GType<ParentBufferMeta>;
constructor(copy: ParentBufferMeta);
// Fields
buffer: Buffer;
// Members
static get_info(): MetaInfo;
}
export class ParseContext {
static $gtype: GObject.GType<ParseContext>;
constructor();
constructor(copy: ParseContext);
// Constructors
static ["new"](): ParseContext;
// Members
copy(): ParseContext | null;
free(): void;
get_missing_elements(): string[] | null;
}
export class PipelinePrivate {
static $gtype: GObject.GType<PipelinePrivate>;
constructor(copy: PipelinePrivate);
}
export class PluginDesc {
static $gtype: GObject.GType<PluginDesc>;
constructor(copy: PluginDesc);
// Fields
major_version: number;
minor_version: number;
name: string;
description: string;
plugin_init: PluginInitFunc;
version: string;
license: string;
source: string;
"package": string;
origin: string;
release_datetime: string;
}
export class Poll {
static $gtype: GObject.GType<Poll>;
constructor(copy: Poll);
// Members
add_fd(fd: PollFD): boolean;
fd_can_read(fd: PollFD): boolean;
fd_can_write(fd: PollFD): boolean;
fd_ctl_pri(fd: PollFD, active: boolean): boolean;
fd_ctl_read(fd: PollFD, active: boolean): boolean;
fd_ctl_write(fd: PollFD, active: boolean): boolean;
fd_has_closed(fd: PollFD): boolean;
fd_has_error(fd: PollFD): boolean;
fd_has_pri(fd: PollFD): boolean;
fd_ignored(fd: PollFD): void;
free(): void;
get_read_gpollfd(fd: GLib.PollFD): void;
read_control(): boolean;
remove_fd(fd: PollFD): boolean;
restart(): void;
set_controllable(controllable: boolean): boolean;
set_flushing(flushing: boolean): void;
wait(timeout: ClockTime): number;
write_control(): boolean;
}
export class PollFD {
static $gtype: GObject.GType<PollFD>;
constructor(
properties?: Partial<{
fd?: number;
idx?: number;
}>
);
constructor(copy: PollFD);
// Fields
fd: number;
idx: number;
// Members
init(): void;
}
export class Promise {
static $gtype: GObject.GType<Promise>;
constructor();
constructor(copy: Promise);
// Constructors
static ["new"](): Promise;
static new_with_change_func(func: PromiseChangeFunc): Promise;
// Members
expire(): void;
get_reply(): Structure | null;
interrupt(): void;
reply(s?: Structure | null): void;
wait(): PromiseResult;
}
export class ProtectionMeta {
static $gtype: GObject.GType<ProtectionMeta>;
constructor(copy: ProtectionMeta);
// Fields
meta: Meta;
info: Structure;
// Members
static get_info(): MetaInfo;
}
export class ProxyPadPrivate {
static $gtype: GObject.GType<ProxyPadPrivate>;
constructor(copy: ProxyPadPrivate);
}
export class Query {
static $gtype: GObject.GType<Query>;
constructor(caps: Caps);
constructor(copy: Query);
// Fields
mini_object: MiniObject;
type: QueryType;
// Constructors
static new_accept_caps(caps: Caps): Query;
static new_allocation(caps: Caps, need_pool: boolean): Query;
static new_bitrate(): Query;
static new_buffering(format: Format): Query;
static new_caps(filter: Caps): Query;
static new_context(context_type: string): Query;
static new_convert(src_format: Format, value: number, dest_format: Format): Query;
static new_custom(type: QueryType, structure?: Structure | null): Query;
static new_drain(): Query;
static new_duration(format: Format): Query;
static new_formats(): Query;
static new_latency(): Query;
static new_position(format: Format): Query;
static new_scheduling(): Query;
static new_seeking(format: Format): Query;
static new_segment(format: Format): Query;
static new_uri(): Query;
// Members
add_allocation_meta(api: GObject.GType, params?: Structure | null): void;
add_allocation_param(allocator?: Allocator | null, params?: AllocationParams | null): void;
add_allocation_pool(pool: BufferPool | null, size: number, min_buffers: number, max_buffers: number): void;
add_buffering_range(start: number, stop: number): boolean;
add_scheduling_mode(mode: PadMode): void;
find_allocation_meta(api: GObject.GType): [boolean, number | null];
get_n_allocation_metas(): number;
get_n_allocation_params(): number;
get_n_allocation_pools(): number;
get_n_buffering_ranges(): number;
get_n_scheduling_modes(): number;
get_structure(): Structure | null;
has_scheduling_mode(mode: PadMode): boolean;
has_scheduling_mode_with_flags(mode: PadMode, flags: SchedulingFlags): boolean;
parse_accept_caps(): Caps;
parse_accept_caps_result(): boolean | null;
parse_allocation(): [Caps | null, boolean | null];
parse_bitrate(): number | null;
parse_buffering_percent(): [boolean | null, number | null];
parse_buffering_range(): [Format | null, number | null, number | null, number | null];
parse_buffering_stats(): [BufferingMode | null, number | null, number | null, number | null];
parse_caps(): Caps;
parse_caps_result(): Caps;
parse_context(): Context;
parse_context_type(): [boolean, string | null];
parse_convert(): [Format | null, number | null, Format | null, number | null];
parse_duration(): [Format | null, number | null];
parse_latency(): [boolean | null, ClockTime | null, ClockTime | null];
parse_n_formats(): number | null;
parse_nth_allocation_meta(index: number): [GObject.GType, Structure | null];
parse_nth_allocation_param(index: number): [Allocator | null, AllocationParams | null];
parse_nth_allocation_pool(index: number): [BufferPool | null, number | null, number | null, number | null];
parse_nth_buffering_range(index: number): [boolean, number | null, number | null];
parse_nth_format(nth: number): Format | null;
parse_nth_scheduling_mode(index: number): PadMode;
parse_position(): [Format | null, number | null];
parse_scheduling(): [SchedulingFlags | null, number | null, number | null, number | null];
parse_seeking(): [Format | null, boolean | null, number | null, number | null];
parse_segment(): [number | null, Format | null, number | null, number | null];
parse_uri(): string | null;
parse_uri_redirection(): string | null;
parse_uri_redirection_permanent(): boolean | null;
remove_nth_allocation_meta(index: number): void;
remove_nth_allocation_param(index: number): void;
remove_nth_allocation_pool(index: number): void;
set_accept_caps_result(result: boolean): void;
set_bitrate(nominal_bitrate: number): void;
set_buffering_percent(busy: boolean, percent: number): void;
set_buffering_range(format: Format, start: number, stop: number, estimated_total: number): void;
set_buffering_stats(mode: BufferingMode, avg_in: number, avg_out: number, buffering_left: number): void;
set_caps_result(caps: Caps): void;
set_context(context: Context): void;
set_convert(src_format: Format, src_value: number, dest_format: Format, dest_value: number): void;
set_duration(format: Format, duration: number): void;
set_formatsv(formats: Format[]): void;
set_latency(live: boolean, min_latency: ClockTime, max_latency: ClockTime): void;
set_nth_allocation_param(index: number, allocator?: Allocator | null, params?: AllocationParams | null): void;
set_nth_allocation_pool(
index: number,
pool: BufferPool | null,
size: number,
min_buffers: number,
max_buffers: number
): void;
set_position(format: Format, cur: number): void;
set_scheduling(flags: SchedulingFlags, minsize: number, maxsize: number, align: number): void;
set_seeking(format: Format, seekable: boolean, segment_start: number, segment_end: number): void;
set_segment(rate: number, format: Format, start_value: number, stop_value: number): void;
set_uri(uri: string): void;
set_uri_redirection(uri: string): void;
set_uri_redirection_permanent(permanent: boolean): void;
writable_structure(): Structure;
}
export class ReferenceTimestampMeta {
static $gtype: GObject.GType<ReferenceTimestampMeta>;
constructor(copy: ReferenceTimestampMeta);
// Fields
reference: Caps;
timestamp: ClockTime;
duration: ClockTime;
// Members
static get_info(): MetaInfo;
}
export class RegistryPrivate {
static $gtype: GObject.GType<RegistryPrivate>;
constructor(copy: RegistryPrivate);
}
export class Sample {
static $gtype: GObject.GType<Sample>;
constructor(buffer?: Buffer | null, caps?: Caps | null, segment?: Segment | null, info?: Structure | null);
constructor(copy: Sample);
// Constructors
static ["new"](
buffer?: Buffer | null,
caps?: Caps | null,
segment?: Segment | null,
info?: Structure | null
): Sample;
// Members
get_buffer(): Buffer | null;
get_buffer_list(): BufferList | null;
get_caps(): Caps | null;
get_info(): Structure | null;
get_segment(): Segment;
set_buffer(buffer: Buffer): void;
set_buffer_list(buffer_list: BufferList): void;
set_caps(caps: Caps): void;
set_info(info: Structure): boolean;
set_segment(segment: Segment): void;
}
export class Segment {
static $gtype: GObject.GType<Segment>;
constructor();
constructor(copy: Segment);
// Fields
flags: SegmentFlags;
rate: number;
applied_rate: number;
format: Format;
base: number;
offset: number;
start: number;
stop: number;
time: number;
position: number;
duration: number;
// Constructors
static ["new"](): Segment;
// Members
clip(format: Format, start: number, stop: number): [boolean, number | null, number | null];
copy(): Segment;
copy_into(dest: Segment): void;
do_seek(
rate: number,
format: Format,
flags: SeekFlags,
start_type: SeekType,
start: number,
stop_type: SeekType,
stop: number
): [boolean, boolean | null];
free(): void;
init(format: Format): void;
is_equal(s1: Segment): boolean;
offset_running_time(format: Format, offset: number): boolean;
position_from_running_time(format: Format, running_time: number): number;
position_from_running_time_full(format: Format, running_time: number): [number, number];
position_from_stream_time(format: Format, stream_time: number): number;
position_from_stream_time_full(format: Format, stream_time: number): [number, number];
set_running_time(format: Format, running_time: number): boolean;
to_position(format: Format, running_time: number): number;
to_running_time(format: Format, position: number): number;
to_running_time_full(format: Format, position: number): [number, number | null];
to_stream_time(format: Format, position: number): number;
to_stream_time_full(format: Format, position: number): [number, number];
}
export class StaticCaps {
static $gtype: GObject.GType<StaticCaps>;
constructor(copy: StaticCaps);
// Fields
caps: Caps;
string: string;
// Members
cleanup(): void;
get(): Caps | null;
}
export class StaticPadTemplate {
static $gtype: GObject.GType<StaticPadTemplate>;
constructor(copy: StaticPadTemplate);
// Fields
name_template: string;
direction: PadDirection;
presence: PadPresence;
static_caps: StaticCaps;
// Members
get(): PadTemplate | null;
get_caps(): Caps;
}
export class StreamCollectionPrivate {
static $gtype: GObject.GType<StreamCollectionPrivate>;
constructor(copy: StreamCollectionPrivate);
}
export class StreamPrivate {
static $gtype: GObject.GType<StreamPrivate>;
constructor(copy: StreamPrivate);
}
export class Structure {
static $gtype: GObject.GType<Structure>;
constructor(string: string);
constructor(copy: Structure);
// Fields
type: GObject.GType;
name: GLib.Quark;
// Constructors
static from_string(string: string): Structure;
static new_empty(name: string): Structure;
static new_from_string(string: string): Structure;
static new_id_empty(quark: GLib.Quark): Structure;
// Members
can_intersect(struct2: Structure): boolean;
copy(): Structure;
filter_and_map_in_place(func: StructureFilterMapFunc): void;
fixate(): void;
fixate_field(field_name: string): boolean;
fixate_field_boolean(field_name: string, target: boolean): boolean;
fixate_field_nearest_double(field_name: string, target: number): boolean;
fixate_field_nearest_fraction(field_name: string, target_numerator: number, target_denominator: number): boolean;
fixate_field_nearest_int(field_name: string, target: number): boolean;
fixate_field_string(field_name: string, target: string): boolean;
foreach(func: StructureForeachFunc): boolean;
free(): void;
get_array(fieldname: string): [boolean, GObject.ValueArray];
get_boolean(fieldname: string): [boolean, boolean];
get_clock_time(fieldname: string): [boolean, ClockTime];
get_date(fieldname: string): [boolean, GLib.Date];
get_date_time(fieldname: string): [boolean, DateTime];
get_double(fieldname: string): [boolean, number];
get_enum(fieldname: string, enumtype: GObject.GType): [boolean, number];
get_field_type(fieldname: string): GObject.GType;
get_flagset(fieldname: string): [boolean, number | null, number | null];
get_fraction(fieldname: string): [boolean, number, number];
get_int(fieldname: string): [boolean, number];
get_int64(fieldname: string): [boolean, number];
get_list(fieldname: string): [boolean, GObject.ValueArray];
get_name(): string;
get_name_id(): GLib.Quark;
get_string(fieldname: string): string | null;
get_uint(fieldname: string): [boolean, number];
get_uint64(fieldname: string): [boolean, number];
get_value(fieldname: string): GObject.Value | null;
has_field(fieldname: string): boolean;
has_field_typed(fieldname: string, type: GObject.GType): boolean;
has_name(name: string): boolean;
id_get_value(field: GLib.Quark): GObject.Value | null;
id_has_field(field: GLib.Quark): boolean;
id_has_field_typed(field: GLib.Quark, type: GObject.GType): boolean;
id_set_value(field: GLib.Quark, value: any): void;
id_take_value(field: GLib.Quark, value: any): void;
intersect(struct2: Structure): Structure | null;
is_equal(structure2: Structure): boolean;
is_subset(superset: Structure): boolean;
map_in_place(func: StructureMapFunc): boolean;
n_fields(): number;
nth_field_name(index: number): string;
remove_all_fields(): void;
remove_field(fieldname: string): void;
set_array(fieldname: string, array: GObject.ValueArray): void;
set_list(fieldname: string, array: GObject.ValueArray): void;
set_name(name: string): void;
set_parent_refcount(refcount: number): boolean;
set_value(fieldname: string, value: any): void;
take_value(fieldname: string, value: any): void;
to_string(): string;
static take(oldstr_ptr?: Structure | null, newstr?: Structure | null): [boolean, Structure | null];
}
export class SystemClockPrivate {
static $gtype: GObject.GType<SystemClockPrivate>;
constructor(copy: SystemClockPrivate);
}
export class TagList {
static $gtype: GObject.GType<TagList>;
constructor();
constructor(copy: TagList);
// Fields
mini_object: MiniObject;
// Constructors
static new_empty(): TagList;
static new_from_string(str: string): TagList;
// Members
add_value(mode: TagMergeMode, tag: string, value: any): void;
copy(): TagList;
foreach(func: TagForeachFunc): void;
get_boolean(tag: string): [boolean, boolean];
get_boolean_index(tag: string, index: number): [boolean, boolean];
get_date(tag: string): [boolean, GLib.Date];
get_date_index(tag: string, index: number): [boolean, GLib.Date];
get_date_time(tag: string): [boolean, DateTime];
get_date_time_index(tag: string, index: number): [boolean, DateTime];
get_double(tag: string): [boolean, number];
get_double_index(tag: string, index: number): [boolean, number];
get_float(tag: string): [boolean, number];
get_float_index(tag: string, index: number): [boolean, number];
get_int(tag: string): [boolean, number];
get_int64(tag: string): [boolean, number];
get_int64_index(tag: string, index: number): [boolean, number];
get_int_index(tag: string, index: number): [boolean, number];
get_pointer(tag: string): [boolean, any | null];
get_pointer_index(tag: string, index: number): [boolean, any | null];
get_sample(tag: string): [boolean, Sample];
get_sample_index(tag: string, index: number): [boolean, Sample];
get_scope(): TagScope;
get_string(tag: string): [boolean, string];
get_string_index(tag: string, index: number): [boolean, string];
get_tag_size(tag: string): number;
get_uint(tag: string): [boolean, number];
get_uint64(tag: string): [boolean, number];
get_uint64_index(tag: string, index: number): [boolean, number];
get_uint_index(tag: string, index: number): [boolean, number];
get_value_index(tag: string, index: number): GObject.Value | null;
insert(from: TagList, mode: TagMergeMode): void;
is_empty(): boolean;
is_equal(list2: TagList): boolean;
merge(list2: TagList | null, mode: TagMergeMode): TagList | null;
n_tags(): number;
nth_tag_name(index: number): string;
peek_string_index(tag: string, index: number): [boolean, string];
remove_tag(tag: string): void;
set_scope(scope: TagScope): void;
to_string(): string | null;
static copy_value(list: TagList, tag: string): [boolean, unknown];
}
export class TaskPrivate {
static $gtype: GObject.GType<TaskPrivate>;
constructor(copy: TaskPrivate);
}
export class TimedValue {
static $gtype: GObject.GType<TimedValue>;
constructor(copy: TimedValue);
// Fields
timestamp: ClockTime;
value: number;
}
export class Toc {
static $gtype: GObject.GType<Toc>;
constructor(scope: TocScope);
constructor(copy: Toc);
// Constructors
static ["new"](scope: TocScope): Toc;
// Members
append_entry(entry: TocEntry): void;
dump(): void;
find_entry(uid: string): TocEntry | null;
get_entries(): TocEntry[];
get_scope(): TocScope;
get_tags(): TagList;
merge_tags(tags: TagList | null, mode: TagMergeMode): void;
set_tags(tags?: TagList | null): void;
}
export class TocEntry {
static $gtype: GObject.GType<TocEntry>;
constructor(type: TocEntryType, uid: string);
constructor(copy: TocEntry);
// Constructors
static ["new"](type: TocEntryType, uid: string): TocEntry;
// Members
append_sub_entry(subentry: TocEntry): void;
get_entry_type(): TocEntryType;
get_loop(): [boolean, TocLoopType | null, number | null];
get_parent(): TocEntry | null;
get_start_stop_times(): [boolean, number | null, number | null];
get_sub_entries(): TocEntry[];
get_tags(): TagList;
get_toc(): Toc;
get_uid(): string;
is_alternative(): boolean;
is_sequence(): boolean;
merge_tags(tags: TagList | null, mode: TagMergeMode): void;
set_loop(loop_type: TocLoopType, repeat_count: number): void;
set_start_stop_times(start: number, stop: number): void;
set_tags(tags?: TagList | null): void;
}
export class TracerPrivate {
static $gtype: GObject.GType<TracerPrivate>;
constructor(copy: TracerPrivate);
}
export class TypeFind {
static $gtype: GObject.GType<TypeFind>;
constructor(
properties?: Partial<{
data?: any;
}>
);
constructor(copy: TypeFind);
// Fields
data: any;
// Members
get_length(): number;
peek(offset: number): Uint8Array | null;
suggest(probability: number, caps: Caps): void;
static register(
plugin: Plugin | null,
name: string,
rank: number,
func: TypeFindFunction,
extensions?: string | null,
possible_caps?: Caps | null
): boolean;
}
export class Uri {
static $gtype: GObject.GType<Uri>;
constructor(
scheme: string | null,
userinfo: string | null,
host: string | null,
port: number,
path?: string | null,
query?: string | null,
fragment?: string | null
);
constructor(copy: Uri);
// Constructors
static ["new"](
scheme: string | null,
userinfo: string | null,
host: string | null,
port: number,
path?: string | null,
query?: string | null,
fragment?: string | null
): Uri;
// Members
append_path(relative_path: string): boolean;
append_path_segment(path_segment: string): boolean;
equal(second: Uri): boolean;
from_string_with_base(uri: string): Uri;
get_fragment(): string | null;
get_host(): string | null;
get_media_fragment_table(): GLib.HashTable<string, string> | null;
get_path(): string | null;
get_path_segments(): string[];
get_path_string(): string | null;
get_port(): number;
get_query_keys(): string[];
get_query_string(): string | null;
get_query_table(): GLib.HashTable<string, string> | null;
get_query_value(query_key: string): string | null;
get_scheme(): string | null;
get_userinfo(): string | null;
is_normalized(): boolean;
is_writable(): boolean;
join(ref_uri?: Uri | null): Uri | null;
make_writable(): Uri;
new_with_base(
scheme: string | null,
userinfo: string | null,
host: string | null,
port: number,
path?: string | null,
query?: string | null,
fragment?: string | null
): Uri;
normalize(): boolean;
query_has_key(query_key: string): boolean;
remove_query_key(query_key: string): boolean;
set_fragment(fragment?: string | null): boolean;
set_host(host: string): boolean;
set_path(path: string): boolean;
set_path_segments(path_segments?: string[] | null): boolean;
set_path_string(path: string): boolean;
set_port(port: number): boolean;
set_query_string(query: string): boolean;
set_query_table(query_table?: GLib.HashTable<string, string> | null): boolean;
set_query_value(query_key: string, query_value?: string | null): boolean;
set_scheme(scheme: string): boolean;
set_userinfo(userinfo: string): boolean;
to_string(): string;
static construct(protocol: string, location: string): string;
static from_string(uri: string): Uri | null;
static from_string_escaped(uri: string): Uri | null;
static get_location(uri: string): string | null;
static get_protocol(uri: string): string | null;
static has_protocol(uri: string, protocol: string): boolean;
static is_valid(uri: string): boolean;
static join_strings(base_uri: string, ref_uri: string): string;
static protocol_is_supported(type: URIType, protocol: string): boolean;
static protocol_is_valid(protocol: string): boolean;
}
export class ValueTable {
static $gtype: GObject.GType<ValueTable>;
constructor(copy: ValueTable);
// Fields
type: GObject.GType;
compare: ValueCompareFunc;
serialize: ValueSerializeFunc;
deserialize: ValueDeserializeFunc;
}
export interface ChildProxyNamespace {
$gtype: GObject.GType<ChildProxy>;
prototype: ChildProxyPrototype;
}
export type ChildProxy = ChildProxyPrototype;
export interface ChildProxyPrototype extends GObject.Object {
// Members
child_added(child: GObject.Object, name: string): void;
child_removed(child: GObject.Object, name: string): void;
get_child_by_index<T = GObject.Object>(index: number): T;
get_child_by_name<T = GObject.Object>(name: string): T;
get_children_count(): number;
get_property(name: string): unknown;
get_property(...args: never[]): never;
lookup(name: string): [boolean, GObject.Object | null, GObject.ParamSpec | null];
set_property(name: string, value: any): void;
set_property(...args: never[]): never;
vfunc_child_added(child: GObject.Object, name: string): void;
vfunc_child_removed(child: GObject.Object, name: string): void;
vfunc_get_child_by_index<T = GObject.Object>(index: number): T;
vfunc_get_child_by_name<T = GObject.Object>(name: string): T;
vfunc_get_children_count(): number;
}
export const ChildProxy: ChildProxyNamespace;
export interface PresetNamespace {
$gtype: GObject.GType<Preset>;
prototype: PresetPrototype;
get_app_dir(): string | null;
set_app_dir(app_dir: string): boolean;
}
export type Preset = PresetPrototype;
export interface PresetPrototype extends GObject.Object {
// Members
delete_preset(name: string): boolean;
get_meta(name: string, tag: string): [boolean, string];
get_preset_names(): string[];
get_property_names(): string[];
is_editable(): boolean;
load_preset(name: string): boolean;
rename_preset(old_name: string, new_name: string): boolean;
save_preset(name: string): boolean;
set_meta(name: string, tag: string, value?: string | null): boolean;
vfunc_delete_preset(name: string): boolean;
vfunc_get_meta(name: string, tag: string): [boolean, string];
vfunc_get_preset_names(): string[];
vfunc_get_property_names(): string[];
vfunc_load_preset(name: string): boolean;
vfunc_rename_preset(old_name: string, new_name: string): boolean;
vfunc_save_preset(name: string): boolean;
vfunc_set_meta(name: string, tag: string, value?: string | null): boolean;
}
export const Preset: PresetNamespace;
export interface TagSetterNamespace {
$gtype: GObject.GType<TagSetter>;
prototype: TagSetterPrototype;
}
export type TagSetter = TagSetterPrototype;
export interface TagSetterPrototype extends Element {
// Members
add_tag_value(mode: TagMergeMode, tag: string, value: any): void;
get_tag_list(): TagList | null;
get_tag_merge_mode(): TagMergeMode;
merge_tags(list: TagList, mode: TagMergeMode): void;
reset_tags(): void;
set_tag_merge_mode(mode: TagMergeMode): void;
}
export const TagSetter: TagSetterNamespace;
export interface TocSetterNamespace {
$gtype: GObject.GType<TocSetter>;
prototype: TocSetterPrototype;
}
export type TocSetter = TocSetterPrototype;
export interface TocSetterPrototype extends Element {
// Members
get_toc(): Toc | null;
reset(): void;
set_toc(toc?: Toc | null): void;
}
export const TocSetter: TocSetterNamespace;
export interface URIHandlerNamespace {
$gtype: GObject.GType<URIHandler>;
prototype: URIHandlerPrototype;
}
export type URIHandler = URIHandlerPrototype;
export interface URIHandlerPrototype extends GObject.Object {
// Members
get_protocols(): string[] | null;
get_uri(): string | null;
get_uri_type(): URIType;
set_uri(uri: string): boolean;
vfunc_get_uri(): string | null;
vfunc_set_uri(uri: string): boolean;
}
export const URIHandler: URIHandlerNamespace;
export type ClockID = any;
export type ClockTime = number;
export type ClockTimeDiff = number;
export type ElementFactoryListType = number; | the_stack |
import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import {
Observable,
of as observableOf,
Subscription,
BehaviorSubject,
combineLatest as observableCombineLatest,
ObservedValueOf,
} from 'rxjs';
import { map, mergeMap, switchMap, take } from 'rxjs/operators';
import {buildPaginatedList, PaginatedList} from '../../../../core/data/paginated-list.model';
import { RemoteData } from '../../../../core/data/remote-data';
import { EPersonDataService } from '../../../../core/eperson/eperson-data.service';
import { GroupDataService } from '../../../../core/eperson/group-data.service';
import { EPerson } from '../../../../core/eperson/models/eperson.model';
import { Group } from '../../../../core/eperson/models/group.model';
import {
getFirstSucceededRemoteData,
getFirstCompletedRemoteData, getAllCompletedRemoteData, getRemoteDataPayload
} from '../../../../core/shared/operators';
import { NotificationsService } from '../../../../shared/notifications/notifications.service';
import { PaginationComponentOptions } from '../../../../shared/pagination/pagination-component-options.model';
import {EpersonDtoModel} from '../../../../core/eperson/models/eperson-dto.model';
import { PaginationService } from '../../../../core/pagination/pagination.service';
/**
* Keys to keep track of specific subscriptions
*/
enum SubKey {
ActiveGroup,
MembersDTO,
SearchResultsDTO,
}
@Component({
selector: 'ds-members-list',
templateUrl: './members-list.component.html'
})
/**
* The list of members in the edit group page
*/
export class MembersListComponent implements OnInit, OnDestroy {
@Input()
messagePrefix: string;
/**
* EPeople being displayed in search result, initially all members, after search result of search
*/
ePeopleSearchDtos: BehaviorSubject<PaginatedList<EpersonDtoModel>> = new BehaviorSubject<PaginatedList<EpersonDtoModel>>(undefined);
/**
* List of EPeople members of currently active group being edited
*/
ePeopleMembersOfGroupDtos: BehaviorSubject<PaginatedList<EpersonDtoModel>> = new BehaviorSubject<PaginatedList<EpersonDtoModel>>(undefined);
/**
* Pagination config used to display the list of EPeople that are result of EPeople search
*/
configSearch: PaginationComponentOptions = Object.assign(new PaginationComponentOptions(), {
id: 'sml',
pageSize: 5,
currentPage: 1
});
/**
* Pagination config used to display the list of EPerson Membes of active group being edited
*/
config: PaginationComponentOptions = Object.assign(new PaginationComponentOptions(), {
id: 'ml',
pageSize: 5,
currentPage: 1
});
/**
* Map of active subscriptions
*/
subs: Map<SubKey, Subscription> = new Map();
// The search form
searchForm;
// Current search in edit group - epeople search form
currentSearchQuery: string;
currentSearchScope: string;
// Whether or not user has done a EPeople search yet
searchDone: boolean;
// current active group being edited
groupBeingEdited: Group;
paginationSub: Subscription;
constructor(private groupDataService: GroupDataService,
public ePersonDataService: EPersonDataService,
private translateService: TranslateService,
private notificationsService: NotificationsService,
private formBuilder: FormBuilder,
private paginationService: PaginationService,
private router: Router) {
this.currentSearchQuery = '';
this.currentSearchScope = 'metadata';
}
ngOnInit() {
this.searchForm = this.formBuilder.group(({
scope: 'metadata',
query: '',
}));
this.subs.set(SubKey.ActiveGroup, this.groupDataService.getActiveGroup().subscribe((activeGroup: Group) => {
if (activeGroup != null) {
this.groupBeingEdited = activeGroup;
this.retrieveMembers(this.config.currentPage);
}
}));
}
/**
* Retrieve the EPersons that are members of the group
*
* @param page the number of the page to retrieve
* @private
*/
private retrieveMembers(page: number) {
this.unsubFrom(SubKey.MembersDTO);
this.subs.set(SubKey.MembersDTO,
this.paginationService.getCurrentPagination(this.config.id, this.config).pipe(
switchMap((currentPagination) => {
return this.ePersonDataService.findAllByHref(this.groupBeingEdited._links.epersons.href, {
currentPage: currentPagination.currentPage,
elementsPerPage: currentPagination.pageSize
}
);
}),
getAllCompletedRemoteData(),
map((rd: RemoteData<any>) => {
if (rd.hasFailed) {
this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.failure', {cause: rd.errorMessage}));
} else {
return rd;
}
}),
switchMap((epersonListRD: RemoteData<PaginatedList<EPerson>>) => {
const dtos$ = observableCombineLatest(...epersonListRD.payload.page.map((member: EPerson) => {
const dto$: Observable<EpersonDtoModel> = observableCombineLatest(
this.isMemberOfGroup(member), (isMember: ObservedValueOf<Observable<boolean>>) => {
const epersonDtoModel: EpersonDtoModel = new EpersonDtoModel();
epersonDtoModel.eperson = member;
epersonDtoModel.memberOfGroup = isMember;
return epersonDtoModel;
});
return dto$;
}));
return dtos$.pipe(map((dtos: EpersonDtoModel[]) => {
return buildPaginatedList(epersonListRD.payload.pageInfo, dtos);
}));
}))
.subscribe((paginatedListOfDTOs: PaginatedList<EpersonDtoModel>) => {
this.ePeopleMembersOfGroupDtos.next(paginatedListOfDTOs);
}));
}
/**
* Whether or not the given ePerson is a member of the group currently being edited
* @param possibleMember EPerson that is a possible member (being tested) of the group currently being edited
*/
isMemberOfGroup(possibleMember: EPerson): Observable<boolean> {
return this.groupDataService.getActiveGroup().pipe(take(1),
mergeMap((group: Group) => {
if (group != null) {
return this.ePersonDataService.findAllByHref(group._links.epersons.href, {
currentPage: 1,
elementsPerPage: 9999
}, false)
.pipe(
getFirstSucceededRemoteData(),
getRemoteDataPayload(),
map((listEPeopleInGroup: PaginatedList<EPerson>) => listEPeopleInGroup.page.filter((ePersonInList: EPerson) => ePersonInList.id === possibleMember.id)),
map((epeople: EPerson[]) => epeople.length > 0));
} else {
return observableOf(false);
}
}));
}
/**
* Unsubscribe from a subscription if it's still subscribed, and remove it from the map of
* active subscriptions
*
* @param key The key of the subscription to unsubscribe from
* @private
*/
private unsubFrom(key: SubKey) {
if (this.subs.has(key)) {
this.subs.get(key).unsubscribe();
this.subs.delete(key);
}
}
/**
* Deletes a given EPerson from the members list of the group currently being edited
* @param ePerson EPerson we want to delete as member from group that is currently being edited
*/
deleteMemberFromGroup(ePerson: EpersonDtoModel) {
this.groupDataService.getActiveGroup().pipe(take(1)).subscribe((activeGroup: Group) => {
if (activeGroup != null) {
const response = this.groupDataService.deleteMemberFromGroup(activeGroup, ePerson.eperson);
this.showNotifications('deleteMember', response, ePerson.eperson.name, activeGroup);
this.search({ scope: this.currentSearchScope, query: this.currentSearchQuery });
} else {
this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.failure.noActiveGroup'));
}
});
}
/**
* Adds a given EPerson to the members list of the group currently being edited
* @param ePerson EPerson we want to add as member to group that is currently being edited
*/
addMemberToGroup(ePerson: EpersonDtoModel) {
ePerson.memberOfGroup = true;
this.groupDataService.getActiveGroup().pipe(take(1)).subscribe((activeGroup: Group) => {
if (activeGroup != null) {
const response = this.groupDataService.addMemberToGroup(activeGroup, ePerson.eperson);
this.showNotifications('addMember', response, ePerson.eperson.name, activeGroup);
} else {
this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.failure.noActiveGroup'));
}
});
}
/**
* Search in the EPeople by name, email or metadata
* @param data Contains scope and query param
*/
search(data: any) {
this.unsubFrom(SubKey.SearchResultsDTO);
this.subs.set(SubKey.SearchResultsDTO,
this.paginationService.getCurrentPagination(this.configSearch.id, this.configSearch).pipe(
switchMap((paginationOptions) => {
const query: string = data.query;
const scope: string = data.scope;
if (query != null && this.currentSearchQuery !== query && this.groupBeingEdited) {
this.router.navigate([], {
queryParamsHandling: 'merge'
});
this.currentSearchQuery = query;
this.paginationService.resetPage(this.configSearch.id);
}
if (scope != null && this.currentSearchScope !== scope && this.groupBeingEdited) {
this.router.navigate([], {
queryParamsHandling: 'merge'
});
this.currentSearchScope = scope;
this.paginationService.resetPage(this.configSearch.id);
}
this.searchDone = true;
return this.ePersonDataService.searchByScope(this.currentSearchScope, this.currentSearchQuery, {
currentPage: paginationOptions.currentPage,
elementsPerPage: paginationOptions.pageSize
});
}),
getAllCompletedRemoteData(),
map((rd: RemoteData<any>) => {
if (rd.hasFailed) {
this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.failure', {cause: rd.errorMessage}));
} else {
return rd;
}
}),
switchMap((epersonListRD: RemoteData<PaginatedList<EPerson>>) => {
const dtos$ = observableCombineLatest(...epersonListRD.payload.page.map((member: EPerson) => {
const dto$: Observable<EpersonDtoModel> = observableCombineLatest(
this.isMemberOfGroup(member), (isMember: ObservedValueOf<Observable<boolean>>) => {
const epersonDtoModel: EpersonDtoModel = new EpersonDtoModel();
epersonDtoModel.eperson = member;
epersonDtoModel.memberOfGroup = isMember;
return epersonDtoModel;
});
return dto$;
}));
return dtos$.pipe(map((dtos: EpersonDtoModel[]) => {
return buildPaginatedList(epersonListRD.payload.pageInfo, dtos);
}));
}))
.subscribe((paginatedListOfDTOs: PaginatedList<EpersonDtoModel>) => {
this.ePeopleSearchDtos.next(paginatedListOfDTOs);
}));
}
/**
* unsub all subscriptions
*/
ngOnDestroy(): void {
for (const key of this.subs.keys()) {
this.unsubFrom(key);
}
this.paginationService.clearPagination(this.config.id);
this.paginationService.clearPagination(this.configSearch.id);
}
/**
* Shows a notification based on the success/failure of the request
* @param messageSuffix Suffix for message
* @param response RestResponse observable containing success/failure request
* @param nameObject Object request was about
* @param activeGroup Group currently being edited
*/
showNotifications(messageSuffix: string, response: Observable<RemoteData<any>>, nameObject: string, activeGroup: Group) {
response.pipe(getFirstCompletedRemoteData()).subscribe((rd: RemoteData<any>) => {
if (rd.hasSucceeded) {
this.notificationsService.success(this.translateService.get(this.messagePrefix + '.notification.success.' + messageSuffix, { name: nameObject }));
this.ePersonDataService.clearLinkRequests(activeGroup._links.epersons.href);
} else {
this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.failure.' + messageSuffix, { name: nameObject }));
}
});
}
/**
* Reset all input-fields to be empty and search all search
*/
clearFormAndResetResult() {
this.searchForm.patchValue({
query: '',
});
this.search({ query: '' });
}
} | the_stack |
* @module Tiles
*/
import { assert, PriorityQueue } from "@itwin/core-bentley";
import { IModelConnection } from "../IModelConnection";
import { Tile, TileContent, TileRequest } from "./internal";
class TileRequestQueue extends PriorityQueue<TileRequest> {
public constructor() {
super((lhs, rhs) => {
const diff = lhs.tile.tree.loadPriority - rhs.tile.tree.loadPriority;
return 0 !== diff ? diff : lhs.priority - rhs.priority;
});
}
}
/** Statistics regarding the current and cumulative state of one or more [[TileRequestChannel]]s. Useful for monitoring performance and diagnosing problems.
* @see [[TileRequestChannel.statistics]] for a specific channel's statistics.
* @see [[TileRequestChannels.statistics]] for statistics from all channels.
* @see [[TileAdmin.statistics]] for additional statistics.
* @public
*/
export class TileRequestChannelStatistics {
/** The number of queued requests that have not yet been dispatched. */
public numPendingRequests = 0;
/** The number of requests that have been dispatched but not yet completed. */
public numActiveRequests = 0;
/** The number of requests canceled during the most recent update. */
public numCanceled = 0;
/** The total number of completed requests during this session. */
public totalCompletedRequests = 0;
/** The total number of failed requests during this session. */
public totalFailedRequests = 0;
/** The total number of timed-out requests during this session. */
public totalTimedOutRequests = 0;
/** The total number of completed requests during this session which produced an empty tile.
* These tiles also contribute to [[totalCompletedRequests]], but not to [[totalUndisplayableTiles]].
*/
public totalEmptyTiles = 0;
/** The total number of completed requests during this session that produced an undisplayable tile.
* These tiles also contribute to [[totalCompletedRequests]], but not to [[totalEmptyTiles]].
*/
public totalUndisplayableTiles = 0;
/** The total number of tiles whose contents were not found in cloud storage cache and therefore resulted in a backend request to generate the tile content. */
public totalCacheMisses = 0;
/** The total number of tiles for which content requests were dispatched. */
public totalDispatchedRequests = 0;
/** The total number of tiles for which content requests were dispatched and then canceled on the backend before completion. */
public totalAbortedRequests = 0;
/** @internal */
public addTo(stats: TileRequestChannelStatistics): void {
for (const propName in this) { // eslint-disable-line guard-for-in
const key = propName as keyof TileRequestChannelStatistics;
const val = this[key];
if (typeof val === "number") {
// This type guard ought to suffice but doesn't.
assert(typeof stats[key] === "number");
(stats[key] as number) += val;
}
}
}
}
/** A channel over which requests for tile content can be made. The channel may request content over HTTP, calls to the backend via IPC or RPC, or any other method like generating the content
* on the frontend. The channel consists of a queue of pending requests and a set of "active" requests (dispatched and awaiting a response). Incoming requests are placed onto the queue. Requests are popped of the queue in order of priority and dispatched, until the maximum number of simultaneously-active requests is reached.
* The maximum number of active requests depends on the transport mechanism. For HTTP 1.1, browsers impose a limit of 6 simultaneous connections to a given domain, so ideally each unique domain will use its own unique channel with a limit of 6 active requests. Even for requests satisfied entirely by the frontend, imposing a limit is important for throttling the amount of work done at one time, especially because as the user navigates the view, tiles that were previously requested may no longer be of interest and we shouldn't waste resources producing their content.
* A channel must be registered with [[TileRequestChannels]] and must have a unique name among all registered channels.
* @see [[TileRequestChannels.getForHttp]] to obtain (and register if not already registered) an HTTP-based channel.
* @see [[TileAdmin.channels]] for the channels configured for use with the iTwin.js display system.
* @see [[Tile.channel]] to specify the channel to be used to request a given tile's content.
* @public
*/
export class TileRequestChannel {
/** The channel's name. It must be unique among all registered [[TileRequestChannels]]. */
public readonly name: string;
private _concurrency: number;
/** Protected strictly for tests. @internal */
protected readonly _active = new Set<TileRequest>();
private _pending = new TileRequestQueue();
private _previouslyPending = new TileRequestQueue();
protected _statistics = new TileRequestChannelStatistics();
/** Callback invoked by recordCompletion. See IModelTileMetadataCacheChannel.
* @internal
*/
public contentCallback?: (tile: Tile, content: TileContent) => void;
/** Create a new channel.
* @param name The unique name of the channel.
* @param concurrency The maximum number of requests that can be dispatched and awaiting a response at any given time. Requests beyond this maximum are enqueued for deferred dispatch.
* @see [[TileRequestChannels.getForHttp]] to create an HTTP-based channel.
*/
public constructor(name: string, concurrency: number) {
this.name = name;
this._concurrency = concurrency;
}
/** The maximum number of active requests. This is generally only modified for debugging purposes.
* @note When reducing `concurrency`, the number of active requests ([[numActive]]) will only decrease to the new value after a sufficient number of dispatched requests are resolved.
*/
public get concurrency(): number {
return this._concurrency;
}
public set concurrency(max: number) {
this._concurrency = max;
}
/** The number of requests that have been dispatched and are awaiting a response. */
public get numActive(): number {
return this._active.size;
}
/** The number of requests that have been enqueued for later dispatch. */
public get numPending(): number {
return this._pending.length;
}
/** The total number of requests in this channel, whether dispatched or enqueued. */
public get size(): number {
return this.numActive + this.numPending;
}
/** Statistics intended primarily for debugging. */
public get statistics(): Readonly<TileRequestChannelStatistics> {
this._statistics.numPendingRequests = this.numPending;
this._statistics.numActiveRequests = this.numActive;
return this._statistics;
}
/** Reset all of this channel's [[statistics]] to zero. */
public resetStatistics(): void {
this._statistics = new TileRequestChannelStatistics();
}
/** Invoked by [[TileRequest]] when a request times out.
* @internal
*/
public recordTimeout(): void {
++this._statistics.totalTimedOutRequests;
}
/** Invoked by [[TileRequest]] when a request fails to produce a response.
* @internal
*/
public recordFailure(): void {
++this._statistics.totalFailedRequests;
}
/** Invoked by [[TileRequest]] after a request completes.
* @internal
*/
public recordCompletion(tile: Tile, content: TileContent): void {
++this._statistics.totalCompletedRequests;
if (tile.isEmpty)
++this._statistics.totalEmptyTiles;
else if (!tile.isDisplayable)
++this._statistics.totalUndisplayableTiles;
if (this.contentCallback)
this.contentCallback(tile, content);
}
/** Invoked by [[TileRequestChannels.swapPending]] when [[TileAdmin]] is about to start enqueuing new requests.
* @internal
*/
public swapPending(): void {
const previouslyPending = this._pending;
this._pending = this._previouslyPending;
this._previouslyPending = previouslyPending;
}
/** Invoked by [[TileAdmin.processRequests]] to enqueue a request. Ordering is ignored - the queue will be re-sorted later.
* @internal
*/
public append(request: TileRequest): void {
assert(request.channel === this);
this._pending.append(request);
}
/** Invoked by [[TileRequestChannels.process]] to process the active and pending requests.
* @internal
*/
public process(): void {
this._statistics.numCanceled = 0;
// Recompute priority of each request.
for (const pending of this._pending)
pending.priority = pending.tile.computeLoadPriority(pending.viewports);
// Sort pending requests by priority.
this._pending.sort();
// Cancel any previously pending requests that are no longer needed.
for (const queued of this._previouslyPending)
if (queued.viewports.isEmpty)
this.cancel(queued);
this._previouslyPending.clear();
// Cancel any active requests that are no longer needed.
// NB: Do NOT remove them from the active set until their http activity has completed.
for (const active of this._active)
if (active.viewports.isEmpty)
this.cancel(active);
// Batch-cancel running requests.
this.processCancellations();
// Dispatch requests from the queue up to our maximum.
while (this._active.size < this._concurrency) {
const request = this._pending.pop();
if (!request)
break;
this.dispatch(request);
}
}
/** Cancel all active and queued requests and clear the active set and queue.
* @internal
*/
public cancelAndClearAll(): void {
for (const active of this._active)
active.cancel();
for (const queued of this._pending)
queued.cancel();
this._active.clear();
this._pending.clear();
}
/** Invoked when [[Tile.requestContent]] returns `undefined`. Return true if the request can be retried, e.g., via different channel.
* If so, the tile will remain marked as "not loaded" and, if re-selected for display, a new [[TileRequest]] will be enqueued for it.
* Otherwise, the tile will be marked as "failed to load" and no further requests will be made for its content.
* The default implementation always returns `false`.
*/
public onNoContent(_request: TileRequest): boolean {
return false;
}
/** Invoked when a request that was previously dispatched is canceled before a response is received.
* Some channels accumulate such requests for later cancellation in [[processCancellations]].
*/
public onActiveRequestCanceled(_request: TileRequest): void { }
/** Invoked to do any additional work to cancel tiles accumulated by [[onActiveRequestCanceled]]. For example, a channel that requests tile content
* over IPC may signal to the tile generation process that it should cease generating content for those tiles.
*/
public processCancellations(): void { }
/** Invoked when an iModel is closed, to clean up any state associated with that iModel. */
public onIModelClosed(_iModel: IModelConnection): void { }
/** Request content for the specified tile. The default implementation simply forwards to [[Tile.requestContent]]. */
public async requestContent(tile: Tile, isCanceled: () => boolean): Promise<TileRequest.Response> {
return tile.requestContent(isCanceled);
}
/** Protected only for tests - do not override.
* @internal
*/
protected dispatch(request: TileRequest): void {
++this._statistics.totalDispatchedRequests;
this._active.add(request);
request.dispatch(() => {
this.dropActiveRequest(request);
}).catch((_) => {
//
});
}
/** Protected only for tests - do not override.
* @internal
*/
protected cancel(request: TileRequest): void {
request.cancel();
++this._statistics.numCanceled;
}
/** Protected only for tests - do not override.
* @internal
*/
protected dropActiveRequest(request: TileRequest): void {
assert(this._active.has(request) || request.isCanceled);
this._active.delete(request);
}
} | the_stack |
import {
symbolLayoutAttributes,
collisionVertexAttributes,
collisionBoxLayout,
dynamicLayoutAttributes,
} from './symbol_attributes';
import {SymbolLayoutArray,
SymbolDynamicLayoutArray,
SymbolOpacityArray,
CollisionBoxLayoutArray,
CollisionVertexArray,
PlacedSymbolArray,
SymbolInstanceArray,
GlyphOffsetArray,
SymbolLineVertexArray
} from '../array_types';
import Point from '../../util/point';
import SegmentVector from '../segment';
import {ProgramConfigurationSet} from '../program_configuration';
import {TriangleIndexArray, LineIndexArray} from '../index_array_type';
import transformText from '../../symbol/transform_text';
import mergeLines from '../../symbol/mergelines';
import {allowsVerticalWritingMode, stringContainsRTLText} from '../../util/script_detection';
import {WritingMode} from '../../symbol/shaping';
import loadGeometry from '../load_geometry';
import toEvaluationFeature from '../evaluation_feature';
import mvt from '@mapbox/vector-tile';
const vectorTileFeatureTypes = mvt.VectorTileFeature.types;
import {verticalizedCharacterMap} from '../../util/verticalize_punctuation';
import Anchor from '../../symbol/anchor';
import {getSizeData} from '../../symbol/symbol_size';
import {MAX_PACKED_SIZE} from '../../symbol/symbol_layout';
import {register} from '../../util/web_worker_transfer';
import EvaluationParameters from '../../style/evaluation_parameters';
import Formatted from '../../style-spec/expression/types/formatted';
import ResolvedImage from '../../style-spec/expression/types/resolved_image';
import {plugin as globalRTLTextPlugin, getRTLTextPluginStatus} from '../../source/rtl_text_plugin';
import {mat4} from 'gl-matrix';
import type {CanonicalTileID} from '../../source/tile_id';
import type {
Bucket,
BucketParameters,
IndexedFeature,
PopulateParameters
} from '../bucket';
import type {CollisionBoxArray, CollisionBox, SymbolInstance} from '../array_types';
import type {StructArray, StructArrayMember, ViewType} from '../../util/struct_array';
import SymbolStyleLayer from '../../style/style_layer/symbol_style_layer';
import type Context from '../../gl/context';
import type IndexBuffer from '../../gl/index_buffer';
import type VertexBuffer from '../../gl/vertex_buffer';
import type {SymbolQuad} from '../../symbol/quads';
import type {SizeData} from '../../symbol/symbol_size';
import type {FeatureStates} from '../../source/source_state';
import type {ImagePosition} from '../../render/image_atlas';
export type SingleCollisionBox = {
x1: number;
y1: number;
x2: number;
y2: number;
anchorPointX: number;
anchorPointY: number;
};
export type CollisionArrays = {
textBox?: SingleCollisionBox;
verticalTextBox?: SingleCollisionBox;
iconBox?: SingleCollisionBox;
verticalIconBox?: SingleCollisionBox;
textFeatureIndex?: number;
verticalTextFeatureIndex?: number;
iconFeatureIndex?: number;
verticalIconFeatureIndex?: number;
};
export type SymbolFeature = {
sortKey: number | void;
text: Formatted | void;
icon: ResolvedImage;
index: number;
sourceLayerIndex: number;
geometry: Array<Array<Point>>;
properties: any;
type: 'Point' | 'LineString' | 'Polygon';
id?: any;
};
export type SortKeyRange = {
sortKey: number;
symbolInstanceStart: number;
symbolInstanceEnd: number;
};
// Opacity arrays are frequently updated but don't contain a lot of information, so we pack them
// tight. Each Uint32 is actually four duplicate Uint8s for the four corners of a glyph
// 7 bits are for the current opacity, and the lowest bit is the target opacity
// actually defined in symbol_attributes.js
// const placementOpacityAttributes = [
// { name: 'a_fade_opacity', components: 1, type: 'Uint32' }
// ];
const shaderOpacityAttributes = [
{name: 'a_fade_opacity', components: 1, type: 'Uint8' as ViewType, offset: 0}
];
function addVertex(
array: StructArray,
anchorX: number,
anchorY: number,
ox: number,
oy: number,
tx: number,
ty: number,
sizeVertex: number,
isSDF: boolean,
pixelOffsetX: number,
pixelOffsetY: number,
minFontScaleX: number,
minFontScaleY: number
) {
const aSizeX = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[0])) : 0;
const aSizeY = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[1])) : 0;
array.emplaceBack(
// a_pos_offset
anchorX,
anchorY,
Math.round(ox * 32),
Math.round(oy * 32),
// a_data
tx, // x coordinate of symbol on glyph atlas texture
ty, // y coordinate of symbol on glyph atlas texture
(aSizeX << 1) + (isSDF ? 1 : 0),
aSizeY,
pixelOffsetX * 16,
pixelOffsetY * 16,
minFontScaleX * 256,
minFontScaleY * 256
);
}
function addDynamicAttributes(dynamicLayoutVertexArray: StructArray, p: Point, angle: number) {
dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);
dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);
dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);
dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);
}
function containsRTLText(formattedText: Formatted): boolean {
for (const section of formattedText.sections) {
if (stringContainsRTLText(section.text)) {
return true;
}
}
return false;
}
export class SymbolBuffers {
layoutVertexArray: SymbolLayoutArray;
layoutVertexBuffer: VertexBuffer;
indexArray: TriangleIndexArray;
indexBuffer: IndexBuffer;
programConfigurations: ProgramConfigurationSet<SymbolStyleLayer>;
segments: SegmentVector;
dynamicLayoutVertexArray: SymbolDynamicLayoutArray;
dynamicLayoutVertexBuffer: VertexBuffer;
opacityVertexArray: SymbolOpacityArray;
opacityVertexBuffer: VertexBuffer;
collisionVertexArray: CollisionVertexArray;
collisionVertexBuffer: VertexBuffer;
placedSymbolArray: PlacedSymbolArray;
constructor(programConfigurations: ProgramConfigurationSet<SymbolStyleLayer>) {
this.layoutVertexArray = new SymbolLayoutArray();
this.indexArray = new TriangleIndexArray();
this.programConfigurations = programConfigurations;
this.segments = new SegmentVector();
this.dynamicLayoutVertexArray = new SymbolDynamicLayoutArray();
this.opacityVertexArray = new SymbolOpacityArray();
this.placedSymbolArray = new PlacedSymbolArray();
}
isEmpty() {
return this.layoutVertexArray.length === 0 &&
this.indexArray.length === 0 &&
this.dynamicLayoutVertexArray.length === 0 &&
this.opacityVertexArray.length === 0;
}
upload(context: Context, dynamicIndexBuffer: boolean, upload?: boolean, update?: boolean) {
if (this.isEmpty()) {
return;
}
if (upload) {
this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, symbolLayoutAttributes.members);
this.indexBuffer = context.createIndexBuffer(this.indexArray, dynamicIndexBuffer);
this.dynamicLayoutVertexBuffer = context.createVertexBuffer(this.dynamicLayoutVertexArray, dynamicLayoutAttributes.members, true);
this.opacityVertexBuffer = context.createVertexBuffer(this.opacityVertexArray, shaderOpacityAttributes, true);
// This is a performance hack so that we can write to opacityVertexArray with uint32s
// even though the shaders read uint8s
this.opacityVertexBuffer.itemSize = 1;
}
if (upload || update) {
this.programConfigurations.upload(context);
}
}
destroy() {
if (!this.layoutVertexBuffer) return;
this.layoutVertexBuffer.destroy();
this.indexBuffer.destroy();
this.programConfigurations.destroy();
this.segments.destroy();
this.dynamicLayoutVertexBuffer.destroy();
this.opacityVertexBuffer.destroy();
}
}
register('SymbolBuffers', SymbolBuffers);
class CollisionBuffers {
layoutVertexArray: StructArray;
layoutAttributes: Array<StructArrayMember>;
layoutVertexBuffer: VertexBuffer;
indexArray: TriangleIndexArray | LineIndexArray;
indexBuffer: IndexBuffer;
segments: SegmentVector;
collisionVertexArray: CollisionVertexArray;
collisionVertexBuffer: VertexBuffer;
constructor(LayoutArray: {
new (...args: any): StructArray;
},
layoutAttributes: Array<StructArrayMember>,
IndexArray: {
new (...args: any): TriangleIndexArray | LineIndexArray;
}) {
this.layoutVertexArray = new LayoutArray();
this.layoutAttributes = layoutAttributes;
this.indexArray = new IndexArray();
this.segments = new SegmentVector();
this.collisionVertexArray = new CollisionVertexArray();
}
upload(context: Context) {
this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, this.layoutAttributes);
this.indexBuffer = context.createIndexBuffer(this.indexArray);
this.collisionVertexBuffer = context.createVertexBuffer(this.collisionVertexArray, collisionVertexAttributes.members, true);
}
destroy() {
if (!this.layoutVertexBuffer) return;
this.layoutVertexBuffer.destroy();
this.indexBuffer.destroy();
this.segments.destroy();
this.collisionVertexBuffer.destroy();
}
}
register('CollisionBuffers', CollisionBuffers);
/**
* Unlike other buckets, which simply implement #addFeature with type-specific
* logic for (essentially) triangulating feature geometries, SymbolBucket
* requires specialized behavior:
*
* 1. WorkerTile#parse(), the logical owner of the bucket creation process,
* calls SymbolBucket#populate(), which resolves text and icon tokens on
* each feature, adds each glyphs and symbols needed to the passed-in
* collections options.glyphDependencies and options.iconDependencies, and
* stores the feature data for use in subsequent step (this.features).
*
* 2. WorkerTile asynchronously requests from the main thread all of the glyphs
* and icons needed (by this bucket and any others). When glyphs and icons
* have been received, the WorkerTile creates a CollisionIndex and invokes:
*
* 3. performSymbolLayout(bucket, stacks, icons) perform texts shaping and
* layout on a Symbol Bucket. This step populates:
* `this.symbolInstances`: metadata on generated symbols
* `this.collisionBoxArray`: collision data for use by foreground
* `this.text`: SymbolBuffers for text symbols
* `this.icons`: SymbolBuffers for icons
* `this.iconCollisionBox`: Debug SymbolBuffers for icon collision boxes
* `this.textCollisionBox`: Debug SymbolBuffers for text collision boxes
* The results are sent to the foreground for rendering
*
* 4. performSymbolPlacement(bucket, collisionIndex) is run on the foreground,
* and uses the CollisionIndex along with current camera settings to determine
* which symbols can actually show on the map. Collided symbols are hidden
* using a dynamic "OpacityVertexArray".
*
* @private
*/
class SymbolBucket implements Bucket {
static MAX_GLYPHS: number;
static addDynamicAttributes: typeof addDynamicAttributes;
collisionBoxArray: CollisionBoxArray;
zoom: number;
overscaling: number;
layers: Array<SymbolStyleLayer>;
layerIds: Array<string>;
stateDependentLayers: Array<SymbolStyleLayer>;
stateDependentLayerIds: Array<string>;
index: number;
sdfIcons: boolean;
iconsInText: boolean;
iconsNeedLinear: boolean;
bucketInstanceId: number;
justReloaded: boolean;
hasPattern: boolean;
textSizeData: SizeData;
iconSizeData: SizeData;
glyphOffsetArray: GlyphOffsetArray;
lineVertexArray: SymbolLineVertexArray;
features: Array<SymbolFeature>;
symbolInstances: SymbolInstanceArray;
collisionArrays: Array<CollisionArrays>;
sortKeyRanges: Array<SortKeyRange>;
pixelRatio: number;
tilePixelRatio: number;
compareText: {[_: string]: Array<Point>};
fadeStartTime: number;
sortFeaturesByKey: boolean;
sortFeaturesByY: boolean;
canOverlap: boolean;
sortedAngle: number;
featureSortOrder: Array<number>;
collisionCircleArray: Array<number>;
placementInvProjMatrix: mat4;
placementViewportMatrix: mat4;
text: SymbolBuffers;
icon: SymbolBuffers;
textCollisionBox: CollisionBuffers;
iconCollisionBox: CollisionBuffers;
uploaded: boolean;
sourceLayerIndex: number;
sourceID: string;
symbolInstanceIndexes: Array<number>;
writingModes: WritingMode[];
allowVerticalPlacement: boolean;
hasRTLText: boolean;
constructor(options: BucketParameters<SymbolStyleLayer>) {
this.collisionBoxArray = options.collisionBoxArray;
this.zoom = options.zoom;
this.overscaling = options.overscaling;
this.layers = options.layers;
this.layerIds = this.layers.map(layer => layer.id);
this.index = options.index;
this.pixelRatio = options.pixelRatio;
this.sourceLayerIndex = options.sourceLayerIndex;
this.hasPattern = false;
this.hasRTLText = false;
this.sortKeyRanges = [];
this.collisionCircleArray = [];
this.placementInvProjMatrix = mat4.identity([] as any);
this.placementViewportMatrix = mat4.identity([] as any);
const layer = this.layers[0];
const unevaluatedLayoutValues = layer._unevaluatedLayout._values;
this.textSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['text-size']);
this.iconSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['icon-size']);
const layout = this.layers[0].layout;
const sortKey = layout.get('symbol-sort-key');
const zOrder = layout.get('symbol-z-order');
this.canOverlap =
layout.get('text-allow-overlap') ||
layout.get('icon-allow-overlap') ||
layout.get('text-ignore-placement') ||
layout.get('icon-ignore-placement');
this.sortFeaturesByKey = zOrder !== 'viewport-y' && !sortKey.isConstant();
const zOrderByViewportY = zOrder === 'viewport-y' || (zOrder === 'auto' && !this.sortFeaturesByKey);
this.sortFeaturesByY = zOrderByViewportY && this.canOverlap;
if (layout.get('symbol-placement') === 'point') {
this.writingModes = layout.get('text-writing-mode').map(wm => WritingMode[wm]);
}
this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);
this.sourceID = options.sourceID;
}
createArrays() {
this.text = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, property => /^text/.test(property)));
this.icon = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, property => /^icon/.test(property)));
this.glyphOffsetArray = new GlyphOffsetArray();
this.lineVertexArray = new SymbolLineVertexArray();
this.symbolInstances = new SymbolInstanceArray();
}
calculateGlyphDependencies(text: string, stack: {[_: number]: boolean}, textAlongLine: boolean, allowVerticalPlacement: boolean, doesAllowVerticalWritingMode: boolean) {
for (let i = 0; i < text.length; i++) {
stack[text.charCodeAt(i)] = true;
if ((textAlongLine || allowVerticalPlacement) && doesAllowVerticalWritingMode) {
const verticalChar = verticalizedCharacterMap[text.charAt(i)];
if (verticalChar) {
stack[verticalChar.charCodeAt(0)] = true;
}
}
}
}
populate(features: Array<IndexedFeature>, options: PopulateParameters, canonical: CanonicalTileID) {
const layer = this.layers[0];
const layout = layer.layout;
const textFont = layout.get('text-font');
const textField = layout.get('text-field');
const iconImage = layout.get('icon-image');
const hasText =
(textField.value.kind !== 'constant' ||
(textField.value.value instanceof Formatted && !textField.value.value.isEmpty()) ||
textField.value.value.toString().length > 0) &&
(textFont.value.kind !== 'constant' || textFont.value.value.length > 0);
// we should always resolve the icon-image value if the property was defined in the style
// this allows us to fire the styleimagemissing event if image evaluation returns null
// the only way to distinguish between null returned from a coalesce statement with no valid images
// and null returned because icon-image wasn't defined is to check whether or not iconImage.parameters is an empty object
const hasIcon = iconImage.value.kind !== 'constant' || !!iconImage.value.value || Object.keys(iconImage.parameters).length > 0;
const symbolSortKey = layout.get('symbol-sort-key');
this.features = [];
if (!hasText && !hasIcon) {
return;
}
const icons = options.iconDependencies;
const stacks = options.glyphDependencies;
const availableImages = options.availableImages;
const globalProperties = new EvaluationParameters(this.zoom);
for (const {feature, id, index, sourceLayerIndex} of features) {
const needGeometry = layer._featureFilter.needGeometry;
const evaluationFeature = toEvaluationFeature(feature, needGeometry);
if (!layer._featureFilter.filter(globalProperties, evaluationFeature, canonical)) {
continue;
}
if (!needGeometry) evaluationFeature.geometry = loadGeometry(feature);
let text: Formatted | void;
if (hasText) {
// Expression evaluation will automatically coerce to Formatted
// but plain string token evaluation skips that pathway so do the
// conversion here.
const resolvedTokens = layer.getValueAndResolveTokens('text-field', evaluationFeature, canonical, availableImages);
const formattedText = Formatted.factory(resolvedTokens);
if (containsRTLText(formattedText)) {
this.hasRTLText = true;
}
if (
!this.hasRTLText || // non-rtl text so can proceed safely
getRTLTextPluginStatus() === 'unavailable' || // We don't intend to lazy-load the rtl text plugin, so proceed with incorrect shaping
this.hasRTLText && globalRTLTextPlugin.isParsed() // Use the rtlText plugin to shape text
) {
text = transformText(formattedText, layer, evaluationFeature);
}
}
let icon: ResolvedImage;
if (hasIcon) {
// Expression evaluation will automatically coerce to Image
// but plain string token evaluation skips that pathway so do the
// conversion here.
const resolvedTokens = layer.getValueAndResolveTokens('icon-image', evaluationFeature, canonical, availableImages);
if (resolvedTokens instanceof ResolvedImage) {
icon = resolvedTokens;
} else {
icon = ResolvedImage.fromString(resolvedTokens);
}
}
if (!text && !icon) {
continue;
}
const sortKey = this.sortFeaturesByKey ?
symbolSortKey.evaluate(evaluationFeature, {}, canonical) :
undefined;
const symbolFeature: SymbolFeature = {
id,
text,
icon,
index,
sourceLayerIndex,
geometry: evaluationFeature.geometry,
properties: feature.properties,
type: vectorTileFeatureTypes[feature.type],
sortKey
};
this.features.push(symbolFeature);
if (icon) {
icons[icon.name] = true;
}
if (text) {
const fontStack = textFont.evaluate(evaluationFeature, {}, canonical).join(',');
const textAlongLine = layout.get('text-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point';
this.allowVerticalPlacement = this.writingModes && this.writingModes.indexOf(WritingMode.vertical) >= 0;
for (const section of text.sections) {
if (!section.image) {
const doesAllowVerticalWritingMode = allowsVerticalWritingMode(text.toString());
const sectionFont = section.fontStack || fontStack;
const sectionStack = stacks[sectionFont] = stacks[sectionFont] || {};
this.calculateGlyphDependencies(section.text, sectionStack, textAlongLine, this.allowVerticalPlacement, doesAllowVerticalWritingMode);
} else {
// Add section image to the list of dependencies.
icons[section.image.name] = true;
}
}
}
}
if (layout.get('symbol-placement') === 'line') {
// Merge adjacent lines with the same text to improve labelling.
// It's better to place labels on one long line than on many short segments.
this.features = mergeLines(this.features);
}
if (this.sortFeaturesByKey) {
this.features.sort((a, b) => {
// a.sortKey is always a number when sortFeaturesByKey is true
return (a.sortKey as number) - (b.sortKey as number);
});
}
}
update(states: FeatureStates, vtLayer: VectorTileLayer, imagePositions: {[_: string]: ImagePosition}) {
if (!this.stateDependentLayers.length) return;
this.text.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, imagePositions);
this.icon.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, imagePositions);
}
isEmpty() {
// When the bucket encounters only rtl-text but the plugin isnt loaded, no symbol instances will be created.
// In order for the bucket to be serialized, and not discarded as an empty bucket both checks are necessary.
return this.symbolInstances.length === 0 && !this.hasRTLText;
}
uploadPending() {
return !this.uploaded || this.text.programConfigurations.needsUpload || this.icon.programConfigurations.needsUpload;
}
upload(context: Context) {
if (!this.uploaded && this.hasDebugData()) {
this.textCollisionBox.upload(context);
this.iconCollisionBox.upload(context);
}
this.text.upload(context, this.sortFeaturesByY, !this.uploaded, this.text.programConfigurations.needsUpload);
this.icon.upload(context, this.sortFeaturesByY, !this.uploaded, this.icon.programConfigurations.needsUpload);
this.uploaded = true;
}
destroyDebugData() {
this.textCollisionBox.destroy();
this.iconCollisionBox.destroy();
}
destroy() {
this.text.destroy();
this.icon.destroy();
if (this.hasDebugData()) {
this.destroyDebugData();
}
}
addToLineVertexArray(anchor: Anchor, line: any) {
const lineStartIndex = this.lineVertexArray.length;
if (anchor.segment !== undefined) {
let sumForwardLength = anchor.dist(line[anchor.segment + 1]);
let sumBackwardLength = anchor.dist(line[anchor.segment]);
const vertices = {};
for (let i = anchor.segment + 1; i < line.length; i++) {
vertices[i] = {x: line[i].x, y: line[i].y, tileUnitDistanceFromAnchor: sumForwardLength};
if (i < line.length - 1) {
sumForwardLength += line[i + 1].dist(line[i]);
}
}
for (let i = anchor.segment || 0; i >= 0; i--) {
vertices[i] = {x: line[i].x, y: line[i].y, tileUnitDistanceFromAnchor: sumBackwardLength};
if (i > 0) {
sumBackwardLength += line[i - 1].dist(line[i]);
}
}
for (let i = 0; i < line.length; i++) {
const vertex = vertices[i];
this.lineVertexArray.emplaceBack(vertex.x, vertex.y, vertex.tileUnitDistanceFromAnchor);
}
}
return {
lineStartIndex,
lineLength: this.lineVertexArray.length - lineStartIndex
};
}
addSymbols(arrays: SymbolBuffers,
quads: Array<SymbolQuad>,
sizeVertex: any,
lineOffset: [number, number],
alongLine: boolean,
feature: SymbolFeature,
writingMode: WritingMode,
labelAnchor: Anchor,
lineStartIndex: number,
lineLength: number,
associatedIconIndex: number,
canonical: CanonicalTileID) {
const indexArray = arrays.indexArray;
const layoutVertexArray = arrays.layoutVertexArray;
const segment = arrays.segments.prepareSegment(4 * quads.length, layoutVertexArray, indexArray, this.canOverlap ? feature.sortKey as number : undefined);
const glyphOffsetArrayStart = this.glyphOffsetArray.length;
const vertexStartIndex = segment.vertexLength;
const angle = (this.allowVerticalPlacement && writingMode === WritingMode.vertical) ? Math.PI / 2 : 0;
const sections = feature.text && feature.text.sections;
for (let i = 0; i < quads.length; i++) {
const {tl, tr, bl, br, tex, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY, glyphOffset, isSDF, sectionIndex} = quads[i];
const index = segment.vertexLength;
const y = glyphOffset[1];
addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, tl.x, y + tl.y, tex.x, tex.y, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY);
addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, tr.x, y + tr.y, tex.x + tex.w, tex.y, sizeVertex, isSDF, pixelOffsetBR.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY);
addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, bl.x, y + bl.y, tex.x, tex.y + tex.h, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetBR.y, minFontScaleX, minFontScaleY);
addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, br.x, y + br.y, tex.x + tex.w, tex.y + tex.h, sizeVertex, isSDF, pixelOffsetBR.x, pixelOffsetBR.y, minFontScaleX, minFontScaleY);
addDynamicAttributes(arrays.dynamicLayoutVertexArray, labelAnchor, angle);
indexArray.emplaceBack(index, index + 1, index + 2);
indexArray.emplaceBack(index + 1, index + 2, index + 3);
segment.vertexLength += 4;
segment.primitiveLength += 2;
this.glyphOffsetArray.emplaceBack(glyphOffset[0]);
if (i === quads.length - 1 || sectionIndex !== quads[i + 1].sectionIndex) {
arrays.programConfigurations.populatePaintArrays(layoutVertexArray.length, feature, feature.index, {}, canonical, sections && sections[sectionIndex]);
}
}
arrays.placedSymbolArray.emplaceBack(
labelAnchor.x, labelAnchor.y,
glyphOffsetArrayStart,
this.glyphOffsetArray.length - glyphOffsetArrayStart,
vertexStartIndex,
lineStartIndex,
lineLength,
labelAnchor.segment,
sizeVertex ? sizeVertex[0] : 0,
sizeVertex ? sizeVertex[1] : 0,
lineOffset[0], lineOffset[1],
writingMode,
// placedOrientation is null initially; will be updated to horizontal(1)/vertical(2) if placed
0,
false as unknown as number,
// The crossTileID is only filled/used on the foreground for dynamic text anchors
0,
associatedIconIndex
);
}
_addCollisionDebugVertex(layoutVertexArray: StructArray, collisionVertexArray: StructArray, point: Point, anchorX: number, anchorY: number, extrude: Point) {
collisionVertexArray.emplaceBack(0, 0);
return layoutVertexArray.emplaceBack(
// pos
point.x,
point.y,
// a_anchor_pos
anchorX,
anchorY,
// extrude
Math.round(extrude.x),
Math.round(extrude.y));
}
addCollisionDebugVertices(x1: number, y1: number, x2: number, y2: number, arrays: CollisionBuffers, boxAnchorPoint: Point, symbolInstance: SymbolInstance) {
const segment = arrays.segments.prepareSegment(4, arrays.layoutVertexArray, arrays.indexArray);
const index = segment.vertexLength;
const layoutVertexArray = arrays.layoutVertexArray;
const collisionVertexArray = arrays.collisionVertexArray;
const anchorX = symbolInstance.anchorX;
const anchorY = symbolInstance.anchorY;
this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x1, y1));
this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x2, y1));
this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x2, y2));
this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x1, y2));
segment.vertexLength += 4;
const indexArray = arrays.indexArray as LineIndexArray;
indexArray.emplaceBack(index, index + 1);
indexArray.emplaceBack(index + 1, index + 2);
indexArray.emplaceBack(index + 2, index + 3);
indexArray.emplaceBack(index + 3, index);
segment.primitiveLength += 4;
}
addDebugCollisionBoxes(startIndex: number, endIndex: number, symbolInstance: SymbolInstance, isText: boolean) {
for (let b = startIndex; b < endIndex; b++) {
const box: CollisionBox = this.collisionBoxArray.get(b);
const x1 = box.x1;
const y1 = box.y1;
const x2 = box.x2;
const y2 = box.y2;
this.addCollisionDebugVertices(x1, y1, x2, y2,
isText ? this.textCollisionBox : this.iconCollisionBox,
box.anchorPoint, symbolInstance);
}
}
generateCollisionDebugBuffers() {
if (this.hasDebugData()) {
this.destroyDebugData();
}
this.textCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray);
this.iconCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray);
for (let i = 0; i < this.symbolInstances.length; i++) {
const symbolInstance = this.symbolInstances.get(i);
this.addDebugCollisionBoxes(symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance, true);
this.addDebugCollisionBoxes(symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance, true);
this.addDebugCollisionBoxes(symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance, false);
this.addDebugCollisionBoxes(symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex, symbolInstance, false);
}
}
// These flat arrays are meant to be quicker to iterate over than the source
// CollisionBoxArray
_deserializeCollisionBoxesForSymbol(
collisionBoxArray: CollisionBoxArray,
textStartIndex: number,
textEndIndex: number,
verticalTextStartIndex: number,
verticalTextEndIndex: number,
iconStartIndex: number,
iconEndIndex: number,
verticalIconStartIndex: number,
verticalIconEndIndex: number
): CollisionArrays {
const collisionArrays = {} as CollisionArrays;
for (let k = textStartIndex; k < textEndIndex; k++) {
const box: CollisionBox = collisionBoxArray.get(k);
collisionArrays.textBox = {x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY};
collisionArrays.textFeatureIndex = box.featureIndex;
break; // Only one box allowed per instance
}
for (let k = verticalTextStartIndex; k < verticalTextEndIndex; k++) {
const box: CollisionBox = collisionBoxArray.get(k);
collisionArrays.verticalTextBox = {x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY};
collisionArrays.verticalTextFeatureIndex = box.featureIndex;
break; // Only one box allowed per instance
}
for (let k = iconStartIndex; k < iconEndIndex; k++) {
// An icon can only have one box now, so this indexing is a bit vestigial...
const box: CollisionBox = collisionBoxArray.get(k);
collisionArrays.iconBox = {x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY};
collisionArrays.iconFeatureIndex = box.featureIndex;
break; // Only one box allowed per instance
}
for (let k = verticalIconStartIndex; k < verticalIconEndIndex; k++) {
// An icon can only have one box now, so this indexing is a bit vestigial...
const box: CollisionBox = collisionBoxArray.get(k);
collisionArrays.verticalIconBox = {x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY};
collisionArrays.verticalIconFeatureIndex = box.featureIndex;
break; // Only one box allowed per instance
}
return collisionArrays;
}
deserializeCollisionBoxes(collisionBoxArray: CollisionBoxArray) {
this.collisionArrays = [];
for (let i = 0; i < this.symbolInstances.length; i++) {
const symbolInstance = this.symbolInstances.get(i);
this.collisionArrays.push(this._deserializeCollisionBoxesForSymbol(
collisionBoxArray,
symbolInstance.textBoxStartIndex,
symbolInstance.textBoxEndIndex,
symbolInstance.verticalTextBoxStartIndex,
symbolInstance.verticalTextBoxEndIndex,
symbolInstance.iconBoxStartIndex,
symbolInstance.iconBoxEndIndex,
symbolInstance.verticalIconBoxStartIndex,
symbolInstance.verticalIconBoxEndIndex
));
}
}
hasTextData() {
return this.text.segments.get().length > 0;
}
hasIconData() {
return this.icon.segments.get().length > 0;
}
hasDebugData() {
return this.textCollisionBox && this.iconCollisionBox;
}
hasTextCollisionBoxData() {
return this.hasDebugData() && this.textCollisionBox.segments.get().length > 0;
}
hasIconCollisionBoxData() {
return this.hasDebugData() && this.iconCollisionBox.segments.get().length > 0;
}
addIndicesForPlacedSymbol(iconOrText: SymbolBuffers, placedSymbolIndex: number) {
const placedSymbol = iconOrText.placedSymbolArray.get(placedSymbolIndex);
const endIndex = placedSymbol.vertexStartIndex + placedSymbol.numGlyphs * 4;
for (let vertexIndex = placedSymbol.vertexStartIndex; vertexIndex < endIndex; vertexIndex += 4) {
iconOrText.indexArray.emplaceBack(vertexIndex, vertexIndex + 1, vertexIndex + 2);
iconOrText.indexArray.emplaceBack(vertexIndex + 1, vertexIndex + 2, vertexIndex + 3);
}
}
getSortedSymbolIndexes(angle: number) {
if (this.sortedAngle === angle && this.symbolInstanceIndexes !== undefined) {
return this.symbolInstanceIndexes;
}
const sin = Math.sin(angle);
const cos = Math.cos(angle);
const rotatedYs = [];
const featureIndexes = [];
const result = [];
for (let i = 0; i < this.symbolInstances.length; ++i) {
result.push(i);
const symbolInstance = this.symbolInstances.get(i);
rotatedYs.push(Math.round(sin * symbolInstance.anchorX + cos * symbolInstance.anchorY) | 0);
featureIndexes.push(symbolInstance.featureIndex);
}
result.sort((aIndex, bIndex) => {
return (rotatedYs[aIndex] - rotatedYs[bIndex]) ||
(featureIndexes[bIndex] - featureIndexes[aIndex]);
});
return result;
}
addToSortKeyRanges(symbolInstanceIndex: number, sortKey: number) {
const last = this.sortKeyRanges[this.sortKeyRanges.length - 1];
if (last && last.sortKey === sortKey) {
last.symbolInstanceEnd = symbolInstanceIndex + 1;
} else {
this.sortKeyRanges.push({
sortKey,
symbolInstanceStart: symbolInstanceIndex,
symbolInstanceEnd: symbolInstanceIndex + 1
});
}
}
sortFeatures(angle: number) {
if (!this.sortFeaturesByY) return;
if (this.sortedAngle === angle) return;
// The current approach to sorting doesn't sort across segments so don't try.
// Sorting within segments separately seemed not to be worth the complexity.
if (this.text.segments.get().length > 1 || this.icon.segments.get().length > 1) return;
// If the symbols are allowed to overlap sort them by their vertical screen position.
// The index array buffer is rewritten to reference the (unchanged) vertices in the
// sorted order.
// To avoid sorting the actual symbolInstance array we sort an array of indexes.
this.symbolInstanceIndexes = this.getSortedSymbolIndexes(angle);
this.sortedAngle = angle;
this.text.indexArray.clear();
this.icon.indexArray.clear();
this.featureSortOrder = [];
for (const i of this.symbolInstanceIndexes) {
const symbolInstance = this.symbolInstances.get(i);
this.featureSortOrder.push(symbolInstance.featureIndex);
[
symbolInstance.rightJustifiedTextSymbolIndex,
symbolInstance.centerJustifiedTextSymbolIndex,
symbolInstance.leftJustifiedTextSymbolIndex
].forEach((index, i, array) => {
// Only add a given index the first time it shows up,
// to avoid duplicate opacity entries when multiple justifications
// share the same glyphs.
if (index >= 0 && array.indexOf(index) === i) {
this.addIndicesForPlacedSymbol(this.text, index);
}
});
if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) {
this.addIndicesForPlacedSymbol(this.text, symbolInstance.verticalPlacedTextSymbolIndex);
}
if (symbolInstance.placedIconSymbolIndex >= 0) {
this.addIndicesForPlacedSymbol(this.icon, symbolInstance.placedIconSymbolIndex);
}
if (symbolInstance.verticalPlacedIconSymbolIndex >= 0) {
this.addIndicesForPlacedSymbol(this.icon, symbolInstance.verticalPlacedIconSymbolIndex);
}
}
if (this.text.indexBuffer) this.text.indexBuffer.updateData(this.text.indexArray);
if (this.icon.indexBuffer) this.icon.indexBuffer.updateData(this.icon.indexArray);
}
}
register('SymbolBucket', SymbolBucket, {
omit: ['layers', 'collisionBoxArray', 'features', 'compareText']
});
// this constant is based on the size of StructArray indexes used in a symbol
// bucket--namely, glyphOffsetArrayStart
// eg the max valid UInt16 is 65,535
// See https://github.com/mapbox/mapbox-gl-js/issues/2907 for motivation
// lineStartIndex and textBoxStartIndex could potentially be concerns
// but we expect there to be many fewer boxes/lines than glyphs
SymbolBucket.MAX_GLYPHS = 65535;
SymbolBucket.addDynamicAttributes = addDynamicAttributes;
export default SymbolBucket;
export {addDynamicAttributes}; | the_stack |
import './WorkItemRenderer.scss';
import * as React from 'react';
import { InfoIcon } from '../InfoIcon/InfoIcon';
import { getRowColumnStyle } from '../../../redux/Helpers/gridhelper';
import {
TooltipHost, TooltipOverflowMode
} from 'office-ui-fabric-react/lib/Tooltip';
import { css } from '@uifabric/utilities/lib/css';
import { hexToRgb } from '../colorhelper';
import { ProgressDetails } from '../ProgressDetails/ProgressDetails';
import { WorkItemStateColor, WorkItem } from 'TFS/WorkItemTracking/Contracts';
import { State } from '../State/State';
import { Icon } from 'office-ui-fabric-react/lib/Icon';
import { IIterationDuration } from "../../../redux/Contracts/IIterationDuration";
import { IDimension, CropWorkItem } from '../../../redux/Contracts/types';
import { IWorkItemOverrideIteration } from '../../../redux/modules/OverrideIterations/overriddenIterationContracts';
import { IProgressIndicator } from '../../../redux/Contracts/GridViewContracts';
import { ISettingsState, ProgressTrackingCriteria } from '../../../redux/modules/SettingsState/SettingsStateContracts';
import { PredecessorSuccessorIcon } from '../PredecessorSuccessorIcon/PredecessorSuccessorIcon';
interface IIdentity {
displayName: string;
uniqueName: string;
imageUrl: string;
}
export interface IWorkItemRendererProps {
id: number;
title: string;
assignedTo: IIdentity;
workItemStateColor: WorkItemStateColor;
color: string;
isRoot: boolean;
isSubGrid: boolean;
allowOverrideIteration: boolean;
iterationDuration: IIterationDuration;
dimension: IDimension;
crop: CropWorkItem;
progressIndicator: IProgressIndicator;
settingsState: ISettingsState;
efforts: number;
childrernWithNoEfforts: number;
isComplete: boolean;
teamFieldName: string;
onClick: (id: number) => void;
showDetails: (id: number) => void;
overrideIterationStart: (payload: IWorkItemOverrideIteration) => void;
overrideIterationEnd: () => void;
isDragging?: boolean;
connectDragSource?: (element: JSX.Element) => JSX.Element;
predecessors: WorkItem[];
successors: WorkItem[];
highlightPredecessorIcon: boolean;
highlighteSuccessorIcon: boolean;
onHighlightDependencies: (id: number, highlightSuccessor: boolean) => void;
onDismissDependencies: () => void;
}
export interface IWorkItemRendrerState {
left: number;
width: number;
top: number;
height: number;
resizing: boolean;
isLeft: boolean;
}
export class WorkItemRenderer extends React.Component<IWorkItemRendererProps, IWorkItemRendrerState> {
private _div: HTMLDivElement;
private _origPageX: number;
private _origWidth: number;
public constructor(props: IWorkItemRendererProps) {
super(props);
this.state = {
resizing: false
} as IWorkItemRendrerState;
}
public render() {
const {
id,
title,
onClick,
showDetails,
isRoot,
allowOverrideIteration,
isDragging,
crop,
iterationDuration,
progressIndicator,
workItemStateColor,
settingsState,
childrernWithNoEfforts,
efforts,
isSubGrid,
isComplete,
teamFieldName
} = this.props;
const {
resizing,
left,
top,
height,
width
} = this.state
let style = {};
if (!resizing) {
style = getRowColumnStyle(this.props.dimension);
} else {
style['position'] = 'fixed';
style['left'] = left + "px";
style['width'] = width + "px";
style['top'] = top + "px";
style['height'] = height + "px";
}
if (isDragging) {
style['border-color'] = hexToRgb(this.props.color, 0.1);
} else if (isComplete) {
style['border-color'] = hexToRgb(this.props.color, 0.3);
}
else {
style['border-color'] = hexToRgb(this.props.color, 0.7);
}
const rendererClass = isRoot ? "root-work-item-renderer" : "work-item-renderer";
let canOverrideLeft = allowOverrideIteration;
let canOverrideRight = allowOverrideIteration;
let leftCropped = false;
let rightCropped = false;
switch (crop) {
case CropWorkItem.Left: {
canOverrideLeft = false;
leftCropped = true;
break;
}
case CropWorkItem.Right: {
canOverrideRight = false;
rightCropped = true;
break;
}
case CropWorkItem.Both: {
canOverrideLeft = false;
canOverrideRight = false;
leftCropped = true;
rightCropped = true;
break;
}
}
const infoIcon = !isRoot && <InfoIcon id={id} onClick={id => showDetails(id)} />;
const additionalDetailsContainer = infoIcon ? "work-item-details-with-infoicon" : "work-item-details-without-infoicon";
let leftHandle = null;
let rightHandle = null;
if (allowOverrideIteration) {
leftHandle = canOverrideLeft && (
<div
className="work-item-iteration-override-handle"
onMouseDown={this._leftMouseDown}
onMouseUp={this._mouseUp}
/>
);
rightHandle = canOverrideRight && (
<div
className="work-item-iteration-override-handle"
onMouseDown={this._rightMouseDown}
onMouseUp={this._mouseUp}
/>
);
}
let startsFrom = <div />;
if (leftCropped) {
startsFrom = (
<TooltipHost
content={`Starts at ${iterationDuration.startIteration.name}`}>
<div className="work-item-start-iteration-indicator">{`${iterationDuration.startIteration.name}`}</div>
</TooltipHost>
);
}
let endsAt = <div />;
if (rightCropped) {
endsAt = (
<TooltipHost
content={`Ends at ${iterationDuration.endIteration.name}`}>
<div className="work-item-end-iteration-indicator">{`${iterationDuration.endIteration.name}`}</div>
</TooltipHost>
);
}
let secondRow = null;
if (settingsState.showWorkItemDetails) {
let assignedToDiv = null;
const {assignedTo} = this.props;
if(assignedTo) {
assignedToDiv = (
<TooltipHost content={assignedTo.displayName}>
<div className="assigned-to">
<img src={ assignedTo.imageUrl } />
</div>
</TooltipHost>
);
}
let stateIndicator = null;
if (workItemStateColor && !isRoot) {
stateIndicator = <State workItemStateColor={workItemStateColor} />;
}
let warning = null;
let warningMessages = [];
if (iterationDuration.childrenAreOutofBounds) {
warningMessages.push("Some user stories for this feature are outside the bounds of start or end iteration of this feature.");
}
if (settingsState.progressTrackingCriteria === ProgressTrackingCriteria.EffortsField && childrernWithNoEfforts > 0) {
warningMessages.push("Some user stories for this feature do not have story points set.");
}
if (isSubGrid && efforts === 0 && settingsState.progressTrackingCriteria === ProgressTrackingCriteria.EffortsField) {
warningMessages.push("Story points are not set.")
}
if (warningMessages.length > 0 && !isRoot) {
const content = warningMessages.join(",");
warning = (
<TooltipHost
content={content}>
<Icon
iconName={'Warning'}
className="work-item-warning"
onClick={() => {
if (!isSubGrid) {
showDetails(id);
} else {
onClick(id);
}
}
}
/>
</TooltipHost >
);
}
let progressDetails = null;
if (progressIndicator && !isRoot) {
progressDetails = (
<ProgressDetails
{...progressIndicator}
onClick={() => showDetails(id)}
/>);
}
secondRow = (
<div className="work-item-detail-row secondary-row">
{assignedToDiv}
{stateIndicator}
{progressDetails}
{warning}
</div>
);
}
let predecessorsIcon = null;
let successorsIcon = null;
if (this.props.predecessors && this.props.predecessors.length > 0) {
predecessorsIcon = (
<PredecessorSuccessorIcon
id={this.props.id}
hasSuccessors={false}
workItems={this.props.predecessors}
onShowWorkItem={this.props.onClick}
onHighlightDependencies={this.props.onHighlightDependencies}
onDismissDependencies={this.props.onDismissDependencies}
isHighlighted={this.props.highlighteSuccessorIcon}
teamFieldName={teamFieldName}
/>
);
}
if (this.props.successors && this.props.successors.length > 0) {
successorsIcon = (
<PredecessorSuccessorIcon
id={this.props.id}
hasSuccessors={true}
workItems={this.props.successors}
onShowWorkItem={this.props.onClick}
onHighlightDependencies={this.props.onHighlightDependencies}
onDismissDependencies={this.props.onDismissDependencies}
isHighlighted={this.props.highlightPredecessorIcon}
teamFieldName={teamFieldName}
/>
);
}
const item = (
<div
className={rendererClass}
style={style}
ref={(e) => this._div = e}
>
{leftHandle}
<div className="work-item-detail-rows">
<div className="work-item-detail-row">
<div
className={css("work-item-details-container", additionalDetailsContainer)}
>
{predecessorsIcon}
{startsFrom}
<div
className="title-contents"
onClick={() => onClick(id)}
>
<TooltipHost
content={title}
overflowMode={TooltipOverflowMode.Parent}
>
{title}
</TooltipHost>
</div>
{endsAt}
</div>
{infoIcon}
{successorsIcon}
</div>
{secondRow}
</div>
{rightHandle}
</div>
);
if (isRoot) {
return item;
}
const { connectDragSource } = this.props;
return connectDragSource(item);
}
private _leftMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
this._resizeStart(e, true);
}
private _rightMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
this._resizeStart(e, false);
}
private _mouseUp = () => {
window.removeEventListener("mousemove", this._mouseMove);
window.removeEventListener("mouseup", this._mouseUp);
this.setState({
resizing: false
});
this.props.overrideIterationEnd();
}
private _resizeStart(e: React.MouseEvent<HTMLDivElement>, isLeft: boolean) {
e.preventDefault();
const rect = this._div.getBoundingClientRect() as ClientRect;
this._origPageX = e.pageX;
this._origWidth = rect.width;
this.props.overrideIterationStart({
workItemId: this.props.id,
iterationDuration: {
startIterationId: this.props.iterationDuration.startIteration.id,
endIterationId: this.props.iterationDuration.endIteration.id,
user: VSS.getWebContext().user.uniqueName
},
changingStart: isLeft
});
window.addEventListener("mousemove", this._mouseMove);
window.addEventListener("mouseup", this._mouseUp);
this.setState({
left: rect.left,
width: rect.width,
top: rect.top - 10, //The rect.top does not contain margin-top
height: rect.height,
resizing: true,
isLeft: isLeft
});
}
private _mouseMove = (ev: MouseEvent) => {
ev.preventDefault();
const newPageX = ev.pageX;
if (this.state.isLeft) {
let width = 0;
// moved mouse left we need to increase the width
if (newPageX < this._origPageX) {
width = this._origWidth + (this._origPageX - newPageX);
} else {
// moved mouse right we need to decrease the width
width = this._origWidth - (newPageX - this._origPageX);
}
if (width > 100) {
this.setState({
left: ev.clientX,
width: width
});
}
} else {
let width = 0;
// movd left we need to decrease the width
if (newPageX < this._origPageX) {
width = this._origWidth - (this._origPageX - newPageX);
} else {
// We need to increase the width
width = this._origWidth + (newPageX - this._origPageX);
}
if (width > 100) {
this.setState({
width: width
});
}
}
}
} | the_stack |
import { GraphqlService, GraphqlResult, GraphqlServiceApi, } from '@slickgrid-universal/graphql';
import { autoinject } from 'aurelia-framework';
import { HttpClient, json } from 'aurelia-fetch-client';
import {
AureliaGridInstance,
Column,
Filters,
Formatters,
GridOption,
Metrics,
MultipleSelectOption,
OperatorType,
} from '../../aurelia-slickgrid';
import './example25.scss'; // provide custom CSS/SASS styling
const COUNTRIES_API = 'https://countries.trevorblades.com/';
export interface Country {
countryCode: string;
countryName: string;
countryNative: string;
countryPhone: number;
countryCurrency: string;
countryEmoji: string;
continentCode: string;
continentName: string;
languageCode: string;
languageName: string;
languageNative: string;
}
@autoinject()
export class Example25 {
title = 'Example 25: GraphQL Basic API without Pagination';
subTitle = `
Use basic GraphQL query with any external public APIs (<a href="https://github.com/ghiscoding/aurelia-slickgrid/wiki/GraphQL" target="_blank">Wiki docs</a>).
<ul>
<li>This Examples uses a Public GraphQL API that you can find at this link <a href="https://countries.trevorblades.com/" target="_blank">https://countries.trevorblades.com/</a></li>
<li>Compare to the regular and default GraphQL implementation, you will find the following differences</li>
<ul>
<li>There are no Pagination and we only use GraphQL <b>once</b> to load the data, then we use the grid as a regular local in-memory grid</li>
<li>We enabled the following 2 flags "useLocalFiltering" and "useLocalSorting" to use regular (in memory) DataView filtering/sorting</li>
</ul>
<li>NOTE - This Example calls multiple GraphQL queries, this is <b>ONLY</b> for demo purposes, you would typically only call 1 query (which is what GraphQL is good at)</li>
<li>This example is mainly to demo the use of GraphqlService to build the query and retrieve the data but also to demo how to mix that with local (in-memory) Filtering/Sorting strategies</li>
</ul>
`;
aureliaGrid!: AureliaGridInstance;
columnDefinitions: Column[] = [];
gridOptions!: GridOption;
dataset = [];
metrics!: Metrics;
isWithCursor = false;
graphqlQuery = '';
processing = false;
selectedLanguage = '';
status = { text: '', class: '' };
constructor(private http: HttpClient) {
// define the grid options & columns and then create the grid itself
this.defineGrid();
}
defineGrid() {
this.columnDefinitions = [
{ id: 'countryCode', field: 'code', name: 'Code', maxWidth: 90, sortable: true, filterable: true, columnGroup: 'Country' },
{ id: 'countryName', field: 'name', name: 'Name', width: 60, sortable: true, filterable: true, columnGroup: 'Country' },
{ id: 'countryNative', field: 'native', name: 'Native', width: 60, sortable: true, filterable: true, columnGroup: 'Country' },
{ id: 'countryPhone', field: 'phone', name: 'Phone Area Code', maxWidth: 110, sortable: true, filterable: true, columnGroup: 'Country' },
{ id: 'countryCurrency', field: 'currency', name: 'Currency', maxWidth: 90, sortable: true, filterable: true, columnGroup: 'Country' },
{ id: 'countryEmoji', field: 'emoji', name: 'Emoji', maxWidth: 90, sortable: true, columnGroup: 'Country' },
{
id: 'languageName', field: 'languages.name', name: 'Names', width: 60,
formatter: Formatters.arrayObjectToCsv, columnGroup: 'Language',
params: { propertyNames: ['name'], useFormatterOuputToFilter: true },
filterable: true,
// this Filter is a bit more tricky than others since the values are an array of objects
// what we can do is use the Formatter to search from the CSV string coming from the Formatter (with "useFormatterOuputToFilter: true")
// we also need to use the Operator IN_CONTAINS
filter: {
model: Filters.multipleSelect,
collectionAsync: this.getLanguages(),
operator: OperatorType.inContains,
collectionOptions: {
addBlankEntry: true,
// the data is not at the root of the array, so we must tell the Select Filter where to pull the data
collectionInsideObjectProperty: 'data.languages'
},
collectionFilterBy: [
// filter out any empty values
{ property: 'name', value: '', operator: 'NE' },
{ property: 'name', value: null, operator: 'NE' },
],
collectionSortBy: {
property: 'name'
},
customStructure: {
value: 'name',
label: 'name',
},
filterOptions: {
filter: true
} as MultipleSelectOption
},
},
{
id: 'languageNative', field: 'languages.native', name: 'Native', width: 60,
formatter: Formatters.arrayObjectToCsv, params: { propertyNames: ['native'], useFormatterOuputToFilter: true }, columnGroup: 'Language',
filterable: true,
filter: {
model: Filters.multipleSelect,
collectionAsync: this.getLanguages(),
operator: OperatorType.inContains,
collectionOptions: {
addBlankEntry: true,
// the data is not at the root of the array, so we must tell the Select Filter where to pull the data
collectionInsideObjectProperty: 'data.languages'
},
collectionFilterBy: [
// filter out any empty values
{ property: 'native', value: '', operator: 'NE' },
{ property: 'native', value: null, operator: 'NE' },
],
collectionSortBy: {
property: 'native'
},
customStructure: {
value: 'native',
label: 'native',
},
filterOptions: {
filter: true
} as MultipleSelectOption
},
},
{
id: 'languageCode', field: 'languages.code', name: 'Codes', maxWidth: 100,
formatter: Formatters.arrayObjectToCsv, params: { propertyNames: ['code'], useFormatterOuputToFilter: true }, columnGroup: 'Language',
filterable: true,
},
{
id: 'continentName', field: 'continent.name', name: 'Name', width: 60, sortable: true,
filterable: true, formatter: Formatters.complexObject, columnGroup: 'Continent'
},
{
id: 'continentCode', field: 'continent.code', name: 'Code', maxWidth: 90,
sortable: true,
filterable: true,
filter: {
model: Filters.singleSelect,
collectionAsync: this.getContinents(),
collectionOptions: {
// the data is not at the root of the array, so we must tell the Select Filter where to pull the data
collectionInsideObjectProperty: 'data.continents',
addBlankEntry: true,
separatorBetweenTextLabels: ': ',
},
customStructure: {
value: 'code',
label: 'code',
labelSuffix: 'name',
}
},
formatter: Formatters.complexObject, columnGroup: 'Continent',
},
];
this.gridOptions = {
autoResize: {
container: '#demo-container',
rightPadding: 10
},
enableFiltering: true,
enableCellNavigation: true,
enablePagination: false,
enableTranslate: true,
createPreHeaderPanel: true,
showPreHeaderPanel: true,
preHeaderPanelHeight: 28,
datasetIdPropertyName: 'code',
showCustomFooter: true, // display some metrics in the bottom custom footer
backendServiceApi: {
// use the GraphQL Service to build the query but use local (in memory) Filtering/Sorting strategies
// the useLocalFiltering/useLocalSorting flags can be enabled independently
service: new GraphqlService(),
useLocalFiltering: true,
useLocalSorting: true,
options: {
datasetName: 'countries', // the only REQUIRED property
},
// you can define the onInit callback OR enable the "executeProcessCommandOnInit" flag in the service init
preProcess: () => this.displaySpinner(true),
process: (query) => this.getCountries(query),
postProcess: (result: GraphqlResult<Country>) => {
this.metrics = result.metrics as Metrics;
this.displaySpinner(false);
}
} as GraphqlServiceApi
};
}
displaySpinner(isProcessing: boolean) {
this.processing = isProcessing;
this.status = (isProcessing)
? { text: 'processing...', class: 'alert alert-danger' }
: { text: 'done', class: 'alert alert-success' };
}
// --
// NOTE - Demo Code ONLY
// This Example calls multiple GraphQL queries, this is ONLY for demo purposes, you would typically only call 1 query (which is what GraphQL is good at)
// This demo is mainly to show the use of GraphqlService to build the query and retrieve the data but also to show how to mix that with usage of local Filtering/Sorting strategies
// --
/** Calling the GraphQL backend API to get the Countries with the Query created by the "process" method of GraphqlService */
getCountries(query: string): Promise<GraphqlResult<Country>> {
return new Promise(async resolve => {
const response = await this.http.fetch(COUNTRIES_API, {
method: 'post',
body: json({ query })
});
resolve(response.json());
});
}
/**
* Calling again the GraphQL backend API, however in this case we cannot use the GraphQL Service to build the query
* So we will have to write, by hand, the query to get the continents code & name
* We also need to resolve the data in a flat array (singleSelect/multipleSelect Filters only accept data at the root of the array)
*/
getContinents(): Promise<GraphqlResult<{ code: string; name: string; }>> {
const continentQuery = `query { continents { code, name }}`;
return new Promise(async resolve => {
const response = await this.http.fetch(COUNTRIES_API, {
method: 'post',
body: json({ query: continentQuery })
});
resolve(response.json());
});
}
/**
* Calling again the GraphQL backend API, however in this case we cannot use the GraphQL Service to build the query
* So we will have to write, by hand, the query to get the languages code & name
* We also need to resolve the data in a flat array (singleSelect/multipleSelect Filters only accept data at the root of the array)
*/
getLanguages(): Promise<GraphqlResult<{ code: string; name: string; native: string; }>> {
const languageQuery = `query { languages { code, name, native }}`;
return new Promise(async resolve => {
const response = await this.http.fetch(COUNTRIES_API, {
method: 'post',
body: json({ query: languageQuery })
});
resolve(response.json());
});
}
setFiltersDynamically() {
// we can Set Filters Dynamically (or different filters) afterward through the FilterService
this.aureliaGrid.filterService.updateFilters([
{ columnId: 'countryName', searchTerms: ['G'], operator: OperatorType.startsWith },
]);
}
setSortingDynamically() {
this.aureliaGrid.sortService.updateSorting([
// orders matter, whichever is first in array will be the first sorted column
{ columnId: 'billingAddressZip', direction: 'DESC' },
{ columnId: 'company', direction: 'ASC' },
]);
}
} | the_stack |
import { __assign } from 'tslib'
import { EventDef } from '../structs/event-def'
import { EVENT_NON_DATE_REFINERS, EVENT_DATE_REFINERS } from '../structs/event-parse'
import { EventInstance } from '../structs/event-instance'
import { EVENT_UI_REFINERS, EventUiHash } from '../component/event-ui'
import { EventMutation, applyMutationToEventStore } from '../structs/event-mutation'
import { diffDates, computeAlignedDayRange } from '../util/date'
import { createDuration, durationsEqual } from '../datelib/duration'
import { createFormatter } from '../datelib/formatting'
import { CalendarContext } from '../CalendarContext'
import { getRelevantEvents, EventStore } from '../structs/event-store'
import { Dictionary } from '../options'
// public
import {
DateInput,
DurationInput,
FormatterInput,
EventSourceApi,
} from '../api-type-deps'
export class EventApi {
_context: CalendarContext
_def: EventDef
_instance: EventInstance | null
// instance will be null if expressing a recurring event that has no current instances,
// OR if trying to validate an incoming external event that has no dates assigned
constructor(context: CalendarContext, def: EventDef, instance?: EventInstance) {
this._context = context
this._def = def
this._instance = instance || null
}
/*
TODO: make event struct more responsible for this
*/
setProp(name: string, val: any) {
if (name in EVENT_DATE_REFINERS) {
console.warn('Could not set date-related prop \'name\'. Use one of the date-related methods instead.')
// TODO: make proper aliasing system?
} else if (name === 'id') {
val = EVENT_NON_DATE_REFINERS[name](val)
this.mutate({
standardProps: { publicId: val }, // hardcoded internal name
})
} else if (name in EVENT_NON_DATE_REFINERS) {
val = EVENT_NON_DATE_REFINERS[name](val)
this.mutate({
standardProps: { [name]: val },
})
} else if (name in EVENT_UI_REFINERS) {
let ui = EVENT_UI_REFINERS[name](val)
if (name === 'color') {
ui = { backgroundColor: val, borderColor: val }
} else if (name === 'editable') {
ui = { startEditable: val, durationEditable: val }
} else {
ui = { [name]: val }
}
this.mutate({
standardProps: { ui },
})
} else {
console.warn(`Could not set prop '${name}'. Use setExtendedProp instead.`)
}
}
setExtendedProp(name: string, val: any) {
this.mutate({
extendedProps: { [name]: val },
})
}
setStart(startInput: DateInput, options: { granularity?: string, maintainDuration?: boolean } = {}) {
let { dateEnv } = this._context
let start = dateEnv.createMarker(startInput)
if (start && this._instance) { // TODO: warning if parsed bad
let instanceRange = this._instance.range
let startDelta = diffDates(instanceRange.start, start, dateEnv, options.granularity) // what if parsed bad!?
if (options.maintainDuration) {
this.mutate({ datesDelta: startDelta })
} else {
this.mutate({ startDelta })
}
}
}
setEnd(endInput: DateInput | null, options: { granularity?: string } = {}) {
let { dateEnv } = this._context
let end
if (endInput != null) {
end = dateEnv.createMarker(endInput)
if (!end) {
return // TODO: warning if parsed bad
}
}
if (this._instance) {
if (end) {
let endDelta = diffDates(this._instance.range.end, end, dateEnv, options.granularity)
this.mutate({ endDelta })
} else {
this.mutate({ standardProps: { hasEnd: false } })
}
}
}
setDates(startInput: DateInput, endInput: DateInput | null, options: { allDay?: boolean, granularity?: string } = {}) {
let { dateEnv } = this._context
let standardProps = { allDay: options.allDay } as any
let start = dateEnv.createMarker(startInput)
let end
if (!start) {
return // TODO: warning if parsed bad
}
if (endInput != null) {
end = dateEnv.createMarker(endInput)
if (!end) { // TODO: warning if parsed bad
return
}
}
if (this._instance) {
let instanceRange = this._instance.range
// when computing the diff for an event being converted to all-day,
// compute diff off of the all-day values the way event-mutation does.
if (options.allDay === true) {
instanceRange = computeAlignedDayRange(instanceRange)
}
let startDelta = diffDates(instanceRange.start, start, dateEnv, options.granularity)
if (end) {
let endDelta = diffDates(instanceRange.end, end, dateEnv, options.granularity)
if (durationsEqual(startDelta, endDelta)) {
this.mutate({ datesDelta: startDelta, standardProps })
} else {
this.mutate({ startDelta, endDelta, standardProps })
}
} else { // means "clear the end"
standardProps.hasEnd = false
this.mutate({ datesDelta: startDelta, standardProps })
}
}
}
moveStart(deltaInput: DurationInput) {
let delta = createDuration(deltaInput)
if (delta) { // TODO: warning if parsed bad
this.mutate({ startDelta: delta })
}
}
moveEnd(deltaInput: DurationInput) {
let delta = createDuration(deltaInput)
if (delta) { // TODO: warning if parsed bad
this.mutate({ endDelta: delta })
}
}
moveDates(deltaInput: DurationInput) {
let delta = createDuration(deltaInput)
if (delta) { // TODO: warning if parsed bad
this.mutate({ datesDelta: delta })
}
}
setAllDay(allDay: boolean, options: { maintainDuration?: boolean } = {}) {
let standardProps = { allDay } as any
let { maintainDuration } = options
if (maintainDuration == null) {
maintainDuration = this._context.options.allDayMaintainDuration
}
if (this._def.allDay !== allDay) {
standardProps.hasEnd = maintainDuration
}
this.mutate({ standardProps })
}
formatRange(formatInput: FormatterInput) {
let { dateEnv } = this._context
let instance = this._instance
let formatter = createFormatter(formatInput)
if (this._def.hasEnd) {
return dateEnv.formatRange(instance.range.start, instance.range.end, formatter, {
forcedStartTzo: instance.forcedStartTzo,
forcedEndTzo: instance.forcedEndTzo,
})
}
return dateEnv.format(instance.range.start, formatter, {
forcedTzo: instance.forcedStartTzo,
})
}
mutate(mutation: EventMutation) { // meant to be private. but plugins need access
let instance = this._instance
if (instance) {
let def = this._def
let context = this._context
let { eventStore } = context.getCurrentData()
let relevantEvents = getRelevantEvents(eventStore, instance.instanceId)
let eventConfigBase = {
'': { // HACK. always allow API to mutate events
display: '',
startEditable: true,
durationEditable: true,
constraints: [],
overlap: null,
allows: [],
backgroundColor: '',
borderColor: '',
textColor: '',
classNames: [],
},
} as EventUiHash
relevantEvents = applyMutationToEventStore(relevantEvents, eventConfigBase, mutation, context)
let oldEvent = new EventApi(context, def, instance) // snapshot
this._def = relevantEvents.defs[def.defId]
this._instance = relevantEvents.instances[instance.instanceId]
context.dispatch({
type: 'MERGE_EVENTS',
eventStore: relevantEvents,
})
context.emitter.trigger('eventChange', {
oldEvent,
event: this,
relatedEvents: buildEventApis(relevantEvents, context, instance),
revert() {
context.dispatch({
type: 'RESET_EVENTS',
eventStore, // the ORIGINAL store
})
},
})
}
}
remove() {
let context = this._context
let asStore = eventApiToStore(this)
context.dispatch({
type: 'REMOVE_EVENTS',
eventStore: asStore,
})
context.emitter.trigger('eventRemove', {
event: this,
relatedEvents: [],
revert() {
context.dispatch({
type: 'MERGE_EVENTS',
eventStore: asStore,
})
},
})
}
get source(): EventSourceApi | null {
let { sourceId } = this._def
if (sourceId) {
return new EventSourceApi(
this._context,
this._context.getCurrentData().eventSources[sourceId],
)
}
return null
}
get start(): Date | null {
return this._instance ?
this._context.dateEnv.toDate(this._instance.range.start) :
null
}
get end(): Date | null {
return (this._instance && this._def.hasEnd) ?
this._context.dateEnv.toDate(this._instance.range.end) :
null
}
get startStr(): string {
let instance = this._instance
if (instance) {
return this._context.dateEnv.formatIso(instance.range.start, {
omitTime: this._def.allDay,
forcedTzo: instance.forcedStartTzo,
})
}
return ''
}
get endStr(): string {
let instance = this._instance
if (instance && this._def.hasEnd) {
return this._context.dateEnv.formatIso(instance.range.end, {
omitTime: this._def.allDay,
forcedTzo: instance.forcedEndTzo,
})
}
return ''
}
// computable props that all access the def
// TODO: find a TypeScript-compatible way to do this at scale
get id() { return this._def.publicId }
get groupId() { return this._def.groupId }
get allDay() { return this._def.allDay }
get title() { return this._def.title }
get url() { return this._def.url }
get display() { return this._def.ui.display || 'auto' } // bad. just normalize the type earlier
get startEditable() { return this._def.ui.startEditable }
get durationEditable() { return this._def.ui.durationEditable }
get constraint() { return this._def.ui.constraints[0] || null }
get overlap() { return this._def.ui.overlap }
get allow() { return this._def.ui.allows[0] || null }
get backgroundColor() { return this._def.ui.backgroundColor }
get borderColor() { return this._def.ui.borderColor }
get textColor() { return this._def.ui.textColor }
// NOTE: user can't modify these because Object.freeze was called in event-def parsing
get classNames() { return this._def.ui.classNames }
get extendedProps() { return this._def.extendedProps }
toPlainObject(settings: { collapseExtendedProps?: boolean, collapseColor?: boolean } = {}): Dictionary {
let def = this._def
let { ui } = def
let { startStr, endStr } = this
let res: Dictionary = {}
if (def.title) {
res.title = def.title
}
if (startStr) {
res.start = startStr
}
if (endStr) {
res.end = endStr
}
if (def.publicId) {
res.id = def.publicId
}
if (def.groupId) {
res.groupId = def.groupId
}
if (def.url) {
res.url = def.url
}
if (ui.display && ui.display !== 'auto') {
res.display = ui.display
}
// TODO: what about recurring-event properties???
// TODO: include startEditable/durationEditable/constraint/overlap/allow
if (settings.collapseColor && ui.backgroundColor && ui.backgroundColor === ui.borderColor) {
res.color = ui.backgroundColor
} else {
if (ui.backgroundColor) {
res.backgroundColor = ui.backgroundColor
}
if (ui.borderColor) {
res.borderColor = ui.borderColor
}
}
if (ui.textColor) {
res.textColor = ui.textColor
}
if (ui.classNames.length) {
res.classNames = ui.classNames
}
if (Object.keys(def.extendedProps).length) {
if (settings.collapseExtendedProps) {
__assign(res, def.extendedProps)
} else {
res.extendedProps = def.extendedProps
}
}
return res
}
toJSON() {
return this.toPlainObject()
}
}
export function eventApiToStore(eventApi: EventApi): EventStore {
let def = eventApi._def
let instance = eventApi._instance
return {
defs: { [def.defId]: def },
instances: instance
? { [instance.instanceId]: instance }
: {},
}
}
export function buildEventApis(eventStore: EventStore, context: CalendarContext, excludeInstance?: EventInstance): EventApi[] {
let { defs, instances } = eventStore
let eventApis: EventApi[] = []
let excludeInstanceId = excludeInstance ? excludeInstance.instanceId : ''
for (let id in instances) {
let instance = instances[id]
let def = defs[instance.defId]
if (instance.instanceId !== excludeInstanceId) {
eventApis.push(new EventApi(context, def, instance))
}
}
return eventApis
} | the_stack |
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types";
import {
AddCustomRoutingEndpointsCommand,
AddCustomRoutingEndpointsCommandInput,
AddCustomRoutingEndpointsCommandOutput,
} from "./commands/AddCustomRoutingEndpointsCommand";
import {
AdvertiseByoipCidrCommand,
AdvertiseByoipCidrCommandInput,
AdvertiseByoipCidrCommandOutput,
} from "./commands/AdvertiseByoipCidrCommand";
import {
AllowCustomRoutingTrafficCommand,
AllowCustomRoutingTrafficCommandInput,
AllowCustomRoutingTrafficCommandOutput,
} from "./commands/AllowCustomRoutingTrafficCommand";
import {
CreateAcceleratorCommand,
CreateAcceleratorCommandInput,
CreateAcceleratorCommandOutput,
} from "./commands/CreateAcceleratorCommand";
import {
CreateCustomRoutingAcceleratorCommand,
CreateCustomRoutingAcceleratorCommandInput,
CreateCustomRoutingAcceleratorCommandOutput,
} from "./commands/CreateCustomRoutingAcceleratorCommand";
import {
CreateCustomRoutingEndpointGroupCommand,
CreateCustomRoutingEndpointGroupCommandInput,
CreateCustomRoutingEndpointGroupCommandOutput,
} from "./commands/CreateCustomRoutingEndpointGroupCommand";
import {
CreateCustomRoutingListenerCommand,
CreateCustomRoutingListenerCommandInput,
CreateCustomRoutingListenerCommandOutput,
} from "./commands/CreateCustomRoutingListenerCommand";
import {
CreateEndpointGroupCommand,
CreateEndpointGroupCommandInput,
CreateEndpointGroupCommandOutput,
} from "./commands/CreateEndpointGroupCommand";
import {
CreateListenerCommand,
CreateListenerCommandInput,
CreateListenerCommandOutput,
} from "./commands/CreateListenerCommand";
import {
DeleteAcceleratorCommand,
DeleteAcceleratorCommandInput,
DeleteAcceleratorCommandOutput,
} from "./commands/DeleteAcceleratorCommand";
import {
DeleteCustomRoutingAcceleratorCommand,
DeleteCustomRoutingAcceleratorCommandInput,
DeleteCustomRoutingAcceleratorCommandOutput,
} from "./commands/DeleteCustomRoutingAcceleratorCommand";
import {
DeleteCustomRoutingEndpointGroupCommand,
DeleteCustomRoutingEndpointGroupCommandInput,
DeleteCustomRoutingEndpointGroupCommandOutput,
} from "./commands/DeleteCustomRoutingEndpointGroupCommand";
import {
DeleteCustomRoutingListenerCommand,
DeleteCustomRoutingListenerCommandInput,
DeleteCustomRoutingListenerCommandOutput,
} from "./commands/DeleteCustomRoutingListenerCommand";
import {
DeleteEndpointGroupCommand,
DeleteEndpointGroupCommandInput,
DeleteEndpointGroupCommandOutput,
} from "./commands/DeleteEndpointGroupCommand";
import {
DeleteListenerCommand,
DeleteListenerCommandInput,
DeleteListenerCommandOutput,
} from "./commands/DeleteListenerCommand";
import {
DenyCustomRoutingTrafficCommand,
DenyCustomRoutingTrafficCommandInput,
DenyCustomRoutingTrafficCommandOutput,
} from "./commands/DenyCustomRoutingTrafficCommand";
import {
DeprovisionByoipCidrCommand,
DeprovisionByoipCidrCommandInput,
DeprovisionByoipCidrCommandOutput,
} from "./commands/DeprovisionByoipCidrCommand";
import {
DescribeAcceleratorAttributesCommand,
DescribeAcceleratorAttributesCommandInput,
DescribeAcceleratorAttributesCommandOutput,
} from "./commands/DescribeAcceleratorAttributesCommand";
import {
DescribeAcceleratorCommand,
DescribeAcceleratorCommandInput,
DescribeAcceleratorCommandOutput,
} from "./commands/DescribeAcceleratorCommand";
import {
DescribeCustomRoutingAcceleratorAttributesCommand,
DescribeCustomRoutingAcceleratorAttributesCommandInput,
DescribeCustomRoutingAcceleratorAttributesCommandOutput,
} from "./commands/DescribeCustomRoutingAcceleratorAttributesCommand";
import {
DescribeCustomRoutingAcceleratorCommand,
DescribeCustomRoutingAcceleratorCommandInput,
DescribeCustomRoutingAcceleratorCommandOutput,
} from "./commands/DescribeCustomRoutingAcceleratorCommand";
import {
DescribeCustomRoutingEndpointGroupCommand,
DescribeCustomRoutingEndpointGroupCommandInput,
DescribeCustomRoutingEndpointGroupCommandOutput,
} from "./commands/DescribeCustomRoutingEndpointGroupCommand";
import {
DescribeCustomRoutingListenerCommand,
DescribeCustomRoutingListenerCommandInput,
DescribeCustomRoutingListenerCommandOutput,
} from "./commands/DescribeCustomRoutingListenerCommand";
import {
DescribeEndpointGroupCommand,
DescribeEndpointGroupCommandInput,
DescribeEndpointGroupCommandOutput,
} from "./commands/DescribeEndpointGroupCommand";
import {
DescribeListenerCommand,
DescribeListenerCommandInput,
DescribeListenerCommandOutput,
} from "./commands/DescribeListenerCommand";
import {
ListAcceleratorsCommand,
ListAcceleratorsCommandInput,
ListAcceleratorsCommandOutput,
} from "./commands/ListAcceleratorsCommand";
import {
ListByoipCidrsCommand,
ListByoipCidrsCommandInput,
ListByoipCidrsCommandOutput,
} from "./commands/ListByoipCidrsCommand";
import {
ListCustomRoutingAcceleratorsCommand,
ListCustomRoutingAcceleratorsCommandInput,
ListCustomRoutingAcceleratorsCommandOutput,
} from "./commands/ListCustomRoutingAcceleratorsCommand";
import {
ListCustomRoutingEndpointGroupsCommand,
ListCustomRoutingEndpointGroupsCommandInput,
ListCustomRoutingEndpointGroupsCommandOutput,
} from "./commands/ListCustomRoutingEndpointGroupsCommand";
import {
ListCustomRoutingListenersCommand,
ListCustomRoutingListenersCommandInput,
ListCustomRoutingListenersCommandOutput,
} from "./commands/ListCustomRoutingListenersCommand";
import {
ListCustomRoutingPortMappingsByDestinationCommand,
ListCustomRoutingPortMappingsByDestinationCommandInput,
ListCustomRoutingPortMappingsByDestinationCommandOutput,
} from "./commands/ListCustomRoutingPortMappingsByDestinationCommand";
import {
ListCustomRoutingPortMappingsCommand,
ListCustomRoutingPortMappingsCommandInput,
ListCustomRoutingPortMappingsCommandOutput,
} from "./commands/ListCustomRoutingPortMappingsCommand";
import {
ListEndpointGroupsCommand,
ListEndpointGroupsCommandInput,
ListEndpointGroupsCommandOutput,
} from "./commands/ListEndpointGroupsCommand";
import {
ListListenersCommand,
ListListenersCommandInput,
ListListenersCommandOutput,
} from "./commands/ListListenersCommand";
import {
ListTagsForResourceCommand,
ListTagsForResourceCommandInput,
ListTagsForResourceCommandOutput,
} from "./commands/ListTagsForResourceCommand";
import {
ProvisionByoipCidrCommand,
ProvisionByoipCidrCommandInput,
ProvisionByoipCidrCommandOutput,
} from "./commands/ProvisionByoipCidrCommand";
import {
RemoveCustomRoutingEndpointsCommand,
RemoveCustomRoutingEndpointsCommandInput,
RemoveCustomRoutingEndpointsCommandOutput,
} from "./commands/RemoveCustomRoutingEndpointsCommand";
import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand";
import {
UntagResourceCommand,
UntagResourceCommandInput,
UntagResourceCommandOutput,
} from "./commands/UntagResourceCommand";
import {
UpdateAcceleratorAttributesCommand,
UpdateAcceleratorAttributesCommandInput,
UpdateAcceleratorAttributesCommandOutput,
} from "./commands/UpdateAcceleratorAttributesCommand";
import {
UpdateAcceleratorCommand,
UpdateAcceleratorCommandInput,
UpdateAcceleratorCommandOutput,
} from "./commands/UpdateAcceleratorCommand";
import {
UpdateCustomRoutingAcceleratorAttributesCommand,
UpdateCustomRoutingAcceleratorAttributesCommandInput,
UpdateCustomRoutingAcceleratorAttributesCommandOutput,
} from "./commands/UpdateCustomRoutingAcceleratorAttributesCommand";
import {
UpdateCustomRoutingAcceleratorCommand,
UpdateCustomRoutingAcceleratorCommandInput,
UpdateCustomRoutingAcceleratorCommandOutput,
} from "./commands/UpdateCustomRoutingAcceleratorCommand";
import {
UpdateCustomRoutingListenerCommand,
UpdateCustomRoutingListenerCommandInput,
UpdateCustomRoutingListenerCommandOutput,
} from "./commands/UpdateCustomRoutingListenerCommand";
import {
UpdateEndpointGroupCommand,
UpdateEndpointGroupCommandInput,
UpdateEndpointGroupCommandOutput,
} from "./commands/UpdateEndpointGroupCommand";
import {
UpdateListenerCommand,
UpdateListenerCommandInput,
UpdateListenerCommandOutput,
} from "./commands/UpdateListenerCommand";
import {
WithdrawByoipCidrCommand,
WithdrawByoipCidrCommandInput,
WithdrawByoipCidrCommandOutput,
} from "./commands/WithdrawByoipCidrCommand";
import { GlobalAcceleratorClient } from "./GlobalAcceleratorClient";
/**
* <fullname>AWS Global Accelerator</fullname>
* <p>This is the <i>AWS Global Accelerator API Reference</i>. This guide is for developers who need detailed information about
* AWS Global Accelerator API actions, data types, and errors. For more information about Global Accelerator features, see the
* <a href="https://docs.aws.amazon.com/global-accelerator/latest/dg/Welcome.html">AWS Global Accelerator Developer Guide</a>.</p>
*
* <p>AWS Global Accelerator is a service in which you create <i>accelerators</i> to improve the performance
* of your applications for local and global users. Depending on the type of accelerator you choose, you can
* gain additional benefits. </p>
* <ul>
* <li>
* <p>By using a standard accelerator, you can improve availability of your internet applications
* that are used by a global audience. With a standard accelerator, Global Accelerator directs traffic to optimal endpoints over the AWS
* global network. </p>
* </li>
* <li>
* <p>For other scenarios, you might choose a custom routing accelerator. With a custom routing accelerator, you
* can use application logic to directly map one or more users to a specific endpoint among many endpoints.</p>
* </li>
* </ul>
* <important>
* <p>Global Accelerator is a global service that supports endpoints in multiple AWS Regions but you must specify the
* US West (Oregon) Region to create or update accelerators.</p>
* </important>
* <p>By default, Global Accelerator provides you with two static IP addresses that you associate with your accelerator. With
* a standard accelerator, instead of using the
* IP addresses that Global Accelerator provides, you can configure these entry points to be IPv4 addresses from your own IP address ranges
* that you bring to Global Accelerator. The static IP addresses are anycast from the AWS edge network. For a standard accelerator,
* they distribute incoming application traffic across multiple endpoint resources in multiple AWS Regions, which increases
* the availability of your applications. Endpoints for standard accelerators can be Network Load Balancers, Application Load Balancers,
* Amazon EC2 instances, or Elastic IP addresses that are located in one AWS Region or multiple Regions. For custom routing
* accelerators, you map traffic that arrives to the static IP addresses to specific Amazon EC2 servers in endpoints that
* are virtual private cloud (VPC) subnets.</p>
*
* <important>
* <p>The static IP addresses remain assigned to your accelerator for as long as it exists, even if you
* disable the accelerator and it no longer accepts or routes traffic. However, when you
* <i>delete</i> an accelerator, you lose the static IP addresses that
* are assigned to it, so you can no longer route traffic by using them. You can use
* IAM policies like tag-based permissions with Global Accelerator to limit the users who have
* permissions to delete an accelerator. For more information, see <a href="https://docs.aws.amazon.com/global-accelerator/latest/dg/access-control-manage-access-tag-policies.html">Tag-based policies</a>.</p>
* </important>
* <p>For standard accelerators, Global Accelerator uses the AWS global network to route traffic to the optimal regional endpoint based
* on health, client location, and policies that you configure. The service reacts instantly to
* changes in health or configuration to ensure that internet traffic from clients is always
* directed to healthy endpoints.</p>
*
* <p>For a list of the AWS Regions where Global Accelerator and other services are currently supported, see the
* <a href="https://docs.aws.amazon.com/about-aws/global-infrastructure/regional-product-services/">AWS
* Region Table</a>.</p>
*
* <p>AWS Global Accelerator includes the following components:</p>
* <dl>
* <dt>Static IP addresses</dt>
* <dd>
* <p>Global Accelerator provides you with a set of two static IP addresses that are anycast from the AWS edge
* network. If you bring your own IP address range to AWS (BYOIP) to use with a standard accelerator, you
* can instead assign IP addresses from your own pool to use with your accelerator. For more information,
* see <a href="https://docs.aws.amazon.com/global-accelerator/latest/dg/using-byoip.html">
* Bring your own IP addresses (BYOIP) in AWS Global Accelerator</a>.</p>
* <p>The IP addresses serve as single fixed entry points for your clients. If you already have Elastic
* Load Balancing load balancers, Amazon EC2 instances, or Elastic IP address resources set up for your applications,
* you can easily add those to a standard accelerator in Global Accelerator. This allows Global Accelerator to use static IP addresses
* to access the resources.</p>
* <p>The static IP addresses remain assigned to your accelerator for as long as it exists, even
* if you disable the accelerator and it no longer accepts or routes traffic.
* However, when you <i>delete</i> an accelerator, you lose the
* static IP addresses that are assigned to it, so you can no longer route
* traffic by using them. You can use IAM policies like tag-based permissions
* with Global Accelerator to delete an accelerator. For more information, see <a href="https://docs.aws.amazon.com/global-accelerator/latest/dg/access-control-manage-access-tag-policies.html">Tag-based policies</a>.</p>
* </dd>
* <dt>Accelerator</dt>
* <dd>
* <p>An accelerator directs traffic to endpoints over the AWS global network to improve the
* performance of your internet applications. Each accelerator includes one or more listeners.</p>
* <p>There are two types of accelerators:</p>
* <ul>
* <li>
* <p>A <i>standard</i> accelerator directs traffic to the optimal AWS endpoint based
* on several factors, including the user’s location, the health of the endpoint, and the endpoint weights
* that you configure. This improves the availability and performance of your applications.
* Endpoints can be Network Load Balancers, Application Load Balancers, Amazon EC2 instances, or Elastic IP addresses.</p>
* </li>
* <li>
* <p>A <i>custom routing</i> accelerator directs traffic to one of possibly thousands of
* Amazon EC2 instances running in a single or multiple virtual private
* clouds (VPCs). With custom routing, listener ports are mapped to
* statically associate port ranges with VPC subnets, which
* allows Global Accelerator to determine an EC2 instance IP address at the time of
* connection. By default, all port mapping destinations in a VPC
* subnet can't receive traffic. You can choose to configure all
* destinations in the subnet to receive traffic, or to specify
* individual port mappings that can receive traffic.</p>
* </li>
* </ul>
* <p>For more information, see <a href="https://docs.aws.amazon.com/global-accelerator/latest/dg/introduction-accelerator-types.html">Types of accelerators</a>.</p>
* </dd>
* <dt>DNS name</dt>
* <dd>
* <p>Global Accelerator assigns each accelerator a default Domain Name System (DNS) name, similar to
* <code>a1234567890abcdef.awsglobalaccelerator.com</code>, that points to
* the static IP addresses that Global Accelerator assigns to you or that you choose from your
* own IP address range. Depending on the use
* case, you can use your accelerator's static IP addresses or DNS name to
* route traffic to your accelerator, or set up DNS records to route traffic using
* your own custom domain name.</p>
* </dd>
* <dt>Network zone</dt>
* <dd>
* <p>A network zone services the static IP addresses for your accelerator from a unique IP subnet. Similar to an
* AWS Availability Zone, a network zone is an isolated unit with its own set of physical infrastructure.
* When you configure an accelerator, by default, Global Accelerator allocates two IPv4 addresses for it. If one IP address from a
* network zone becomes unavailable due to IP address blocking by certain client networks, or network
* disruptions, then client applications can retry on the healthy static IP address from the other isolated
* network zone.</p>
* </dd>
* <dt>Listener</dt>
* <dd>
* <p>A listener processes inbound connections from clients to Global Accelerator, based on the port (or port range)
* and protocol (or protocols) that you configure. A listener can be configured for TCP, UDP, or both TCP and UDP protocols. Each
* listener has one or more endpoint groups associated with it, and traffic is forwarded
* to endpoints in one of the groups. You associate endpoint groups with listeners by specifying the Regions that you
* want to distribute traffic to. With a standard accelerator, traffic is distributed to optimal endpoints within the endpoint
* groups associated with a listener.</p>
* </dd>
* <dt>Endpoint group</dt>
* <dd>
* <p>Each endpoint group is associated with a specific AWS Region. Endpoint groups include one or
* more endpoints in the Region. With a standard accelerator, you can increase or reduce the percentage of
* traffic that would be otherwise directed to an endpoint group by adjusting a
* setting called a <i>traffic dial</i>. The traffic dial lets
* you easily do performance testing or blue/green deployment testing, for example, for new
* releases across different AWS Regions. </p>
* </dd>
* <dt>Endpoint</dt>
* <dd>
* <p>An endpoint is a resource that Global Accelerator directs traffic to.</p>
* <p>Endpoints for standard accelerators can be Network Load Balancers, Application Load Balancers, Amazon EC2 instances, or Elastic IP
* addresses. An Application Load Balancer endpoint can be internet-facing or internal. Traffic for
* standard accelerators is routed to endpoints based on the health of the
* endpoint along with configuration options that you choose, such as endpoint
* weights. For each endpoint, you can configure weights, which are numbers
* that you can use to specify the proportion of traffic to route to each one.
* This can be useful, for example, to do performance testing within a
* Region.</p>
* <p>Endpoints for custom routing accelerators are virtual private cloud (VPC) subnets with one
* or many EC2 instances.</p>
* </dd>
* </dl>
*/
export class GlobalAccelerator extends GlobalAcceleratorClient {
/**
* <p>Associate a virtual private cloud (VPC) subnet endpoint with your custom routing accelerator.</p>
* <p>The listener port range must be large enough to support the number of IP addresses that can be
* specified in your subnet. The number of ports required is: subnet size times the number
* of ports per destination EC2 instances. For example, a subnet defined as /24 requires a listener
* port range of at least 255 ports. </p>
* <p>Note: You must have enough remaining listener ports available to
* map to the subnet ports, or the call will fail with a LimitExceededException.</p>
* <p>By default, all destinations in a subnet in a custom routing accelerator cannot receive traffic. To enable all
* destinations to receive traffic, or to specify individual port mappings that can receive
* traffic, see the <a href="https://docs.aws.amazon.com/global-accelerator/latest/api/API_AllowCustomRoutingTraffic.html">
* AllowCustomRoutingTraffic</a> operation.</p>
*/
public addCustomRoutingEndpoints(
args: AddCustomRoutingEndpointsCommandInput,
options?: __HttpHandlerOptions
): Promise<AddCustomRoutingEndpointsCommandOutput>;
public addCustomRoutingEndpoints(
args: AddCustomRoutingEndpointsCommandInput,
cb: (err: any, data?: AddCustomRoutingEndpointsCommandOutput) => void
): void;
public addCustomRoutingEndpoints(
args: AddCustomRoutingEndpointsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: AddCustomRoutingEndpointsCommandOutput) => void
): void;
public addCustomRoutingEndpoints(
args: AddCustomRoutingEndpointsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AddCustomRoutingEndpointsCommandOutput) => void),
cb?: (err: any, data?: AddCustomRoutingEndpointsCommandOutput) => void
): Promise<AddCustomRoutingEndpointsCommandOutput> | void {
const command = new AddCustomRoutingEndpointsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Advertises an IPv4 address range that is provisioned for use with your AWS resources
* through bring your own IP addresses (BYOIP). It can take a few minutes before traffic to
* the specified addresses starts routing to AWS because of propagation delays. </p>
* <p>To stop advertising the BYOIP address range, use <a href="https://docs.aws.amazon.com/global-accelerator/latest/api/WithdrawByoipCidr.html">
* WithdrawByoipCidr</a>.</p>
* <p>For more information, see <a href="https://docs.aws.amazon.com/global-accelerator/latest/dg/using-byoip.html">Bring Your Own
* IP Addresses (BYOIP)</a> in the <i>AWS Global Accelerator Developer Guide</i>.</p>
*/
public advertiseByoipCidr(
args: AdvertiseByoipCidrCommandInput,
options?: __HttpHandlerOptions
): Promise<AdvertiseByoipCidrCommandOutput>;
public advertiseByoipCidr(
args: AdvertiseByoipCidrCommandInput,
cb: (err: any, data?: AdvertiseByoipCidrCommandOutput) => void
): void;
public advertiseByoipCidr(
args: AdvertiseByoipCidrCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: AdvertiseByoipCidrCommandOutput) => void
): void;
public advertiseByoipCidr(
args: AdvertiseByoipCidrCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AdvertiseByoipCidrCommandOutput) => void),
cb?: (err: any, data?: AdvertiseByoipCidrCommandOutput) => void
): Promise<AdvertiseByoipCidrCommandOutput> | void {
const command = new AdvertiseByoipCidrCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Specify the Amazon EC2 instance (destination) IP addresses and ports for a VPC subnet endpoint that can receive traffic
* for a custom routing accelerator. You can allow traffic to all destinations in the subnet endpoint, or allow traffic to a
* specified list of destination IP addresses and ports in the subnet. Note that you cannot specify IP addresses or ports
* outside of the range that you configured for the endpoint group.</p>
* <p>After you make changes, you can verify that the updates are complete by checking the status of your
* accelerator: the status changes from IN_PROGRESS to DEPLOYED.</p>
*/
public allowCustomRoutingTraffic(
args: AllowCustomRoutingTrafficCommandInput,
options?: __HttpHandlerOptions
): Promise<AllowCustomRoutingTrafficCommandOutput>;
public allowCustomRoutingTraffic(
args: AllowCustomRoutingTrafficCommandInput,
cb: (err: any, data?: AllowCustomRoutingTrafficCommandOutput) => void
): void;
public allowCustomRoutingTraffic(
args: AllowCustomRoutingTrafficCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: AllowCustomRoutingTrafficCommandOutput) => void
): void;
public allowCustomRoutingTraffic(
args: AllowCustomRoutingTrafficCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AllowCustomRoutingTrafficCommandOutput) => void),
cb?: (err: any, data?: AllowCustomRoutingTrafficCommandOutput) => void
): Promise<AllowCustomRoutingTrafficCommandOutput> | void {
const command = new AllowCustomRoutingTrafficCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Create an accelerator. An accelerator includes one or more listeners that process inbound connections and direct traffic
* to one or more endpoint groups, each of which includes endpoints, such as Network Load Balancers. </p>
* <important>
* <p>Global Accelerator is a global service that supports endpoints in multiple AWS Regions but you must specify the
* US West (Oregon) Region to create or update accelerators.</p>
* </important>
*/
public createAccelerator(
args: CreateAcceleratorCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateAcceleratorCommandOutput>;
public createAccelerator(
args: CreateAcceleratorCommandInput,
cb: (err: any, data?: CreateAcceleratorCommandOutput) => void
): void;
public createAccelerator(
args: CreateAcceleratorCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateAcceleratorCommandOutput) => void
): void;
public createAccelerator(
args: CreateAcceleratorCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateAcceleratorCommandOutput) => void),
cb?: (err: any, data?: CreateAcceleratorCommandOutput) => void
): Promise<CreateAcceleratorCommandOutput> | void {
const command = new CreateAcceleratorCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Create a custom routing accelerator. A custom routing accelerator directs traffic to one of possibly thousands
* of Amazon EC2 instance destinations running in a single or multiple virtual private clouds (VPC) subnet endpoints.</p>
* <p>Be aware that, by default, all destination EC2 instances in a VPC subnet endpoint cannot receive
* traffic. To enable all destinations to receive traffic, or to specify individual port
* mappings that can receive traffic, see the <a href="https://docs.aws.amazon.com/global-accelerator/latest/api/API_AllowCustomRoutingTraffic.html">
* AllowCustomRoutingTraffic</a> operation.</p>
* <important>
* <p>Global Accelerator is a global service that supports endpoints in multiple AWS Regions but you must specify the
* US West (Oregon) Region to create or update accelerators.</p>
* </important>
*/
public createCustomRoutingAccelerator(
args: CreateCustomRoutingAcceleratorCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateCustomRoutingAcceleratorCommandOutput>;
public createCustomRoutingAccelerator(
args: CreateCustomRoutingAcceleratorCommandInput,
cb: (err: any, data?: CreateCustomRoutingAcceleratorCommandOutput) => void
): void;
public createCustomRoutingAccelerator(
args: CreateCustomRoutingAcceleratorCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateCustomRoutingAcceleratorCommandOutput) => void
): void;
public createCustomRoutingAccelerator(
args: CreateCustomRoutingAcceleratorCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateCustomRoutingAcceleratorCommandOutput) => void),
cb?: (err: any, data?: CreateCustomRoutingAcceleratorCommandOutput) => void
): Promise<CreateCustomRoutingAcceleratorCommandOutput> | void {
const command = new CreateCustomRoutingAcceleratorCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Create an endpoint group for the specified listener for a custom routing accelerator.
* An endpoint group is a collection of endpoints in one AWS
* Region. </p>
*/
public createCustomRoutingEndpointGroup(
args: CreateCustomRoutingEndpointGroupCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateCustomRoutingEndpointGroupCommandOutput>;
public createCustomRoutingEndpointGroup(
args: CreateCustomRoutingEndpointGroupCommandInput,
cb: (err: any, data?: CreateCustomRoutingEndpointGroupCommandOutput) => void
): void;
public createCustomRoutingEndpointGroup(
args: CreateCustomRoutingEndpointGroupCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateCustomRoutingEndpointGroupCommandOutput) => void
): void;
public createCustomRoutingEndpointGroup(
args: CreateCustomRoutingEndpointGroupCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateCustomRoutingEndpointGroupCommandOutput) => void),
cb?: (err: any, data?: CreateCustomRoutingEndpointGroupCommandOutput) => void
): Promise<CreateCustomRoutingEndpointGroupCommandOutput> | void {
const command = new CreateCustomRoutingEndpointGroupCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Create a listener to process inbound connections from clients to a custom routing accelerator.
* Connections arrive to assigned static IP addresses on the port range that you specify. </p>
*/
public createCustomRoutingListener(
args: CreateCustomRoutingListenerCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateCustomRoutingListenerCommandOutput>;
public createCustomRoutingListener(
args: CreateCustomRoutingListenerCommandInput,
cb: (err: any, data?: CreateCustomRoutingListenerCommandOutput) => void
): void;
public createCustomRoutingListener(
args: CreateCustomRoutingListenerCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateCustomRoutingListenerCommandOutput) => void
): void;
public createCustomRoutingListener(
args: CreateCustomRoutingListenerCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateCustomRoutingListenerCommandOutput) => void),
cb?: (err: any, data?: CreateCustomRoutingListenerCommandOutput) => void
): Promise<CreateCustomRoutingListenerCommandOutput> | void {
const command = new CreateCustomRoutingListenerCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Create an endpoint group for the specified listener. An endpoint group is a collection of endpoints in one AWS
* Region. A resource must be valid and active when you add it as an endpoint.</p>
*/
public createEndpointGroup(
args: CreateEndpointGroupCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateEndpointGroupCommandOutput>;
public createEndpointGroup(
args: CreateEndpointGroupCommandInput,
cb: (err: any, data?: CreateEndpointGroupCommandOutput) => void
): void;
public createEndpointGroup(
args: CreateEndpointGroupCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateEndpointGroupCommandOutput) => void
): void;
public createEndpointGroup(
args: CreateEndpointGroupCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateEndpointGroupCommandOutput) => void),
cb?: (err: any, data?: CreateEndpointGroupCommandOutput) => void
): Promise<CreateEndpointGroupCommandOutput> | void {
const command = new CreateEndpointGroupCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Create a listener to process inbound connections from clients to an accelerator. Connections arrive to assigned static
* IP addresses on a port, port range, or list of port ranges that you specify. </p>
*/
public createListener(
args: CreateListenerCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateListenerCommandOutput>;
public createListener(
args: CreateListenerCommandInput,
cb: (err: any, data?: CreateListenerCommandOutput) => void
): void;
public createListener(
args: CreateListenerCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateListenerCommandOutput) => void
): void;
public createListener(
args: CreateListenerCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateListenerCommandOutput) => void),
cb?: (err: any, data?: CreateListenerCommandOutput) => void
): Promise<CreateListenerCommandOutput> | void {
const command = new CreateListenerCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Delete an accelerator. Before you can delete an accelerator, you must disable it and remove all dependent resources
* (listeners and endpoint groups). To disable the accelerator, update the accelerator to set <code>Enabled</code> to false.</p>
* <important>
* <p>When you create an accelerator, by default, Global Accelerator provides you with a set of two static IP addresses.
* Alternatively, you can bring your own IP address ranges to Global Accelerator and assign IP addresses from those ranges.
* </p>
* <p>The IP addresses are assigned to your accelerator for as long as it exists, even if you disable the accelerator and
* it no longer accepts or routes traffic. However, when you <i>delete</i> an accelerator, you lose the
* static IP addresses that are assigned to the accelerator, so you can no longer route traffic by using them.
* As a best practice, ensure that you have permissions in place to avoid inadvertently deleting accelerators. You
* can use IAM policies with Global Accelerator to limit the users who have permissions to delete an accelerator. For more information,
* see <a href="https://docs.aws.amazon.com/global-accelerator/latest/dg/auth-and-access-control.html">Authentication and Access Control</a> in
* the <i>AWS Global Accelerator Developer Guide</i>.</p>
* </important>
*/
public deleteAccelerator(
args: DeleteAcceleratorCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteAcceleratorCommandOutput>;
public deleteAccelerator(
args: DeleteAcceleratorCommandInput,
cb: (err: any, data?: DeleteAcceleratorCommandOutput) => void
): void;
public deleteAccelerator(
args: DeleteAcceleratorCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteAcceleratorCommandOutput) => void
): void;
public deleteAccelerator(
args: DeleteAcceleratorCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteAcceleratorCommandOutput) => void),
cb?: (err: any, data?: DeleteAcceleratorCommandOutput) => void
): Promise<DeleteAcceleratorCommandOutput> | void {
const command = new DeleteAcceleratorCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Delete a custom routing accelerator. Before you can delete an accelerator, you must disable it and remove all dependent resources
* (listeners and endpoint groups). To disable the accelerator, update the accelerator to set <code>Enabled</code> to false.</p>
* <important>
* <p>When you create a custom routing accelerator, by default, Global Accelerator provides you with a set of two static IP addresses.
* </p>
* <p>The IP
* addresses are assigned to your accelerator for as long as it exists, even if you disable the accelerator and
* it no longer accepts or routes traffic. However, when you <i>delete</i> an accelerator, you lose the
* static IP addresses that are assigned to the accelerator, so you can no longer route traffic by using them.
* As a best practice, ensure that you have permissions in place to avoid inadvertently deleting accelerators. You
* can use IAM policies with Global Accelerator to limit the users who have permissions to delete an accelerator. For more information,
* see <a href="https://docs.aws.amazon.com/global-accelerator/latest/dg/auth-and-access-control.html">Authentication and Access Control</a> in
* the <i>AWS Global Accelerator Developer Guide</i>.</p>
* </important>
*/
public deleteCustomRoutingAccelerator(
args: DeleteCustomRoutingAcceleratorCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteCustomRoutingAcceleratorCommandOutput>;
public deleteCustomRoutingAccelerator(
args: DeleteCustomRoutingAcceleratorCommandInput,
cb: (err: any, data?: DeleteCustomRoutingAcceleratorCommandOutput) => void
): void;
public deleteCustomRoutingAccelerator(
args: DeleteCustomRoutingAcceleratorCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteCustomRoutingAcceleratorCommandOutput) => void
): void;
public deleteCustomRoutingAccelerator(
args: DeleteCustomRoutingAcceleratorCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteCustomRoutingAcceleratorCommandOutput) => void),
cb?: (err: any, data?: DeleteCustomRoutingAcceleratorCommandOutput) => void
): Promise<DeleteCustomRoutingAcceleratorCommandOutput> | void {
const command = new DeleteCustomRoutingAcceleratorCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Delete an endpoint group from a listener for a custom routing accelerator.</p>
*/
public deleteCustomRoutingEndpointGroup(
args: DeleteCustomRoutingEndpointGroupCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteCustomRoutingEndpointGroupCommandOutput>;
public deleteCustomRoutingEndpointGroup(
args: DeleteCustomRoutingEndpointGroupCommandInput,
cb: (err: any, data?: DeleteCustomRoutingEndpointGroupCommandOutput) => void
): void;
public deleteCustomRoutingEndpointGroup(
args: DeleteCustomRoutingEndpointGroupCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteCustomRoutingEndpointGroupCommandOutput) => void
): void;
public deleteCustomRoutingEndpointGroup(
args: DeleteCustomRoutingEndpointGroupCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteCustomRoutingEndpointGroupCommandOutput) => void),
cb?: (err: any, data?: DeleteCustomRoutingEndpointGroupCommandOutput) => void
): Promise<DeleteCustomRoutingEndpointGroupCommandOutput> | void {
const command = new DeleteCustomRoutingEndpointGroupCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Delete a listener for a custom routing accelerator.</p>
*/
public deleteCustomRoutingListener(
args: DeleteCustomRoutingListenerCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteCustomRoutingListenerCommandOutput>;
public deleteCustomRoutingListener(
args: DeleteCustomRoutingListenerCommandInput,
cb: (err: any, data?: DeleteCustomRoutingListenerCommandOutput) => void
): void;
public deleteCustomRoutingListener(
args: DeleteCustomRoutingListenerCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteCustomRoutingListenerCommandOutput) => void
): void;
public deleteCustomRoutingListener(
args: DeleteCustomRoutingListenerCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteCustomRoutingListenerCommandOutput) => void),
cb?: (err: any, data?: DeleteCustomRoutingListenerCommandOutput) => void
): Promise<DeleteCustomRoutingListenerCommandOutput> | void {
const command = new DeleteCustomRoutingListenerCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Delete an endpoint group from a listener.</p>
*/
public deleteEndpointGroup(
args: DeleteEndpointGroupCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteEndpointGroupCommandOutput>;
public deleteEndpointGroup(
args: DeleteEndpointGroupCommandInput,
cb: (err: any, data?: DeleteEndpointGroupCommandOutput) => void
): void;
public deleteEndpointGroup(
args: DeleteEndpointGroupCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteEndpointGroupCommandOutput) => void
): void;
public deleteEndpointGroup(
args: DeleteEndpointGroupCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteEndpointGroupCommandOutput) => void),
cb?: (err: any, data?: DeleteEndpointGroupCommandOutput) => void
): Promise<DeleteEndpointGroupCommandOutput> | void {
const command = new DeleteEndpointGroupCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Delete a listener from an accelerator.</p>
*/
public deleteListener(
args: DeleteListenerCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteListenerCommandOutput>;
public deleteListener(
args: DeleteListenerCommandInput,
cb: (err: any, data?: DeleteListenerCommandOutput) => void
): void;
public deleteListener(
args: DeleteListenerCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteListenerCommandOutput) => void
): void;
public deleteListener(
args: DeleteListenerCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteListenerCommandOutput) => void),
cb?: (err: any, data?: DeleteListenerCommandOutput) => void
): Promise<DeleteListenerCommandOutput> | void {
const command = new DeleteListenerCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Specify the Amazon EC2 instance (destination) IP addresses and ports for a VPC subnet endpoint that cannot receive traffic
* for a custom routing accelerator. You can deny traffic to all destinations in the VPC endpoint, or deny traffic to a
* specified list of destination IP addresses and ports. Note that you cannot specify IP addresses
* or ports outside of the range that you configured for the endpoint group.</p>
* <p>After you make changes, you can verify that the updates are complete by checking the status of your
* accelerator: the status changes from IN_PROGRESS to DEPLOYED.</p>
*/
public denyCustomRoutingTraffic(
args: DenyCustomRoutingTrafficCommandInput,
options?: __HttpHandlerOptions
): Promise<DenyCustomRoutingTrafficCommandOutput>;
public denyCustomRoutingTraffic(
args: DenyCustomRoutingTrafficCommandInput,
cb: (err: any, data?: DenyCustomRoutingTrafficCommandOutput) => void
): void;
public denyCustomRoutingTraffic(
args: DenyCustomRoutingTrafficCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DenyCustomRoutingTrafficCommandOutput) => void
): void;
public denyCustomRoutingTraffic(
args: DenyCustomRoutingTrafficCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DenyCustomRoutingTrafficCommandOutput) => void),
cb?: (err: any, data?: DenyCustomRoutingTrafficCommandOutput) => void
): Promise<DenyCustomRoutingTrafficCommandOutput> | void {
const command = new DenyCustomRoutingTrafficCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Releases the specified address range that you provisioned to use with your AWS resources
* through bring your own IP addresses (BYOIP) and deletes the corresponding address pool. </p>
* <p>Before you can release an address range, you must stop advertising it by using <a href="https://docs.aws.amazon.com/global-accelerator/latest/api/WithdrawByoipCidr.html">WithdrawByoipCidr</a> and you must not have
* any accelerators that are using static IP addresses allocated from its address range.
* </p>
* <p>For more information, see <a href="https://docs.aws.amazon.com/global-accelerator/latest/dg/using-byoip.html">Bring Your Own
* IP Addresses (BYOIP)</a> in the <i>AWS Global Accelerator Developer Guide</i>.</p>
*/
public deprovisionByoipCidr(
args: DeprovisionByoipCidrCommandInput,
options?: __HttpHandlerOptions
): Promise<DeprovisionByoipCidrCommandOutput>;
public deprovisionByoipCidr(
args: DeprovisionByoipCidrCommandInput,
cb: (err: any, data?: DeprovisionByoipCidrCommandOutput) => void
): void;
public deprovisionByoipCidr(
args: DeprovisionByoipCidrCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeprovisionByoipCidrCommandOutput) => void
): void;
public deprovisionByoipCidr(
args: DeprovisionByoipCidrCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeprovisionByoipCidrCommandOutput) => void),
cb?: (err: any, data?: DeprovisionByoipCidrCommandOutput) => void
): Promise<DeprovisionByoipCidrCommandOutput> | void {
const command = new DeprovisionByoipCidrCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Describe an accelerator. </p>
*/
public describeAccelerator(
args: DescribeAcceleratorCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeAcceleratorCommandOutput>;
public describeAccelerator(
args: DescribeAcceleratorCommandInput,
cb: (err: any, data?: DescribeAcceleratorCommandOutput) => void
): void;
public describeAccelerator(
args: DescribeAcceleratorCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeAcceleratorCommandOutput) => void
): void;
public describeAccelerator(
args: DescribeAcceleratorCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeAcceleratorCommandOutput) => void),
cb?: (err: any, data?: DescribeAcceleratorCommandOutput) => void
): Promise<DescribeAcceleratorCommandOutput> | void {
const command = new DescribeAcceleratorCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Describe the attributes of an accelerator.
* </p>
*/
public describeAcceleratorAttributes(
args: DescribeAcceleratorAttributesCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeAcceleratorAttributesCommandOutput>;
public describeAcceleratorAttributes(
args: DescribeAcceleratorAttributesCommandInput,
cb: (err: any, data?: DescribeAcceleratorAttributesCommandOutput) => void
): void;
public describeAcceleratorAttributes(
args: DescribeAcceleratorAttributesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeAcceleratorAttributesCommandOutput) => void
): void;
public describeAcceleratorAttributes(
args: DescribeAcceleratorAttributesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeAcceleratorAttributesCommandOutput) => void),
cb?: (err: any, data?: DescribeAcceleratorAttributesCommandOutput) => void
): Promise<DescribeAcceleratorAttributesCommandOutput> | void {
const command = new DescribeAcceleratorAttributesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Describe a custom routing accelerator. </p>
*/
public describeCustomRoutingAccelerator(
args: DescribeCustomRoutingAcceleratorCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeCustomRoutingAcceleratorCommandOutput>;
public describeCustomRoutingAccelerator(
args: DescribeCustomRoutingAcceleratorCommandInput,
cb: (err: any, data?: DescribeCustomRoutingAcceleratorCommandOutput) => void
): void;
public describeCustomRoutingAccelerator(
args: DescribeCustomRoutingAcceleratorCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeCustomRoutingAcceleratorCommandOutput) => void
): void;
public describeCustomRoutingAccelerator(
args: DescribeCustomRoutingAcceleratorCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeCustomRoutingAcceleratorCommandOutput) => void),
cb?: (err: any, data?: DescribeCustomRoutingAcceleratorCommandOutput) => void
): Promise<DescribeCustomRoutingAcceleratorCommandOutput> | void {
const command = new DescribeCustomRoutingAcceleratorCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Describe the attributes of a custom routing accelerator. </p>
*/
public describeCustomRoutingAcceleratorAttributes(
args: DescribeCustomRoutingAcceleratorAttributesCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeCustomRoutingAcceleratorAttributesCommandOutput>;
public describeCustomRoutingAcceleratorAttributes(
args: DescribeCustomRoutingAcceleratorAttributesCommandInput,
cb: (err: any, data?: DescribeCustomRoutingAcceleratorAttributesCommandOutput) => void
): void;
public describeCustomRoutingAcceleratorAttributes(
args: DescribeCustomRoutingAcceleratorAttributesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeCustomRoutingAcceleratorAttributesCommandOutput) => void
): void;
public describeCustomRoutingAcceleratorAttributes(
args: DescribeCustomRoutingAcceleratorAttributesCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: DescribeCustomRoutingAcceleratorAttributesCommandOutput) => void),
cb?: (err: any, data?: DescribeCustomRoutingAcceleratorAttributesCommandOutput) => void
): Promise<DescribeCustomRoutingAcceleratorAttributesCommandOutput> | void {
const command = new DescribeCustomRoutingAcceleratorAttributesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Describe an endpoint group for a custom routing accelerator. </p>
*/
public describeCustomRoutingEndpointGroup(
args: DescribeCustomRoutingEndpointGroupCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeCustomRoutingEndpointGroupCommandOutput>;
public describeCustomRoutingEndpointGroup(
args: DescribeCustomRoutingEndpointGroupCommandInput,
cb: (err: any, data?: DescribeCustomRoutingEndpointGroupCommandOutput) => void
): void;
public describeCustomRoutingEndpointGroup(
args: DescribeCustomRoutingEndpointGroupCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeCustomRoutingEndpointGroupCommandOutput) => void
): void;
public describeCustomRoutingEndpointGroup(
args: DescribeCustomRoutingEndpointGroupCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeCustomRoutingEndpointGroupCommandOutput) => void),
cb?: (err: any, data?: DescribeCustomRoutingEndpointGroupCommandOutput) => void
): Promise<DescribeCustomRoutingEndpointGroupCommandOutput> | void {
const command = new DescribeCustomRoutingEndpointGroupCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>The description of a listener for a custom routing accelerator.</p>
*/
public describeCustomRoutingListener(
args: DescribeCustomRoutingListenerCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeCustomRoutingListenerCommandOutput>;
public describeCustomRoutingListener(
args: DescribeCustomRoutingListenerCommandInput,
cb: (err: any, data?: DescribeCustomRoutingListenerCommandOutput) => void
): void;
public describeCustomRoutingListener(
args: DescribeCustomRoutingListenerCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeCustomRoutingListenerCommandOutput) => void
): void;
public describeCustomRoutingListener(
args: DescribeCustomRoutingListenerCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeCustomRoutingListenerCommandOutput) => void),
cb?: (err: any, data?: DescribeCustomRoutingListenerCommandOutput) => void
): Promise<DescribeCustomRoutingListenerCommandOutput> | void {
const command = new DescribeCustomRoutingListenerCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Describe an endpoint group. </p>
*/
public describeEndpointGroup(
args: DescribeEndpointGroupCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeEndpointGroupCommandOutput>;
public describeEndpointGroup(
args: DescribeEndpointGroupCommandInput,
cb: (err: any, data?: DescribeEndpointGroupCommandOutput) => void
): void;
public describeEndpointGroup(
args: DescribeEndpointGroupCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeEndpointGroupCommandOutput) => void
): void;
public describeEndpointGroup(
args: DescribeEndpointGroupCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeEndpointGroupCommandOutput) => void),
cb?: (err: any, data?: DescribeEndpointGroupCommandOutput) => void
): Promise<DescribeEndpointGroupCommandOutput> | void {
const command = new DescribeEndpointGroupCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Describe a listener. </p>
*/
public describeListener(
args: DescribeListenerCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeListenerCommandOutput>;
public describeListener(
args: DescribeListenerCommandInput,
cb: (err: any, data?: DescribeListenerCommandOutput) => void
): void;
public describeListener(
args: DescribeListenerCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeListenerCommandOutput) => void
): void;
public describeListener(
args: DescribeListenerCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeListenerCommandOutput) => void),
cb?: (err: any, data?: DescribeListenerCommandOutput) => void
): Promise<DescribeListenerCommandOutput> | void {
const command = new DescribeListenerCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>List the accelerators for an AWS account. </p>
*/
public listAccelerators(
args: ListAcceleratorsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListAcceleratorsCommandOutput>;
public listAccelerators(
args: ListAcceleratorsCommandInput,
cb: (err: any, data?: ListAcceleratorsCommandOutput) => void
): void;
public listAccelerators(
args: ListAcceleratorsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListAcceleratorsCommandOutput) => void
): void;
public listAccelerators(
args: ListAcceleratorsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListAcceleratorsCommandOutput) => void),
cb?: (err: any, data?: ListAcceleratorsCommandOutput) => void
): Promise<ListAcceleratorsCommandOutput> | void {
const command = new ListAcceleratorsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists the IP address ranges that were specified in calls to <a href="https://docs.aws.amazon.com/global-accelerator/latest/api/ProvisionByoipCidr.html">ProvisionByoipCidr</a>, including
* the current state and a history of state changes.</p>
*/
public listByoipCidrs(
args: ListByoipCidrsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListByoipCidrsCommandOutput>;
public listByoipCidrs(
args: ListByoipCidrsCommandInput,
cb: (err: any, data?: ListByoipCidrsCommandOutput) => void
): void;
public listByoipCidrs(
args: ListByoipCidrsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListByoipCidrsCommandOutput) => void
): void;
public listByoipCidrs(
args: ListByoipCidrsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListByoipCidrsCommandOutput) => void),
cb?: (err: any, data?: ListByoipCidrsCommandOutput) => void
): Promise<ListByoipCidrsCommandOutput> | void {
const command = new ListByoipCidrsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>List the custom routing accelerators for an AWS account. </p>
*/
public listCustomRoutingAccelerators(
args: ListCustomRoutingAcceleratorsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListCustomRoutingAcceleratorsCommandOutput>;
public listCustomRoutingAccelerators(
args: ListCustomRoutingAcceleratorsCommandInput,
cb: (err: any, data?: ListCustomRoutingAcceleratorsCommandOutput) => void
): void;
public listCustomRoutingAccelerators(
args: ListCustomRoutingAcceleratorsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListCustomRoutingAcceleratorsCommandOutput) => void
): void;
public listCustomRoutingAccelerators(
args: ListCustomRoutingAcceleratorsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListCustomRoutingAcceleratorsCommandOutput) => void),
cb?: (err: any, data?: ListCustomRoutingAcceleratorsCommandOutput) => void
): Promise<ListCustomRoutingAcceleratorsCommandOutput> | void {
const command = new ListCustomRoutingAcceleratorsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>List the endpoint groups that are associated with a listener for a custom routing accelerator. </p>
*/
public listCustomRoutingEndpointGroups(
args: ListCustomRoutingEndpointGroupsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListCustomRoutingEndpointGroupsCommandOutput>;
public listCustomRoutingEndpointGroups(
args: ListCustomRoutingEndpointGroupsCommandInput,
cb: (err: any, data?: ListCustomRoutingEndpointGroupsCommandOutput) => void
): void;
public listCustomRoutingEndpointGroups(
args: ListCustomRoutingEndpointGroupsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListCustomRoutingEndpointGroupsCommandOutput) => void
): void;
public listCustomRoutingEndpointGroups(
args: ListCustomRoutingEndpointGroupsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListCustomRoutingEndpointGroupsCommandOutput) => void),
cb?: (err: any, data?: ListCustomRoutingEndpointGroupsCommandOutput) => void
): Promise<ListCustomRoutingEndpointGroupsCommandOutput> | void {
const command = new ListCustomRoutingEndpointGroupsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>List the listeners for a custom routing accelerator. </p>
*/
public listCustomRoutingListeners(
args: ListCustomRoutingListenersCommandInput,
options?: __HttpHandlerOptions
): Promise<ListCustomRoutingListenersCommandOutput>;
public listCustomRoutingListeners(
args: ListCustomRoutingListenersCommandInput,
cb: (err: any, data?: ListCustomRoutingListenersCommandOutput) => void
): void;
public listCustomRoutingListeners(
args: ListCustomRoutingListenersCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListCustomRoutingListenersCommandOutput) => void
): void;
public listCustomRoutingListeners(
args: ListCustomRoutingListenersCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListCustomRoutingListenersCommandOutput) => void),
cb?: (err: any, data?: ListCustomRoutingListenersCommandOutput) => void
): Promise<ListCustomRoutingListenersCommandOutput> | void {
const command = new ListCustomRoutingListenersCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Provides a complete mapping from the public accelerator IP address and port to destination EC2 instance
* IP addresses and ports in the virtual public cloud (VPC) subnet endpoint for a custom routing accelerator.
* For each subnet endpoint that you add, Global Accelerator creates a new static port mapping for the accelerator. The port
* mappings don't change after Global Accelerator generates them, so you can retrieve and cache the full mapping on your servers. </p>
* <p>If you remove a subnet from your accelerator, Global Accelerator removes (reclaims) the port mappings. If you add a subnet to
* your accelerator, Global Accelerator creates new port mappings (the existing ones don't change). If you add or remove EC2 instances
* in your subnet, the port mappings don't change, because the mappings are created when you add the subnet to Global Accelerator.</p>
* <p>The mappings also include a flag for each destination denoting which destination IP addresses and
* ports are allowed or denied traffic.</p>
*/
public listCustomRoutingPortMappings(
args: ListCustomRoutingPortMappingsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListCustomRoutingPortMappingsCommandOutput>;
public listCustomRoutingPortMappings(
args: ListCustomRoutingPortMappingsCommandInput,
cb: (err: any, data?: ListCustomRoutingPortMappingsCommandOutput) => void
): void;
public listCustomRoutingPortMappings(
args: ListCustomRoutingPortMappingsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListCustomRoutingPortMappingsCommandOutput) => void
): void;
public listCustomRoutingPortMappings(
args: ListCustomRoutingPortMappingsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListCustomRoutingPortMappingsCommandOutput) => void),
cb?: (err: any, data?: ListCustomRoutingPortMappingsCommandOutput) => void
): Promise<ListCustomRoutingPortMappingsCommandOutput> | void {
const command = new ListCustomRoutingPortMappingsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>List the port mappings for a specific EC2 instance (destination) in a VPC subnet endpoint. The
* response is the mappings for one destination IP address. This is useful when your subnet endpoint has mappings that
* span multiple custom routing accelerators in your account, or for scenarios where you only want to
* list the port mappings for a specific destination instance.</p>
*/
public listCustomRoutingPortMappingsByDestination(
args: ListCustomRoutingPortMappingsByDestinationCommandInput,
options?: __HttpHandlerOptions
): Promise<ListCustomRoutingPortMappingsByDestinationCommandOutput>;
public listCustomRoutingPortMappingsByDestination(
args: ListCustomRoutingPortMappingsByDestinationCommandInput,
cb: (err: any, data?: ListCustomRoutingPortMappingsByDestinationCommandOutput) => void
): void;
public listCustomRoutingPortMappingsByDestination(
args: ListCustomRoutingPortMappingsByDestinationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListCustomRoutingPortMappingsByDestinationCommandOutput) => void
): void;
public listCustomRoutingPortMappingsByDestination(
args: ListCustomRoutingPortMappingsByDestinationCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: ListCustomRoutingPortMappingsByDestinationCommandOutput) => void),
cb?: (err: any, data?: ListCustomRoutingPortMappingsByDestinationCommandOutput) => void
): Promise<ListCustomRoutingPortMappingsByDestinationCommandOutput> | void {
const command = new ListCustomRoutingPortMappingsByDestinationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>List the endpoint groups that are associated with a listener. </p>
*/
public listEndpointGroups(
args: ListEndpointGroupsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListEndpointGroupsCommandOutput>;
public listEndpointGroups(
args: ListEndpointGroupsCommandInput,
cb: (err: any, data?: ListEndpointGroupsCommandOutput) => void
): void;
public listEndpointGroups(
args: ListEndpointGroupsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListEndpointGroupsCommandOutput) => void
): void;
public listEndpointGroups(
args: ListEndpointGroupsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListEndpointGroupsCommandOutput) => void),
cb?: (err: any, data?: ListEndpointGroupsCommandOutput) => void
): Promise<ListEndpointGroupsCommandOutput> | void {
const command = new ListEndpointGroupsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>List the listeners for an accelerator. </p>
*/
public listListeners(
args: ListListenersCommandInput,
options?: __HttpHandlerOptions
): Promise<ListListenersCommandOutput>;
public listListeners(
args: ListListenersCommandInput,
cb: (err: any, data?: ListListenersCommandOutput) => void
): void;
public listListeners(
args: ListListenersCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListListenersCommandOutput) => void
): void;
public listListeners(
args: ListListenersCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListListenersCommandOutput) => void),
cb?: (err: any, data?: ListListenersCommandOutput) => void
): Promise<ListListenersCommandOutput> | void {
const command = new ListListenersCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>List all tags for an accelerator. </p>
* <p>For more information, see <a href="https://docs.aws.amazon.com/global-accelerator/latest/dg/tagging-in-global-accelerator.html">Tagging
* in AWS Global Accelerator</a> in the <i>AWS Global Accelerator Developer Guide</i>. </p>
*/
public listTagsForResource(
args: ListTagsForResourceCommandInput,
options?: __HttpHandlerOptions
): Promise<ListTagsForResourceCommandOutput>;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
cb: (err: any, data?: ListTagsForResourceCommandOutput) => void
): void;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListTagsForResourceCommandOutput) => void
): void;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void),
cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void
): Promise<ListTagsForResourceCommandOutput> | void {
const command = new ListTagsForResourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Provisions an IP address range to use with your AWS resources through bring your own IP
* addresses (BYOIP) and creates a corresponding address pool. After the address range is provisioned,
* it is ready to be advertised using <a href="https://docs.aws.amazon.com/global-accelerator/latest/api/AdvertiseByoipCidr.html">
* AdvertiseByoipCidr</a>.</p>
* <p>For more information, see <a href="https://docs.aws.amazon.com/global-accelerator/latest/dg/using-byoip.html">Bring Your Own
* IP Addresses (BYOIP)</a> in the <i>AWS Global Accelerator Developer Guide</i>.</p>
*/
public provisionByoipCidr(
args: ProvisionByoipCidrCommandInput,
options?: __HttpHandlerOptions
): Promise<ProvisionByoipCidrCommandOutput>;
public provisionByoipCidr(
args: ProvisionByoipCidrCommandInput,
cb: (err: any, data?: ProvisionByoipCidrCommandOutput) => void
): void;
public provisionByoipCidr(
args: ProvisionByoipCidrCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ProvisionByoipCidrCommandOutput) => void
): void;
public provisionByoipCidr(
args: ProvisionByoipCidrCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ProvisionByoipCidrCommandOutput) => void),
cb?: (err: any, data?: ProvisionByoipCidrCommandOutput) => void
): Promise<ProvisionByoipCidrCommandOutput> | void {
const command = new ProvisionByoipCidrCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Remove endpoints from a custom routing accelerator.</p>
*/
public removeCustomRoutingEndpoints(
args: RemoveCustomRoutingEndpointsCommandInput,
options?: __HttpHandlerOptions
): Promise<RemoveCustomRoutingEndpointsCommandOutput>;
public removeCustomRoutingEndpoints(
args: RemoveCustomRoutingEndpointsCommandInput,
cb: (err: any, data?: RemoveCustomRoutingEndpointsCommandOutput) => void
): void;
public removeCustomRoutingEndpoints(
args: RemoveCustomRoutingEndpointsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: RemoveCustomRoutingEndpointsCommandOutput) => void
): void;
public removeCustomRoutingEndpoints(
args: RemoveCustomRoutingEndpointsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RemoveCustomRoutingEndpointsCommandOutput) => void),
cb?: (err: any, data?: RemoveCustomRoutingEndpointsCommandOutput) => void
): Promise<RemoveCustomRoutingEndpointsCommandOutput> | void {
const command = new RemoveCustomRoutingEndpointsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Add tags to an accelerator resource. </p>
* <p>For more information, see <a href="https://docs.aws.amazon.com/global-accelerator/latest/dg/tagging-in-global-accelerator.html">Tagging
* in AWS Global Accelerator</a> in the <i>AWS Global Accelerator Developer Guide</i>. </p>
*/
public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>;
public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void;
public tagResource(
args: TagResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: TagResourceCommandOutput) => void
): void;
public tagResource(
args: TagResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void),
cb?: (err: any, data?: TagResourceCommandOutput) => void
): Promise<TagResourceCommandOutput> | void {
const command = new TagResourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Remove tags from a Global Accelerator resource. When you specify a tag key, the action removes both that key and its associated value.
* The operation succeeds even if you attempt to remove tags from an accelerator that was already removed.</p>
* <p>For more information, see <a href="https://docs.aws.amazon.com/global-accelerator/latest/dg/tagging-in-global-accelerator.html">Tagging
* in AWS Global Accelerator</a> in the <i>AWS Global Accelerator Developer Guide</i>.</p>
*/
public untagResource(
args: UntagResourceCommandInput,
options?: __HttpHandlerOptions
): Promise<UntagResourceCommandOutput>;
public untagResource(
args: UntagResourceCommandInput,
cb: (err: any, data?: UntagResourceCommandOutput) => void
): void;
public untagResource(
args: UntagResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UntagResourceCommandOutput) => void
): void;
public untagResource(
args: UntagResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void),
cb?: (err: any, data?: UntagResourceCommandOutput) => void
): Promise<UntagResourceCommandOutput> | void {
const command = new UntagResourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Update an accelerator. </p>
*
* <important>
* <p>Global Accelerator is a global service that supports endpoints in multiple AWS Regions but you must specify the
* US West (Oregon) Region to create or update accelerators.</p>
* </important>
*/
public updateAccelerator(
args: UpdateAcceleratorCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateAcceleratorCommandOutput>;
public updateAccelerator(
args: UpdateAcceleratorCommandInput,
cb: (err: any, data?: UpdateAcceleratorCommandOutput) => void
): void;
public updateAccelerator(
args: UpdateAcceleratorCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateAcceleratorCommandOutput) => void
): void;
public updateAccelerator(
args: UpdateAcceleratorCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateAcceleratorCommandOutput) => void),
cb?: (err: any, data?: UpdateAcceleratorCommandOutput) => void
): Promise<UpdateAcceleratorCommandOutput> | void {
const command = new UpdateAcceleratorCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Update the attributes for an accelerator. </p>
*/
public updateAcceleratorAttributes(
args: UpdateAcceleratorAttributesCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateAcceleratorAttributesCommandOutput>;
public updateAcceleratorAttributes(
args: UpdateAcceleratorAttributesCommandInput,
cb: (err: any, data?: UpdateAcceleratorAttributesCommandOutput) => void
): void;
public updateAcceleratorAttributes(
args: UpdateAcceleratorAttributesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateAcceleratorAttributesCommandOutput) => void
): void;
public updateAcceleratorAttributes(
args: UpdateAcceleratorAttributesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateAcceleratorAttributesCommandOutput) => void),
cb?: (err: any, data?: UpdateAcceleratorAttributesCommandOutput) => void
): Promise<UpdateAcceleratorAttributesCommandOutput> | void {
const command = new UpdateAcceleratorAttributesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Update a custom routing accelerator. </p>
*/
public updateCustomRoutingAccelerator(
args: UpdateCustomRoutingAcceleratorCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateCustomRoutingAcceleratorCommandOutput>;
public updateCustomRoutingAccelerator(
args: UpdateCustomRoutingAcceleratorCommandInput,
cb: (err: any, data?: UpdateCustomRoutingAcceleratorCommandOutput) => void
): void;
public updateCustomRoutingAccelerator(
args: UpdateCustomRoutingAcceleratorCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateCustomRoutingAcceleratorCommandOutput) => void
): void;
public updateCustomRoutingAccelerator(
args: UpdateCustomRoutingAcceleratorCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateCustomRoutingAcceleratorCommandOutput) => void),
cb?: (err: any, data?: UpdateCustomRoutingAcceleratorCommandOutput) => void
): Promise<UpdateCustomRoutingAcceleratorCommandOutput> | void {
const command = new UpdateCustomRoutingAcceleratorCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Update the attributes for a custom routing accelerator. </p>
*/
public updateCustomRoutingAcceleratorAttributes(
args: UpdateCustomRoutingAcceleratorAttributesCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateCustomRoutingAcceleratorAttributesCommandOutput>;
public updateCustomRoutingAcceleratorAttributes(
args: UpdateCustomRoutingAcceleratorAttributesCommandInput,
cb: (err: any, data?: UpdateCustomRoutingAcceleratorAttributesCommandOutput) => void
): void;
public updateCustomRoutingAcceleratorAttributes(
args: UpdateCustomRoutingAcceleratorAttributesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateCustomRoutingAcceleratorAttributesCommandOutput) => void
): void;
public updateCustomRoutingAcceleratorAttributes(
args: UpdateCustomRoutingAcceleratorAttributesCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: UpdateCustomRoutingAcceleratorAttributesCommandOutput) => void),
cb?: (err: any, data?: UpdateCustomRoutingAcceleratorAttributesCommandOutput) => void
): Promise<UpdateCustomRoutingAcceleratorAttributesCommandOutput> | void {
const command = new UpdateCustomRoutingAcceleratorAttributesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Update a listener for a custom routing accelerator. </p>
*/
public updateCustomRoutingListener(
args: UpdateCustomRoutingListenerCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateCustomRoutingListenerCommandOutput>;
public updateCustomRoutingListener(
args: UpdateCustomRoutingListenerCommandInput,
cb: (err: any, data?: UpdateCustomRoutingListenerCommandOutput) => void
): void;
public updateCustomRoutingListener(
args: UpdateCustomRoutingListenerCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateCustomRoutingListenerCommandOutput) => void
): void;
public updateCustomRoutingListener(
args: UpdateCustomRoutingListenerCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateCustomRoutingListenerCommandOutput) => void),
cb?: (err: any, data?: UpdateCustomRoutingListenerCommandOutput) => void
): Promise<UpdateCustomRoutingListenerCommandOutput> | void {
const command = new UpdateCustomRoutingListenerCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Update an endpoint group. A resource must be valid and active when you add it as an endpoint.</p>
*/
public updateEndpointGroup(
args: UpdateEndpointGroupCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateEndpointGroupCommandOutput>;
public updateEndpointGroup(
args: UpdateEndpointGroupCommandInput,
cb: (err: any, data?: UpdateEndpointGroupCommandOutput) => void
): void;
public updateEndpointGroup(
args: UpdateEndpointGroupCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateEndpointGroupCommandOutput) => void
): void;
public updateEndpointGroup(
args: UpdateEndpointGroupCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateEndpointGroupCommandOutput) => void),
cb?: (err: any, data?: UpdateEndpointGroupCommandOutput) => void
): Promise<UpdateEndpointGroupCommandOutput> | void {
const command = new UpdateEndpointGroupCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Update a listener. </p>
*/
public updateListener(
args: UpdateListenerCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateListenerCommandOutput>;
public updateListener(
args: UpdateListenerCommandInput,
cb: (err: any, data?: UpdateListenerCommandOutput) => void
): void;
public updateListener(
args: UpdateListenerCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateListenerCommandOutput) => void
): void;
public updateListener(
args: UpdateListenerCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateListenerCommandOutput) => void),
cb?: (err: any, data?: UpdateListenerCommandOutput) => void
): Promise<UpdateListenerCommandOutput> | void {
const command = new UpdateListenerCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Stops advertising an address range that is provisioned as an address pool.
* You can perform this operation at most once every 10 seconds, even if you specify different address
* ranges each time.</p>
* <p>It can take a few minutes before traffic to the specified addresses stops routing to AWS because of
* propagation delays.</p>
* <p>For more information, see <a href="https://docs.aws.amazon.com/global-accelerator/latest/dg/using-byoip.html">Bring Your Own
* IP Addresses (BYOIP)</a> in the <i>AWS Global Accelerator Developer Guide</i>.</p>
*/
public withdrawByoipCidr(
args: WithdrawByoipCidrCommandInput,
options?: __HttpHandlerOptions
): Promise<WithdrawByoipCidrCommandOutput>;
public withdrawByoipCidr(
args: WithdrawByoipCidrCommandInput,
cb: (err: any, data?: WithdrawByoipCidrCommandOutput) => void
): void;
public withdrawByoipCidr(
args: WithdrawByoipCidrCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: WithdrawByoipCidrCommandOutput) => void
): void;
public withdrawByoipCidr(
args: WithdrawByoipCidrCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: WithdrawByoipCidrCommandOutput) => void),
cb?: (err: any, data?: WithdrawByoipCidrCommandOutput) => void
): Promise<WithdrawByoipCidrCommandOutput> | void {
const command = new WithdrawByoipCidrCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
} | the_stack |
import { CatalystLabels } from '../../utils/constants';
import { CurrencyId } from '../../models';
const findBlock = (blockNumber?: number, blockHash?: string): string => `
SELECT
b.hash as hash,
b.block_no as number,
(b.time at time zone 'utc') as "createdAt",
CASE
WHEN b2.block_no IS NOT NULL THEN b2.block_no
WHEN b3.block_no IS NOT NULL THEN b3.block_no
ELSE 0
END AS "previousBlockNumber",
CASE
WHEN b2.block_no IS NOT NULL THEN b2.hash
WHEN b3.block_no IS NOT NULL THEN b3.hash
WHEN b.block_no = 1 THEN b3.hash -- block 1
ELSE b.hash -- genesis
END AS "previousBlockHash",
b.tx_count as "transactionsCount",
s.description as "createdBy",
b.size as size,
b.epoch_no as "epochNo",
b.slot_no as "slotNo"
FROM
block b
LEFT JOIN slot_leader s ON b.slot_leader_id = s.id
LEFT JOIN block b2 ON b.previous_id = b2.id
LEFT JOIN block b3 ON b2.previous_id = b3.id
WHERE
${blockNumber ? 'b.block_no = $1' : '$1 = $1'} AND
${blockHash ? 'b.hash = $2' : '$2 = $2'}
LIMIT 1
`;
const currenciesQuery = (currencies: CurrencyId[]): string =>
`SELECT tx_out_id
FROM ma_tx_out
WHERE (${currencies
.map(({ symbol, policy }) => `name = DECODE('${symbol}', 'hex') AND policy = DECODE('${policy}', 'hex')`)
.join('OR ')})`;
// AND (block.block_no = $2 OR (block.block_no is null AND $2 = 0))
// This condition is made because genesis block has block_no = null
// Also, genesis number is 0, thats why $2 = 0.
const findTransactionsByBlock = (blockNumber?: number, blockHash?: string): string => `
SELECT
tx.hash,
tx.fee,
tx.size,
tx.valid_contract AS "validContract",
tx.script_size AS "scriptSize",
block.hash as "blockHash"
FROM tx
JOIN block ON block.id = tx.block_id
WHERE
${blockNumber ? '(block.block_no = $1 OR (block.block_no is null AND $1 = 0))' : '$1 = $1'} AND
${blockHash ? 'block.hash = $2' : '$2 = $2'}
`;
export interface FindTransactionFieldResult {
txHash: Buffer;
}
export interface FindTransactionInOutResult extends FindTransactionFieldResult {
id: number;
address: string;
value: string;
policy?: Buffer;
name?: Buffer;
quantity?: string;
}
// AND (block.block_no = $2 OR (block.block_no is null AND $2 = 0))
// This condition is made because genesis block has block_no = null
// Also, genesis number is 0, thats why $2 = 0.
const findTransactionByHashAndBlock = `
SELECT
tx.hash,
tx.fee,
tx.size,
tx.valid_contract AS "validContract",
tx.script_size AS "scriptSize",
block.hash as "blockHash"
FROM tx
JOIN block ON block.id = tx.block_id
WHERE
tx.hash = $1
AND (block.block_no = $2 OR (block.block_no is null AND $2 = 0))
AND block.hash = $3
`;
export interface FindTransactionsInputs extends FindTransactionInOutResult {
sourceTxHash: Buffer;
sourceTxIndex: number;
}
const findTransactionsInputs = `SELECT
tx_in.id as id,
source_tx_out.address as address,
source_tx_out.value as value,
tx.hash as "txHash",
source_tx.hash as "sourceTxHash",
tx_in.tx_out_index as "sourceTxIndex",
source_ma_tx_out.policy as policy,
source_ma_tx_out.name as name,
source_ma_tx_out.quantity as quantity
FROM
tx
JOIN tx_in
ON tx_in.tx_in_id = tx.id
JOIN tx_out as source_tx_out
ON tx_in.tx_out_id = source_tx_out.tx_id
AND tx_in.tx_out_index = source_tx_out.index
JOIN tx as source_tx
ON source_tx_out.tx_id = source_tx.id
LEFT JOIN ma_tx_out as source_ma_tx_out
ON source_ma_tx_out.tx_out_id = source_tx_out.id
WHERE
tx.hash = ANY ($1)
ORDER BY policy, name, id`;
const findGenesisBlock = `
SELECT
hash,
block_no as index
FROM
block
WHERE
previous_id IS NULL
LIMIT 1`;
export interface FindTransactionsOutputs extends FindTransactionInOutResult {
index: number;
}
const findTransactionsOutputs = `
SELECT
tx_out.id as id,
address,
value,
tx.hash as "txHash",
index,
ma_tx_out.policy as policy,
ma_tx_out.name as name,
ma_tx_out.quantity as quantity
FROM tx
JOIN tx_out
ON tx.id = tx_out.tx_id
LEFT JOIN ma_tx_out
ON ma_tx_out.tx_out_id = tx_out.id
WHERE
tx.hash = ANY ($1)
ORDER BY
policy,
name,
id
`;
export interface FindTransactionWithdrawals extends FindTransactionFieldResult {
address: string;
amount: string;
}
export interface FindTransactionRegistrations extends FindTransactionFieldResult {
address: string;
amount: string;
}
export interface FindTransactionDeregistrations extends FindTransactionFieldResult {
address: string;
amount: string;
}
export interface FindTransactionDelegations extends FindTransactionFieldResult {
address: string;
poolHash: Buffer;
}
const findTransactionWithdrawals = `
SELECT
amount,
sa.view as "address",
tx.hash as "txHash"
FROM withdrawal w
INNER JOIN tx on w.tx_id = tx.id
INNER JOIN stake_address sa on w.addr_id = sa.id
WHERE
tx.hash = ANY ($1)
`;
export interface FindTransactionPoolRegistrationsData extends FindTransactionFieldResult {
poolId: number;
updateId: number;
vrfKeyHash: Buffer;
pledge: string;
margin: string;
cost: string;
address: Buffer;
poolHash: Buffer;
metadataUrl: string;
metadataHash: Buffer;
}
export interface FindTransactionPoolOwners extends FindTransactionFieldResult {
poolId: number;
owner: Buffer;
}
export interface FindTransactionPoolRelays extends FindTransactionFieldResult {
updateId: number;
vrfKeyHash: Buffer;
ipv4: string;
ipv6: string;
dnsName: string;
port: string;
}
const findTransactionRegistrations = `
SELECT
tx.deposit as "amount",
sa.view as "address",
tx.hash as "txHash"
FROM stake_registration sr
INNER JOIN tx on tx.id = sr.tx_id
INNER JOIN stake_address sa on sr.addr_id = sa.id
WHERE
tx.hash = ANY ($1)
`;
const findTransactionDeregistrations = `
SELECT
sa.view as "address",
tx.deposit as "amount",
tx.hash as "txHash"
FROM stake_deregistration sd
INNER JOIN stake_address sa
ON sd.addr_id = sa.id
INNER JOIN tx
ON tx.id = sd.tx_id
WHERE tx.hash = ANY($1)
`;
const findTransactionDelegations = `
SELECT
sa.view as "address",
ph.hash_raw as "poolHash",
tx.hash as "txHash"
FROM delegation d
INNER JOIN stake_address sa
ON d.addr_id = sa.id
INNER JOIN pool_hash ph
ON d.pool_hash_id = ph.id
INNER JOIN tx
ON d.tx_id = tx.id
WHERE tx.hash = ANY($1)
`;
const findLatestBlockNumber = `
SELECT
block_no as "blockHeight"
FROM block
WHERE block_no IS NOT NULL
ORDER BY block_no DESC
LIMIT 1
`;
export interface FindBalance {
balance: string;
}
export interface FindUtxo {
value: string;
txHash: Buffer;
index: number;
policy: Buffer;
name: Buffer;
quantity: string;
}
export interface FindMaBalance {
name: Buffer;
policy: Buffer;
value: string;
}
export interface FindPoolRetirements extends FindTransactionFieldResult {
address: Buffer;
poolKeyHash: Buffer;
epoch: number;
}
export interface FindTransactionMetadata extends FindTransactionFieldResult {
data: any;
signature: any;
}
const poolRegistrationQuery = `
WITH pool_registration AS (
SELECT
tx.hash as "txHash",
tx.id as "txId",
pu.id as "updateId",
ph.id as "poolId",
pu.vrf_key_hash as "vrfKeyHash",
pu.pledge as pledge,
pu.margin as margin,
pu.fixed_cost as cost,
pu.reward_addr as address,
ph.hash_raw as "poolHash",
pm.url as "metadataUrl",
pm.hash as "metadataHash"
FROM pool_update pu
JOIN tx
ON pu.registered_tx_id = tx.id
JOIN pool_hash ph
ON ph.id = pu.hash_id
LEFT JOIN pool_metadata_ref pm
ON pu.meta_id = pm.id
WHERE
tx.hash = ANY ($1)
)
`;
const findTransactionPoolRegistrationsData = `
${poolRegistrationQuery}
SELECT *
FROM pool_registration
`;
const findTransactionPoolOwners = `
${poolRegistrationQuery}
SELECT
po.pool_hash_id AS "poolId",
sa."view" AS "owner",
pr."txHash"
FROM pool_registration pr
JOIN pool_owner po
ON (po.pool_hash_id = pr."poolId"
AND po.registered_tx_id = pr."txId")
JOIN stake_address sa
ON po.addr_id = sa.id
`;
const findTransactionPoolRelays = `
${poolRegistrationQuery}
SELECT
prelay.update_id as "updateId",
prelay.ipv4 as ipv4,
prelay.ipv6 as ipv6,
prelay.port as port,
prelay.dns_name as "dnsName",
pr."txHash"
FROM pool_registration pr
JOIN pool_relay prelay
ON prelay.update_id = pr."updateId"
`;
const findTransactionMetadata = `
WITH metadata AS (
SELECT
metadata.json,
metadata.key,
tx.hash AS "txHash",
tx.id AS "txId"
FROM tx_metadata AS metadata
JOIN tx
ON tx.id = metadata.tx_id
WHERE tx.hash = ANY($1)
),
metadata_data AS (
SELECT
json AS data,
metadata."txHash",
metadata."txId"
FROM metadata
WHERE key = ${CatalystLabels.DATA}
),
metadata_sig AS (
SELECT
json AS signature,
metadata."txHash",
metadata."txId"
FROM metadata
WHERE key = ${CatalystLabels.SIG}
)
SELECT
data,
signature,
metadata_data."txHash"
FROM metadata_data
INNER JOIN metadata_sig
ON metadata_data."txId" = metadata_sig."txId"
`;
const utxoQuery = `
WITH utxo AS (
SELECT
tx_out.value as value,
tx_out_tx.hash as "txHash",
tx_out.index as index,
tx_out.id as tx_out_id
FROM tx_out
LEFT JOIN tx_in ON
tx_out.tx_id = tx_in.tx_out_id AND
tx_out.index::smallint = tx_in.tx_out_index::smallint
LEFT JOIN tx as tx_in_tx ON
tx_in_tx.id = tx_in.tx_in_id AND
tx_in_tx.block_id <= (select id from block where hash = $2) AND
tx_in_tx.valid_contract = TRUE
JOIN tx AS tx_out_tx ON
tx_out_tx.id = tx_out.tx_id AND
tx_out_tx.block_id <= (select id from block where hash = $2) AND
tx_out_tx.valid_contract = TRUE
WHERE
tx_out.address = $1 AND
tx_in_tx.id IS NULL
)`;
const findPoolRetirements = `
SELECT
pr.retiring_epoch AS "epoch",
ph.hash_raw AS "address",
tx.hash as "txHash"
FROM pool_retire pr
INNER JOIN pool_hash ph
ON pr.hash_id = ph.id
INNER JOIN tx
ON tx.id = pr.announced_tx_id
WHERE tx.hash = ANY($1)
`;
const findUtxoByAddressAndBlock = (currencies?: CurrencyId[]): string => `
${utxoQuery}
SELECT
utxo.value,
utxo."txHash",
utxo.index,
ma_tx_out.name as "name",
ma_tx_out.policy as "policy",
ma_tx_out.quantity
FROM utxo
LEFT JOIN ma_tx_out
ON ma_tx_out.tx_out_id = utxo.tx_out_id
${currencies && currencies.length > 0 ? `WHERE utxo.tx_out_id IN (${currenciesQuery(currencies)})` : ''}
ORDER BY
utxo."txHash", utxo.index, ma_tx_out.policy, ma_tx_out.name
`;
const findMaBalanceByAddressAndBlock = `
${utxoQuery}
SELECT
ma_tx_out.name as "name",
ma_tx_out.policy as "policy",
SUM(ma_tx_out.quantity) as value
FROM utxo
LEFT JOIN ma_tx_out
ON ma_tx_out.tx_out_id = utxo.tx_out_id
WHERE ma_tx_out.policy IS NOT NULL
GROUP BY ma_tx_out.name, ma_tx_out.policy
ORDER BY ma_tx_out.policy, ma_tx_out.name
`;
const findBalanceByAddressAndBlock = `
SELECT (SELECT COALESCE(SUM(r.amount),0)
FROM reward r
JOIN stake_address ON
stake_address.id = r.addr_id
WHERE stake_address.view = $1
AND r.spendable_epoch <= (SELECT epoch_no FROM block WHERE hash = $2)
) - (
SELECT COALESCE(SUM(w.amount),0)
FROM withdrawal w
JOIN tx ON tx.id = w.tx_id AND
tx.valid_contract = TRUE AND
tx.block_id <= (SELECT id FROM block WHERE hash = $2)
JOIN stake_address ON stake_address.id = w.addr_id
WHERE stake_address.view = $1)
AS balance
`;
const findLatestMinFeeAAndMinFeeB = `
SELECT
min_fee_a, min_fee_b FROM epoch_param
WHERE
min_fee_a is not null and min_fee_b is not null
ORDER BY id
DESC LIMIT 1
`;
const Queries = {
findBalanceByAddressAndBlock,
findBlock,
findLatestBlockNumber,
findGenesisBlock,
findMaBalanceByAddressAndBlock,
findTransactionByHashAndBlock,
findTransactionDelegations,
findTransactionDeregistrations,
findTransactionMetadata,
findTransactionPoolOwners,
findTransactionPoolRelays,
findTransactionPoolRegistrationsData,
findTransactionRegistrations,
findTransactionWithdrawals,
findTransactionsByBlock,
findTransactionsInputs,
findPoolRetirements,
findTransactionsOutputs,
findUtxoByAddressAndBlock,
findLatestMinFeeAAndMinFeeB
};
export default Queries; | the_stack |
import * as Delir from '@delirvfx/core'
import { connectToStores, ContextProp, useStore, withFleurContext } from '@fleur/react'
import classnames from 'classnames'
import { clipboard } from 'electron'
import _ from 'lodash'
import mouseWheel from 'mouse-wheel'
import React from 'react'
import { Platform } from 'utils/platform'
import { SpreadType } from '../../utils/Spread'
import { MeasurePoint } from '../../utils/TimePixelConversion'
import * as EditorOps from '../../domain/Editor/operations'
import * as ProjectOps from '../../domain/Project/operations'
import { PropertyInput } from 'components/PropertyInput/PropertyInput'
import { getActiveComp } from 'domain/Editor/selectors'
import { memo } from 'react'
import { SortEndHandler } from 'react-sortable-hoc'
import { Button } from '../../components/Button'
import { ContextMenu, MenuItem, MenuItemOption } from '../../components/ContextMenu'
import { LabelInput } from '../../components/LabelInput'
import { Pane } from '../../components/Pane'
import { Workspace } from '../../components/Workspace'
import EditorStore, { EditorState } from '../../domain/Editor/EditorStore'
import { ParameterTarget } from '../../domain/Editor/types'
import ProjectStore, { ProjectStoreState } from '../../domain/Project/ProjectStore'
import RendererStore from '../../domain/Renderer/RendererStore'
import { PX_PER_SEC } from '../Timeline/Timeline'
import { EffectList, EffectListItem, EffectSortHandle } from './EffectList'
import ExpressionEditor from './ExpressionEditor'
import t from './KeyframeEditor.i18n'
import s from './KeyframeEditor.sass'
import { KeyframePatch } from './KeyframeGraph'
import { KeyframeMediator } from './KeyframeMediator'
import { ScriptParamEditor } from './ScriptParamEditor'
export interface EditorResult {
code: string | null
target: ParameterTarget
}
interface OwnProps {
activeComposition: SpreadType<Delir.Entity.Composition> | null
activeClip: SpreadType<Delir.Entity.Clip> | null
scrollLeft: number
scale: number
pxPerSec: number
measures: MeasurePoint[]
onScroll: (dx: number, dy: number) => void
onScaled: (scale: number) => void
}
interface ConnectedProps {
editor: EditorState
activeParam: ParameterTarget | null
project: ProjectStoreState
userCodeException: Delir.Exceptions.UserCodeException | null
postEffectPlugins: Delir.PluginSupport.Types.PluginSummary[]
}
interface State {
graphWidth: number
graphHeight: number
keyframeViewViewBox: { width: number; height: number } | undefined
editorOpened: boolean
scriptParamEditorOpened: boolean
}
type Props = OwnProps & ConnectedProps & ContextProp
const Measures = memo(({ measures }: { measures: MeasurePoint[] }) => {
const { activeComp } = useStore(getStore => ({
activeComp: getActiveComp(getStore),
}))
if (!activeComp) return null
return (
<>
{measures.map(point => (
<div
key={point.index}
className={classnames(s.measureLine, {
[s['--grid']]: point.frameNumber % 10 === 0,
[s['--endFrame']]: point.frameNumber === activeComp.durationFrames,
})}
style={{ left: point.left }}
>
{point.frameNumber}
</div>
))}
</>
)
})
// const EffectList = styled.div<{ opened: boolean }>`
// position: absolute;
// bottom: calc(100% + 4px);
// z-index: 1;
// width: 100%;
// background-color: ${cssVars.colors.popupBg};
// visibility: hidden;
// pointer-events: none;
// transition-property: visibility ${cssVars.animate.bgColorDuration} ${cssVars.animate.function};
// border-radius: ${cssVars.size.radius};
// box-shadow: ${cssVars.style.popupDropshadow};
// ${({ opened }) =>
// opened &&
// `
// visibility: visible;
// pointer-events: all;
// `}
// `
// const EffectEntry = styled.div`
// padding: 4px;
// transition: background-color ${cssVars.animate.bgColorDuration} ${cssVars.animate.function};
// &:hover {
// background-color: ${cssVars.colors.listItemHovered};
// }
// `
// const AddEffectButton = ({ clipId }: { clipId: string }) => {
// const { executeOperation } = useFleurContext()
// const [opened, setOpened] = useState(false)
// const effects = useStore(getStore => getStore(RendererStore).getPostEffectPlugins())
// const handleClickOpen = useCallback(() => {
// setOpened(opened => !opened)
// }, [])
// const handleClickEntry = useCallback(({ currentTarget }: MouseEvent<HTMLDivElement>) => {
// setOpened(false)
// executeOperation(ProjectOps.addEffectIntoClip, { clipId, processorId: currentTarget.dataset.processorId! })
// }, [])
// return (
// <div style={{ position: 'relative' }}>
// <Button blocked style={{ margin: '8px 0' }} onClick={handleClickOpen}>
// <span style={{ marginRight: '8px' }}>
// <Icon kind="plus" />
// </span>
// Add Effect
// </Button>
// <EffectList opened={opened}>
// {effects.map(entry => (
// <EffectEntry data-processor-id={entry.id} onClick={handleClickEntry}>
// {entry.name}
// </EffectEntry>
// ))}
// </EffectList>
// </div>
// )
// }
export const KeyframeEditor = withFleurContext(
connectToStores(
(getStore): ConnectedProps => ({
editor: getStore(EditorStore).getState(),
activeParam: getStore(EditorStore).getActiveParam(),
project: getStore(ProjectStore).getState(),
userCodeException: getStore(RendererStore).getUserCodeException(),
postEffectPlugins: getStore(RendererStore).getPostEffectPlugins(),
}),
)(
class KeyframeEditor extends React.Component<Props, State> {
public static defaultProps: Partial<Props> = {
scrollLeft: 0,
}
public state: State = {
graphWidth: 0,
graphHeight: 0,
keyframeViewViewBox: undefined,
editorOpened: false,
scriptParamEditorOpened: false,
}
public refs: {
svgParent: HTMLDivElement
}
public componentDidMount() {
this._syncGraphHeight()
window.addEventListener('resize', _.debounce(this._syncGraphHeight, 1000 / 30))
mouseWheel(this.refs.svgParent, this.handleScrolling)
}
public componentDidUpdate(prevProps: Props) {
if (this.props.activeClip && prevProps.activeClip && this.props.activeClip.id !== prevProps.activeClip.id) {
this.setState({
editorOpened: false,
scriptParamEditorOpened: false,
})
}
}
public render() {
const { activeClip, editor, activeParam, scrollLeft, postEffectPlugins, scale, measures } = this.props
const { keyframeViewViewBox, graphWidth, graphHeight, editorOpened, scriptParamEditorOpened } = this.state
const activeEntityObject = this.activeEntityObject
const activeParamDescriptor = activeParam ? this._getDescriptorByParamName(activeParam.paramName) : null
const expressionCode =
!activeEntityObject || !activeParam
? null
: activeEntityObject.expressions[activeParam.paramName]
? activeEntityObject.expressions[activeParam.paramName].code
: null
let keyframes: ReadonlyArray<Delir.Entity.Keyframe> | null = null
if (activeClip && activeParam) {
if (activeParam.type === 'effect') {
const activeEffect = activeClip.effects.find(e => e.id === activeParam.entityId)
keyframes = activeEffect ? activeEffect.keyframes[activeParam.paramName] : null
} else {
keyframes = activeClip.keyframes[activeParam.paramName]
}
}
return (
<Workspace direction="horizontal" className={s.keyframeView}>
<Pane className={s.paramList}>
{activeClip && (
<ContextMenu>
<MenuItem label={t(t.k.contextMenu.effect)}>
{postEffectPlugins.length ? (
postEffectPlugins.map(entry => (
<MenuItem
key={entry.id}
label={entry.name}
data-clip-id={activeClip.id}
data-effect-id={entry.id}
onClick={this.handleAddEffect}
/>
))
) : (
<MenuItem label={t(t.k.contextMenu.pluginUnavailable)} enabled={false} />
)}
</MenuItem>
</ContextMenu>
)}
{this.renderProperties()}
<EffectList useDragHandle onSortEnd={this.handleSortEffect}>
{this.renderEffectProperties()}
</EffectList>
{/* {activeClip && <AddEffectButton clipId={activeClip.id} />} */}
</Pane>
<Pane>
<div ref="svgParent" className={s.keyframeContainer} tabIndex={-1} onWheel={this._scaleTimeline}>
{activeParam && editorOpened && activeParamDescriptor && (
<ExpressionEditor
title={activeParamDescriptor.label}
target={activeParam}
code={expressionCode}
onClose={this.handleCloseExpressionEditor}
/>
)}
{scriptParamEditorOpened &&
activeParam &&
activeParamDescriptor &&
activeParamDescriptor.type === 'CODE' &&
(() => {
if (!activeClip || !this.activeEntityObject) return null
const value = Delir.KeyframeCalcurator.calcKeyframeAt(
editor.currentPreviewFrame,
activeClip.placedFrame,
activeParamDescriptor,
this.activeEntityObject.keyframes[activeParam.paramName] || [],
) as Delir.Values.Expression
return (
<ScriptParamEditor
title={activeParamDescriptor.label}
target={activeParam}
langType={value.language}
code={value.code}
onClose={this.handleCloseScriptParamEditor}
/>
)
})()}
<div className={s.measureContainer}>
<div
ref="mesures"
className={s.measureLayer}
style={{
transform: `translateX(-${scrollLeft}px)`,
}}
>
<Measures measures={measures} />
</div>
</div>
{activeClip && activeParamDescriptor && activeParam && keyframes && (
<KeyframeMediator
activeClip={activeClip}
paramName={activeParam.paramName}
descriptor={activeParamDescriptor}
entity={activeEntityObject}
keyframeViewViewBox={keyframeViewViewBox}
graphWidth={graphWidth}
graphHeight={graphHeight}
scrollLeft={scrollLeft}
pxPerSec={PX_PER_SEC}
keyframes={keyframes}
scale={scale}
onRemoveKeyframe={this.handleRemoveKeyframe}
onModifyKeyframe={this.handleModifyKeyframe}
/>
)}
</div>
</Pane>
</Workspace>
)
}
private renderProperties = () => {
const {
activeClip,
activeParam,
project: { project },
editor,
userCodeException,
} = this.props
if (!activeClip) return null
return this.clipParamDescriptors.map(desc => {
const value = activeClip
? Delir.KeyframeCalcurator.calcKeyframeAt(
editor.currentPreviewFrame,
activeClip.placedFrame,
desc,
activeClip.keyframes[desc.paramName] || [],
)
: undefined
const isSelected = activeParam && activeParam.type === 'clip' && activeParam.paramName === desc.paramName
const hasKeyframe = desc.animatable && (activeClip.keyframes[desc.paramName] || []).length !== 0
const hasExpression =
activeClip.expressions[desc.paramName] && activeClip.expressions[desc.paramName].code !== ''
const hasError =
userCodeException &&
userCodeException.location.type === 'clip' &&
userCodeException.location.entityId === activeClip.id &&
userCodeException.location.paramName === desc.paramName
return (
<div
key={activeClip.id + desc.paramName}
className={classnames(s.paramItem, {
[s.paramItemActive]: isSelected,
[s.paramItemError]: hasError,
})}
data-entity-type="clip"
data-entity-id={activeClip.id}
data-param-name={desc.paramName}
onClick={this.selectProperty}
>
<ContextMenu>
<MenuItem
label={t(t.k.contextMenu.expression)}
data-entity-type="clip"
data-entity-id={activeClip.id}
data-param-name={desc.paramName}
enabled={desc.animatable}
onClick={this.openExpressionEditor}
/>
<MenuItem type="separator" />
<MenuItem
label={t(t.k.contextMenu.copyParamName)}
data-param-name={desc.paramName}
onClick={this.handleCopyParamName}
/>
</ContextMenu>
<span
className={classnames(s.paramIndicator, {
[s['paramIndicator--active']]: hasExpression,
})}
data-entity-type="clip"
data-entity-id={activeClip.id}
data-param-name={desc.paramName}
onClick={this.handleClickExpressionIndicator}
>
{desc.animatable && <i className="twa twa-abcd" />}
</span>
<span
className={classnames(s.paramIndicator, {
[s['paramIndicator--active']]: hasKeyframe,
})}
>
{desc.animatable && <i className="twa twa-clock12" />}
</span>
<span className={s.paramItemName}>{desc.label}</span>
<div className={s.paramItemInput}>
{desc.type === 'CODE' ? (
<div>
<Button kind="normal" onClick={this.handleOpenScriptParamEditor}>
{t(t.k.editScriptParam)}
</Button>
</div>
) : (
<PropertyInput
assets={project ? project.assets : null}
descriptor={desc}
value={value!}
onChange={this.valueChanged}
/>
)}
</div>
</div>
)
})
}
private renderEffectProperties = () => {
const rendererStore = this.props.getStore(RendererStore)
const {
activeClip,
activeParam,
editor,
project: { project },
userCodeException,
} = this.props
if (!activeClip) return null
return activeClip.effects.map((effect, idx) => {
const processorInfo = rendererStore.getPostEffectPlugins().find(entry => entry.id === effect.processor)!
if (!processorInfo) {
return (
<EffectListItem index={idx}>
<div
key={effect.id}
className={classnames(s.paramItem, s.paramItemEffectContainer)}
title={t(t.k.pluginMissing, {
processorId: effect.processor,
})}
>
<div key={effect.id} className={classnames(s.paramItem, s.paramItemHeader, s.paramItemPluginMissing)}>
<ContextMenu>
<MenuItem
label={t(t.k.contextMenu.removeEffect)}
data-clip-id={activeClip.id}
data-effect-id={effect.id}
onClick={this.removeEffect}
/>
</ContextMenu>
<i className="fa fa-exclamation" />
{effect.processor}
</div>
</div>
</EffectListItem>
)
}
const descriptors: Delir.AnyParameterTypeDescriptor[] | null = rendererStore.getPostEffectParametersById(
effect.processor,
)!
return (
<EffectListItem key={effect.id} index={idx} className={classnames(s.paramItem, s.paramItemEffectContainer)}>
<div className={classnames(s.paramItem, s.paramItemHeader)}>
<ContextMenu>
<MenuItem
label={t(t.k.contextMenu.removeEffect)}
data-clip-id={activeClip.id}
data-effect-id={effect.id}
onClick={this.removeEffect}
/>
<MenuItem type="separator" />
{effect.referenceName != null && (
<MenuItem
label={t(t.k.contextMenu.copyReferenceName)}
data-reference-name={effect.referenceName}
onClick={this.handleCopyReferenceName}
/>
)}
</ContextMenu>
<EffectSortHandle />
<i className="fa fa-magic" />
<LabelInput
className={s.referenceNameInput}
doubleClickToEdit
placeholder={processorInfo.name}
defaultValue={effect.referenceName || ''}
onChange={this.handleChangeEffectReferenceName}
data-effect-id={effect.id}
/>
{effect.referenceName != null && <span className={s.processorName}>{processorInfo.name}</span>}
</div>
{descriptors.map(desc => {
const isSelected =
activeParam &&
activeParam.type === 'effect' &&
activeParam.entityId === effect.id &&
activeParam.paramName === desc.paramName
const hasKeyframe = desc.animatable && (effect.keyframes[desc.paramName] || []).length !== 0
const hasError =
userCodeException &&
userCodeException.location.type === 'effect' &&
userCodeException.location.entityId === effect.id &&
userCodeException.location.paramName === desc.paramName
const hasExpression =
effect.expressions[desc.paramName] && effect.expressions[desc.paramName].code !== ''
const value = activeClip
? Delir.KeyframeCalcurator.calcKeyframeAt(
editor.currentPreviewFrame,
activeClip.placedFrame,
desc,
effect.keyframes[desc.paramName] || [],
)
: undefined
return (
<div
key={`${activeClip.id}-${effect.id}-${desc.paramName}`}
className={classnames(s.paramItem, {
[s.paramItemActive]: isSelected,
[s.paramItemError]: hasError,
})}
data-entity-type="effect"
data-entity-id={effect.id}
data-param-name={desc.paramName}
onClick={this.selectProperty}
>
<ContextMenu>
<MenuItem
label={t(t.k.contextMenu.expression)}
data-entity-type="effect"
data-entity-id={effect.id}
data-param-name={desc.paramName}
onClick={this.openExpressionEditor}
/>
<MenuItem type="separator" />
<MenuItem
label={t(t.k.contextMenu.copyParamName)}
data-param-name={desc.paramName}
onClick={this.handleCopyParamName}
/>
</ContextMenu>
<span
className={classnames(s.paramIndicator, {
[s['paramIndicator--active']]: hasExpression,
})}
data-entity-type="effect"
data-entity-id={effect.id}
data-param-name={desc.paramName}
onDoubleClick={this.handleClickExpressionIndicator}
>
{desc.animatable && <i className="twa twa-abcd" />}
</span>
<span
className={classnames(s.paramIndicator, {
[s['paramIndicator--active']]: hasKeyframe,
})}
>
{desc.animatable && <i className="twa twa-clock12" />}
</span>
<span className={s.paramItemName}>{desc.label}</span>
<div className={s.paramItemInput}>
{desc.type === 'CODE' ? (
<div>
<Button kind="normal" onClick={this.handleOpenScriptParamEditor}>
{t(t.k.editScriptParam)}
</Button>
</div>
) : (
<PropertyInput
key={desc.paramName}
assets={project ? project.assets : null}
descriptor={desc}
value={value!}
onChange={this.effectValueChanged.bind(null, effect.id)}
/>
)}
</div>
</div>
)
})}
</EffectListItem>
)
})
}
private get clipParamDescriptors() {
const { activeClip } = this.props
return activeClip ? Delir.Engine.Renderers.getInfo(activeClip.renderer).parameter.properties || [] : []
}
private get activeEntityObject(): SpreadType<Delir.Entity.Clip> | SpreadType<Delir.Entity.Effect> | null {
const { activeClip, activeParam } = this.props
if (activeClip) {
if (activeParam && activeParam.type === 'effect') {
return activeClip.effects.find(e => e.id === activeParam.entityId)!
} else {
return activeClip
}
}
return null
}
private handleClickExpressionIndicator = ({ currentTarget }: React.MouseEvent<HTMLSpanElement>) => {
const { entityType, entityId, paramName } = currentTarget.dataset
this.props.executeOperation(EditorOps.changeActiveParam, {
target: {
type: entityType as 'clip' | 'effect',
entityId: entityId!,
paramName: paramName!,
},
})
this.setState({ editorOpened: true })
}
private handleSortEffect: SortEndHandler = ({ oldIndex, newIndex }) => {
const { activeClip } = this.props
if (!activeClip) return
const effectId = activeClip.effects[oldIndex].id
this.props.executeOperation(ProjectOps.moveEffectOrder, { effectId, newIndex })
}
private handleCopyReferenceName = ({ dataset: { referenceName } }: MenuItemOption<{ referenceName: string }>) => {
clipboard.writeText(referenceName)
}
private handleCopyParamName = ({ dataset: { paramName } }: MenuItemOption<{ paramName: string }>) => {
clipboard.writeText(paramName)
}
private handleOpenScriptParamEditor = () => {
this.setState({ scriptParamEditorOpened: true })
}
private handleCloseScriptParamEditor = (result: EditorResult) => {
const { activeClip } = this.props
if (!activeClip) return
if (result.target.type === 'clip') {
this.props.executeOperation(ProjectOps.createOrModifyClipKeyframe, {
clipId: result.target.entityId,
frameOnClip: 0,
paramName: result.target.paramName,
patch: {
value: new Delir.Values.Expression('javascript', result.code!),
},
})
} else if (result.target.type === 'effect') {
this.props.executeOperation(ProjectOps.createOrModifyEffectKeyframe, {
clipId: activeClip.id,
effectId: result.target.entityId,
frameOnClip: 0,
paramName: result.target.paramName,
patch: {
value: new Delir.Values.Expression('javascript', result.code!),
},
})
}
this.setState({ scriptParamEditorOpened: false })
}
private handleCloseExpressionEditor = (result: EditorResult) => {
const { activeClip } = this.props
if (!activeClip) return
if (result.target.type === 'clip') {
this.props.executeOperation(ProjectOps.modifyClipExpression, {
clipId: activeClip.id,
paramName: result.target.paramName,
expr: {
language: 'typescript',
code: result.code!,
},
})
} else {
this.props.executeOperation(ProjectOps.modifyEffectExpression, {
clipId: activeClip.id,
effectId: result.target.entityId,
paramName: result.target.paramName,
expr: {
language: 'typescript',
code: result.code!,
},
})
}
this.setState({ editorOpened: false })
}
private handleAddEffect = ({ dataset }: MenuItemOption<{ clipId: string; effectId: string }>) => {
this.props.executeOperation(ProjectOps.addEffectIntoClip, {
clipId: dataset.clipId,
processorId: dataset.effectId,
})
}
private _syncGraphHeight = () => {
const box = this.refs.svgParent.getBoundingClientRect()
this.setState({
graphWidth: box.width,
graphHeight: box.height,
keyframeViewViewBox: { width: box.width, height: box.height },
})
}
private _scaleTimeline = (e: React.WheelEvent<HTMLDivElement>) => {
if (Platform.isMacOS && e.ctrlKey) {
this.props.onScaled(Math.max(this.props.scale - e.deltaY * 0.1, 0.1))
return
}
if (e.altKey) {
const newScale = this.props.scale + e.deltaY * 0.05
this.props.onScaled(Math.max(newScale, 0.1))
e.preventDefault()
}
}
private handleScrolling = (dx: number, dy: number) => {
this.props.onScroll(dx, dy)
}
private selectProperty = ({ currentTarget }: React.MouseEvent<HTMLDivElement>) => {
const { entityType, entityId, paramName } = currentTarget.dataset as {
[_: string]: string
}
this.props.executeOperation(EditorOps.changeActiveParam, {
target: {
type: entityType as 'clip' | 'effect',
entityId,
paramName,
},
})
}
private valueChanged = (desc: Delir.AnyParameterTypeDescriptor, value: any) => {
const {
activeClip,
editor: { currentPreviewFrame },
} = this.props
if (!activeClip) return
const frameOnClip = currentPreviewFrame - activeClip.placedFrame
this.props.executeOperation(ProjectOps.createOrModifyClipKeyframe, {
clipId: activeClip.id!,
paramName: desc.paramName,
frameOnClip,
patch: { value },
})
}
private effectValueChanged = (effectId: string, desc: Delir.AnyParameterTypeDescriptor, value: any) => {
const {
activeClip,
editor: { currentPreviewFrame },
} = this.props
if (!activeClip) return
const frameOnClip = currentPreviewFrame - activeClip.placedFrame
this.props.executeOperation(ProjectOps.createOrModifyEffectKeyframe, {
clipId: activeClip.id,
effectId,
paramName: desc.paramName,
frameOnClip,
patch: { value },
})
}
private handleModifyKeyframe = (
parentClipId: string,
paramName: string,
frameOnClip: number,
patch: KeyframePatch,
) => {
const { activeParam } = this.props
if (!activeParam) return
switch (activeParam.type) {
case 'clip': {
this.props.executeOperation(ProjectOps.createOrModifyClipKeyframe, {
clipId: parentClipId,
paramName,
frameOnClip,
patch,
})
break
}
case 'effect': {
this.props.executeOperation(ProjectOps.createOrModifyEffectKeyframe, {
clipId: parentClipId,
effectId: activeParam.entityId,
paramName,
frameOnClip,
patch,
})
break
}
default: {
throw new Error('unreachable')
}
}
}
private handleRemoveKeyframe = (parentClipId: string, keyframeId: string) => {
const { activeParam } = this.props
if (!activeParam) return
if (activeParam.type === 'clip') {
this.props.executeOperation(ProjectOps.removeKeyframe, {
clipId: parentClipId,
paramName: activeParam.paramName,
keyframeId,
})
} else {
this.props.executeOperation(ProjectOps.removeEffectKeyframe, {
clipId: parentClipId,
effectId: activeParam.entityId,
paramName: activeParam.paramName,
keyframeId,
})
}
}
private openExpressionEditor = ({
dataset,
}: MenuItemOption<{
entityType: 'clip' | 'effect'
entityId: string
paramName: string
}>) => {
const { entityType, entityId, paramName } = dataset
this.props.executeOperation(EditorOps.changeActiveParam, {
target: { type: entityType, entityId, paramName },
})
this.setState({ editorOpened: true })
}
private removeEffect = ({ dataset }: MenuItemOption<{ clipId: string; effectId: string }>) => {
this.setState({ editorOpened: false }, () => {
this.props.executeOperation(ProjectOps.removeEffect, {
holderClipId: dataset.clipId,
effectId: dataset.effectId,
})
})
}
private handleChangeEffectReferenceName = (referenceName: string, { effectId }: { effectId: string }) => {
this.props.executeOperation(ProjectOps.modifyEffect, {
clipId: this.props.activeClip!.id,
effectId,
patch: { referenceName: referenceName !== '' ? referenceName : null },
})
}
private _getDescriptorByParamName(paramName: string | null) {
const rendererStore = this.props.getStore(RendererStore)
const { activeParam } = this.props
const activeEntityObject = this.activeEntityObject
if (!activeEntityObject || !activeParam) return null
let parameters: Delir.AnyParameterTypeDescriptor[]
if (activeParam.type === 'clip') {
const info = Delir.Engine.Renderers.getInfo((activeEntityObject as Delir.Entity.Clip).renderer)
parameters = info ? info.parameter.properties : []
} else if (activeParam.type === 'effect') {
parameters =
rendererStore.getPostEffectParametersById((activeEntityObject as Delir.Entity.Effect).processor) || []
} else {
throw new Error('Unexpected entity type')
}
return parameters.find(desc => desc.paramName === paramName) || null
}
},
),
) | the_stack |
const path = require("path");
interface Options {
readonly httpUrl: string
readonly networkId: string
readonly feeToken: string
readonly gasPrice: GasPrice
readonly bech32prefix: string
readonly hdPath: readonly Slip10RawIndex[]
readonly faucetUrl?: string
readonly defaultKeyFile: string
readonly gasLimits: Partial<GasLimits<CosmWasmFeeTable>> // only set the ones you want to override
}
const hackatomOptions: Options = {
httpUrl: 'https://lcd.heldernet.cosmwasm.com',
networkId: 'hackatom-wasm',
gasPrice: GasPrice.fromString("0.025ucosm"),
bech32prefix: 'cosmos',
feeToken: 'ucosm',
faucetUrl: 'https://faucet.heldernet.cosmwasm.com/credit',
hdPath: makeCosmoshubPath(0),
defaultKeyFile: path.join(process.env.HOME, ".heldernet.key"),
gasLimits: {
upload: 1500000,
init: 600000,
register:800000,
transfer: 80000,
},
}
interface Network {
setup: (password: string, filename?: string) => Promise<SigningCosmWasmClient>
recoverMnemonic: (password: string, filename?: string) => Promise<string>
}
const useOptions = (options: Options): Network => {
const loadOrCreateWallet = async (options: Options, filename: string, password: string): Promise<Secp256k1HdWallet> => {
let encrypted: string;
try {
encrypted = fs.readFileSync(filename, 'utf8');
} catch (err) {
// generate if no file exists
const wallet = await Secp256k1HdWallet.generate(12, options.hdPath, options.bech32prefix);
const encrypted = await wallet.serialize(password);
fs.writeFileSync(filename, encrypted, 'utf8');
return wallet;
}
// otherwise, decrypt the file (we cannot put deserialize inside try or it will over-write on a bad password)
const wallet = await Secp256k1HdWallet.deserialize(encrypted, password);
return wallet;
};
const connect = async (
wallet: Secp256k1HdWallet,
options: Options
): Promise<SigningCosmWasmClient> => {
const [{ address }] = await wallet.getAccounts();
const client = new SigningCosmWasmClient(
options.httpUrl,
address,
wallet,
hackatomOptions.gasPrice,
hackatomOptions.gasLimits,
);
return client;
};
const hitFaucet = async (
faucetUrl: string,
address: string,
denom: string
): Promise<void> => {
await axios.post(faucetUrl, { denom, address });
}
const setup = async (password: string, filename?: string): Promise<SigningCosmWasmClient> => {
const keyfile = filename || options.defaultKeyFile;
const wallet = await loadOrCreateWallet(hackatomOptions, keyfile, password);
const client = await connect(wallet, hackatomOptions);
// ensure we have some tokens
if (options.faucetUrl) {
const account = await client.getAccount();
if (!account) {
console.log(`Getting ${options.feeToken} from faucet`);
await hitFaucet(options.faucetUrl, client.senderAddress, options.feeToken);
}
}
return client;
}
const recoverMnemonic = async (password: string, filename?: string): Promise<string> => {
const keyfile = filename || options.defaultKeyFile;
const wallet = await loadOrCreateWallet(hackatomOptions, keyfile, password);
return wallet.mnemonic;
}
return {setup, recoverMnemonic};
}
interface InitMsg {
readonly admin: string,
readonly leftover_addr: string,
readonly create_proposal_whitelist?: string[],
readonly vote_proposal_whitelist?: string[],
readonly voting_period: Expiration,
readonly proposal_period: Expiration,
readonly budget_denom: string,
readonly algorithm: QuadraticFundingAlgorithm,
}
interface QuadraticFundingAlgorithm {
readonly capital_constrained_liberal_radicalism: CapitalConstrainedLiberalRadicalism
}
interface CapitalConstrainedLiberalRadicalism { parameter: String }
interface Config {
readonly admin: string,
readonly create_proposal_whitelist?: string[],
readonly vote_proposal_whitelist?: string[],
readonly voting_period: Expiration,
readonly proposal_period: Expiration,
readonly budget: Coin,
readonly algorithm: QuadraticFundingAlgorithm,
}
interface Proposal {
readonly id: number,
readonly title: string,
readonly description: string,
readonly metadata?: BinaryType,
readonly fund_address: string,
}
interface Vote {
readonly proposalId: number,
readonly voter: string,
readonly fund: Coin,
}
type Expiration = {readonly at_height: number} | {readonly at_time: number} | {readonly never: {}};
interface QuadraticFundingInstance {
readonly contractAddress: string
// queries
proposal: (id: number) => Promise<Proposal>
// actions
createProposal: (title: string, description: string, fundAddress: string , metadata?: BinaryType) => Promise<string>
voteProposal: (proposalId: number, amount: readonly Coin[]) => Promise<any>
triggerDistribution: () => Promise<any>
}
interface QuadraticFundingContract{
upload: () => Promise<number>
instantiate: (codeId: number, initMsg: Record<string, unknown>, label: string, amount: readonly Coin[]) => Promise<QuadraticFundingInstance>
use: (contractAddress: string) => QuadraticFundingInstance
}
const QuadraticFunding = (client: SigningCosmWasmClient): QuadraticFundingContract=> {
const use = (contractAddress: string): QuadraticFundingInstance => {
const proposal = async (id: number): Promise<Proposal> => {
return client.queryContractSmart(contractAddress, {proposal: { id}});
};
const createProposal = async (title: string, description: string , fundAddress: string, metadata?: BinaryType): Promise<string> => {
const result = await client.execute(contractAddress, {create_proposal: { title, description, fund_address: fundAddress, metadata}}, "");
return result.transactionHash;
};
const voteProposal = async (proposalId: number, amount: readonly Coin[]): Promise<any> => {
const result = await client.execute(contractAddress, {vote_proposal: { proposal_id: proposalId }}, "", amount);
return result.transactionHash;
};
const triggerDistribution = async (): Promise<any> => {
const result = await client.execute(contractAddress, {trigger_distribution: {}}, "");
return result.transactionHash;
};
return {
contractAddress,
proposal,
createProposal,
voteProposal,
triggerDistribution
};
}
const downloadWasm = async (url: string): Promise<Uint8Array> => {
const r = await axios.get(url, { responseType: 'arraybuffer' })
if (r.status !== 200) {
throw new Error(`Download error: ${r.status}`)
}
return r.data
}
const upload = async (): Promise<number> => {
const meta = {
source: "https://github.com/CosmWasm/cosmwasm-examples/tree/nameservice-0.7.0/nameservice",
builder: "cosmwasm/rust-optimizer:0.10.4"
};
const sourceUrl = "https://github.com/CosmWasm/cosmwasm-examples/releases/download/nameservice-0.7.0/contract.wasm";
const wasm = await downloadWasm(sourceUrl);
const result = await client.upload(wasm, meta);
return result.codeId;
}
const instantiate = async (codeId: number, initMsg: Record<string, unknown>, label: string, amount: readonly Coin[]): Promise<QuadraticFundingInstance> => {
const result = await client.instantiate(codeId, initMsg, label, { memo: `Init ${label}`, transferAmount: amount});
return use(result.contractAddress);
}
return { upload, instantiate, use };
}
// Demo:
// const client = await useOptions(hackatomOptions).setup(PASSWORD);
// const { address } = await client.getAccount()
// const factory = QuadraticFunding(client)
//
// const codeId = await factory.upload();
// codeId -> 12
// const initMsg = { admin: "cosmos1t6a7zh7s5c2hr7hwdhv6x86ddej2mum2gwy8z4", voting_period: { at_height: "257600" }, proposal_period: { at_height: 257600 }, budget_denom: "ucosm", quadratic_funding_algorithm: {capital_constrained_liberal_radicalism: {params: "param"}}}
// const contract = await factory.instantiate(90, initMsg, "cw1-subkey test")
// contract.contractAddress -> 'coral1267wq2zk22kt5juypdczw3k4wxhc4z47mug9fd'
//
// OR
//
// const contract = factory.use('coral1267wq2zk22kt5juypdczw3k4wxhc4z47mug9fd')
//
// const randomAddress = 'cosmos12my0yfs9ft4kafrzy0p2r7dn2ppd8zu65ll0ay'
//
// contract.createProposal("title", "desc", "cosmos10g4t8zcz7w8yeh0hufsyn9jluju64vnyll7luw")
// Full test
/*
const client = await useOptions(hackatomOptions).setup("test");
const { address } = await client.getAccount()
const initMsg = {
admin: "cosmos1t6a7zh7s5c2hr7hwdhv6x86ddej2mum2gwy8z4",
leftover_addr: "cosmos1t6a7zh7s5c2hr7hwdhv6x86ddej2mum2gwy8z4",
voting_period: {at_height: 284270},
proposal_period: {at_height: 284270},
budget_denom: "ucosm",
algorithm: {
capital_constrained_liberal_radicalism: {parameter: "param"}
}
}
const factory = QuadraticFunding(client)
const contract = await factory.use("cosmos180n6vgpfh7xvfmn7v5mtjwgvn5uysf9sl5w982")
await contract.createProposal("title1", "desc", "cosmos146sch227m6erjytl4ax5fl78gh4fw03qmaehfh")
await contract.createProposal("title2", "desc", "cosmos16hn7q0yhfrm28ta9zlk7fu46a98wss33xwfxys")
await contract.createProposal("title3", "desc", "cosmos18nhdjva7vzkvtdmqqcllq6dk4te4h6afu2kaqg")
await contract.createProposal("title4", "desc", "cosmos19ysc75nxtzkdnhnu90u7dw3ext6wmwdesyysx2")
// terminal 1
await contract.voteProposal(1, [{amount: "1200", denom: "ucosm"}])
await contract.voteProposal(2, [{amount: "30000", denom: "ucosm"}])
await contract.voteProposal(3, [{amount: "230000", denom: "ucosm"}])
await contract.voteProposal(4, [{amount: "100000", denom: "ucosm"}])
// terminal 2
await contract.voteProposal(1, [{amount: "44999", denom: "ucosm"}])
await contract.voteProposal(2, [{amount: "58999", denom: "ucosm"}])
await contract.voteProposal(3, [{amount: "100", denom: "ucosm"}])
await contract.voteProposal(4, [{amount: "5", denom: "ucosm"}])
// terminal 3
await contract.voteProposal(1, [{amount: "33", denom: "ucosm"}])
// main terminal
await contract.triggerDistribution()
*/ | the_stack |
import { OverlayContainer } from '@angular/cdk/overlay';
import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, HostBinding, HostListener, Inject, OnDestroy, OnInit } from '@angular/core';
import { MatDialog, MatDialogConfig, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatSnackBar, MAT_SNACK_BAR_DATA } from '@angular/material/snack-bar';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { environment as env } from '@env/environment';
import { BehaviorSubject, Subject } from 'rxjs';
import { filter, takeUntil } from 'rxjs/operators';
import { AuthService } from './service/auth.service';
import { DestinyCacheService } from './service/destiny-cache.service';
import { IconService } from './service/icon.service';
import { ClanRow, Const, SelectedUser, UserInfo } from './service/model';
import { NotificationService } from './service/notification.service';
import { PwaService } from './service/pwa.service';
import { SignedOnUserService } from './service/signed-on-user.service';
import { StorageService } from './service/storage.service';
import { getDefaultTheme } from './shared/utilities';
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'd2c-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy, AfterViewInit {
private unsubscribe$: Subject<void> = new Subject<void>();
navigating$: BehaviorSubject<boolean> = new BehaviorSubject(false);
private lastPath$: BehaviorSubject<string> = new BehaviorSubject(null);
@HostBinding('class') componentCssClass;
readonly version = env.versions.app;
readonly year = new Date().getFullYear();
public readonly const: Const = Const;
public PLATFORMS_DICT = Const.PLATFORMS_DICT;
disableads: boolean; // for GA
// signed on info
public signedOnUser: BehaviorSubject<SelectedUser> = new BehaviorSubject(null);
public showInstallButton: BehaviorSubject<boolean> = new BehaviorSubject(false);
public debugmode: BehaviorSubject<boolean> = new BehaviorSubject(false);
deferredPrompt: any;
constructor(
public signedOnUserService: SignedOnUserService,
public iconService: IconService,
private notificationService: NotificationService, private storageService: StorageService,
private authService: AuthService,
public overlayContainer: OverlayContainer,
public destinyCacheService: DestinyCacheService,
private router: Router, public snackBar: MatSnackBar,
private route: ActivatedRoute,
public dialog: MatDialog,
private pwaService: PwaService,
private ref: ChangeDetectorRef) {
const defaultTheme = getDefaultTheme();
this.componentCssClass = defaultTheme;
this.overlayContainer.getContainerElement().classList.add(defaultTheme);
this.logon(false);
this.storageService.settingFeed.pipe(
takeUntil(this.unsubscribe$))
.subscribe(
x => {
if (x.theme != null) {
this.overlayContainer.getContainerElement().classList.remove(this.componentCssClass);
document.body.classList.remove('parent-' + this.componentCssClass);
this.componentCssClass = x.theme;
this.overlayContainer.getContainerElement().classList.add(x.theme);
document.body.classList.add('parent-' + x.theme);
this.ref.markForCheck();
}
if (x.disableads != null) {
this.disableads = x.disableads;
this.ref.markForCheck();
}
if (x.debugmode != null) {
this.debugmode.next(x.debugmode);
}
});
this.notificationService.notifyFeed.pipe(
takeUntil(this.unsubscribe$))
.subscribe(
x => {
if (x.mode === 'success') {
this.snackBar.openFromComponent(SuccessSnackbarComponent, {
duration: 2000,
data: {
message: x.message
}
});
} else if (x.mode === 'info') {
this.snackBar.openFromComponent(InfoSnackbarComponent, {
duration: 2000,
data: {
message: x.message
}
});
} else if (x.mode === 'error') {
this.snackBar.openFromComponent(WarnSnackbarComponent, {
duration: 5000,
data: {
message: x.message
}
});
}
});
}
@HostListener('window:beforeinstallprompt', ['$event'])
beforeInstall(e) {
console.log(e);
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
this.deferredPrompt = e;
this.showInstallButton.next(true);
}
install() {
// hide our user interface that shows our A2HS button
this.showInstallButton.next(false);
if (!this.deferredPrompt) {
return;
}
// Show the prompt
this.deferredPrompt.prompt();
// Wait for the user to respond to the prompt
this.deferredPrompt.userChoice
.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the A2HS prompt');
} else {
console.log('User dismissed the A2HS prompt');
}
this.deferredPrompt = null;
});
}
public openDialog(): void {
const dc = new MatDialogConfig();
dc.disableClose = false;
dc.autoFocus = true;
dc.width = '300px';
dc.data = this.signedOnUser.value.membership.destinyMemberships;
const dialogRef = this.dialog.open(SelectPlatformDialogComponent, dc);
dialogRef.afterClosed().subscribe(async (result) => {
if (result == null) { return; }
this.selectUser(result);
});
}
loadClan(clanRow: ClanRow) {
if (this.signedOnUser != null) {
this.router.navigate(['clan', clanRow.id]);
}
}
private static getFinalComponent(r: ActivatedRoute): string {
// grab platform while we're here
if (r.snapshot.params.platform != null) {
(window as any).ga('set', 'platform', r.snapshot.params.platform);
}
if (r.children != null && r.children.length > 0) {
if (r.routeConfig != null) {
return r.routeConfig.path + '/' + AppComponent.getFinalComponent(r.children[0]);
}
return AppComponent.getFinalComponent(r.children[0]);
}
return r.routeConfig.path;
}
ngOnInit(): void {
this.signedOnUserService.signedOnUser$.pipe(takeUntil(this.unsubscribe$)).subscribe((selectedUser: SelectedUser) => {
this.signedOnUser.next(selectedUser);
if (selectedUser == null) { return; }
if (selectedUser.promptForPlatform === true) {
selectedUser.promptForPlatform = false;
this.openDialog();
}
});
this.router.events.pipe(
filter(event => event instanceof NavigationEnd),
takeUntil(this.unsubscribe$))
.subscribe(
(navEnd: NavigationEnd) => {
try {
const route = this.route;
const baseRoute = route.firstChild?.routeConfig?.path;
const lastPath = this.lastPath$.getValue();
this.lastPath$.next(baseRoute);
// we've navigated to a new "page"
if (lastPath && (lastPath !== baseRoute)) {
// console.log(`New page: ${baseRoute}`);
this.navigating$.next(true);
setTimeout(() => {
this.navigating$.next(false);
}, 200);
}
const path = AppComponent.getFinalComponent(route);
(window as any).ga('set', 'disabled-ads', this.disableads);
(window as any).ga('send', 'pageview', path);
} catch (err) {
console.dir(err);
}
}
);
}
ngAfterViewInit(): void {
if (window['NitroPayCCPA']) {
window['NitroPayCCPA'].init();
}
if (window['__cmp']) {
window['__cmp']('addConsentLink');
}
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
logon(force: boolean) {
this.authService.getCurrentMemberId(force);
this.ref.markForCheck();
}
selectUser(user) {
this.signedOnUserService.selectUser(user);
this.ref.markForCheck();
}
onLoginClick() {
this.logon(true);
}
onLogoutClick() {
this.authService.signOut();
this.ref.markForCheck();
}
}
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'd2c-success-snack',
templateUrl: 'snackbars/success.html',
styleUrls: ['snackbars/success.css']
})
export class SuccessSnackbarComponent {
message: string;
constructor(@Inject(MAT_SNACK_BAR_DATA) public data: any) {
this.message = data.message;
}
}
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'd2c-info-snack',
templateUrl: 'snackbars/info.html',
styleUrls: ['snackbars/info.css'],
})
export class InfoSnackbarComponent {
message: string;
constructor(@Inject(MAT_SNACK_BAR_DATA) public data: any) {
this.message = data.message;
}
}
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'd2c-warn-snack',
templateUrl: 'snackbars/warn.html',
styleUrls: ['snackbars/warn.css']
})
export class WarnSnackbarComponent {
message: string;
constructor(@Inject(MAT_SNACK_BAR_DATA) public data: any) {
this.message = data.message;
}
}
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'd2c-select-platform-dialog',
templateUrl: './select-platform-dialog.component.html',
})
export class SelectPlatformDialogComponent {
public const: Const = Const;
public PLATFORMS_DICT = Const.PLATFORMS_DICT;
newMessage = '';
constructor(
public dialogRef: MatDialogRef<SelectPlatformDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: UserInfo[]) { }
onSelect(u: UserInfo): void {
this.dialogRef.close(u);
}
} | the_stack |
import {Request} from '../lib/request';
import {Response} from '../lib/response';
import {AWSError} from '../lib/error';
import {Service} from '../lib/service';
import {ServiceConfigurationOptions} from '../lib/service';
import {ConfigBase as Config} from '../lib/config-base';
interface Blob {}
declare class SavingsPlans extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: SavingsPlans.Types.ClientConfiguration)
config: Config & SavingsPlans.Types.ClientConfiguration;
/**
* Creates a Savings Plan.
*/
createSavingsPlan(params: SavingsPlans.Types.CreateSavingsPlanRequest, callback?: (err: AWSError, data: SavingsPlans.Types.CreateSavingsPlanResponse) => void): Request<SavingsPlans.Types.CreateSavingsPlanResponse, AWSError>;
/**
* Creates a Savings Plan.
*/
createSavingsPlan(callback?: (err: AWSError, data: SavingsPlans.Types.CreateSavingsPlanResponse) => void): Request<SavingsPlans.Types.CreateSavingsPlanResponse, AWSError>;
/**
* Deletes the queued purchase for the specified Savings Plan.
*/
deleteQueuedSavingsPlan(params: SavingsPlans.Types.DeleteQueuedSavingsPlanRequest, callback?: (err: AWSError, data: SavingsPlans.Types.DeleteQueuedSavingsPlanResponse) => void): Request<SavingsPlans.Types.DeleteQueuedSavingsPlanResponse, AWSError>;
/**
* Deletes the queued purchase for the specified Savings Plan.
*/
deleteQueuedSavingsPlan(callback?: (err: AWSError, data: SavingsPlans.Types.DeleteQueuedSavingsPlanResponse) => void): Request<SavingsPlans.Types.DeleteQueuedSavingsPlanResponse, AWSError>;
/**
* Describes the specified Savings Plans rates.
*/
describeSavingsPlanRates(params: SavingsPlans.Types.DescribeSavingsPlanRatesRequest, callback?: (err: AWSError, data: SavingsPlans.Types.DescribeSavingsPlanRatesResponse) => void): Request<SavingsPlans.Types.DescribeSavingsPlanRatesResponse, AWSError>;
/**
* Describes the specified Savings Plans rates.
*/
describeSavingsPlanRates(callback?: (err: AWSError, data: SavingsPlans.Types.DescribeSavingsPlanRatesResponse) => void): Request<SavingsPlans.Types.DescribeSavingsPlanRatesResponse, AWSError>;
/**
* Describes the specified Savings Plans.
*/
describeSavingsPlans(params: SavingsPlans.Types.DescribeSavingsPlansRequest, callback?: (err: AWSError, data: SavingsPlans.Types.DescribeSavingsPlansResponse) => void): Request<SavingsPlans.Types.DescribeSavingsPlansResponse, AWSError>;
/**
* Describes the specified Savings Plans.
*/
describeSavingsPlans(callback?: (err: AWSError, data: SavingsPlans.Types.DescribeSavingsPlansResponse) => void): Request<SavingsPlans.Types.DescribeSavingsPlansResponse, AWSError>;
/**
* Describes the specified Savings Plans offering rates.
*/
describeSavingsPlansOfferingRates(params: SavingsPlans.Types.DescribeSavingsPlansOfferingRatesRequest, callback?: (err: AWSError, data: SavingsPlans.Types.DescribeSavingsPlansOfferingRatesResponse) => void): Request<SavingsPlans.Types.DescribeSavingsPlansOfferingRatesResponse, AWSError>;
/**
* Describes the specified Savings Plans offering rates.
*/
describeSavingsPlansOfferingRates(callback?: (err: AWSError, data: SavingsPlans.Types.DescribeSavingsPlansOfferingRatesResponse) => void): Request<SavingsPlans.Types.DescribeSavingsPlansOfferingRatesResponse, AWSError>;
/**
* Describes the specified Savings Plans offerings.
*/
describeSavingsPlansOfferings(params: SavingsPlans.Types.DescribeSavingsPlansOfferingsRequest, callback?: (err: AWSError, data: SavingsPlans.Types.DescribeSavingsPlansOfferingsResponse) => void): Request<SavingsPlans.Types.DescribeSavingsPlansOfferingsResponse, AWSError>;
/**
* Describes the specified Savings Plans offerings.
*/
describeSavingsPlansOfferings(callback?: (err: AWSError, data: SavingsPlans.Types.DescribeSavingsPlansOfferingsResponse) => void): Request<SavingsPlans.Types.DescribeSavingsPlansOfferingsResponse, AWSError>;
/**
* Lists the tags for the specified resource.
*/
listTagsForResource(params: SavingsPlans.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: SavingsPlans.Types.ListTagsForResourceResponse) => void): Request<SavingsPlans.Types.ListTagsForResourceResponse, AWSError>;
/**
* Lists the tags for the specified resource.
*/
listTagsForResource(callback?: (err: AWSError, data: SavingsPlans.Types.ListTagsForResourceResponse) => void): Request<SavingsPlans.Types.ListTagsForResourceResponse, AWSError>;
/**
* Adds the specified tags to the specified resource.
*/
tagResource(params: SavingsPlans.Types.TagResourceRequest, callback?: (err: AWSError, data: SavingsPlans.Types.TagResourceResponse) => void): Request<SavingsPlans.Types.TagResourceResponse, AWSError>;
/**
* Adds the specified tags to the specified resource.
*/
tagResource(callback?: (err: AWSError, data: SavingsPlans.Types.TagResourceResponse) => void): Request<SavingsPlans.Types.TagResourceResponse, AWSError>;
/**
* Removes the specified tags from the specified resource.
*/
untagResource(params: SavingsPlans.Types.UntagResourceRequest, callback?: (err: AWSError, data: SavingsPlans.Types.UntagResourceResponse) => void): Request<SavingsPlans.Types.UntagResourceResponse, AWSError>;
/**
* Removes the specified tags from the specified resource.
*/
untagResource(callback?: (err: AWSError, data: SavingsPlans.Types.UntagResourceResponse) => void): Request<SavingsPlans.Types.UntagResourceResponse, AWSError>;
}
declare namespace SavingsPlans {
export type Amount = string;
export type ClientToken = string;
export interface CreateSavingsPlanRequest {
/**
* The ID of the offering.
*/
savingsPlanOfferingId: SavingsPlanOfferingId;
/**
* The hourly commitment, in USD. This is a value between 0.001 and 1 million. You cannot specify more than three digits after the decimal point.
*/
commitment: Amount;
/**
* The up-front payment amount. This is a whole number between 50 and 99 percent of the total value of the Savings Plan. This parameter is supported only if the payment option is Partial Upfront.
*/
upfrontPaymentAmount?: Amount;
/**
* The time at which to purchase the Savings Plan, in UTC format (YYYY-MM-DDTHH:MM:SSZ).
*/
purchaseTime?: DateTime;
/**
* Unique, case-sensitive identifier that you provide to ensure the idempotency of the request.
*/
clientToken?: ClientToken;
/**
* One or more tags.
*/
tags?: TagMap;
}
export interface CreateSavingsPlanResponse {
/**
* The ID of the Savings Plan.
*/
savingsPlanId?: SavingsPlanId;
}
export type CurrencyCode = "CNY"|"USD"|string;
export type CurrencyList = CurrencyCode[];
export type DateTime = Date;
export interface DeleteQueuedSavingsPlanRequest {
/**
* The ID of the Savings Plan.
*/
savingsPlanId: SavingsPlanId;
}
export interface DeleteQueuedSavingsPlanResponse {
}
export interface DescribeSavingsPlanRatesRequest {
/**
* The ID of the Savings Plan.
*/
savingsPlanId: SavingsPlanId;
/**
* The filters.
*/
filters?: SavingsPlanRateFilterList;
/**
* The token for the next page of results.
*/
nextToken?: PaginationToken;
/**
* The maximum number of results to return with a single call. To retrieve additional results, make another call with the returned token value.
*/
maxResults?: MaxResults;
}
export interface DescribeSavingsPlanRatesResponse {
/**
* The ID of the Savings Plan.
*/
savingsPlanId?: SavingsPlanId;
/**
* Information about the Savings Plans rates.
*/
searchResults?: SavingsPlanRateList;
/**
* The token to use to retrieve the next page of results. This value is null when there are no more results to return.
*/
nextToken?: PaginationToken;
}
export interface DescribeSavingsPlansOfferingRatesRequest {
/**
* The IDs of the offerings.
*/
savingsPlanOfferingIds?: UUIDs;
/**
* The payment options.
*/
savingsPlanPaymentOptions?: SavingsPlanPaymentOptionList;
/**
* The plan types.
*/
savingsPlanTypes?: SavingsPlanTypeList;
/**
* The AWS products.
*/
products?: SavingsPlanProductTypeList;
/**
* The services.
*/
serviceCodes?: SavingsPlanRateServiceCodeList;
/**
* The usage details of the line item in the billing report.
*/
usageTypes?: SavingsPlanRateUsageTypeList;
/**
* The specific AWS operation for the line item in the billing report.
*/
operations?: SavingsPlanRateOperationList;
/**
* The filters.
*/
filters?: SavingsPlanOfferingRateFiltersList;
/**
* The token for the next page of results.
*/
nextToken?: PaginationToken;
/**
* The maximum number of results to return with a single call. To retrieve additional results, make another call with the returned token value.
*/
maxResults?: PageSize;
}
export interface DescribeSavingsPlansOfferingRatesResponse {
/**
* Information about the Savings Plans offering rates.
*/
searchResults?: SavingsPlanOfferingRatesList;
/**
* The token to use to retrieve the next page of results. This value is null when there are no more results to return.
*/
nextToken?: PaginationToken;
}
export interface DescribeSavingsPlansOfferingsRequest {
/**
* The IDs of the offerings.
*/
offeringIds?: UUIDs;
/**
* The payment options.
*/
paymentOptions?: SavingsPlanPaymentOptionList;
/**
* The product type.
*/
productType?: SavingsPlanProductType;
/**
* The plan type.
*/
planTypes?: SavingsPlanTypeList;
/**
* The durations, in seconds.
*/
durations?: DurationsList;
/**
* The currencies.
*/
currencies?: CurrencyList;
/**
* The descriptions.
*/
descriptions?: SavingsPlanDescriptionsList;
/**
* The services.
*/
serviceCodes?: SavingsPlanServiceCodeList;
/**
* The usage details of the line item in the billing report.
*/
usageTypes?: SavingsPlanUsageTypeList;
/**
* The specific AWS operation for the line item in the billing report.
*/
operations?: SavingsPlanOperationList;
/**
* The filters.
*/
filters?: SavingsPlanOfferingFiltersList;
/**
* The token for the next page of results.
*/
nextToken?: PaginationToken;
/**
* The maximum number of results to return with a single call. To retrieve additional results, make another call with the returned token value.
*/
maxResults?: PageSize;
}
export interface DescribeSavingsPlansOfferingsResponse {
/**
* Information about the Savings Plans offerings.
*/
searchResults?: SavingsPlanOfferingsList;
/**
* The token to use to retrieve the next page of results. This value is null when there are no more results to return.
*/
nextToken?: PaginationToken;
}
export interface DescribeSavingsPlansRequest {
/**
* The Amazon Resource Names (ARN) of the Savings Plans.
*/
savingsPlanArns?: SavingsPlanArnList;
/**
* The IDs of the Savings Plans.
*/
savingsPlanIds?: SavingsPlanIdList;
/**
* The token for the next page of results.
*/
nextToken?: PaginationToken;
/**
* The maximum number of results to return with a single call. To retrieve additional results, make another call with the returned token value.
*/
maxResults?: MaxResults;
/**
* The states.
*/
states?: SavingsPlanStateList;
/**
* The filters.
*/
filters?: SavingsPlanFilterList;
}
export interface DescribeSavingsPlansResponse {
/**
* Information about the Savings Plans.
*/
savingsPlans?: SavingsPlanList;
/**
* The token to use to retrieve the next page of results. This value is null when there are no more results to return.
*/
nextToken?: PaginationToken;
}
export type DurationsList = SavingsPlansDuration[];
export type EC2InstanceFamily = string;
export type FilterValuesList = JsonSafeFilterValueString[];
export type JsonSafeFilterValueString = string;
export type ListOfStrings = String[];
export interface ListTagsForResourceRequest {
/**
* The Amazon Resource Name (ARN) of the resource.
*/
resourceArn: SavingsPlanArn;
}
export interface ListTagsForResourceResponse {
/**
* Information about the tags.
*/
tags?: TagMap;
}
export type MaxResults = number;
export type PageSize = number;
export type PaginationToken = string;
export interface ParentSavingsPlanOffering {
/**
* The ID of the offering.
*/
offeringId?: UUID;
/**
* The payment option.
*/
paymentOption?: SavingsPlanPaymentOption;
/**
* The plan type.
*/
planType?: SavingsPlanType;
/**
* The duration, in seconds.
*/
durationSeconds?: SavingsPlansDuration;
/**
* The currency.
*/
currency?: CurrencyCode;
/**
* The description.
*/
planDescription?: SavingsPlanDescription;
}
export type Region = string;
export interface SavingsPlan {
/**
* The ID of the offering.
*/
offeringId?: SavingsPlanOfferingId;
/**
* The ID of the Savings Plan.
*/
savingsPlanId?: SavingsPlanId;
/**
* The Amazon Resource Name (ARN) of the Savings Plan.
*/
savingsPlanArn?: SavingsPlanArn;
/**
* The description.
*/
description?: String;
/**
* The start time.
*/
start?: String;
/**
* The end time.
*/
end?: String;
/**
* The state.
*/
state?: SavingsPlanState;
/**
* The AWS Region.
*/
region?: Region;
/**
* The EC2 instance family.
*/
ec2InstanceFamily?: EC2InstanceFamily;
/**
* The plan type.
*/
savingsPlanType?: SavingsPlanType;
/**
* The payment option.
*/
paymentOption?: SavingsPlanPaymentOption;
/**
* The product types.
*/
productTypes?: SavingsPlanProductTypeList;
/**
* The currency.
*/
currency?: CurrencyCode;
/**
* The hourly commitment, in USD.
*/
commitment?: Amount;
/**
* The up-front payment amount.
*/
upfrontPaymentAmount?: Amount;
/**
* The recurring payment amount.
*/
recurringPaymentAmount?: Amount;
/**
* The duration of the term, in seconds.
*/
termDurationInSeconds?: TermDurationInSeconds;
/**
* One or more tags.
*/
tags?: TagMap;
}
export type SavingsPlanArn = string;
export type SavingsPlanArnList = SavingsPlanArn[];
export type SavingsPlanDescription = string;
export type SavingsPlanDescriptionsList = SavingsPlanDescription[];
export interface SavingsPlanFilter {
/**
* The filter name.
*/
name?: SavingsPlansFilterName;
/**
* The filter value.
*/
values?: ListOfStrings;
}
export type SavingsPlanFilterList = SavingsPlanFilter[];
export type SavingsPlanId = string;
export type SavingsPlanIdList = SavingsPlanId[];
export type SavingsPlanList = SavingsPlan[];
export interface SavingsPlanOffering {
/**
* The ID of the offering.
*/
offeringId?: UUID;
/**
* The product type.
*/
productTypes?: SavingsPlanProductTypeList;
/**
* The plan type.
*/
planType?: SavingsPlanType;
/**
* The description.
*/
description?: SavingsPlanDescription;
/**
* The payment option.
*/
paymentOption?: SavingsPlanPaymentOption;
/**
* The duration, in seconds.
*/
durationSeconds?: SavingsPlansDuration;
/**
* The currency.
*/
currency?: CurrencyCode;
/**
* The service.
*/
serviceCode?: SavingsPlanServiceCode;
/**
* The usage details of the line item in the billing report.
*/
usageType?: SavingsPlanUsageType;
/**
* The specific AWS operation for the line item in the billing report.
*/
operation?: SavingsPlanOperation;
/**
* The properties.
*/
properties?: SavingsPlanOfferingPropertyList;
}
export type SavingsPlanOfferingFilterAttribute = "region"|"instanceFamily"|string;
export interface SavingsPlanOfferingFilterElement {
/**
* The filter name.
*/
name?: SavingsPlanOfferingFilterAttribute;
/**
* The filter values.
*/
values?: FilterValuesList;
}
export type SavingsPlanOfferingFiltersList = SavingsPlanOfferingFilterElement[];
export type SavingsPlanOfferingId = string;
export interface SavingsPlanOfferingProperty {
/**
* The property name.
*/
name?: SavingsPlanOfferingPropertyKey;
/**
* The property value.
*/
value?: JsonSafeFilterValueString;
}
export type SavingsPlanOfferingPropertyKey = "region"|"instanceFamily"|string;
export type SavingsPlanOfferingPropertyList = SavingsPlanOfferingProperty[];
export interface SavingsPlanOfferingRate {
/**
* The Savings Plan offering.
*/
savingsPlanOffering?: ParentSavingsPlanOffering;
/**
* The Savings Plan rate.
*/
rate?: SavingsPlanRatePricePerUnit;
/**
* The unit.
*/
unit?: SavingsPlanRateUnit;
/**
* The product type.
*/
productType?: SavingsPlanProductType;
/**
* The service.
*/
serviceCode?: SavingsPlanRateServiceCode;
/**
* The usage details of the line item in the billing report.
*/
usageType?: SavingsPlanRateUsageType;
/**
* The specific AWS operation for the line item in the billing report.
*/
operation?: SavingsPlanRateOperation;
/**
* The properties.
*/
properties?: SavingsPlanOfferingRatePropertyList;
}
export interface SavingsPlanOfferingRateFilterElement {
/**
* The filter name.
*/
name?: SavingsPlanRateFilterAttribute;
/**
* The filter values.
*/
values?: FilterValuesList;
}
export type SavingsPlanOfferingRateFiltersList = SavingsPlanOfferingRateFilterElement[];
export interface SavingsPlanOfferingRateProperty {
/**
* The property name.
*/
name?: JsonSafeFilterValueString;
/**
* The property value.
*/
value?: JsonSafeFilterValueString;
}
export type SavingsPlanOfferingRatePropertyList = SavingsPlanOfferingRateProperty[];
export type SavingsPlanOfferingRatesList = SavingsPlanOfferingRate[];
export type SavingsPlanOfferingsList = SavingsPlanOffering[];
export type SavingsPlanOperation = string;
export type SavingsPlanOperationList = SavingsPlanOperation[];
export type SavingsPlanPaymentOption = "All Upfront"|"Partial Upfront"|"No Upfront"|string;
export type SavingsPlanPaymentOptionList = SavingsPlanPaymentOption[];
export type SavingsPlanProductType = "EC2"|"Fargate"|"Lambda"|string;
export type SavingsPlanProductTypeList = SavingsPlanProductType[];
export interface SavingsPlanRate {
/**
* The rate.
*/
rate?: Amount;
/**
* The currency.
*/
currency?: CurrencyCode;
/**
* The unit.
*/
unit?: SavingsPlanRateUnit;
/**
* The product type.
*/
productType?: SavingsPlanProductType;
/**
* The service.
*/
serviceCode?: SavingsPlanRateServiceCode;
/**
* The usage details of the line item in the billing report.
*/
usageType?: SavingsPlanRateUsageType;
/**
* The specific AWS operation for the line item in the billing report.
*/
operation?: SavingsPlanRateOperation;
/**
* The properties.
*/
properties?: SavingsPlanRatePropertyList;
}
export interface SavingsPlanRateFilter {
/**
* The filter name.
*/
name?: SavingsPlanRateFilterName;
/**
* The filter values.
*/
values?: ListOfStrings;
}
export type SavingsPlanRateFilterAttribute = "region"|"instanceFamily"|"instanceType"|"productDescription"|"tenancy"|"productId"|string;
export type SavingsPlanRateFilterList = SavingsPlanRateFilter[];
export type SavingsPlanRateFilterName = "region"|"instanceType"|"productDescription"|"tenancy"|"productType"|"serviceCode"|"usageType"|"operation"|string;
export type SavingsPlanRateList = SavingsPlanRate[];
export type SavingsPlanRateOperation = string;
export type SavingsPlanRateOperationList = SavingsPlanRateOperation[];
export type SavingsPlanRatePricePerUnit = string;
export interface SavingsPlanRateProperty {
/**
* The property name.
*/
name?: SavingsPlanRatePropertyKey;
/**
* The property value.
*/
value?: JsonSafeFilterValueString;
}
export type SavingsPlanRatePropertyKey = "region"|"instanceType"|"instanceFamily"|"productDescription"|"tenancy"|string;
export type SavingsPlanRatePropertyList = SavingsPlanRateProperty[];
export type SavingsPlanRateServiceCode = "AmazonEC2"|"AmazonECS"|"AWSLambda"|string;
export type SavingsPlanRateServiceCodeList = SavingsPlanRateServiceCode[];
export type SavingsPlanRateUnit = "Hrs"|"Lambda-GB-Second"|"Request"|string;
export type SavingsPlanRateUsageType = string;
export type SavingsPlanRateUsageTypeList = SavingsPlanRateUsageType[];
export type SavingsPlanServiceCode = string;
export type SavingsPlanServiceCodeList = SavingsPlanServiceCode[];
export type SavingsPlanState = "payment-pending"|"payment-failed"|"active"|"retired"|"queued"|"queued-deleted"|string;
export type SavingsPlanStateList = SavingsPlanState[];
export type SavingsPlanType = "Compute"|"EC2Instance"|string;
export type SavingsPlanTypeList = SavingsPlanType[];
export type SavingsPlanUsageType = string;
export type SavingsPlanUsageTypeList = SavingsPlanUsageType[];
export type SavingsPlansDuration = number;
export type SavingsPlansFilterName = "region"|"ec2-instance-family"|"commitment"|"upfront"|"term"|"savings-plan-type"|"payment-option"|"start"|"end"|string;
export type String = string;
export type TagKey = string;
export type TagKeyList = TagKey[];
export type TagMap = {[key: string]: TagValue};
export interface TagResourceRequest {
/**
* The Amazon Resource Name (ARN) of the resource.
*/
resourceArn: SavingsPlanArn;
/**
* One or more tags. For example, { "tags": {"key1":"value1", "key2":"value2"} }.
*/
tags: TagMap;
}
export interface TagResourceResponse {
}
export type TagValue = string;
export type TermDurationInSeconds = number;
export type UUID = string;
export type UUIDs = UUID[];
export interface UntagResourceRequest {
/**
* The Amazon Resource Name (ARN) of the resource.
*/
resourceArn: SavingsPlanArn;
/**
* The tag keys.
*/
tagKeys: TagKeyList;
}
export interface UntagResourceResponse {
}
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
export type apiVersion = "2019-06-28"|"latest"|string;
export interface ClientApiVersions {
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
apiVersion?: apiVersion;
}
export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions;
/**
* Contains interfaces for use with the SavingsPlans client.
*/
export import Types = SavingsPlans;
}
export = SavingsPlans; | the_stack |
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { SpyLocation } from '@angular/common/testing';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { DebugElement, Inject } from '@angular/core';
import { By } from '@angular/platform-browser';
import { Router, NavigationStart } from '@angular/router';
import { Observable } from 'rxjs';
import { SensorParserListComponent } from './sensor-parser-list.component';
import { SensorParserConfigService } from '../../service/sensor-parser-config.service';
import { MetronAlerts } from '../../shared/metron-alerts';
import { TopologyStatus } from '../../model/topology-status';
import { SensorParserConfig } from '../../model/sensor-parser-config';
import { AuthenticationService } from '../../service/authentication.service';
import { SensorParserListModule } from './sensor-parser-list.module';
import { MetronDialogBox } from '../../shared/metron-dialog-box';
import { Sort } from '../../util/enums';
import 'jquery';
import { SensorParserConfigHistoryService } from '../../service/sensor-parser-config-history.service';
import { SensorParserConfigHistory } from '../../model/sensor-parser-config-history';
import { StormService } from '../../service/storm.service';
import {AppConfigService} from '../../service/app-config.service';
import {MockAppConfigService} from '../../service/mock.app-config.service';
class MockAuthenticationService extends AuthenticationService {
public checkAuthentication() {}
public getCurrentUser(options: {}): Observable<HttpResponse<{}>> {
return Observable.create(observer => {
observer.next(new HttpResponse({ body: 'test' }));
observer.complete();
});
}
}
class MockSensorParserConfigHistoryService extends SensorParserConfigHistoryService {
private allSensorParserConfigHistory: SensorParserConfigHistory[];
public setSensorParserConfigHistoryForTest(
allSensorParserConfigHistory: SensorParserConfigHistory[]
) {
this.allSensorParserConfigHistory = allSensorParserConfigHistory;
}
public getAll(): Observable<SensorParserConfigHistory[]> {
return Observable.create(observer => {
observer.next(this.allSensorParserConfigHistory);
observer.complete();
});
}
}
class MockSensorParserConfigService extends SensorParserConfigService {
private sensorParserConfigs: {};
public setSensorParserConfigForTest(sensorParserConfigs: {}) {
this.sensorParserConfigs = sensorParserConfigs;
}
public getAll(): Observable<{ string: SensorParserConfig }> {
return Observable.create(observer => {
observer.next(this.sensorParserConfigs);
observer.complete();
});
}
public deleteSensorParserConfigs(
sensorNames: string[]
): Observable<{ success: Array<string>; failure: Array<string> }> {
let result: { success: Array<string>; failure: Array<string> } = {
success: [],
failure: []
};
let observable = Observable.create(observer => {
for (let i = 0; i < sensorNames.length; i++) {
result.success.push(sensorNames[i]);
}
observer.next(result);
observer.complete();
});
return observable;
}
}
class MockStormService extends StormService {
private topologyStatuses: TopologyStatus[];
public setTopologyStatusForTest(topologyStatuses: TopologyStatus[]) {
this.topologyStatuses = topologyStatuses;
}
public pollGetAll(): Observable<TopologyStatus[]> {
return Observable.create(observer => {
observer.next(this.topologyStatuses);
observer.complete();
});
}
public getAll(): Observable<TopologyStatus[]> {
return Observable.create(observer => {
observer.next(this.topologyStatuses);
observer.complete();
});
}
}
class MockRouter {
events: Observable<Event> = Observable.create(observer => {
observer.next(new NavigationStart(1, '/sensors'));
observer.complete();
});
navigateByUrl(url: string) {}
}
class MockMetronDialogBox {
public showConfirmationMessage(message: string) {
return Observable.create(observer => {
observer.next(true);
observer.complete();
});
}
}
describe('Component: SensorParserList', () => {
let comp: SensorParserListComponent;
let fixture: ComponentFixture<SensorParserListComponent>;
let authenticationService: MockAuthenticationService;
let sensorParserConfigService: MockSensorParserConfigService;
let stormService: MockStormService;
let sensorParserConfigHistoryService: MockSensorParserConfigHistoryService;
let router: Router;
let metronAlerts: MetronAlerts;
let metronDialog: MetronDialogBox;
let dialogEl: DebugElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [SensorParserListModule],
providers: [
{ provide: HttpClient },
{ provide: Location, useClass: SpyLocation },
{ provide: AuthenticationService, useClass: MockAuthenticationService },
{
provide: SensorParserConfigService,
useClass: MockSensorParserConfigService
},
{ provide: StormService, useClass: MockStormService },
{
provide: SensorParserConfigHistoryService,
useClass: MockSensorParserConfigHistoryService
},
{ provide: Router, useClass: MockRouter },
{ provide: MetronDialogBox, useClass: MockMetronDialogBox },
{ provide: AppConfigService, useClass: MockAppConfigService },
MetronAlerts
]
});
fixture = TestBed.createComponent(SensorParserListComponent);
comp = fixture.componentInstance;
authenticationService = TestBed.get(AuthenticationService);
sensorParserConfigService = TestBed.get(SensorParserConfigService);
stormService = TestBed.get(StormService);
sensorParserConfigHistoryService = TestBed.get(
SensorParserConfigHistoryService
);
router = TestBed.get(Router);
metronAlerts = TestBed.get(MetronAlerts);
metronDialog = TestBed.get(MetronDialogBox);
dialogEl = fixture.debugElement.query(By.css('.primary'));
}));
it('should create an instance', async(() => {
let component: SensorParserListComponent = fixture.componentInstance;
expect(component).toBeDefined();
fixture.destroy();
}));
it('getSensors should call getStatus and poll status and all variables should be initialised', async(() => {
let sensorParserConfigHistory1 = new SensorParserConfigHistory();
let sensorParserConfigHistory2 = new SensorParserConfigHistory();
let sensorParserConfig1 = new SensorParserConfig();
let sensorParserConfig2 = new SensorParserConfig();
sensorParserConfigHistory1.sensorName = 'squid';
sensorParserConfigHistory2.sensorName = 'bro';
sensorParserConfigHistory1.config = sensorParserConfig1;
sensorParserConfigHistory2.config = sensorParserConfig2;
let sensorParserStatus1 = new TopologyStatus();
let sensorParserStatus2 = new TopologyStatus();
sensorParserStatus1.name = 'squid';
sensorParserStatus1.status = 'KILLED';
sensorParserStatus2.name = 'bro';
sensorParserStatus2.status = 'KILLED';
sensorParserConfigService.setSensorParserConfigForTest({
squid: sensorParserConfig1,
bro: sensorParserConfig2
});
stormService.setTopologyStatusForTest([
sensorParserStatus1,
sensorParserStatus2
]);
let component: SensorParserListComponent = fixture.componentInstance;
component.enableAutoRefresh = false;
component.ngOnInit();
expect(component.sensors[0].sensorName).toEqual(
sensorParserConfigHistory1.sensorName
);
expect(component.sensors[1].sensorName).toEqual(
sensorParserConfigHistory2.sensorName
);
expect(component.sensorsStatus[0]).toEqual(
Object.assign(new TopologyStatus(), sensorParserStatus1)
);
expect(component.sensorsStatus[1]).toEqual(
Object.assign(new TopologyStatus(), sensorParserStatus2)
);
expect(component.selectedSensors).toEqual([]);
expect(component.count).toEqual(2);
fixture.destroy();
}));
it('getParserType should return the Type of Parser', async(() => {
let component: SensorParserListComponent = fixture.componentInstance;
let sensorParserConfig1 = new SensorParserConfig();
sensorParserConfig1.sensorTopic = 'squid';
sensorParserConfig1.parserClassName =
'org.apache.metron.parsers.GrokParser';
let sensorParserConfig2 = new SensorParserConfig();
sensorParserConfig2.sensorTopic = 'bro';
sensorParserConfig2.parserClassName =
'org.apache.metron.parsers.bro.BasicBroParser';
expect(component.getParserType(sensorParserConfig1)).toEqual('Grok');
expect(component.getParserType(sensorParserConfig2)).toEqual('Bro');
fixture.destroy();
}));
it('navigateToSensorEdit should set selected sensor and change url', async(() => {
let event = new Event('mouse');
event.stopPropagation = jasmine.createSpy('stopPropagation');
spyOn(router, 'navigateByUrl');
let component: SensorParserListComponent = fixture.componentInstance;
let sensorParserConfigHistory1 = new SensorParserConfigHistory();
sensorParserConfigHistory1.sensorName = 'squid';
component.navigateToSensorEdit(sensorParserConfigHistory1, event);
let expectStr = router.navigateByUrl['calls'].argsFor(0);
expect(expectStr).toEqual(['/sensors(dialog:sensors-config/squid)']);
expect(event.stopPropagation).toHaveBeenCalled();
fixture.destroy();
}));
it('addAddSensor should change the URL', async(() => {
spyOn(router, 'navigateByUrl');
let component: SensorParserListComponent = fixture.componentInstance;
component.addAddSensor();
let expectStr = router.navigateByUrl['calls'].argsFor(0);
expect(expectStr).toEqual(['/sensors(dialog:sensors-config/new)']);
fixture.destroy();
}));
it('onRowSelected should add add/remove items from the selected stack', async(() => {
let component: SensorParserListComponent = fixture.componentInstance;
let event = { target: { checked: true } };
let sensorParserConfigHistory = new SensorParserConfigHistory();
let sensorParserConfig = new SensorParserConfig();
sensorParserConfig.sensorTopic = 'squid';
sensorParserConfigHistory.config = sensorParserConfig;
component.onRowSelected(sensorParserConfigHistory, event);
expect(component.selectedSensors[0]).toEqual(sensorParserConfigHistory);
event = { target: { checked: false } };
component.onRowSelected(sensorParserConfigHistory, event);
expect(component.selectedSensors).toEqual([]);
fixture.destroy();
}));
it('onSelectDeselectAll should populate items into selected stack', async(() => {
let component: SensorParserListComponent = fixture.componentInstance;
let sensorParserConfig1 = new SensorParserConfig();
let sensorParserConfig2 = new SensorParserConfig();
let sensorParserConfigHistory1 = new SensorParserConfigHistory();
let sensorParserConfigHistory2 = new SensorParserConfigHistory();
sensorParserConfig1.sensorTopic = 'squid';
sensorParserConfigHistory1.config = sensorParserConfig1;
sensorParserConfig2.sensorTopic = 'bro';
sensorParserConfigHistory2.config = sensorParserConfig2;
component.sensors.push(sensorParserConfigHistory1);
component.sensors.push(sensorParserConfigHistory2);
let event = { target: { checked: true } };
component.onSelectDeselectAll(event);
expect(component.selectedSensors).toEqual([
sensorParserConfigHistory1,
sensorParserConfigHistory2
]);
event = { target: { checked: false } };
component.onSelectDeselectAll(event);
expect(component.selectedSensors).toEqual([]);
fixture.destroy();
}));
it('onSensorRowSelect should change the url and updated the selected items stack', async(() => {
let sensorParserConfigHistory1 = new SensorParserConfigHistory();
sensorParserConfigHistory1.sensorName = 'squid';
let component: SensorParserListComponent = fixture.componentInstance;
let event = {
target: { type: 'div', parentElement: { firstChild: { type: 'div' } } }
};
component.selectedSensor = sensorParserConfigHistory1;
component.onSensorRowSelect(sensorParserConfigHistory1, event);
expect(component.selectedSensor).toEqual(null);
component.onSensorRowSelect(sensorParserConfigHistory1, event);
expect(component.selectedSensor).toEqual(sensorParserConfigHistory1);
component.selectedSensor = sensorParserConfigHistory1;
event = {
target: {
type: 'checkbox',
parentElement: { firstChild: { type: 'div' } }
}
};
component.onSensorRowSelect(sensorParserConfigHistory1, event);
expect(component.selectedSensor).toEqual(sensorParserConfigHistory1);
fixture.destroy();
}));
it('onSensorRowSelect should change the url and updated the selected items stack', async(() => {
let component: SensorParserListComponent = fixture.componentInstance;
let sensorParserConfigHistory = new SensorParserConfigHistory();
let sensorParserConfig = new SensorParserConfig();
sensorParserConfig.sensorTopic = 'squid';
sensorParserConfigHistory.config = sensorParserConfig;
component.toggleStartStopInProgress(sensorParserConfigHistory);
expect(sensorParserConfig['startStopInProgress']).toEqual(true);
component.toggleStartStopInProgress(sensorParserConfigHistory);
expect(sensorParserConfig['startStopInProgress']).toEqual(false);
}));
it('onDeleteSensor should call the appropriate url', async(() => {
spyOn(metronAlerts, 'showSuccessMessage');
spyOn(metronDialog, 'showConfirmationMessage').and.callThrough();
let event = new Event('mouse');
event.stopPropagation = jasmine.createSpy('stopPropagation');
let component: SensorParserListComponent = fixture.componentInstance;
let sensorParserConfigHistory1 = new SensorParserConfigHistory();
let sensorParserConfigHistory2 = new SensorParserConfigHistory();
let sensorParserConfig1 = new SensorParserConfig();
let sensorParserConfig2 = new SensorParserConfig();
sensorParserConfigHistory1.sensorName = 'squid';
sensorParserConfigHistory2.sensorName = 'bro';
sensorParserConfigHistory1.config = sensorParserConfig1;
sensorParserConfigHistory2.config = sensorParserConfig2;
component.selectedSensors.push(sensorParserConfigHistory1);
component.selectedSensors.push(sensorParserConfigHistory2);
component.onDeleteSensor();
expect(metronAlerts.showSuccessMessage).toHaveBeenCalled();
component.deleteSensor(event, [sensorParserConfigHistory1]);
expect(metronDialog.showConfirmationMessage).toHaveBeenCalled();
expect(metronDialog.showConfirmationMessage['calls'].count()).toEqual(2);
expect(metronDialog.showConfirmationMessage['calls'].count()).toEqual(2);
expect(metronDialog.showConfirmationMessage['calls'].all()[0].args).toEqual(
['Are you sure you want to delete sensor(s) squid, bro ?']
);
expect(metronDialog.showConfirmationMessage['calls'].all()[1].args).toEqual(
['Are you sure you want to delete sensor(s) squid ?']
);
expect(event.stopPropagation).toHaveBeenCalled();
fixture.destroy();
}));
it('onStopSensor should call the appropriate url', async(() => {
let event = new Event('mouse');
event.stopPropagation = jasmine.createSpy('stopPropagation');
let sensorParserConfigHistory1 = new SensorParserConfigHistory();
let sensorParserConfig1 = new SensorParserConfig();
sensorParserConfig1.sensorTopic = 'squid';
sensorParserConfigHistory1.config = sensorParserConfig1;
let observableToReturn = Observable.create(observer => {
observer.next({ status: 'success', message: 'Some Message' });
observer.complete();
});
spyOn(metronAlerts, 'showSuccessMessage');
spyOn(stormService, 'stopParser').and.returnValue(observableToReturn);
let component: SensorParserListComponent = fixture.componentInstance;
component.onStopSensor(sensorParserConfigHistory1, event);
expect(stormService.stopParser).toHaveBeenCalled();
expect(event.stopPropagation).toHaveBeenCalled();
expect(metronAlerts.showSuccessMessage).toHaveBeenCalled();
fixture.destroy();
}));
it('onStartSensor should call the appropriate url', async(() => {
let event = new Event('mouse');
event.stopPropagation = jasmine.createSpy('stopPropagation');
let sensorParserConfigHistory1 = new SensorParserConfigHistory();
let sensorParserConfig1 = new SensorParserConfig();
sensorParserConfig1.sensorTopic = 'squid';
sensorParserConfigHistory1.config = sensorParserConfig1;
let observableToReturn = Observable.create(observer => {
observer.next({ status: 'success', message: 'Some Message' });
observer.complete();
});
spyOn(metronAlerts, 'showSuccessMessage');
spyOn(stormService, 'startParser').and.returnValue(observableToReturn);
let component: SensorParserListComponent = fixture.componentInstance;
component.onStartSensor(sensorParserConfigHistory1, event);
expect(stormService.startParser).toHaveBeenCalled();
expect(event.stopPropagation).toHaveBeenCalled();
expect(metronAlerts.showSuccessMessage).toHaveBeenCalled();
fixture.destroy();
}));
it('onEnableSensor should call the appropriate url', async(() => {
let event = new Event('mouse');
event.stopPropagation = jasmine.createSpy('stopPropagation');
let sensorParserConfigHistory1 = new SensorParserConfigHistory();
let sensorParserConfig1 = new SensorParserConfig();
sensorParserConfig1.sensorTopic = 'squid';
sensorParserConfigHistory1.config = sensorParserConfig1;
let observableToReturn = Observable.create(observer => {
observer.next({ status: 'success', message: 'Some Message' });
observer.complete();
});
spyOn(metronAlerts, 'showSuccessMessage');
spyOn(stormService, 'activateParser').and.returnValue(observableToReturn);
let component: SensorParserListComponent = fixture.componentInstance;
component.onEnableSensor(sensorParserConfigHistory1, event);
expect(stormService.activateParser).toHaveBeenCalled();
expect(event.stopPropagation).toHaveBeenCalled();
expect(metronAlerts.showSuccessMessage).toHaveBeenCalled();
fixture.destroy();
}));
it('onDisableSensor should call the appropriate url', async(() => {
let event = new Event('mouse');
event.stopPropagation = jasmine.createSpy('stopPropagation');
let sensorParserConfigHistory1 = new SensorParserConfigHistory();
let sensorParserConfig1 = new SensorParserConfig();
sensorParserConfig1.sensorTopic = 'squid';
sensorParserConfigHistory1.config = sensorParserConfig1;
let observableToReturn = Observable.create(observer => {
observer.next({ status: 'success', message: 'Some Message' });
observer.complete();
});
spyOn(metronAlerts, 'showSuccessMessage');
spyOn(stormService, 'deactivateParser').and.returnValue(observableToReturn);
let component: SensorParserListComponent = fixture.componentInstance;
component.onDisableSensor(sensorParserConfigHistory1, event);
expect(stormService.deactivateParser).toHaveBeenCalled();
expect(event.stopPropagation).toHaveBeenCalled();
expect(metronAlerts.showSuccessMessage).toHaveBeenCalled();
fixture.destroy();
}));
it(
'onStartSensors/onStopSensors should call start on all sensors that have status != ' +
'Running and status != Running respectively',
async(() => {
let component: SensorParserListComponent = fixture.componentInstance;
spyOn(component, 'onStartSensor');
spyOn(component, 'onStopSensor');
spyOn(component, 'onDisableSensor');
spyOn(component, 'onEnableSensor');
let sensorParserConfigHistory1 = new SensorParserConfigHistory();
let sensorParserConfigHistory2 = new SensorParserConfigHistory();
let sensorParserConfigHistory3 = new SensorParserConfigHistory();
let sensorParserConfigHistory4 = new SensorParserConfigHistory();
let sensorParserConfigHistory5 = new SensorParserConfigHistory();
let sensorParserConfigHistory6 = new SensorParserConfigHistory();
let sensorParserConfigHistory7 = new SensorParserConfigHistory();
let sensorParserConfig1 = new SensorParserConfig();
let sensorParserConfig2 = new SensorParserConfig();
let sensorParserConfig3 = new SensorParserConfig();
let sensorParserConfig4 = new SensorParserConfig();
let sensorParserConfig5 = new SensorParserConfig();
let sensorParserConfig6 = new SensorParserConfig();
let sensorParserConfig7 = new SensorParserConfig();
sensorParserConfig1.sensorTopic = 'squid';
sensorParserConfigHistory1['status'] = 'Running';
sensorParserConfigHistory1.config = sensorParserConfig1;
sensorParserConfig2.sensorTopic = 'bro';
sensorParserConfigHistory2['status'] = 'Stopped';
sensorParserConfigHistory2.config = sensorParserConfig2;
sensorParserConfig3.sensorTopic = 'test';
sensorParserConfigHistory3['status'] = 'Stopped';
sensorParserConfigHistory3.config = sensorParserConfig3;
sensorParserConfig4.sensorTopic = 'test1';
sensorParserConfigHistory4['status'] = 'Stopped';
sensorParserConfigHistory4.config = sensorParserConfig4;
sensorParserConfig5.sensorTopic = 'test2';
sensorParserConfigHistory5['status'] = 'Running';
sensorParserConfigHistory5.config = sensorParserConfig5;
sensorParserConfig6.sensorTopic = 'test2';
sensorParserConfigHistory6['status'] = 'Disabled';
sensorParserConfigHistory6.config = sensorParserConfig6;
sensorParserConfig7.sensorTopic = 'test3';
sensorParserConfigHistory7['status'] = 'Disabled';
sensorParserConfigHistory7.config = sensorParserConfig7;
component.selectedSensors = [
sensorParserConfigHistory1,
sensorParserConfigHistory2,
sensorParserConfigHistory3,
sensorParserConfigHistory4,
sensorParserConfigHistory5,
sensorParserConfigHistory6,
sensorParserConfigHistory7
];
component.onStartSensors();
expect(component.onStartSensor['calls'].count()).toEqual(3);
component.onStopSensors();
expect(component.onStopSensor['calls'].count()).toEqual(4);
component.onDisableSensors();
expect(component.onDisableSensor['calls'].count()).toEqual(2);
component.onEnableSensors();
expect(component.onEnableSensor['calls'].count()).toEqual(2);
fixture.destroy();
})
);
it('sort', async(() => {
let component: SensorParserListComponent = fixture.componentInstance;
component.sensors = [
Object.assign(new SensorParserConfigHistory(), {
sensorName: 'abc',
config: {
parserClassName: 'org.apache.metron.parsers.GrokParser',
sensorTopic: 'abc'
},
createdBy: 'raghu',
modifiedBy: 'abc',
createdDate: '2016-11-25 09:09:12',
modifiedByDate: '2016-11-25 09:09:12'
}),
Object.assign(new SensorParserConfigHistory(), {
sensorName: 'plm',
config: {
parserClassName: 'org.apache.metron.parsers.Bro',
sensorTopic: 'plm'
},
createdBy: 'raghu',
modifiedBy: 'plm',
createdDate: '2016-11-25 12:39:21',
modifiedByDate: '2016-11-25 12:39:21'
}),
Object.assign(new SensorParserConfigHistory(), {
sensorName: 'xyz',
config: {
parserClassName: 'org.apache.metron.parsers.GrokParser',
sensorTopic: 'xyz'
},
createdBy: 'raghu',
modifiedBy: 'xyz',
createdDate: '2016-11-25 12:44:03',
modifiedByDate: '2016-11-25 12:44:03'
})
];
component.onSort({ sortBy: 'sensorName', sortOrder: Sort.ASC });
expect(component.sensors[0].sensorName).toEqual('abc');
expect(component.sensors[1].sensorName).toEqual('plm');
expect(component.sensors[2].sensorName).toEqual('xyz');
component.onSort({ sortBy: 'sensorName', sortOrder: Sort.DSC });
expect(component.sensors[0].sensorName).toEqual('xyz');
expect(component.sensors[1].sensorName).toEqual('plm');
expect(component.sensors[2].sensorName).toEqual('abc');
component.onSort({ sortBy: 'parserClassName', sortOrder: Sort.ASC });
expect(component.sensors[0].config.parserClassName).toEqual(
'org.apache.metron.parsers.Bro'
);
expect(component.sensors[1].config.parserClassName).toEqual(
'org.apache.metron.parsers.GrokParser'
);
expect(component.sensors[2].config.parserClassName).toEqual(
'org.apache.metron.parsers.GrokParser'
);
component.onSort({ sortBy: 'parserClassName', sortOrder: Sort.DSC });
expect(component.sensors[0].config.parserClassName).toEqual(
'org.apache.metron.parsers.GrokParser'
);
expect(component.sensors[1].config.parserClassName).toEqual(
'org.apache.metron.parsers.GrokParser'
);
expect(component.sensors[2].config.parserClassName).toEqual(
'org.apache.metron.parsers.Bro'
);
component.onSort({ sortBy: 'modifiedBy', sortOrder: Sort.ASC });
expect(component.sensors[0].modifiedBy).toEqual('abc');
expect(component.sensors[1].modifiedBy).toEqual('plm');
expect(component.sensors[2].modifiedBy).toEqual('xyz');
component.onSort({ sortBy: 'modifiedBy', sortOrder: Sort.DSC });
expect(component.sensors[0].modifiedBy).toEqual('xyz');
expect(component.sensors[1].modifiedBy).toEqual('plm');
expect(component.sensors[2].modifiedBy).toEqual('abc');
}));
it('sort', async(() => {
let component: SensorParserListComponent = fixture.componentInstance;
component.sensors = [
Object.assign(new SensorParserConfigHistory(), {
sensorName: 'abc',
config: {
parserClassName: 'org.apache.metron.parsers.GrokParser',
sensorTopic: 'abc'
},
createdBy: 'raghu',
modifiedBy: 'abc',
createdDate: '2016-11-25 09:09:12',
modifiedByDate: '2016-11-25 09:09:12'
})
];
component.sensorsStatus = [
Object.assign(new TopologyStatus(), {
name: 'abc',
status: 'ACTIVE',
latency: '10',
throughput: '23'
})
];
component.updateSensorStatus();
expect(component.sensors[0]['status']).toEqual('Running');
expect(component.sensors[0]['latency']).toEqual('10ms');
expect(component.sensors[0]['throughput']).toEqual('23kb/s');
component.sensorsStatus[0].status = 'KILLED';
component.updateSensorStatus();
expect(component.sensors[0]['status']).toEqual('Stopped');
expect(component.sensors[0]['latency']).toEqual('-');
expect(component.sensors[0]['throughput']).toEqual('-');
component.sensorsStatus[0].status = 'INACTIVE';
component.updateSensorStatus();
expect(component.sensors[0]['status']).toEqual('Disabled');
expect(component.sensors[0]['latency']).toEqual('-');
expect(component.sensors[0]['throughput']).toEqual('-');
component.sensorsStatus = [];
component.updateSensorStatus();
expect(component.sensors[0]['status']).toEqual('Stopped');
expect(component.sensors[0]['latency']).toEqual('-');
expect(component.sensors[0]['throughput']).toEqual('-');
}));
}); | the_stack |
import * as Geo from "../../geo/Geo";
import { TransitionMode } from "../TransitionMode";
import { EulerRotation } from "../interfaces/EulerRotation";
import { IStateBase } from "../interfaces/IStateBase";
import { ArgumentMapillaryError } from "../../error/ArgumentMapillaryError";
import { Camera } from "../../geo/Camera";
import { Spatial } from "../../geo/Spatial";
import { Transform } from "../../geo/Transform";
import { LngLatAlt } from "../../api/interfaces/LngLatAlt";
import { Image } from "../../graph/Image";
import { CameraType } from "../../geo/interfaces/CameraType";
export abstract class StateBase implements IStateBase {
protected _spatial: Spatial;
protected _reference: LngLatAlt;
protected _alpha: number;
protected _camera: Camera;
protected _zoom: number;
protected _currentIndex: number;
protected _trajectory: Image[];
protected _currentImage: Image;
protected _previousImage: Image;
protected _trajectoryTransforms: Transform[];
protected _trajectoryCameras: Camera[];
protected _currentCamera: Camera;
protected _previousCamera: Camera;
protected _motionless: boolean;
private _referenceThreshold: number;
private _transitionMode: TransitionMode;
constructor(state: IStateBase) {
this._spatial = new Spatial();
this._referenceThreshold = 0.01;
this._transitionMode = state.transitionMode;
this._reference = state.reference;
this._alpha = state.alpha;
this._camera = state.camera.clone();
this._zoom = state.zoom;
this._currentIndex = state.currentIndex;
this._trajectory = state.trajectory.slice();
this._trajectoryTransforms = [];
this._trajectoryCameras = [];
for (let image of this._trajectory) {
let translation: number[] = this._imageToTranslation(image, this._reference);
let transform: Transform = new Transform(
image.exifOrientation,
image.width,
image.height,
image.scale,
image.rotation,
translation,
image.image,
undefined,
image.cameraParameters,
<CameraType>image.cameraType);
this._trajectoryTransforms.push(transform);
this._trajectoryCameras.push(new Camera(transform));
}
this._currentImage = this._trajectory.length > 0 ?
this._trajectory[this._currentIndex] :
null;
this._previousImage = this._trajectory.length > 1 && this.currentIndex > 0 ?
this._trajectory[this._currentIndex - 1] :
null;
this._currentCamera = this._trajectoryCameras.length > 0 ?
this._trajectoryCameras[this._currentIndex].clone() :
new Camera();
this._previousCamera = this._trajectoryCameras.length > 1 && this.currentIndex > 0 ?
this._trajectoryCameras[this._currentIndex - 1].clone() :
this._currentCamera.clone();
}
public get reference(): LngLatAlt {
return this._reference;
}
public get alpha(): number {
return this._getAlpha();
}
public get camera(): Camera {
return this._camera;
}
public get zoom(): number {
return this._zoom;
}
public get trajectory(): Image[] {
return this._trajectory;
}
public get currentIndex(): number {
return this._currentIndex;
}
public get currentImage(): Image {
return this._currentImage;
}
public get previousImage(): Image {
return this._previousImage;
}
public get currentCamera(): Camera {
return this._currentCamera;
}
public get currentTransform(): Transform {
return this._trajectoryTransforms.length > 0 ?
this._trajectoryTransforms[this.currentIndex] : null;
}
public get previousTransform(): Transform {
return this._trajectoryTransforms.length > 1 && this.currentIndex > 0 ?
this._trajectoryTransforms[this.currentIndex - 1] : null;
}
public get motionless(): boolean {
return this._motionless;
}
public get transitionMode(): TransitionMode {
return this._transitionMode;
}
public move(delta: number): void { /*noop*/ }
public moveTo(position: number): void { /*noop*/ }
public rotate(delta: EulerRotation): void { /*noop*/ }
public rotateUnbounded(delta: EulerRotation): void { /*noop*/ }
public rotateWithoutInertia(delta: EulerRotation): void { /*noop*/ }
public rotateBasic(basicRotation: number[]): void { /*noop*/ }
public rotateBasicUnbounded(basicRotation: number[]): void { /*noop*/ }
public rotateBasicWithoutInertia(basicRotation: number[]): void { /*noop*/ }
public rotateToBasic(basic: number[]): void { /*noop*/ }
public setSpeed(speed: number): void { /*noop*/ }
public zoomIn(delta: number, reference: number[]): void { /*noop*/ }
public update(fps: number): void { /*noop*/ }
public setCenter(center: number[]): void { /*noop*/ }
public setZoom(zoom: number): void { /*noop*/ }
public dolly(delta: number): void { /*noop*/ }
public orbit(rotation: EulerRotation): void { /*noop*/ }
public setViewMatrix(matrix: number[]): void { /*noop*/ }
public truck(direction: number[]): void { /*noop*/ }
public append(images: Image[]): void {
if (images.length < 1) {
throw Error("Trajectory can not be empty");
}
if (this._currentIndex < 0) {
this.set(images);
} else {
this._trajectory = this._trajectory.concat(images);
this._appendToTrajectories(images);
}
}
public prepend(images: Image[]): void {
if (images.length < 1) {
throw Error("Trajectory can not be empty");
}
this._trajectory = images.slice().concat(this._trajectory);
this._currentIndex += images.length;
this._setCurrentImage();
let referenceReset: boolean = this._setReference(this._currentImage);
if (referenceReset) {
this._setTrajectories();
} else {
this._prependToTrajectories(images);
}
this._setCurrentCamera();
}
public remove(n: number): void {
if (n < 0) {
throw Error("n must be a positive integer");
}
if (this._currentIndex - 1 < n) {
throw Error("Current and previous images can not be removed");
}
for (let i: number = 0; i < n; i++) {
this._trajectory.shift();
this._trajectoryTransforms.shift();
this._trajectoryCameras.shift();
this._currentIndex--;
}
this._setCurrentImage();
}
public clearPrior(): void {
if (this._currentIndex > 0) {
this.remove(this._currentIndex - 1);
}
}
public clear(): void {
this.cut();
if (this._currentIndex > 0) {
this.remove(this._currentIndex - 1);
}
}
public cut(): void {
while (this._trajectory.length - 1 > this._currentIndex) {
this._trajectory.pop();
this._trajectoryTransforms.pop();
this._trajectoryCameras.pop();
}
}
public set(images: Image[]): void {
this._setTrajectory(images);
this._setCurrentImage();
this._setReference(this._currentImage);
this._setTrajectories();
this._setCurrentCamera();
}
public getCenter(): number[] {
return this._currentImage != null ?
this.currentTransform.projectBasic(this._camera.lookat.toArray()) :
[0.5, 0.5];
}
public setTransitionMode(mode: TransitionMode): void {
this._transitionMode = mode;
}
protected _getAlpha(): number { return 1; }
protected _setCurrent(): void {
this._setCurrentImage();
let referenceReset: boolean = this._setReference(this._currentImage);
if (referenceReset) {
this._setTrajectories();
}
this._setCurrentCamera();
}
protected _setCurrentCamera(): void {
this._currentCamera = this._trajectoryCameras[this._currentIndex].clone();
this._previousCamera = this._currentIndex > 0 ?
this._trajectoryCameras[this._currentIndex - 1].clone() :
this._currentCamera.clone();
}
protected _motionlessTransition(): boolean {
let imagesSet: boolean = this._currentImage != null && this._previousImage != null;
return imagesSet && (
this._transitionMode === TransitionMode.Instantaneous || !(
this._currentImage.merged &&
this._previousImage.merged &&
this._withinOriginalDistance() &&
this._sameConnectedComponent()
));
}
private _setReference(image: Image): boolean {
// do not reset reference if image is within threshold distance
if (Math.abs(image.lngLat.lat - this.reference.lat) < this._referenceThreshold &&
Math.abs(image.lngLat.lng - this.reference.lng) < this._referenceThreshold) {
return false;
}
// do not reset reference if previous image exist and transition is with motion
if (this._previousImage != null && !this._motionlessTransition()) {
return false;
}
this._reference.lat = image.lngLat.lat;
this._reference.lng = image.lngLat.lng;
this._reference.alt = image.computedAltitude;
return true;
}
private _setCurrentImage(): void {
this._currentImage = this._trajectory.length > 0 ?
this._trajectory[this._currentIndex] :
null;
this._previousImage = this._currentIndex > 0 ?
this._trajectory[this._currentIndex - 1] :
null;
}
private _setTrajectory(images: Image[]): void {
if (images.length < 1) {
throw new ArgumentMapillaryError("Trajectory can not be empty");
}
if (this._currentImage != null) {
this._trajectory = [this._currentImage].concat(images);
this._currentIndex = 1;
} else {
this._trajectory = images.slice();
this._currentIndex = 0;
}
}
private _setTrajectories(): void {
this._trajectoryTransforms.length = 0;
this._trajectoryCameras.length = 0;
this._appendToTrajectories(this._trajectory);
}
private _appendToTrajectories(images: Image[]): void {
for (let image of images) {
if (!image.assetsCached) {
throw new ArgumentMapillaryError("Assets must be cached when image is added to trajectory");
}
let translation: number[] = this._imageToTranslation(image, this.reference);
let transform: Transform = new Transform(
image.exifOrientation,
image.width,
image.height,
image.scale,
image.rotation,
translation,
image.image,
undefined,
image.cameraParameters,
<CameraType>image.cameraType);
this._trajectoryTransforms.push(transform);
this._trajectoryCameras.push(new Camera(transform));
}
}
private _prependToTrajectories(images: Image[]): void {
for (let image of images.reverse()) {
if (!image.assetsCached) {
throw new ArgumentMapillaryError("Assets must be cached when added to trajectory");
}
let translation: number[] = this._imageToTranslation(image, this.reference);
let transform: Transform = new Transform(
image.exifOrientation,
image.width,
image.height,
image.scale,
image.rotation,
translation,
image.image,
undefined,
image.cameraParameters,
<CameraType>image.cameraType);
this._trajectoryTransforms.unshift(transform);
this._trajectoryCameras.unshift(new Camera(transform));
}
}
private _imageToTranslation(image: Image, reference: LngLatAlt): number[] {
return Geo.computeTranslation(
{ alt: image.computedAltitude, lat: image.lngLat.lat, lng: image.lngLat.lng },
image.rotation,
reference);
}
private _sameConnectedComponent(): boolean {
let current: Image = this._currentImage;
let previous: Image = this._previousImage;
return !!current && !!previous &&
current.mergeId === previous.mergeId;
}
private _withinOriginalDistance(): boolean {
let current: Image = this._currentImage;
let previous: Image = this._previousImage;
if (!current || !previous) {
return true;
}
// 50 km/h moves 28m in 2s
let distance = this._spatial.distanceFromLngLat(
current.originalLngLat.lng,
current.originalLngLat.lat,
previous.originalLngLat.lng,
previous.originalLngLat.lat);
return distance < 25;
}
} | the_stack |
import Obniz from '../../../obniz';
import PeripheralI2C from '../../../obniz/libs/io_peripherals/i2c';
import ObnizPartsInterface, {
ObnizPartsInfo,
} from '../../../obniz/ObnizPartsInterface';
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface DPS310Options {}
export default class DPS310 implements ObnizPartsInterface {
public static info(): ObnizPartsInfo {
return {
name: 'DPS310',
datasheet: '',
};
}
public requiredKeys: string[];
public keys: string[];
public ioKeys: string[];
public params: any;
private configration = {
DPS310__STD_SLAVE_ADDRESS: 0x77,
};
private DPS310__OSR_SE = 3;
private DPS310__LSB = 0x01;
private DPS310__PRS_STD_MR = 2;
private DPS310__PRS_STD_OSR = 3;
private DPS310__TEMP_STD_MR = 2;
private DPS310__TEMP_STD_OSR = 3;
private DPS310__SUCCEEDED = 0;
private DPS310__FAIL_UNKNOWN = -1;
private DPS310__FAIL_INIT_FAILED = -2;
private DPS310__FAIL_TOOBUSY = -3;
private DPS310__FAIL_UNFINISHED = -4;
private prsMr = 0;
private prsOsr = 0;
private tempMr = 0;
private tempOsr = 0;
private m_lastTempScal = 0;
private mode = {
IDLE: 0x00,
CMD_PRS: 0x01,
CMD_TEMP: 0x02,
INVAL_OP_CMD_BOTH: 0x03, // invalid
INVAL_OP_CONT_NONE: 0x04, // invalid
CONT_PRS: 0x05,
CONT_TMP: 0x06,
CONT_BOTH: 0x07,
};
private bitFileds = {
DPS310__REG_INFO_PROD_ID: {
address: 0x0d,
mask: 0x0f,
shift: 0,
},
DPS310__REG_INFO_REV_ID: {
address: 0x0d,
mask: 0xf0,
shift: 4,
},
DPS310__REG_INFO_TEMP_SENSORREC: {
address: 0x28,
mask: 0x80,
shift: 7,
},
DPS310__REG_INFO_TEMP_SENSOR: {
address: 0x07,
mask: 0x80,
shift: 7,
},
DPS310__REG_INFO_OPMODE: {
address: 0x08,
mask: 0x07,
shift: 0,
},
DPS310__REG_INFO_FIFO_FL: {
address: 0x0c,
mask: 0x80,
shift: 7,
},
DPS310__REG_INFO_FIFO_EN: {
address: 0x09,
mask: 0x02,
shift: 1,
},
DPS310__REG_INFO_TEMP_MR: {
address: 0x07,
mask: 0x70,
shift: 4,
},
DPS310__REG_INFO_TEMP_OSR: {
address: 0x07,
mask: 0x07,
shift: 0,
},
DPS310__REG_INFO_PRS_MR: {
address: 0x06,
mask: 0x70,
shift: 4,
},
DPS310__REG_INFO_PRS_OSR: {
address: 0x06,
mask: 0x07,
shift: 0,
},
DPS310__REG_INFO_PRS_SE: {
address: 0x09,
mask: 0x04,
shift: 2,
},
DPS310__REG_INFO_PRS_RDY: {
address: 0x08,
mask: 0x10,
shift: 4,
},
DPS310__REG_INFO_TEMP_SE: {
address: 0x09,
mask: 0x08,
shift: 3,
},
DPS310__REG_INFO_TEMP_RDY: {
address: 0x08,
mask: 0x20,
shift: 5,
},
};
private dataBlock = {
DPS310__REG_ADR_COEF: {
address: 0x10,
length: 18,
},
DPS310__REG_ADR_PRS: {
address: 0x00,
length: 3,
},
DPS310__REG_ADR_TEMP: {
address: 0x03,
length: 3,
},
};
private scaling_facts = [
524288,
1572864,
3670016,
7864320,
253952,
516096,
1040384,
2088960,
];
private opMode: any;
private coeffs: any;
private obniz!: Obniz;
private address: any;
private i2c!: PeripheralI2C;
constructor() {
this.requiredKeys = ['sda', 'scl'];
this.keys = ['gpio3', 'vcc', 'gnd', 'scl', 'sda'];
this.ioKeys = ['gpio3', 'vcc', 'gnd', 'scl', 'sda'];
this.coeffs = {};
this.opMode = this.mode.IDLE;
}
public wired(obniz: Obniz) {
this.obniz = obniz;
this.address = 0x77;
this.params.clock = this.params.clock || 100 * 1000;
this.params.mode = 'master';
this.params.pull = '3v';
this.i2c = obniz.getI2CWithConfig(this.params);
this.obniz.wait(10);
}
public async initWait(): Promise<void> {
const prodId: any = await this.readByteBitfieldWait(
this.bitFileds.DPS310__REG_INFO_PROD_ID
);
if (prodId !== 0) {
throw new Error('invalid prodId');
}
await this.readByteBitfieldWait(this.bitFileds.DPS310__REG_INFO_REV_ID);
await this.readByteBitfieldWait(
this.bitFileds.DPS310__REG_INFO_TEMP_SENSORREC
);
await this.writeByteBitfieldWait(
this.bitFileds.DPS310__REG_INFO_TEMP_SENSOR,
0
);
await this.readCoeffsWait();
await this.standbyWait();
await this.configTempWait(
this.DPS310__TEMP_STD_MR,
this.DPS310__TEMP_STD_OSR
);
await this.configPressureWait(
this.DPS310__PRS_STD_MR,
this.DPS310__PRS_STD_OSR
);
await this.standbyWait();
await this.measureTempOnceWait();
await this.standbyWait();
await this.correctTempWait();
}
public async measurePressureOnceWait(oversamplingRate: any) {
if (oversamplingRate === undefined) {
oversamplingRate = this.prsOsr;
}
await this.startMeasurePressureOnceWait(oversamplingRate);
await this.obniz.wait(100);
const ret: any = await this.getSingleResultWait();
return ret;
}
private async readByteWait(regAddress: any): Promise<number> {
this.i2c.write(this.address, [regAddress]);
await this.obniz.wait(1);
const results: number[] = await this.i2c.readWait(this.address, 1);
return results[0];
}
private async readByteBitfieldWait(field: any): Promise<number> {
const regAddress: any = field.address;
const mask: any = field.mask;
const shift: any = field.shift;
let ret: number = await this.readByteWait(regAddress);
if (ret < 0) {
return ret;
}
if (mask !== undefined) {
ret = ret & mask;
}
if (shift !== undefined) {
ret = ret >> shift;
}
return ret;
}
private async readBlockWait(datablock: any): Promise<number[]> {
const address: any = datablock.address;
const length: any = datablock.length;
await this.obniz.wait(1);
this.i2c.write(this.address, [address]);
const results: number[] = await this.i2c.readWait(this.address, length);
return results;
}
private async writeByteWait(
regAddress: any,
data: any,
check?: any
): Promise<void> {
this.i2c.write(this.address, [regAddress, data]);
if (check) {
if ((await this.readByteWait(regAddress)) !== data) {
throw new Error('DPS310 data write failed');
}
}
}
private async writeByteBitfieldWait(
field: any,
data: any,
check?: any
): Promise<void> {
const old: any = await this.readByteWait(field.address);
const sendData: any =
(old & ~field.mask) | ((data << field.shift) & field.mask);
await this.writeByteWait(field.address, sendData, check);
}
private async setOpModeDetailWait(
background: any,
temperature: any,
pressure: any
): Promise<void> {
const opMode: any =
((background & this.DPS310__LSB) << 2) |
((temperature & this.DPS310__LSB) << 1) |
(pressure & this.DPS310__LSB);
return await this.setOpModeWait(opMode);
}
private async setOpModeWait(opMode: any): Promise<void> {
opMode &=
this.bitFileds.DPS310__REG_INFO_OPMODE.mask >>
this.bitFileds.DPS310__REG_INFO_OPMODE.shift;
await this.writeByteWait(
this.bitFileds.DPS310__REG_INFO_OPMODE.address,
opMode
);
this.opMode = opMode;
}
private async standbyWait(): Promise<void> {
this.setOpModeWait(this.mode.IDLE);
await this.writeByteBitfieldWait(
this.bitFileds.DPS310__REG_INFO_FIFO_FL,
1
);
await this.writeByteBitfieldWait(
this.bitFileds.DPS310__REG_INFO_FIFO_EN,
0
);
}
private async configTempWait(tempMr: any, tempOsr: any): Promise<void> {
await this.writeByteBitfieldWait(
this.bitFileds.DPS310__REG_INFO_TEMP_MR,
tempMr
);
await this.writeByteBitfieldWait(
this.bitFileds.DPS310__REG_INFO_TEMP_OSR,
tempOsr
);
if (tempOsr > this.DPS310__OSR_SE) {
await this.writeByteBitfieldWait(
this.bitFileds.DPS310__REG_INFO_TEMP_SE,
1
);
} else {
await this.writeByteBitfieldWait(
this.bitFileds.DPS310__REG_INFO_TEMP_SE,
0
);
}
this.tempMr = tempMr;
this.tempOsr = tempOsr;
}
private async configPressureWait(prsMr: any, prsOsr: any): Promise<void> {
await this.writeByteBitfieldWait(
this.bitFileds.DPS310__REG_INFO_PRS_MR,
prsMr
);
await this.writeByteBitfieldWait(
this.bitFileds.DPS310__REG_INFO_PRS_OSR,
prsOsr
);
if (prsOsr > this.DPS310__OSR_SE) {
await this.writeByteBitfieldWait(
this.bitFileds.DPS310__REG_INFO_PRS_SE,
1
);
} else {
await this.writeByteBitfieldWait(
this.bitFileds.DPS310__REG_INFO_PRS_SE,
0
);
}
this.prsMr = prsMr;
this.prsOsr = prsOsr;
}
private async readCoeffsWait(): Promise<void> {
const buffer: any = await this.readBlockWait(
this.dataBlock.DPS310__REG_ADR_COEF
);
this.coeffs.m_c0Half = (buffer[0] << 4) | ((buffer[1] >> 4) & 0x0f);
if (this.coeffs.m_c0Half & (1 << 11)) {
this.coeffs.m_c0Half -= 1 << 12;
}
this.coeffs.m_c0Half = this.coeffs.m_c0Half / 2;
this.coeffs.m_c1 = ((buffer[1] & 0x0f) << 8) | buffer[2];
if (this.coeffs.m_c1 & (1 << 11)) {
this.coeffs.m_c1 -= 1 << 12;
}
this.coeffs.m_c00 =
(buffer[3] << 12) | (buffer[4] << 4) | ((buffer[5] >> 4) & 0x0f);
if (this.coeffs.m_c00 & (1 << 19)) {
this.coeffs.m_c00 -= 1 << 20;
}
this.coeffs.m_c10 =
((buffer[5] & 0x0f) << 16) | (buffer[6] << 8) | buffer[7];
if (this.coeffs.m_c10 & (1 << 19)) {
this.coeffs.m_c10 -= 1 << 20;
}
this.coeffs.m_c01 = (buffer[8] << 8) | buffer[9];
if (this.coeffs.m_c01 & (1 << 15)) {
this.coeffs.m_c01 -= 1 << 16;
}
this.coeffs.m_c11 = (buffer[10] << 8) | buffer[11];
if (this.coeffs.m_c11 & (1 << 15)) {
this.coeffs.m_c11 -= 1 << 16;
}
this.coeffs.m_c20 = (buffer[12] << 8) | buffer[13];
if (this.coeffs.m_c20 & (1 << 15)) {
this.coeffs.m_c20 -= 1 << 16;
}
this.coeffs.m_c21 = (buffer[14] << 8) | buffer[15];
if (this.coeffs.m_c21 & (1 << 15)) {
this.coeffs.m_c21 -= 1 << 16;
}
this.coeffs.m_c30 = (buffer[16] << 8) | buffer[17];
if (this.coeffs.m_c30 & (1 << 15)) {
this.coeffs.m_c30 -= 1 << 16;
}
}
private async getSingleResultWait(): Promise<number> {
let rdy: any;
switch (this.opMode) {
case this.mode.CMD_TEMP:
rdy = await this.readByteBitfieldWait(
this.bitFileds.DPS310__REG_INFO_TEMP_RDY
);
break;
case this.mode.CMD_PRS:
rdy = await this.readByteBitfieldWait(
this.bitFileds.DPS310__REG_INFO_PRS_RDY
);
break;
default:
return this.DPS310__FAIL_TOOBUSY;
}
let oldMode: any;
switch (rdy) {
case this.DPS310__FAIL_UNKNOWN:
throw new Error('DPS310__FAIL_UNKNOWN');
case 0:
return this.obniz.wait(10).then(() => {
return this.getSingleResultWait();
});
case 1:
oldMode = this.opMode;
this.opMode = this.mode.IDLE;
switch (oldMode) {
case this.mode.CMD_TEMP:
return await this.getTempWait();
case this.mode.CMD_PRS:
return await this.getPressureWait();
default:
throw new Error('DPS310__FAIL_UNKNOWN');
}
}
throw new Error('DPS310__FAIL_UNKNOWN');
}
private async startMeasureTempOnceWait(oversamplingRate: any): Promise<void> {
await this.configTempWait(0, oversamplingRate);
await this.setOpModeDetailWait(0, 1, 0);
}
private async startMeasurePressureOnceWait(
oversamplingRate: any
): Promise<void> {
await this.configPressureWait(0, oversamplingRate);
await this.setOpModeDetailWait(0, 0, 1);
}
private calcPressure(raw: any): number {
let prs: any = raw;
prs /= this.scaling_facts[this.prsOsr];
prs =
this.coeffs.m_c00 +
prs *
(this.coeffs.m_c10 +
prs * (this.coeffs.m_c20 + prs * this.coeffs.m_c30)) +
this.m_lastTempScal *
(this.coeffs.m_c01 +
prs * (this.coeffs.m_c11 + prs * this.coeffs.m_c21));
return prs;
}
private calcTemp(raw: any): number {
let temp: any = raw;
temp /= this.scaling_facts[this.tempOsr];
this.m_lastTempScal = temp;
temp = this.coeffs.m_c0Half + this.coeffs.m_c1 * temp;
return temp;
}
private async correctTempWait(): Promise<void> {
this.writeByteWait(0x0e, 0xe5);
this.writeByteWait(0x0f, 0x96);
this.writeByteWait(0x62, 0x02);
this.writeByteWait(0x0e, 0x00);
this.writeByteWait(0x0f, 0x00);
await this.measureTempOnceWait();
}
private async measureTempOnceWait(oversamplingRate?: any): Promise<number> {
if (oversamplingRate === undefined) {
oversamplingRate = this.tempOsr;
}
await this.startMeasureTempOnceWait(oversamplingRate);
await this.obniz.wait(100);
return await this.getSingleResultWait();
}
private async getTempWait(): Promise<number> {
const data: any = await this.readBlockWait(
this.dataBlock.DPS310__REG_ADR_TEMP
);
let temp: any = (data[0] << 16) | (data[1] << 8) | data[2];
if (temp & (1 << 23)) {
temp -= 1 << 24;
}
return this.calcTemp(temp);
}
private async getPressureWait(): Promise<number> {
const data: any = await this.readBlockWait(
this.dataBlock.DPS310__REG_ADR_PRS
);
let prs: any = (data[0] << 16) | (data[1] << 8) | data[2];
if (prs & (1 << 23)) {
prs -= 1 << 24;
}
return this.calcPressure(prs);
}
} | the_stack |
import {
Button,
Typography,
Grid,
Paper,
Tooltip,
Link,
LinearProgress,
useMediaQuery,
Container,
Box,
SvgIcon,
} from "@material-ui/core";
import Countdown from "react-countdown";
import { ReactComponent as ClockIcon } from "../../assets/icons/clock.svg";
import { ReactComponent as CheckIcon } from "../../assets/icons/check-circle.svg";
import { ReactComponent as ArrowRight } from "../../assets/icons/arrow-right.svg";
import { ReactComponent as DonorsIcon } from "../../assets/icons/donors.svg";
import { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { useTheme } from "@material-ui/core/styles";
import { useAppDispatch } from "src/hooks";
import { getDonorNumbers, getRedemptionBalancesAsync } from "src/helpers/GiveRedemptionBalanceHelper";
import { useWeb3Context } from "src/hooks/web3Context";
import { Skeleton } from "@material-ui/lab";
import { BigNumber } from "bignumber.js";
import { RecipientModal } from "src/views/Give/RecipientModal";
import { SubmitCallback, CancelCallback } from "src/views/Give/Interfaces";
import { changeGive, changeMockGive, ACTION_GIVE, isSupportedChain } from "src/slices/GiveThunk";
import { error } from "../../slices/MessagesSlice";
import { Project } from "./project.type";
import { countDecimals, roundToDecimal, toInteger } from "./utils";
import { ReactComponent as WebsiteIcon } from "../../assets/icons/website.svg";
import { ReactComponent as DonatedIcon } from "../../assets/icons/donated.svg";
import { ReactComponent as GoalIcon } from "../../assets/icons/goal.svg";
import MarkdownIt from "markdown-it";
import { t, Trans } from "@lingui/macro";
import { useAppSelector } from "src/hooks";
import { IAccountSlice } from "src/slices/AccountSlice";
import { IPendingTxn } from "src/slices/PendingTxnsSlice";
import { IAppData } from "src/slices/AppSlice";
import { useLocation } from "react-router-dom";
import { EnvHelper } from "src/helpers/Environment";
import { GiveHeader } from "./GiveHeader";
import { NetworkId } from "src/constants";
type CountdownProps = {
total: number;
days: number;
hours: number;
minutes: number;
seconds: number;
milliseconds: number;
completed: boolean;
formatted: {
days: string;
hours: string;
minutes: string;
seconds: string;
};
};
export enum ProjectDetailsMode {
Card = "Card",
Page = "Page",
}
type ProjectDetailsProps = {
project: Project;
mode: ProjectDetailsMode;
};
type State = {
account: IAccountSlice;
pendingTransactions: IPendingTxn[];
app: IAppData;
};
export default function ProjectCard({ project, mode }: ProjectDetailsProps) {
const location = useLocation();
const isVerySmallScreen = useMediaQuery("(max-width: 375px)");
const isSmallScreen = useMediaQuery("(max-width: 600px) and (min-width: 375px)") && !isVerySmallScreen;
const isMediumScreen = useMediaQuery("(max-width: 960px) and (min-width: 600px)") && !isSmallScreen;
const { provider, address, connected, networkId, providerInitialized } = useWeb3Context();
const { title, owner, shortDescription, details, finishDate, photos, category, wallet, depositGoal } = project;
const [recipientInfoIsLoading, setRecipientInfoIsLoading] = useState(true);
const [donorCountIsLoading, setDonorCountIsLoading] = useState(true);
const [totalDebt, setTotalDebt] = useState("");
const [donorCount, setDonorCount] = useState(0);
const [isGiveModalOpen, setIsGiveModalOpen] = useState(false);
const donationInfo = useSelector((state: State) => {
return networkId === NetworkId.TESTNET_RINKEBY && EnvHelper.isMockSohmEnabled(location.search)
? state.account.mockGiving && state.account.mockGiving.donationInfo
: state.account.giving && state.account.giving.donationInfo;
});
const userTotalDebt = useSelector((state: State) => {
return networkId === NetworkId.TESTNET_RINKEBY && EnvHelper.isMockSohmEnabled(location.search)
? state.account.mockRedeeming && state.account.mockRedeeming.recipientInfo.totalDebt
: state.account.redeeming && state.account.redeeming.recipientInfo.totalDebt;
});
const theme = useTheme();
// We use useAppDispatch here so the result of the AsyncThunkAction is typed correctly
// See: https://stackoverflow.com/a/66753532
const dispatch = useAppDispatch();
const svgFillColour: string = theme.palette.type === "light" ? "black" : "white";
useEffect(() => {
let items = document.getElementsByClassName("project-container");
if (items.length > 0) {
items[0].scrollIntoView();
}
}, [location.pathname]);
// When the user's wallet is connected, we perform these actions
useEffect(() => {
if (!connected || !providerInitialized) return;
// We use dispatch to asynchronously fetch the results, and then update state variables so that the component refreshes
// We DO NOT use dispatch here, because it will overwrite the state variables in the redux store, which then creates havoc
// e.g. the redeem yield page will show someone else's deposited sOHM and redeemable yield
getRedemptionBalancesAsync({
networkID: networkId,
provider: provider,
address: wallet,
})
.then(resultAction => {
setTotalDebt(resultAction.redeeming.recipientInfo.totalDebt);
setRecipientInfoIsLoading(false);
})
.catch(e => console.log(e));
getDonorNumbers({
networkID: networkId,
provider: provider,
address: wallet,
})
.then(resultAction => {
setDonorCount(!resultAction ? 0 : resultAction.length);
setDonorCountIsLoading(false);
})
.catch(e => console.log(e));
}, [connected, networkId, isGiveModalOpen]);
// The JSON file returns a string, so we convert it
const finishDateObject = finishDate ? new Date(finishDate) : null;
const countdownRenderer = ({ completed, formatted }: CountdownProps) => {
if (completed)
return (
<>
<div className="cause-info-icon">
<SvgIcon component={ClockIcon} fill={svgFillColour} />
</div>
<div>
<div className="cause-info-main-text">
<strong>00:00:00</strong>
</div>
<span className="cause-info-bottom-text">
<Trans>Completed</Trans>
</span>
</div>
</>
);
return (
<>
<div className="cause-info-icon">
<SvgIcon component={ClockIcon} fill={svgFillColour} />
</div>
<div>
<Tooltip
title={!finishDateObject ? "" : t`Finishes at ` + finishDateObject.toLocaleString() + t` in your timezone`}
arrow
>
<div>
<div className="cause-info-main-text">
<strong>
{formatted.days}:{formatted.hours}:{formatted.minutes}
</strong>
</div>
<span className="cause-info-bottom-text">
<Trans>Remaining</Trans>
</span>
</div>
</Tooltip>
</div>
</>
);
};
// Removed for now. Will leave this function in for when we re-add this feature
const countdownRendererDetailed = ({ completed, formatted }: CountdownProps) => {
if (completed)
return (
<>
<Grid container className="countdown-container">
<Grid item xs={3}>
<SvgIcon component={ClockIcon} fill={svgFillColour} />
</Grid>
<Grid item xs={9} className="project-countdown-text">
<div>
<div className="cause-info-main-text">
<strong>00:00:00</strong>
</div>
<span className="cause-info-bottom-text">
<Trans>Completed</Trans>
</span>
</div>
</Grid>
</Grid>
</>
);
return (
<>
<>
<Grid container className="countdown-container">
<Tooltip
title={
!finishDateObject ? "" : t`Finishes at ` + finishDateObject.toLocaleString() + t` in your timezone`
}
arrow
>
<Grid item xs={12} className="countdown-object">
<div>
<SvgIcon component={ClockIcon} fill={svgFillColour} />
</div>
<div className="project-countdown-text">
<div>
{" "}
<Typography variant="h6">
<strong>
{formatted.days}:{formatted.hours}:{formatted.minutes}
</strong>
</Typography>
<span className="cause-info-bottom-text">
<Trans> remaining</Trans>
</span>
</div>
</div>
</Grid>
</Tooltip>
</Grid>
</>
</>
);
};
const getGoalCompletion = (): string => {
if (!depositGoal) return "0";
if (recipientInfoIsLoading) return "0"; // This shouldn't be needed, but just to be sure...
if (!totalDebt) return "0";
const totalDebtNumber = new BigNumber(totalDebt);
return totalDebtNumber.div(depositGoal).multipliedBy(100).toFixed();
};
const renderGoalCompletion = (): JSX.Element => {
const goalCompletion = getGoalCompletion();
const formattedGoalCompletion =
countDecimals(goalCompletion) === 0 ? toInteger(goalCompletion) : roundToDecimal(goalCompletion);
return (
<>
<div className="cause-info-icon">
<SvgIcon component={CheckIcon} fill={svgFillColour} />
</div>
<div>
<Tooltip
title={
!address
? t`Connect your wallet to view the fundraising progress`
: `${totalDebt} of ${depositGoal} sOHM raised`
}
arrow
>
<div>
<div className="cause-info-main-text">
<Typography variant="body1">
<strong>{recipientInfoIsLoading ? <Skeleton /> : formattedGoalCompletion}% </strong>
of goal
</Typography>
</div>
</div>
</Tooltip>
</div>
</>
);
};
const renderGoalCompletionDetailed = (): JSX.Element => {
const goalProgress = parseFloat(getGoalCompletion()) > 100 ? 100 : parseFloat(getGoalCompletion());
const formattedTotalDebt = new BigNumber(totalDebt).toFormat();
return (
<>
<Grid container className="project-goal">
<Grid item xs={4} className="project-donated">
<div className="project-donated-icon">
<SvgIcon
component={DonatedIcon}
viewBox={"0 0 16 12"}
style={{ marginRight: "0.33rem" }}
fill={svgFillColour}
/>
<Typography variant="h6">
<strong>{recipientInfoIsLoading ? <Skeleton /> : formattedTotalDebt}</strong>
</Typography>
</div>
<div className="subtext">
<Trans>sOHM Donated</Trans>
</div>
</Grid>
<Grid item xs={4} />
<Grid item xs={4} className="project-completion">
<div className="project-completion-icon">
<SvgIcon
component={GoalIcon}
viewBox={"0 0 16 12"}
style={{ marginRight: "0.33rem" }}
fill={svgFillColour}
/>
<Typography variant="h6">
<strong>{new BigNumber(depositGoal).toFormat()}</strong>
</Typography>
</div>
<div className="subtext">
<Trans>sOHM Goal</Trans>
</div>
</Grid>
</Grid>
<div className="project-goal-progress">
<LinearProgress variant="determinate" value={goalProgress} />
</div>
</>
);
};
const getProjectImage = (): JSX.Element => {
// We return an empty image with a set width, so that the spacing remains the same.
if (!photos || photos.length < 1)
return (
<div className="cause-image">
<img width="100%" src="" />
</div>
);
// For the moment, we only display the first photo
return (
<div className="cause-image">
<Link href={`#/give/projects/${project.slug}`}>
<img width="100%" src={`${process.env.PUBLIC_URL}${photos[0]}`} />
</Link>
</div>
);
};
const handleGiveButtonClick = () => {
setIsGiveModalOpen(true);
};
const handleGiveModalSubmit: SubmitCallback = async (
walletAddress: string,
depositAmount: BigNumber,
depositAmountDiff?: BigNumber,
) => {
if (depositAmount.isEqualTo(new BigNumber(0))) {
return dispatch(error(t`Please enter a value!`));
}
// If reducing the amount of deposit, withdraw
if (networkId === NetworkId.TESTNET_RINKEBY && EnvHelper.isMockSohmEnabled(location.search)) {
await dispatch(
changeMockGive({
action: ACTION_GIVE,
value: depositAmount.toFixed(),
recipient: walletAddress,
provider,
address,
networkID: networkId,
version2: false,
rebase: false,
}),
);
} else {
await dispatch(
changeGive({
action: ACTION_GIVE,
value: depositAmount.toFixed(),
recipient: walletAddress,
provider,
address,
networkID: networkId,
version2: false,
rebase: false,
}),
);
}
setIsGiveModalOpen(false);
};
const handleGiveModalCancel: CancelCallback = () => {
setIsGiveModalOpen(false);
};
const getTitle = () => {
if (!owner) return title;
return owner + " - " + title;
};
const getRenderedDetails = (shorten: boolean) => {
return {
__html: MarkdownIt({ html: true }).render(shorten ? `${shortDescription}` : `${details}`),
};
};
const getCardContent = () => {
return (
<>
<Paper style={{ width: "100%", borderRadius: "10px" }}>
<Grid item className={isVerySmallScreen ? "cause-card very-small" : "cause-card"} key={title}>
{getProjectImage()}
<div className="cause-content">
<Grid container className="cause-header">
<Grid item className="cause-title">
<Link href={`#/give/projects/${project.slug}`}>
<Typography variant="h5">
<strong>{getTitle()}</strong>
</Typography>
</Link>
</Grid>
<Grid item className="view-details">
<Link href={`#/give/projects/${project.slug}`} className="cause-link">
<Typography variant="body1">
<Trans>View Details</Trans>
</Typography>
<SvgIcon
component={ArrowRight}
style={{ width: "30px", marginLeft: "0.33em" }}
viewBox={"0 0 57 24"}
fill={svgFillColour}
/>
</Link>
</Grid>
</Grid>
<div className="cause-body">
<Typography variant="body1" style={{ lineHeight: "20px" }}>
<div dangerouslySetInnerHTML={getRenderedDetails(true)} />
</Typography>
</div>
<Grid container direction="column" className="cause-misc-info">
<Grid item xs={6}>
{renderGoalCompletion()}
</Grid>
<Grid item xs={6} sm={12} md={6} className="give-button-grid">
<Button
variant="contained"
color="primary"
className="cause-give-button"
onClick={() => handleGiveButtonClick()}
>
<Typography variant="h6">
<Trans>Donate Yield</Trans>
</Typography>
</Button>
</Grid>
</Grid>
</div>
</Grid>
</Paper>
<RecipientModal
isModalOpen={isGiveModalOpen}
callbackFunc={handleGiveModalSubmit}
cancelFunc={handleGiveModalCancel}
project={project}
key={title}
/>
</>
);
};
const renderCountdownDetailed = () => {
if (!finishDateObject) return <></>;
return (
<Grid container className="project-countdown">
<Grid item xs={3}></Grid>
<Grid item xs={6}>
<Countdown date={finishDateObject} renderer={countdownRendererDetailed} />
</Grid>{" "}
<Grid item xs={3}></Grid>
</Grid>
);
};
const getPageContent = () => {
return (
<>
<Container
style={{
paddingLeft: isSmallScreen || isVerySmallScreen ? 0 : "3.3rem",
paddingRight: isSmallScreen || isVerySmallScreen ? 0 : "4.4rem",
display: "flex",
justifyContent: "center",
}}
className="project-container"
>
<Box className={isSmallScreen ? "subnav-paper mobile" : "subnav-paper"}>
<GiveHeader
isSmallScreen={isSmallScreen}
isVerySmallScreen={isVerySmallScreen}
totalDebt={new BigNumber(userTotalDebt)}
networkId={networkId}
/>
<div
className={`${isMediumScreen && "medium"}
${isSmallScreen && "smaller"}
${isVerySmallScreen && "very-small"}`}
>
<Box className="project-content-container">
<Grid container className="project">
<Grid
item
xs={12}
md={5}
style={{
paddingLeft: "1rem",
paddingRight: isMediumScreen || isSmallScreen || isVerySmallScreen ? "1rem" : 0,
}}
>
<Paper className="project-sidebar">
<Grid container className="project-intro" justifyContent="space-between">
<Grid item className="project-title">
<Typography variant="h5">
<strong>{getTitle()}</strong>
</Typography>
</Grid>
<Grid item className="project-link">
<Link href={project.website} target="_blank">
<SvgIcon component={WebsiteIcon} fill={svgFillColour} />
</Link>
</Grid>
</Grid>
<Grid item className="project-visual-info">
{getProjectImage()}
<Grid item className="goal-graphics">
{renderGoalCompletionDetailed()}
<div className="visual-info-bottom">
{renderCountdownDetailed()}
<div className="project-give-button">
<Button
variant="contained"
color="primary"
onClick={() => handleGiveButtonClick()}
disabled={!address || !isSupportedChain(networkId)}
>
<Typography variant="h6">
<Trans>Donate Yield</Trans>
</Typography>
</Button>
</div>
</div>
</Grid>
</Grid>
</Paper>
<Paper className="project-sidebar">
<Grid container direction="column">
<Grid item className="donors-title">
<Typography variant="h5">
<strong>
<Trans>Donations</Trans>
</strong>
</Typography>
</Grid>
<Grid item xs={12} md={4} className="project-goal">
<Grid container className="project-donated-icon">
<Grid item xs={1} md={2}>
<SvgIcon component={DonorsIcon} viewBox={"0 0 18 13"} fill={svgFillColour} />
</Grid>
<Grid item xs={4}>
<Typography variant="h6">
{donorCountIsLoading ? <Skeleton /> : <strong>{donorCount}</strong>}
</Typography>
<div className="subtext">
<Trans>Donors</Trans>
</div>
</Grid>
</Grid>
</Grid>
</Grid>
</Paper>
</Grid>
<Grid
item
xs={12}
md={6}
style={{
marginBottom: isMediumScreen || isSmallScreen || isVerySmallScreen ? "1rem" : 0,
paddingRight: isMediumScreen || isSmallScreen || isVerySmallScreen ? "1rem" : 0,
paddingLeft: isMediumScreen || isSmallScreen || isVerySmallScreen ? "1rem" : 0,
}}
>
<Paper className="project-info">
<Typography variant="h5" className="project-about-header">
<strong>
<Trans>About</Trans>
</strong>
</Typography>
<div className="project-content" dangerouslySetInnerHTML={getRenderedDetails(false)} />
</Paper>
</Grid>
</Grid>
</Box>
</div>
</Box>
</Container>
<RecipientModal
isModalOpen={isGiveModalOpen}
callbackFunc={handleGiveModalSubmit}
cancelFunc={handleGiveModalCancel}
project={project}
key={title}
/>
</>
);
};
if (mode == ProjectDetailsMode.Card) return getCardContent();
else return getPageContent();
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement, Operator } from "../shared";
/**
* Statement provider for service [datapipeline](https://docs.aws.amazon.com/service-authorization/latest/reference/list_datapipeline.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Datapipeline extends PolicyStatement {
public servicePrefix = 'datapipeline';
/**
* Statement provider for service [datapipeline](https://docs.aws.amazon.com/service-authorization/latest/reference/list_datapipeline.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Validates the specified pipeline and starts processing pipeline tasks. If the pipeline does not pass validation, activation fails.
*
* Access Level: Write
*
* Possible conditions:
* - .ifPipelineCreator()
* - .ifTag()
* - .ifWorkerGroup()
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_ActivatePipeline.html
*/
public toActivatePipeline() {
return this.to('ActivatePipeline');
}
/**
* Adds or modifies tags for the specified pipeline.
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifPipelineCreator()
* - .ifTag()
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_AddTags.html
*/
public toAddTags() {
return this.to('AddTags');
}
/**
* Creates a new, empty pipeline.
*
* Access Level: Write
*
* Possible conditions:
* - .ifTag()
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_CreatePipeline.html
*/
public toCreatePipeline() {
return this.to('CreatePipeline');
}
/**
* Deactivates the specified running pipeline.
*
* Access Level: Write
*
* Possible conditions:
* - .ifPipelineCreator()
* - .ifTag()
* - .ifWorkerGroup()
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_DeactivatePipeline.html
*/
public toDeactivatePipeline() {
return this.to('DeactivatePipeline');
}
/**
* Deletes a pipeline, its pipeline definition, and its run history.
*
* Access Level: Write
*
* Possible conditions:
* - .ifPipelineCreator()
* - .ifTag()
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_DeletePipeline.html
*/
public toDeletePipeline() {
return this.to('DeletePipeline');
}
/**
* Gets the object definitions for a set of objects associated with the pipeline.
*
* Access Level: Read
*
* Possible conditions:
* - .ifPipelineCreator()
* - .ifTag()
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_DescribeObjects.html
*/
public toDescribeObjects() {
return this.to('DescribeObjects');
}
/**
* Retrieves metadata about one or more pipelines.
*
* Access Level: List
*
* Possible conditions:
* - .ifPipelineCreator()
* - .ifTag()
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_DescribePipelines.html
*/
public toDescribePipelines() {
return this.to('DescribePipelines');
}
/**
* Task runners call EvaluateExpression to evaluate a string in the context of the specified object.
*
* Access Level: Read
*
* Possible conditions:
* - .ifPipelineCreator()
* - .ifTag()
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_EvaluateExpression.html
*/
public toEvaluateExpression() {
return this.to('EvaluateExpression');
}
/**
* Description for GetAccountLimits
*
* Access Level: List
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_GetAccountLimits.html
*/
public toGetAccountLimits() {
return this.to('GetAccountLimits');
}
/**
* Gets the definition of the specified pipeline.
*
* Access Level: Read
*
* Possible conditions:
* - .ifPipelineCreator()
* - .ifTag()
* - .ifWorkerGroup()
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_GetPipelineDefinition.html
*/
public toGetPipelineDefinition() {
return this.to('GetPipelineDefinition');
}
/**
* Lists the pipeline identifiers for all active pipelines that you have permission to access.
*
* Access Level: List
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_ListPipelines.html
*/
public toListPipelines() {
return this.to('ListPipelines');
}
/**
* Task runners call PollForTask to receive a task to perform from AWS Data Pipeline.
*
* Access Level: Write
*
* Possible conditions:
* - .ifWorkerGroup()
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_PollForTask.html
*/
public toPollForTask() {
return this.to('PollForTask');
}
/**
* Description for PutAccountLimits
*
* Access Level: Write
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_PutAccountLimits.html
*/
public toPutAccountLimits() {
return this.to('PutAccountLimits');
}
/**
* Adds tasks, schedules, and preconditions to the specified pipeline.
*
* Access Level: Write
*
* Possible conditions:
* - .ifPipelineCreator()
* - .ifTag()
* - .ifWorkerGroup()
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_PutPipelineDefinition.html
*/
public toPutPipelineDefinition() {
return this.to('PutPipelineDefinition');
}
/**
* Queries the specified pipeline for the names of objects that match the specified set of conditions.
*
* Access Level: Read
*
* Possible conditions:
* - .ifPipelineCreator()
* - .ifTag()
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_QueryObjects.html
*/
public toQueryObjects() {
return this.to('QueryObjects');
}
/**
* Removes existing tags from the specified pipeline.
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifPipelineCreator()
* - .ifTag()
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_RemoveTags.html
*/
public toRemoveTags() {
return this.to('RemoveTags');
}
/**
* Task runners call ReportTaskProgress when assigned a task to acknowledge that it has the task.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_ReportTaskProgress.html
*/
public toReportTaskProgress() {
return this.to('ReportTaskProgress');
}
/**
* Task runners call ReportTaskRunnerHeartbeat every 15 minutes to indicate that they are operational.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_ReportTaskRunnerHeartbeat.html
*/
public toReportTaskRunnerHeartbeat() {
return this.to('ReportTaskRunnerHeartbeat');
}
/**
* Requests that the status of the specified physical or logical pipeline objects be updated in the specified pipeline.
*
* Access Level: Write
*
* Possible conditions:
* - .ifPipelineCreator()
* - .ifTag()
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_SetStatus.html
*/
public toSetStatus() {
return this.to('SetStatus');
}
/**
* Task runners call SetTaskStatus to notify AWS Data Pipeline that a task is completed and provide information about the final status.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_SetTaskStatus.html
*/
public toSetTaskStatus() {
return this.to('SetTaskStatus');
}
/**
* Validates the specified pipeline definition to ensure that it is well formed and can be run without error.
*
* Access Level: Read
*
* Possible conditions:
* - .ifPipelineCreator()
* - .ifTag()
* - .ifWorkerGroup()
*
* https://docs.aws.amazon.com/datapipeline/latest/APIReference/API_ValidatePipelineDefinition.html
*/
public toValidatePipelineDefinition() {
return this.to('ValidatePipelineDefinition');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"ActivatePipeline",
"CreatePipeline",
"DeactivatePipeline",
"DeletePipeline",
"PollForTask",
"PutAccountLimits",
"PutPipelineDefinition",
"ReportTaskProgress",
"ReportTaskRunnerHeartbeat",
"SetStatus",
"SetTaskStatus"
],
"Tagging": [
"AddTags",
"RemoveTags"
],
"Read": [
"DescribeObjects",
"EvaluateExpression",
"GetPipelineDefinition",
"QueryObjects",
"ValidatePipelineDefinition"
],
"List": [
"DescribePipelines",
"GetAccountLimits",
"ListPipelines"
]
};
/**
* The IAM user that created the pipeline.
*
* https://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-example-tag-policies.html#ex3
*
* Applies to actions:
* - .toActivatePipeline()
* - .toAddTags()
* - .toDeactivatePipeline()
* - .toDeletePipeline()
* - .toDescribeObjects()
* - .toDescribePipelines()
* - .toEvaluateExpression()
* - .toGetPipelineDefinition()
* - .toPutPipelineDefinition()
* - .toQueryObjects()
* - .toRemoveTags()
* - .toSetStatus()
* - .toValidatePipelineDefinition()
*
* @param value The value(s) to check
* @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike`
*/
public ifPipelineCreator(value: string | string[], operator?: Operator | string) {
return this.if(`PipelineCreator`, value, operator || 'ArnLike');
}
/**
* A customer-specified key/value pair that can be attached to a resource.
*
* https://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-iam-resourcebased-access.html#dp-control-access-tags
*
* Applies to actions:
* - .toActivatePipeline()
* - .toAddTags()
* - .toCreatePipeline()
* - .toDeactivatePipeline()
* - .toDeletePipeline()
* - .toDescribeObjects()
* - .toDescribePipelines()
* - .toEvaluateExpression()
* - .toGetPipelineDefinition()
* - .toPutPipelineDefinition()
* - .toQueryObjects()
* - .toRemoveTags()
* - .toSetStatus()
* - .toValidatePipelineDefinition()
*
* @param value The value(s) to check
* @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike`
*/
public ifTag(value: string | string[], operator?: Operator | string) {
return this.if(`Tag`, value, operator || 'ArnLike');
}
/**
* The name of a worker group for which a Task Runner retrieves work.
*
* https://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-iam-resourcebased-access.html#dp-control-access-workergroup
*
* Applies to actions:
* - .toActivatePipeline()
* - .toDeactivatePipeline()
* - .toGetPipelineDefinition()
* - .toPollForTask()
* - .toPutPipelineDefinition()
* - .toValidatePipelineDefinition()
*
* @param value The value(s) to check
* @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike`
*/
public ifWorkerGroup(value: string | string[], operator?: Operator | string) {
return this.if(`workerGroup`, value, operator || 'ArnLike');
}
} | the_stack |
// @ts-nocheck
// TODO: Stroke constructor's second argument should be optional.
// TODO: ElementStyle's lineWidth is declared as a number, but we pass in a string '3'. Should we also allow string?
// TODO: In StaveNote.preFormat() line 929, should noteHeadPadding default to StaveNote.minNoteheadPadding?
// The bounding box of a note changes slightly when we add a ModifierContext (even if we add zero modifiers).
import { TestOptions, VexFlowTests } from './vexflow_test_helpers';
import { Accidental } from 'accidental';
import { Annotation } from 'annotation';
import { Articulation } from 'articulation';
import { Beam } from 'beam';
import { Flow } from 'flow';
import { Formatter } from 'formatter';
import { Fraction } from 'fraction';
import { FretHandFinger } from 'frethandfinger';
import { Modifier, ModifierPosition } from 'modifier';
import { RenderContext } from 'rendercontext';
import { ContextBuilder } from 'renderer';
import { Stave } from 'stave';
import { StaveNote, StaveNoteStruct } from 'stavenote';
import { Stem } from 'stem';
import { StringNumber } from 'stringnumber';
import { Stroke } from 'strokes';
import { TickContext } from 'tickcontext';
import { ModifierContext } from 'modifiercontext';
const StaveNoteTests = {
Start(): void {
QUnit.module('StaveNote');
test('Tick', ticks);
test('Tick - New API', ticksNewAPI);
test('Stem', stem);
test('Automatic Stem Direction', autoStem);
test('Stem Extension Pitch', stemExtensionPitch);
test('Displacement after calling setStemDirection', setStemDirectionDisplacement);
test('StaveLine', staveLine);
test('Width', width);
test('TickContext', tickContext);
const run = VexFlowTests.runTests;
run('StaveNote Draw - Treble', drawBasic, { clef: 'treble', octaveShift: 0, restKey: 'r/4' });
run('StaveNote BoundingBoxes - Treble', drawBoundingBoxes, { clef: 'treble', octaveShift: 0, restKey: 'r/4' });
run('StaveNote Draw - Alto', drawBasic, { clef: 'alto', octaveShift: -1, restKey: 'r/4' });
run('StaveNote Draw - Tenor', drawBasic, { clef: 'tenor', octaveShift: -1, restKey: 'r/3' });
run('StaveNote Draw - Bass', drawBasic, { clef: 'bass', octaveShift: -2, restKey: 'r/3' });
run('StaveNote Draw - Harmonic And Muted', drawHarmonicAndMuted);
run('StaveNote Draw - Slash', drawSlash);
run('Displacements', displacements);
run('StaveNote Draw - Bass 2', drawBass);
run('StaveNote Draw - Key Styles', drawKeyStyles);
run('StaveNote Draw - StaveNote Stem Styles', drawNoteStemStyles);
run('StaveNote Draw - StaveNote Stem Lengths', drawNoteStemLengths);
run('StaveNote Draw - StaveNote Flag Styles', drawNoteStylesWithFlag);
run('StaveNote Draw - StaveNote Styles', drawNoteStyles);
run('Stave, Ledger Line, Beam, Stem and Flag Styles', drawBeamStyles);
run('Flag and Dot Placement - Stem Up', dotsAndFlagsStemUp);
run('Flag and Dots Placement - Stem Down', dotsAndFlagsStemDown);
run('Beam and Dot Placement - Stem Up', dotsAndBeamsUp);
run('Beam and Dot Placement - Stem Down', dotsAndBeamsDown);
run('Center Aligned Note', centerAlignedRest);
run('Center Aligned Note with Articulation', centerAlignedRestFermata);
run('Center Aligned Note with Annotation', centerAlignedRestAnnotation);
run('Center Aligned Note - Multi Voice', centerAlignedMultiVoice);
run('Center Aligned Note with Multiple Modifiers', centerAlignedNoteMultiModifiers);
// This interactivity test currently only works with the SVG backend.
VexFlowTests.runSVGTest('Interactive Mouseover StaveNote', drawBasic, {
clef: 'treble',
octaveShift: 0,
restKey: 'r/4',
ui: true,
});
},
};
// Helper function to create StaveNotes.
const staveNote = (struct: StaveNoteStruct) => new StaveNote(struct);
/**
* Helper function to draw a note with an optional bounding box.
*/
function draw(
note: StaveNote,
stave: Stave,
context: RenderContext,
x: number,
drawBoundingBox: boolean = false,
addModifierContext: boolean = true
) {
// Associate the note with the stave.
note.setStave(stave);
// A ModifierContext is required for dots and other modifiers to be drawn properly.
// If added, it changes the bounding box of a note, even if there are no modifiers to draw.
// See StaveNote.minNoteheadPadding in stavenote.ts.
if (addModifierContext) {
note.addToModifierContext(new ModifierContext());
}
new TickContext().addTickable(note).preFormat().setX(x);
note.setContext(context).draw();
if (drawBoundingBox) {
const bb = note.getBoundingBox();
context.rect(bb.getX(), bb.getY(), bb.getW(), bb.getH());
context.stroke();
}
return note;
}
function ticks(): void {
const BEAT = (1 * Flow.RESOLUTION) / 4;
// Key value pairs of `testName: [durationString, expectedBeats, expectedNoteType]`
const tickTests: Record<string, [string, number, string]> = {
'Breve note': ['1/2', 8.0, 'n'],
'Whole note': ['w', 4.0, 'n'],
'Quarter note': ['q', 1.0, 'n'],
'Dotted half note': ['hd', 3.0, 'n'],
'Doubled-dotted half note': ['hdd', 3.5, 'n'],
'Triple-dotted half note': ['hddd', 3.75, 'n'],
'Dotted half rest': ['hdr', 3.0, 'r'],
'Double-dotted half rest': ['hddr', 3.5, 'r'],
'Triple-dotted half rest': ['hdddr', 3.75, 'r'],
'Dotted harmonic quarter note': ['qdh', 1.5, 'h'],
'Double-dotted harmonic quarter note': ['qddh', 1.75, 'h'],
'Triple-dotted harmonic quarter note': ['qdddh', 1.875, 'h'],
'Dotted muted 8th note': ['8dm', 0.75, 'm'],
'Double-dotted muted 8th note': ['8ddm', 0.875, 'm'],
'Triple-dotted muted 8th note': ['8dddm', 0.9375, 'm'],
};
Object.keys(tickTests).forEach((testName: string) => {
const testData = tickTests[testName];
const durationString = testData[0];
const expectedBeats = testData[1];
const expectedNoteType = testData[2];
const note = new StaveNote({ keys: ['c/4', 'e/4', 'g/4'], duration: durationString });
equal(note.getTicks().value(), BEAT * expectedBeats, testName + ' must have ' + expectedBeats + ' beats');
equal(note.getNoteType(), expectedNoteType, 'Note type must be ' + expectedNoteType);
});
throws(
() => new StaveNote({ keys: ['c/4', 'e/4', 'g/4'], duration: '8.7dddm' }),
/BadArguments/,
"Invalid note duration '8.7' throws BadArguments exception"
);
throws(
() => new StaveNote({ keys: ['c/4', 'e/4', 'g/4'], duration: '2Z' }),
/BadArguments/,
"Invalid note type 'Z' throws BadArguments exception"
);
throws(
() => new StaveNote({ keys: ['c/4', 'e/4', 'g/4'], duration: '2dddZ' }),
/BadArguments/,
"Invalid note type 'Z' throws BadArguments exception"
);
}
function ticksNewAPI(): void {
const BEAT = (1 * Flow.RESOLUTION) / 4;
// Key value pairs of `testName: [noteData, expectedBeats, expectedNoteType]`
const tickTests: Record<string, [StaveNoteStruct, number, string]> = {
'Breve note': [{ duration: '1/2' }, 8.0, 'n'],
'Whole note': [{ duration: 'w' }, 4.0, 'n'],
'Quarter note': [{ duration: 'q' }, 1.0, 'n'],
'Dotted half note': [{ duration: 'h', dots: 1 }, 3.0, 'n'],
'Doubled-dotted half note': [{ duration: 'h', dots: 2 }, 3.5, 'n'],
'Triple-dotted half note': [{ duration: 'h', dots: 3 }, 3.75, 'n'],
'Dotted half rest': [{ duration: 'h', dots: 1, type: 'r' }, 3.0, 'r'],
'Double-dotted half rest': [{ duration: 'h', dots: 2, type: 'r' }, 3.5, 'r'],
'Triple-dotted half rest': [{ duration: 'h', dots: 3, type: 'r' }, 3.75, 'r'],
'Dotted harmonic quarter note': [{ duration: 'q', dots: 1, type: 'h' }, 1.5, 'h'],
'Double-dotted harmonic quarter note': [{ duration: 'q', dots: 2, type: 'h' }, 1.75, 'h'],
'Triple-dotted harmonic quarter note': [{ duration: 'q', dots: 3, type: 'h' }, 1.875, 'h'],
'Dotted muted 8th note': [{ duration: '8', dots: 1, type: 'm' }, 0.75, 'm'],
'Double-dotted muted 8th note': [{ duration: '8', dots: 2, type: 'm' }, 0.875, 'm'],
'Triple-dotted muted 8th note': [{ duration: '8', dots: 3, type: 'm' }, 0.9375, 'm'],
};
Object.keys(tickTests).forEach(function (testName) {
const testData = tickTests[testName];
const noteData = testData[0];
const expectedBeats = testData[1];
const expectedNoteType = testData[2];
noteData.keys = ['c/4', 'e/4', 'g/4'];
const note = new StaveNote(noteData);
equal(note.getTicks().value(), BEAT * expectedBeats, testName + ' must have ' + expectedBeats + ' beats');
equal(note.getNoteType(), expectedNoteType, 'Note type must be ' + expectedNoteType);
});
throws(
() => new StaveNote({ keys: ['c/4', 'e/4', 'g/4'], duration: '8.7dddm' }),
/BadArguments/,
"Invalid note duration '8.7' throws BadArguments exception"
);
throws(
() => new StaveNote({ keys: ['c/4', 'e/4', 'g/4'], duration: '2Z' }),
/BadArguments/,
"Invalid note type 'Z' throws BadArguments exception"
);
throws(
() => new StaveNote({ keys: ['c/4', 'e/4', 'g/4'], duration: '2dddZ' }),
/BadArguments/,
"Invalid note type 'Z' throws BadArguments exception"
);
}
function stem(): void {
const note = new StaveNote({ keys: ['c/4', 'e/4', 'g/4'], duration: 'w' });
equal(note.getStemDirection(), Stem.UP, 'Default note has UP stem');
}
function autoStem(): void {
const testData: [/* keys */ string[], /* expectedStemDirection */ number][] = [
[['c/5', 'e/5', 'g/5'], Stem.DOWN],
[['e/4', 'g/4', 'c/5'], Stem.UP],
[['c/5'], Stem.DOWN],
[['a/4', 'e/5', 'g/5'], Stem.DOWN],
[['b/4'], Stem.DOWN],
];
testData.forEach((td) => {
const keys = td[0];
const expectedStemDirection = td[1];
const note = new StaveNote({ keys: keys, auto_stem: true, duration: '8' });
equal(
note.getStemDirection(),
expectedStemDirection,
'Stem must be ' + (expectedStemDirection === Stem.UP ? 'up' : 'down')
);
});
}
function stemExtensionPitch(): void {
// [keys, expectedStemExtension, override stem direction]
const testData: [string[], number, number][] = [
[['c/5', 'e/5', 'g/5'], 0, 0],
[['e/4', 'g/4', 'c/5'], 0, 0],
[['c/5'], 0, 0],
[['f/3'], 15, 0],
[['f/3'], 15, Stem.UP],
[['f/3'], 0, Stem.DOWN],
[['f/3', 'e/5'], 0, 0],
[['g/6'], 25, 0],
[['g/6'], 25, Stem.DOWN],
[['g/6'], 0, Stem.UP],
];
testData.forEach((td) => {
const keys = td[0];
const expectedStemExtension = td[1];
const overrideStemDirection = td[2];
let note;
if (overrideStemDirection === 0) {
note = new StaveNote({ keys: keys, auto_stem: true, duration: '4' });
} else {
note = new StaveNote({ keys: keys, duration: '4', stem_direction: overrideStemDirection });
}
equal(
note.getStemExtension(),
expectedStemExtension,
'For ' + keys.toString() + ' StemExtension must be ' + expectedStemExtension
);
// set to weird Stave
const stave = new Stave(10, 10, 300, { spacing_between_lines_px: 20 });
note.setStave(stave);
equal(
note.getStemExtension(),
expectedStemExtension * 2,
'For wide staff ' + keys.toString() + ' StemExtension must be ' + expectedStemExtension * 2
);
const whole_note = new StaveNote({ keys: keys, duration: 'w' });
equal(
whole_note.getStemExtension(),
-1 * Flow.STEM_HEIGHT,
'For ' + keys.toString() + ' whole_note StemExtension must always be -1 * Flow.STEM_HEIGHT'
);
});
}
function setStemDirectionDisplacement(): void {
function getDisplacements(note: StaveNote) {
// eslint-disable-next-line
// @ts-ignore direct access to protected variable .note_heads
return note.note_heads.map((notehead) => notehead.isDisplaced());
}
const stemUpDisplacements = [false, true, false];
const stemDownDisplacements = [true, false, false];
const note = new StaveNote({ keys: ['c/5', 'd/5', 'g/5'], stem_direction: Stem.UP, duration: '4' });
deepEqual(getDisplacements(note), stemUpDisplacements);
note.setStemDirection(Stem.DOWN);
deepEqual(getDisplacements(note), stemDownDisplacements);
note.setStemDirection(Stem.UP);
deepEqual(getDisplacements(note), stemUpDisplacements);
}
function staveLine(): void {
const stave = new Stave(10, 10, 300);
const note = new StaveNote({ keys: ['c/4', 'e/4', 'a/4'], duration: 'w' });
note.setStave(stave);
const props = note.getKeyProps();
equal(props[0].line, 0, 'C/4 on line 0');
equal(props[1].line, 1, 'E/4 on line 1');
equal(props[2].line, 2.5, 'A/4 on line 2.5');
const ys = note.getYs();
equal(ys.length, 3, 'Chord should be rendered on three lines');
equal(ys[0], 100, 'Line for C/4');
equal(ys[1], 90, 'Line for E/4');
equal(ys[2], 75, 'Line for A/4');
}
function width(): void {
const note = new StaveNote({ keys: ['c/4', 'e/4', 'a/4'], duration: 'w' });
throws(() => note.getWidth(), /UnformattedNote/, 'Unformatted note should have no width');
}
function tickContext(): void {
const stave = new Stave(10, 10, 400);
const note = new StaveNote({ keys: ['c/4', 'e/4', 'a/4'], duration: 'w' }).setStave(stave);
new TickContext().addTickable(note).preFormat().setX(10).setPadding(0);
expect(0);
}
function drawBasic(options: TestOptions, contextBuilder: ContextBuilder): void {
const clef = options.params.clef;
const octaveShift = options.params.octaveShift;
const restKey = options.params.restKey;
const ctx = contextBuilder(options.elementId, 700, 180);
const stave = new Stave(10, 30, 750);
stave.setContext(ctx);
stave.addClef(clef);
stave.draw();
const lowerKeys = ['c/', 'e/', 'a/'];
const higherKeys = ['c/', 'e/', 'a/'];
for (let k = 0; k < lowerKeys.length; k++) {
lowerKeys[k] = lowerKeys[k] + (4 + octaveShift);
higherKeys[k] = higherKeys[k] + (5 + octaveShift);
}
const restKeys = [restKey];
const noteStructs: StaveNoteStruct[] = [
{ clef: clef, keys: higherKeys, duration: '1/2' },
{ clef: clef, keys: lowerKeys, duration: 'w' },
{ clef: clef, keys: higherKeys, duration: 'h' },
{ clef: clef, keys: lowerKeys, duration: 'q' },
{ clef: clef, keys: higherKeys, duration: '8' },
{ clef: clef, keys: lowerKeys, duration: '16' },
{ clef: clef, keys: higherKeys, duration: '32' },
{ clef: clef, keys: higherKeys, duration: '64' },
{ clef: clef, keys: higherKeys, duration: '128' },
{ clef: clef, keys: lowerKeys, duration: '1/2', stem_direction: Stem.DOWN },
{ clef: clef, keys: lowerKeys, duration: 'w', stem_direction: Stem.DOWN },
{ clef: clef, keys: lowerKeys, duration: 'h', stem_direction: Stem.DOWN },
{ clef: clef, keys: lowerKeys, duration: 'q', stem_direction: Stem.DOWN },
{ clef: clef, keys: lowerKeys, duration: '8', stem_direction: Stem.DOWN },
{ clef: clef, keys: lowerKeys, duration: '16', stem_direction: Stem.DOWN },
{ clef: clef, keys: lowerKeys, duration: '32', stem_direction: Stem.DOWN },
{ clef: clef, keys: lowerKeys, duration: '64', stem_direction: Stem.DOWN },
{ clef: clef, keys: lowerKeys, duration: '128', stem_direction: Stem.DOWN },
{ clef: clef, keys: restKeys, duration: '1/2r' },
{ clef: clef, keys: restKeys, duration: 'wr' },
{ clef: clef, keys: restKeys, duration: 'hr' },
{ clef: clef, keys: restKeys, duration: 'qr' },
{ clef: clef, keys: restKeys, duration: '8r' },
{ clef: clef, keys: restKeys, duration: '16r' },
{ clef: clef, keys: restKeys, duration: '32r' },
{ clef: clef, keys: restKeys, duration: '64r' },
{ clef: clef, keys: restKeys, duration: '128r' },
{ keys: ['x/4'], duration: 'h' },
];
expect(noteStructs.length * 2);
const colorDescendants = (parentItem: SVGElement, color: string) => () =>
parentItem.querySelectorAll('*').forEach((child) => {
child.setAttribute('fill', color);
child.setAttribute('stroke', color);
});
for (let i = 0; i < noteStructs.length; ++i) {
const note = draw(staveNote(noteStructs[i]), stave, ctx, (i + 1) * 25);
// If this is an interactivity test (ui: true), then attach mouseover & mouseout handlers to the notes.
if (options.params.ui) {
const item = note.getAttribute('el') as SVGElement;
item.addEventListener('mouseover', colorDescendants(item, 'green'), false);
item.addEventListener('mouseout', colorDescendants(item, 'black'), false);
}
ok(note.getX() > 0, 'Note ' + i + ' has X value');
ok(note.getYs().length > 0, 'Note ' + i + ' has Y values');
}
}
function drawBoundingBoxes(options: TestOptions, contextBuilder: ContextBuilder): void {
const clef = options.params.clef;
const octaveShift = options.params.octaveShift;
const restKey = options.params.restKey;
const ctx = contextBuilder(options.elementId, 700, 180);
const stave = new Stave(10, 30, 750);
stave.setContext(ctx);
stave.addClef(clef);
stave.draw();
const lowerKeys = ['c/', 'e/', 'a/'];
const higherKeys = ['c/', 'e/', 'a/'];
for (let k = 0; k < lowerKeys.length; k++) {
lowerKeys[k] = lowerKeys[k] + (4 + octaveShift);
higherKeys[k] = higherKeys[k] + (5 + octaveShift);
}
const restKeys = [restKey];
const noteStructs = [
{ clef: clef, keys: higherKeys, duration: '1/2' },
{ clef: clef, keys: lowerKeys, duration: 'w' },
{ clef: clef, keys: higherKeys, duration: 'h' },
{ clef: clef, keys: lowerKeys, duration: 'q' },
{ clef: clef, keys: higherKeys, duration: '8' },
{ clef: clef, keys: lowerKeys, duration: '16' },
{ clef: clef, keys: higherKeys, duration: '32' },
{ clef: clef, keys: higherKeys, duration: '64' },
{ clef: clef, keys: higherKeys, duration: '128' },
{ clef: clef, keys: lowerKeys, duration: '1/2', stem_direction: Stem.DOWN },
{ clef: clef, keys: lowerKeys, duration: 'w', stem_direction: Stem.DOWN },
{ clef: clef, keys: lowerKeys, duration: 'h', stem_direction: Stem.DOWN },
{ clef: clef, keys: lowerKeys, duration: 'q', stem_direction: Stem.DOWN },
{ clef: clef, keys: lowerKeys, duration: '8', stem_direction: Stem.DOWN },
{ clef: clef, keys: lowerKeys, duration: '16', stem_direction: Stem.DOWN },
{ clef: clef, keys: lowerKeys, duration: '32', stem_direction: Stem.DOWN },
{ clef: clef, keys: lowerKeys, duration: '64', stem_direction: Stem.DOWN },
{ clef: clef, keys: lowerKeys, duration: '128' },
{ clef: clef, keys: restKeys, duration: '1/2r' },
{ clef: clef, keys: restKeys, duration: 'wr' },
{ clef: clef, keys: restKeys, duration: 'hr' },
{ clef: clef, keys: restKeys, duration: 'qr' },
{ clef: clef, keys: restKeys, duration: '8r' },
{ clef: clef, keys: restKeys, duration: '16r' },
{ clef: clef, keys: restKeys, duration: '32r' },
{ clef: clef, keys: restKeys, duration: '64r' },
{ clef: clef, keys: restKeys, duration: '128r' },
{ keys: ['x/4'], duration: 'h' },
];
expect(noteStructs.length * 2);
for (let i = 0; i < noteStructs.length; ++i) {
const note = draw(
staveNote(noteStructs[i]),
stave,
ctx,
(i + 1) * 25,
true /* drawBoundingBox */,
false /* addModifierContext */
);
ok(note.getX() > 0, 'Note ' + i + ' has X value');
ok(note.getYs().length > 0, 'Note ' + i + ' has Y values');
}
}
function drawBass(options: TestOptions, contextBuilder: ContextBuilder): void {
expect(40);
const ctx = contextBuilder(options.elementId, 600, 280);
const stave = new Stave(10, 10, 650);
stave.setContext(ctx);
stave.addClef('bass');
stave.draw();
const noteStructs: StaveNoteStruct[] = [
{ clef: 'bass', keys: ['c/3', 'e/3', 'a/3'], duration: '1/2' },
{ clef: 'bass', keys: ['c/2', 'e/2', 'a/2'], duration: 'w' },
{ clef: 'bass', keys: ['c/3', 'e/3', 'a/3'], duration: 'h' },
{ clef: 'bass', keys: ['c/2', 'e/2', 'a/2'], duration: 'q' },
{ clef: 'bass', keys: ['c/3', 'e/3', 'a/3'], duration: '8' },
{ clef: 'bass', keys: ['c/2', 'e/2', 'a/2'], duration: '16' },
{ clef: 'bass', keys: ['c/3', 'e/3', 'a/3'], duration: '32' },
{ clef: 'bass', keys: ['c/2', 'e/2', 'a/2'], duration: 'h', stem_direction: Stem.DOWN },
{ clef: 'bass', keys: ['c/2', 'e/2', 'a/2'], duration: 'q', stem_direction: Stem.DOWN },
{ clef: 'bass', keys: ['c/2', 'e/2', 'a/2'], duration: '8', stem_direction: Stem.DOWN },
{ clef: 'bass', keys: ['c/2', 'e/2', 'a/2'], duration: '16', stem_direction: Stem.DOWN },
{ clef: 'bass', keys: ['c/2', 'e/2', 'a/2'], duration: '32', stem_direction: Stem.DOWN },
{ keys: ['r/4'], duration: '1/2r' },
{ keys: ['r/4'], duration: 'wr' },
{ keys: ['r/4'], duration: 'hr' },
{ keys: ['r/4'], duration: 'qr' },
{ keys: ['r/4'], duration: '8r' },
{ keys: ['r/4'], duration: '16r' },
{ keys: ['r/4'], duration: '32r' },
{ keys: ['x/4'], duration: 'h' },
];
for (let i = 0; i < noteStructs.length; ++i) {
const note = draw(staveNote(noteStructs[i]), stave, ctx, (i + 1) * 25);
ok(note.getX() > 0, 'Note ' + i + ' has X value');
ok(note.getYs().length > 0, 'Note ' + i + ' has Y values');
}
}
function displacements(options: TestOptions, contextBuilder: ContextBuilder): void {
const ctx = contextBuilder(options.elementId, 700, 140);
ctx.scale(0.9, 0.9);
ctx.fillStyle = '#221';
ctx.strokeStyle = '#221';
const stave = new Stave(10, 10, 650);
stave.setContext(ctx);
stave.draw();
const noteStructs = [
{ keys: ['g/3', 'a/3', 'c/4', 'd/4', 'e/4'], duration: '1/2' },
{ keys: ['g/3', 'a/3', 'c/4', 'd/4', 'e/4'], duration: 'w' },
{ keys: ['d/4', 'e/4', 'f/4'], duration: 'h' },
{ keys: ['f/4', 'g/4', 'a/4', 'b/4'], duration: 'q' },
{ keys: ['e/3', 'b/3', 'c/4', 'e/4', 'f/4', 'g/5', 'a/5'], duration: '8' },
{ keys: ['a/3', 'c/4', 'e/4', 'g/4', 'a/4', 'b/4'], duration: '16' },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '32' },
{ keys: ['c/4', 'e/4', 'a/4', 'a/4'], duration: '64' },
{ keys: ['g/3', 'c/4', 'd/4', 'e/4'], duration: 'h', stem_direction: Stem.DOWN },
{ keys: ['d/4', 'e/4', 'f/4'], duration: 'q', stem_direction: Stem.DOWN },
{ keys: ['f/4', 'g/4', 'a/4', 'b/4'], duration: '8', stem_direction: Stem.DOWN },
{ keys: ['c/4', 'd/4', 'e/4', 'f/4', 'g/4', 'a/4'], duration: '16', stem_direction: Stem.DOWN },
{ keys: ['b/3', 'c/4', 'e/4', 'a/4', 'b/5', 'c/6', 'e/6'], duration: '32', stem_direction: Stem.DOWN },
{
keys: ['b/3', 'c/4', 'e/4', 'a/4', 'b/5', 'c/6', 'e/6', 'e/6'],
duration: '64',
stem_direction: Stem.DOWN,
},
];
expect(noteStructs.length * 2);
for (let i = 0; i < noteStructs.length; ++i) {
const note = draw(staveNote(noteStructs[i]), stave, ctx, (i + 1) * 45);
ok(note.getX() > 0, 'Note ' + i + ' has X value');
ok(note.getYs().length > 0, 'Note ' + i + ' has Y values');
}
}
function drawHarmonicAndMuted(options: TestOptions, contextBuilder: ContextBuilder): void {
const ctx = contextBuilder(options.elementId, 1000, 180);
const stave = new Stave(10, 10, 950);
stave.setContext(ctx);
stave.draw();
const noteStructs = [
{ keys: ['c/4', 'e/4', 'a/4'], duration: '1/2h' },
{ keys: ['c/4', 'e/4', 'a/4'], duration: 'wh' },
{ keys: ['c/4', 'e/4', 'a/4'], duration: 'hh' },
{ keys: ['c/4', 'e/4', 'a/4'], duration: 'qh' },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '8h' },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '16h' },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '32h' },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '64h' },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '128h' },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '1/2h', stem_direction: Stem.DOWN },
{ keys: ['c/4', 'e/4', 'a/4'], duration: 'wh', stem_direction: Stem.DOWN },
{ keys: ['c/4', 'e/4', 'a/4'], duration: 'hh', stem_direction: Stem.DOWN },
{ keys: ['c/4', 'e/4', 'a/4'], duration: 'qh', stem_direction: Stem.DOWN },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '8h', stem_direction: Stem.DOWN },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '16h', stem_direction: Stem.DOWN },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '32h', stem_direction: Stem.DOWN },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '64h', stem_direction: Stem.DOWN },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '128h', stem_direction: Stem.DOWN },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '1/2m' },
{ keys: ['c/4', 'e/4', 'a/4'], duration: 'wm' },
{ keys: ['c/4', 'e/4', 'a/4'], duration: 'hm' },
{ keys: ['c/4', 'e/4', 'a/4'], duration: 'qm' },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '8m' },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '16m' },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '32m' },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '64m' },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '128m' },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '1/2m', stem_direction: Stem.DOWN },
{ keys: ['c/4', 'e/4', 'a/4'], duration: 'wm', stem_direction: Stem.DOWN },
{ keys: ['c/4', 'e/4', 'a/4'], duration: 'hm', stem_direction: Stem.DOWN },
{ keys: ['c/4', 'e/4', 'a/4'], duration: 'qm', stem_direction: Stem.DOWN },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '8m', stem_direction: Stem.DOWN },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '16m', stem_direction: Stem.DOWN },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '32m', stem_direction: Stem.DOWN },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '64m', stem_direction: Stem.DOWN },
{ keys: ['c/4', 'e/4', 'a/4'], duration: '128m', stem_direction: Stem.DOWN },
];
expect(noteStructs.length * 2);
for (let i = 0; i < noteStructs.length; ++i) {
const note = draw(staveNote(noteStructs[i]), stave, ctx, i * 25 + 5);
ok(note.getX() > 0, 'Note ' + i + ' has X value');
ok(note.getYs().length > 0, 'Note ' + i + ' has Y values');
}
}
function drawSlash(options: TestOptions, contextBuilder: ContextBuilder): void {
const ctx = contextBuilder(options.elementId, 700, 180);
const stave = new Stave(10, 10, 650);
stave.setContext(ctx);
stave.draw();
const notes = [
{ keys: ['b/4'], duration: '1/2s', stem_direction: Stem.DOWN },
{ keys: ['b/4'], duration: 'ws', stem_direction: Stem.DOWN },
{ keys: ['b/4'], duration: 'hs', stem_direction: Stem.DOWN },
{ keys: ['b/4'], duration: 'qs', stem_direction: Stem.DOWN },
{ keys: ['b/4'], duration: '8s', stem_direction: Stem.DOWN },
{ keys: ['b/4'], duration: '16s', stem_direction: Stem.DOWN },
{ keys: ['b/4'], duration: '32s', stem_direction: Stem.DOWN },
{ keys: ['b/4'], duration: '64s', stem_direction: Stem.DOWN },
{ keys: ['b/4'], duration: '128s', stem_direction: Stem.DOWN },
{ keys: ['b/4'], duration: '1/2s', stem_direction: Stem.UP },
{ keys: ['b/4'], duration: 'ws', stem_direction: Stem.UP },
{ keys: ['b/4'], duration: 'hs', stem_direction: Stem.UP },
{ keys: ['b/4'], duration: 'qs', stem_direction: Stem.UP },
{ keys: ['b/4'], duration: '8s', stem_direction: Stem.UP },
{ keys: ['b/4'], duration: '16s', stem_direction: Stem.UP },
{ keys: ['b/4'], duration: '32s', stem_direction: Stem.UP },
{ keys: ['b/4'], duration: '64s', stem_direction: Stem.UP },
{ keys: ['b/4'], duration: '128s', stem_direction: Stem.UP },
// Beam
{ keys: ['b/4'], duration: '8s', stem_direction: Stem.DOWN },
{ keys: ['b/4'], duration: '8s', stem_direction: Stem.DOWN },
{ keys: ['b/4'], duration: '8s', stem_direction: Stem.UP },
{ keys: ['b/4'], duration: '8s', stem_direction: Stem.UP },
];
const stave_notes = notes.map((struct) => new StaveNote(struct));
const beam1 = new Beam([stave_notes[16], stave_notes[17]]);
const beam2 = new Beam([stave_notes[18], stave_notes[19]]);
Formatter.FormatAndDraw(ctx, stave, stave_notes, false);
beam1.setContext(ctx).draw();
beam2.setContext(ctx).draw();
ok('Slash Note Heads');
}
function drawKeyStyles(options: TestOptions, contextBuilder: ContextBuilder): void {
const ctx = contextBuilder(options.elementId, 300, 280);
ctx.scale(3, 3);
const stave = new Stave(10, 0, 100);
const note = new StaveNote({ keys: ['g/4', 'bb/4', 'd/5'], duration: 'q' })
.setStave(stave)
.addAccidental(1, new Accidental('b'))
.setKeyStyle(1, { shadowBlur: 2, shadowColor: 'blue', fillStyle: 'blue' });
new TickContext().addTickable(note).preFormat().setX(25);
stave.setContext(ctx).draw();
note.setContext(ctx).draw();
ok(note.getX() > 0, 'Note has X value');
ok(note.getYs().length > 0, 'Note has Y values');
}
function drawNoteStyles(options: TestOptions, contextBuilder: ContextBuilder): void {
const ctx = contextBuilder(options.elementId, 300, 280);
const stave = new Stave(10, 0, 100);
ctx.scale(3, 3);
const note = new StaveNote({ keys: ['g/4', 'bb/4', 'd/5'], duration: '8' })
.setStave(stave)
.addAccidental(1, new Accidental('b'));
note.setStyle({ shadowBlur: 2, shadowColor: 'blue', fillStyle: 'blue', strokeStyle: 'blue' });
new TickContext().addTickable(note).preFormat().setX(25);
stave.setContext(ctx).draw();
note.setContext(ctx).draw();
ok(note.getX() > 0, 'Note has X value');
ok(note.getYs().length > 0, 'Note has Y values');
}
function drawNoteStemStyles(options: TestOptions, contextBuilder: ContextBuilder): void {
const ctx = contextBuilder(options.elementId, 300, 280);
const stave = new Stave(10, 0, 100);
ctx.scale(3, 3);
const note = new StaveNote({ keys: ['g/4', 'bb/4', 'd/5'], duration: 'q' })
.setStave(stave)
.addAccidental(1, new Accidental('b'));
note.setStemStyle({ shadowBlur: 2, shadowColor: 'blue', fillStyle: 'blue', strokeStyle: 'blue' });
new TickContext().addTickable(note).preFormat().setX(25);
stave.setContext(ctx).draw();
note.setContext(ctx).draw();
ok('Note Stem Style');
}
function drawNoteStemLengths(options: TestOptions, contextBuilder: ContextBuilder): void {
const ctx = contextBuilder(options.elementId, 975, 150);
const stave = new Stave(10, 10, 975);
stave.setContext(ctx).draw();
const keys = [
'e/3',
'f/3',
'g/3',
'a/3',
'b/3',
'c/4',
'd/4',
'e/4',
'f/4',
'g/4',
'f/5',
'g/5',
'a/5',
'b/5',
'c/6',
'd/6',
'e/6',
'f/6',
'g/6',
'a/6',
];
const notes: StaveNote[] = [];
let note;
let i;
for (i = 0; i < keys.length; i++) {
let duration = 'q';
if (i % 2 === 1) {
duration = '8';
}
note = new StaveNote({ keys: [keys[i]], duration, auto_stem: true }).setStave(stave);
new TickContext().addTickable(note);
note.setContext(ctx);
notes.push(note);
}
const whole_keys = ['e/3', 'a/3', 'f/5', 'a/5', 'd/6', 'a/6'];
for (i = 0; i < whole_keys.length; i++) {
note = new StaveNote({ keys: [whole_keys[i]], duration: 'w' }).setStave(stave);
new TickContext().addTickable(note);
note.setContext(ctx);
notes.push(note);
}
Formatter.FormatAndDraw(ctx, stave, notes);
ok('Note Stem Length');
}
function drawNoteStylesWithFlag(options: TestOptions, contextBuilder: ContextBuilder): void {
const ctx = contextBuilder(options.elementId, 300, 280);
const stave = new Stave(10, 0, 100);
ctx.scale(3, 3);
const note = new StaveNote({ keys: ['g/4', 'bb/4', 'd/5'], duration: '8' })
.setStave(stave)
.addAccidental(1, new Accidental('b'));
note.setFlagStyle({ shadowBlur: 2, shadowColor: 'blue', fillStyle: 'blue', strokeStyle: 'blue' });
new TickContext().addTickable(note).preFormat().setX(25);
stave.setContext(ctx).draw();
note.setContext(ctx).draw();
ok(note.getX() > 0, 'Note has X value');
ok(note.getYs().length > 0, 'Note has Y values');
}
function drawBeamStyles(options: TestOptions, contextBuilder: ContextBuilder): void {
const ctx = contextBuilder(options.elementId, 400, 160);
const stave = new Stave(10, 10, 380);
stave.setStyle({ strokeStyle: '#EEAAEE', lineWidth: '3' });
stave.setContext(ctx);
stave.draw();
const notes = [
// beam1
{ keys: ['b/4'], duration: '8', stem_direction: Stem.DOWN },
{ keys: ['b/4'], duration: '8', stem_direction: Stem.DOWN },
// should be unstyled...
{ keys: ['b/4'], duration: '8', stem_direction: Stem.DOWN },
// beam2 should also be unstyled
{ keys: ['b/4'], duration: '8', stem_direction: Stem.DOWN },
{ keys: ['b/4'], duration: '8', stem_direction: Stem.DOWN },
// beam3
{ keys: ['b/4'], duration: '8', stem_direction: Stem.UP },
{ keys: ['b/4'], duration: '8', stem_direction: Stem.UP },
// beam4
{ keys: ['d/6'], duration: '8', stem_direction: Stem.DOWN },
{ keys: ['c/6', 'd/6'], duration: '8', stem_direction: Stem.DOWN },
// unbeamed
{ keys: ['d/6', 'e/6'], duration: '8', stem_direction: Stem.DOWN },
// unbeamed, unstyled
{ keys: ['e/6', 'f/6'], duration: '8', stem_direction: Stem.DOWN },
];
const staveNotes = notes.map((note) => new StaveNote(note));
const beam1 = new Beam(staveNotes.slice(0, 2));
const beam2 = new Beam(staveNotes.slice(3, 5));
const beam3 = new Beam(staveNotes.slice(5, 7));
const beam4 = new Beam(staveNotes.slice(7, 9));
// stem, key, ledger, flag; beam.setStyle
beam1.setStyle({ fillStyle: 'blue', strokeStyle: 'blue' });
staveNotes[0].setKeyStyle(0, { fillStyle: 'purple' });
staveNotes[0].setStemStyle({ strokeStyle: 'green' });
staveNotes[1].setStemStyle({ strokeStyle: 'orange' });
staveNotes[1].setKeyStyle(0, { fillStyle: 'darkturquoise' });
staveNotes[5].setStyle({ fillStyle: 'tomato', strokeStyle: 'tomato' });
beam3.setStyle({ shadowBlur: 4, shadowColor: 'blue' });
staveNotes[9].setLedgerLineStyle({ fillStyle: 'lawngreen', strokeStyle: 'lawngreen', lineWidth: 1 });
staveNotes[9].setFlagStyle({ fillStyle: 'orange', strokeStyle: 'orange' });
Formatter.FormatAndDraw(ctx, stave, staveNotes, false);
beam1.setContext(ctx).draw();
beam2.setContext(ctx).draw();
beam3.setContext(ctx).draw();
beam4.setContext(ctx).draw();
ok('draw beam styles');
}
function dotsAndFlagsStemUp(options: TestOptions, contextBuilder: ContextBuilder): void {
const ctx = contextBuilder(options.elementId, 800, 150);
ctx.scale(1.0, 1.0);
ctx.setFillStyle('#221');
ctx.setStrokeStyle('#221');
const stave = new Stave(10, 10, 975);
const notes = [
staveNote({ keys: ['f/4'], duration: '4', stem_direction: Stem.UP }).addDotToAll(),
staveNote({ keys: ['f/4'], duration: '8', stem_direction: Stem.UP }).addDotToAll(),
staveNote({ keys: ['f/4'], duration: '16', stem_direction: Stem.UP }).addDotToAll(),
staveNote({ keys: ['f/4'], duration: '32', stem_direction: Stem.UP }).addDotToAll(),
staveNote({ keys: ['f/4'], duration: '64', stem_direction: Stem.UP }).addDotToAll(),
staveNote({ keys: ['f/4'], duration: '128', stem_direction: Stem.UP })
.addDotToAll()
.addDotToAll(),
staveNote({ keys: ['g/4'], duration: '4', stem_direction: Stem.UP }).addDotToAll(),
staveNote({ keys: ['g/4'], duration: '8', stem_direction: Stem.UP }).addDotToAll(),
staveNote({ keys: ['g/4'], duration: '16', stem_direction: Stem.UP }).addDotToAll(),
staveNote({ keys: ['g/4'], duration: '32' }).addDotToAll(),
staveNote({ keys: ['g/4'], duration: '64', stem_direction: Stem.UP }).addDotToAll(),
staveNote({ keys: ['g/4'], duration: '128', stem_direction: Stem.UP })
.addDotToAll()
.addDotToAll(),
];
stave.setContext(ctx).draw();
for (let i = 0; i < notes.length; ++i) {
draw(notes[i], stave, ctx, i * 65);
}
ok(true, 'Full Dot');
}
function dotsAndFlagsStemDown(options: TestOptions, contextBuilder: ContextBuilder): void {
const ctx = contextBuilder(options.elementId, 800, 160);
ctx.scale(1.0, 1.0);
ctx.setFillStyle('#221');
ctx.setStrokeStyle('#221');
const stave = new Stave(10, 10, 975);
const staveNotes = [
staveNote({ keys: ['e/5'], duration: '4', stem_direction: Stem.DOWN }).addDotToAll(),
staveNote({ keys: ['e/5'], duration: '8', stem_direction: Stem.DOWN }).addDotToAll(),
staveNote({ keys: ['e/5'], duration: '16', stem_direction: Stem.DOWN }).addDotToAll(),
staveNote({ keys: ['e/5'], duration: '32', stem_direction: Stem.DOWN }).addDotToAll(),
staveNote({ keys: ['e/5'], duration: '64', stem_direction: Stem.DOWN }).addDotToAll(),
staveNote({ keys: ['e/5'], duration: '128', stem_direction: Stem.DOWN }).addDotToAll(),
staveNote({ keys: ['d/5'], duration: '4', stem_direction: Stem.DOWN }).addDotToAll(),
staveNote({ keys: ['d/5'], duration: '8', stem_direction: Stem.DOWN }).addDotToAll(),
staveNote({ keys: ['d/5'], duration: '16', stem_direction: Stem.DOWN }).addDotToAll(),
staveNote({ keys: ['d/5'], duration: '32', stem_direction: Stem.DOWN }).addDotToAll(),
staveNote({ keys: ['d/5'], duration: '64', stem_direction: Stem.DOWN }).addDotToAll(),
staveNote({ keys: ['d/5'], duration: '128', stem_direction: Stem.DOWN }).addDotToAll(),
];
stave.setContext(ctx).draw();
for (let i = 0; i < staveNotes.length; ++i) {
draw(staveNotes[i], stave, ctx, i * 65);
}
ok(true, 'Full Dot');
}
function dotsAndBeamsUp(options: TestOptions, contextBuilder: ContextBuilder): void {
const ctx = contextBuilder(options.elementId, 800, 150);
ctx.scale(1.0, 1.0);
ctx.setFillStyle('#221');
ctx.setStrokeStyle('#221');
const stave = new Stave(10, 10, 975);
const staveNotes = [
staveNote({ keys: ['f/4'], duration: '8', stem_direction: Stem.UP }).addDotToAll(),
staveNote({ keys: ['f/4'], duration: '16', stem_direction: Stem.UP }).addDotToAll(),
staveNote({ keys: ['f/4'], duration: '32', stem_direction: Stem.UP }).addDotToAll(),
staveNote({ keys: ['f/4'], duration: '64', stem_direction: Stem.UP }).addDotToAll(),
staveNote({ keys: ['f/4'], duration: '128', stem_direction: Stem.UP })
.addDotToAll()
.addDotToAll(),
staveNote({ keys: ['g/4'], duration: '8', stem_direction: Stem.UP }).addDotToAll(),
staveNote({ keys: ['g/4'], duration: '16', stem_direction: Stem.UP }).addDotToAll(),
staveNote({ keys: ['g/4'], duration: '32' }).addDotToAll(),
staveNote({ keys: ['g/4'], duration: '64', stem_direction: Stem.UP }).addDotToAll(),
staveNote({ keys: ['g/4'], duration: '128', stem_direction: Stem.UP })
.addDotToAll()
.addDotToAll(),
];
const beam = new Beam(staveNotes);
stave.setContext(ctx).draw();
for (let i = 0; i < staveNotes.length; ++i) {
draw(staveNotes[i], stave, ctx, i * 65);
}
beam.setContext(ctx).draw();
ok(true, 'Full Dot');
}
function dotsAndBeamsDown(options: TestOptions, contextBuilder: ContextBuilder): void {
const ctx = contextBuilder(options.elementId, 800, 160);
ctx.scale(1.0, 1.0);
ctx.setFillStyle('#221');
ctx.setStrokeStyle('#221');
const stave = new Stave(10, 10, 975);
const staveNotes = [
staveNote({ keys: ['e/5'], duration: '8', stem_direction: Stem.DOWN }).addDotToAll(),
staveNote({ keys: ['e/5'], duration: '16', stem_direction: Stem.DOWN }).addDotToAll(),
staveNote({ keys: ['e/5'], duration: '32', stem_direction: Stem.DOWN }).addDotToAll(),
staveNote({ keys: ['e/5'], duration: '64', stem_direction: Stem.DOWN }).addDotToAll(),
staveNote({ keys: ['e/5'], duration: '128', stem_direction: Stem.DOWN }).addDotToAll(),
staveNote({ keys: ['d/5'], duration: '8', stem_direction: Stem.DOWN }).addDotToAll(),
staveNote({ keys: ['d/5'], duration: '16', stem_direction: Stem.DOWN }).addDotToAll(),
staveNote({ keys: ['d/5'], duration: '32', stem_direction: Stem.DOWN }).addDotToAll(),
staveNote({ keys: ['d/5'], duration: '64', stem_direction: Stem.DOWN }).addDotToAll(),
staveNote({ keys: ['d/5'], duration: '128', stem_direction: Stem.DOWN }).addDotToAll(),
];
const beam = new Beam(staveNotes);
stave.setContext(ctx).draw();
for (let i = 0; i < staveNotes.length; ++i) {
draw(staveNotes[i], stave, ctx, i * 65);
}
beam.setContext(ctx).draw();
ok(true, 'Full Dot');
}
function centerAlignedRest(options: TestOptions): void {
const f = VexFlowTests.makeFactory(options, 400, 160);
const stave = f.Stave({ x: 10, y: 10, width: 350 }).addClef('treble').addTimeSignature('4/4');
const note = f.StaveNote({ keys: ['b/4'], duration: '1r', align_center: true });
const voice = f.Voice().setStrict(false).addTickables([note]);
f.Formatter().joinVoices([voice]).formatToStave([voice], stave);
f.draw();
ok(true);
}
function centerAlignedRestFermata(options: TestOptions): void {
const f = VexFlowTests.makeFactory(options, 400, 160);
const stave = f.Stave({ x: 10, y: 10, width: 350 }).addClef('treble').addTimeSignature('4/4');
const note = f
.StaveNote({ keys: ['b/4'], duration: '1r', align_center: true })
.addArticulation(0, new Articulation('a@a').setPosition(3));
const voice = f.Voice().setStrict(false).addTickables([note]);
f.Formatter().joinVoices([voice]).formatToStave([voice], stave);
f.draw();
ok(true);
}
function centerAlignedRestAnnotation(options: TestOptions): void {
const f = VexFlowTests.makeFactory(options, 400, 160);
const stave = f.Stave({ x: 10, y: 10, width: 350 }).addClef('treble').addTimeSignature('4/4');
const note = f
.StaveNote({ keys: ['b/4'], duration: '1r', align_center: true })
.addAnnotation(0, new Annotation('Whole measure rest').setPosition(3));
const voice = f.Voice().setStrict(false).addTickables([note]);
f.Formatter().joinVoices([voice]).formatToStave([voice], stave);
f.draw();
ok(true);
}
function centerAlignedNoteMultiModifiers(options: TestOptions): void {
const f = VexFlowTests.makeFactory(options, 400, 160);
const stave = f.Stave({ x: 10, y: 10, width: 350 }).addClef('treble').addTimeSignature('4/4');
function newFinger(num: string, pos: ModifierPosition) {
return new FretHandFinger(num).setPosition(pos);
}
const note = f
.StaveNote({ keys: ['c/4', 'e/4', 'g/4'], duration: '4', align_center: true })
.addAnnotation(0, new Annotation('Test').setPosition(3))
.addStroke(0, new Stroke(2))
.addAccidental(1, new Accidental('#'))
.addModifier(newFinger('3', Modifier.Position.LEFT), 0)
.addModifier(newFinger('2', Modifier.Position.LEFT), 2)
.addModifier(newFinger('1', Modifier.Position.RIGHT), 1)
.addModifier(new StringNumber('4').setPosition(Modifier.Position.BELOW), 2)
.addDotToAll();
const voice = f.Voice().setStrict(false).addTickables([note]);
f.Formatter().joinVoices([voice]).formatToStave([voice], stave);
f.draw();
ok(true);
}
function centerAlignedMultiVoice(options: TestOptions): void {
const f = VexFlowTests.makeFactory(options, 400, 160);
const stave = f.Stave({ x: 10, y: 10, width: 350 }).addClef('treble').addTimeSignature('3/8');
// Set a custom duration of 3 / 8.
const custom_duration = new Fraction(3, 8);
// TODO: Should the whole rest draw a ledger line that is visible to the left/right of the rest?
const notes0 = [
f.StaveNote({
keys: ['c/4'],
duration: '1r',
align_center: true,
duration_override: custom_duration,
}),
];
const createStaveNote = (struct: StaveNoteStruct) => f.StaveNote(struct);
const notes1 = [
{ keys: ['b/4'], duration: '8' },
{ keys: ['b/4'], duration: '8' },
{ keys: ['b/4'], duration: '8' },
].map(createStaveNote);
notes1[1].addAccidental(0, f.Accidental({ type: '#' }));
f.Beam({ notes: notes1 });
const voice0 = f.Voice({ time: '3/8' }).setStrict(false).addTickables(notes0);
const voice1 = f.Voice({ time: '3/8' }).setStrict(false).addTickables(notes1);
f.Formatter().joinVoices([voice0, voice1]).formatToStave([voice0, voice1], stave);
f.draw();
ok(true);
}
export { StaveNoteTests }; | the_stack |
import IndexableArray from "indexable-array";
import { Memoize } from "@typescript-plus/fast-memoize-decorator/dist/src";
import Entity from "../base/entity";
import Constraint from "../base/constraint";
import Trigger from "../trigger";
import PrimaryKey from "../constraint/primary-key";
import ForeignKey from "../constraint/foreign-key";
import M2ORelation from "../relation/m2o-relation";
import O2MRelation from "../relation/o2m-relation";
import M2MRelation from "../relation/m2m-relation";
import Index from "..";
import { isForeignKey, isPrimaryKey, isUniqueConstraint, isCheckConstraint, isExclusionConstraint } from "../../util/type-guard";
import UniqueConstraint from "../constraint/unique-constraint";
import CheckConstraint from "../constraint/check-constraint";
import ExclusionConstraint from "../constraint/exclusion-constraint";
import { Column } from "../..";
import { getForeignKeysTo } from "../../util/helper";
/**
* Class which represent a table. Provides attributes and methods for details of the table.
* Tables may have relationships with other tables.
*
* <span id="exampleSchema"></span>Below is a database schema which is used in code examples.
* 
*/
export default class Table extends Entity {
/**
* All {@link Trigger triggers} in the table as an [[IndexableArray]] ordered by name.
*/
public readonly triggers: IndexableArray<Trigger, "name", never, true> = IndexableArray.throwingFrom([], "name");
/**
* All {@link Constraint constraints} in the table as an [[IndexableArray]] ordered by name.
*/
public readonly constraints: IndexableArray<Constraint, "name", never, true> = IndexableArray.throwingFrom([], "name");
/**
* All {@link ForeignKey foreign keys} which are referring to this {@link Table table} as an [[IndexableArray]].
*
* @see [[Table.o2mRelations]], [[Table.m2oRelations]], [[Table.m2mRelations]] to get more details about relations.
*/
public readonly foreignKeysToThis: IndexableArray<ForeignKey, "name", never, true> = IndexableArray.throwingFrom([], "name");
/**
* All {@link Index indexes} in the table as an [[IndexableArray]], ordered by name.
*/
public readonly indexes: IndexableArray<Index, "name", never, true> = IndexableArray.throwingFrom([], "name");
/**
* Returns {@link ForeignKey foreign keys} from this table to `target` table.
*
* @param target is target {@link Table table} to get foreign keys for. It could be name, full name or {@link Table table} object.
* @returns foreign keys from this table to target table.
*/
public getForeignKeysTo(target: Table | string): IndexableArray<ForeignKey, "name", never, true> {
const targetTable = typeof target === "string" ? this.schema.tables.getMaybe(target) || this.db.tables.get(target) : target;
return getForeignKeysTo(this, targetTable);
}
/**
* Returns {@link ForeignKey foreign keys} from given table to this table.
*
* @param from is {@link Table table} to get foreign keys targeting this table. It could be name, full name or {@link Table table} object.
* @returns foreign keys from given table to this table.
*/
public getForeignKeysFrom(from: Table | string): IndexableArray<ForeignKey, "name", never, true> {
const sourceTable = typeof from === "string" ? this.schema.tables.getMaybe(from) || this.db.tables.get(from) : from;
return getForeignKeysTo(sourceTable, this);
}
/**
* Returns join tables between this table and target table.
*
* @param target is target {@link Table table} to get join tables for. It could be name, full name or {@link Table table} object.
*/
public getJoinTablesTo(target: Table | string): IndexableArray<Table, "name", never, true> {
const targetTable = typeof target === "string" ? this.schema.tables.getMaybe(target) || this.db.tables.get(target) : target;
const joinTables = this.getThroughConstraints()
.filter((tc) => tc.toOther.referencedTable === targetTable)
.map((tc) => tc.toOther.table);
const uniqueJoinTables = new Set(joinTables);
return IndexableArray.throwingFrom(uniqueJoinTables, "name").sortBy("name");
}
/**
* All {@link ForeignKey foreign keys} in the {@link Table table} as an [[IndexableArray]] ordered by name.
*
* @see {@link Table.o2mRelations o2mRelations}, {@link Table.m2oRelations m2oRelations}, {@link Table.m2mRelations m2mRelations} to get more details about relations.
*/
public get foreignKeys(): IndexableArray<ForeignKey, "name", never, true> {
return this.constraints.filter(isForeignKey);
}
/**
* All {@link UniqueConstraint unique constraints} in the {@link Table table} as an [[IndexableArray]] ordered by name.
*/
public get uniqueConstraints(): IndexableArray<UniqueConstraint, "name", never, true> {
return this.constraints.filter(isUniqueConstraint);
}
/**
* All {@link CheckConstraint check constraints} in the {@link Table table} as an [[IndexableArray]] ordered by name.
*/
public get checkConstraints(): IndexableArray<CheckConstraint, "name", never, true> {
return this.constraints.filter(isCheckConstraint);
}
/**
* All {@link ExclusionConstraint exclusion constraints} in the {@link Table table} as an [[IndexableArray]] ordered by name.
*/
public get exclusionConstraints(): IndexableArray<ExclusionConstraint, "name", never, true> {
return this.constraints.filter(isExclusionConstraint);
}
/**
* {@link PrimaryKey Primary key} of this {@link Table table}.
*
* @see {@link Table.primaryKeyColumns primaryKeyColumns} to get primary key columns directly.
* @example
* table.primaryKey.columns.forEach(column => console.log(column.name));
*/
public get primaryKey(): PrimaryKey | undefined {
return this.constraints.find(isPrimaryKey);
}
/**
* {@link Table Tables}, which this {@link Table table} has {@link O2MRelation one to many relationship}, ordered by table name.
* Please note that same table will appear more than once if there are more than one relationship between tables or same named tables from
* different schemas (i.e. `public.account` may have relations with `public.contact` and `vip.contact`).
*
* @see [Example schema](.exampleSchema), {@link IndexableArray}
* @example
* vendorTable.hasManyTables.forEach(table => console.log(table.name));
* vendorTable.hasManyTables.getAll("contact"); // All related tables named contact.
*/
public get hasManyTables(): IndexableArray<Table, "name", never, true> {
return this.foreignKeysToThis.map((fk) => fk.table).sortBy("name");
}
/**
* {@link Table Tables}, which this {@link Table table} has {@link M2ORelation belongs to relationship} (a.k.a. many to one) which is reverse direction of
* {@link O2MRelation one to many relationship} (a.k.a one to many), ordered by table name.
* Please note that same table will appear more than once if there are more than one relationship between tables or same named tables from
* different schemas (i.e. `public.account` may have relations with `public.contact` and `vip.contact`).
*
* @see [Example schema](.exampleSchema), {@link IndexableArray}
* @example
* productTable.belongsToTables.forEach(table => console.log(table.name));
* productTable.belongsToTables.getAll("contact"); // All related tables named contact.
*/
public get belongsToTables(): IndexableArray<Table, "name", never, true> {
return this.foreignKeys.map((fk) => fk.referencedTable).sortBy("name");
}
/**
* {@link Table Tables} which this {@link Table table} has {@link M2MRelation many to many relationship}, ordered by table name
* Please note that same table will appear more than once if there are more than one relationship between tables or same named tables from
* different schemas (i.e. `public.account` may have relations with `public.contact` and `vip.contact`).
*
* @see [Example schema](.exampleSchema)
* @example
* // Cart (id) has many products (id) through line_item join table.
* cartTable.belongsToManyTables.forEach(table => console.log(table.name));
* cartTable.belongsToManyTables.getAll("contact"); // All related tables named contact.
*/
@Memoize()
public get belongsToManyTables(): IndexableArray<Table, "name", never, true> {
const tables = this.getThroughConstraints().map((constraint) => constraint.toOther.referencedTable) as Table[];
return IndexableArray.throwingFrom(tables, "name").sortBy("name");
}
/**
* {@link Table Tables} which this {@link Table table} has {@link M2MRelation many to many relationship} joined by primary keys only in join table, ordered by table name
* Please note that same table will appear more than once if there are more than one relationship between tables or same named tables from
* different schemas (i.e. `public.account` may have relations with `public.contact` and `vip.contact`).
*
* @see [Example schema](.exampleSchema), {@link IndexableArray}
* @example
* // Cart (id) has many products (id) through line_item join table.
* cartTable.belongsToManyTablesPk.forEach(table => console.log(table.name));
* cartTable.belongsToManyTablesPk.getAll("contact"); // All related tables named contact.
*/
@Memoize()
public get belongsToManyTablesPk(): IndexableArray<Table, "name", never, true> {
const tables = this.getThroughConstraints(true).map((constraint) => constraint.toOther.referencedTable) as Table[];
return IndexableArray.throwingFrom(tables, "name").sortBy("name");
}
/**
* Array of {@link M2MRelation many to many relationships} of the {@link Table table}. {@link M2MRelation Many to many relationships} resembles
* `has many through` and `belongs to many` relations in ORMs. It has some useful methods and information for generating ORM classes.
*/
@Memoize()
public get m2mRelations(): IndexableArray<M2MRelation, "name", never, true> {
return IndexableArray.throwingFrom(this.getM2MRelations(false), "name").sortBy("name");
}
/**
* Array of {@link M2MRelation many to many relationships} of the {@link Table table}. Different from {@link Table.m2mRelations m2mRelations},
* this only includes relations joined by `Primary Foreign Keys` in join table. `Primary Foreign Key` means
* foreign key of join table which are also primary key of join table at the same time.
* {@link M2MRelation} resembles `has many through` and `belongs to many` relations in ORMs.
* It has some useful methods and information for generating ORM classes.
*/
@Memoize()
public get m2mRelationsPk(): IndexableArray<M2MRelation, "name", never, true> {
return IndexableArray.throwingFrom(this.getM2MRelations(true), "name").sortBy("name");
}
/**
* Array of {@link O2MRelation one to many relationships} of the {@link Table table}. {@link O2MRelation} resembles
* `has many` relations in ORMs. It has some useful methods and information for generating ORM classes.
*/
@Memoize()
public get o2mRelations(): IndexableArray<O2MRelation, "name", never, true> {
return this.foreignKeysToThis.map((fk) => new O2MRelation({ foreignKey: fk })).sortBy("name");
}
/**
* Array of {@link M2ORelation many to one relationships} of the {@link Table table}. {@link M2ORelation} resembles
* `belongs to` relations in ORMs. It has some useful methods and information for generating ORM classes.
*/
@Memoize()
public get m2oRelations(): IndexableArray<M2ORelation, "name", never, true> {
return this.foreignKeys.map((fk) => new M2ORelation({ foreignKey: fk })).sortBy("name");
}
/**
* List of all relationships of the {@link Table table}. They are sort by type ([[O2MRelation]], [[M2ORelation]], [[M2MRelation]]).
*/
@Memoize()
public get relations(): IndexableArray<O2MRelation | M2ORelation | M2MRelation, "name", never, true> {
return IndexableArray.throwingFrom([...this.o2mRelations, ...this.m2oRelations, ...this.m2mRelations], "name");
}
/**
* Returns through constraints.
*
* @param onlyPk is whether to include only PK column constraints.
* @returns through constraints and their details.
*/
@Memoize()
private getThroughConstraints(
onlyPk = false
): {
toThis: ForeignKey;
toOther: ForeignKey;
}[] {
const result: ReturnType<Table["getThroughConstraints"]> = [];
this.foreignKeysToThis.forEach((fkToThis) => {
const joinTable = fkToThis.table;
joinTable.foreignKeys
.filter((fkToOther) => fkToThis !== fkToOther)
.forEach((fkToOther) => {
result.push({
toThis: fkToThis,
toOther: fkToOther,
});
});
});
return onlyPk
? result.filter((c) => c.toThis.columns.every((col) => col.isPrimaryKey) && c.toOther.columns.every((col) => col.isPrimaryKey))
: result;
}
/** @ignore */
private getM2MRelations(onlyPk: boolean): M2MRelation[] {
return this.getThroughConstraints(onlyPk).map((tc) => new M2MRelation({ foreignKey: tc.toThis, targetForeignKey: tc.toOther }));
}
/**
* Returns {@link Column column} with given name from {@link Table table}.
*
* @param path is the name of the {@link Column column}.
* @returns requested {@link Column columns}.
* @example
* const column = entity.get('contact'), // Returns contact column from entity.
*/
public get(column: string): Column {
return this.columns.get(column);
}
} | the_stack |
import Dayjs from 'dayjs'
import crypto from 'crypto'
import Bcrypt from 'bcryptjs'
import Jwt from 'jsonwebtoken'
import { ReferenceType } from '@mikro-orm/core'
import { validateAll } from 'indicative/validator'
import {
plugin,
resource,
text,
json,
array,
textarea,
belongsTo,
dateTime,
DataPayload,
FieldContract,
hasMany,
boolean,
select,
filter,
password,
graphQlQuery,
GraphQLPluginContext,
route,
GraphQlQueryContract,
ApiContext,
UserRole,
Utils,
hasOne,
ResourceContract,
PluginContract,
timestamp
} from '@tensei/common'
import {
USER_EVENTS,
AuthData,
TokenTypes,
GrantConfig,
AuthResources,
AuthPluginConfig,
SupportedSocialProviders,
defaultProviderScopes,
AuthHookFunction,
AuthContract
} from './config'
export * from './config'
import { setup } from './setup'
import { request, Request } from 'express'
import { Teams } from './teams/Teams'
import {
permission,
PermissionContract,
RoleContract
} from './teams/Permission'
type JwtPayload = {
id: string
refresh?: boolean
}
type AuthSetupFn = (resources: AuthResources) => any
export class Auth implements AuthContract {
public config: AuthPluginConfig & {
setupFn: AuthSetupFn
} = {
prefix: '',
teamPermissions: [],
roles: [],
autoFillUser: true,
autoFilterForUser: true,
tokenResource: 'Token',
enableRefreshTokens: false,
userResource: 'User',
teamResource: 'Team',
teams: false,
excludedPathsFromCsrf: [],
httpOnlyCookiesAuth: false,
passwordResetResource: 'Password Reset',
fields: [],
separateSocialLoginAndRegister: false,
apiPath: 'api',
setupFn: () => this,
beforeLogin: () => {},
afterLogin: () => {},
beforeRegister: () => {},
afterRegister: () => {},
beforePasswordReset: () => {},
afterPasswordReset: () => {},
tokensConfig: {
accessTokenExpiresIn: 60 * 60, // sixty minutes
secretKey: process.env.JWT_SECRET || 'auth-secret-key',
refreshTokenExpiresIn: 60 * 60 * 24 * 30 * 6 // 6 months
},
cookieOptions: {
secure: process.env.NODE_ENV === 'production'
},
refreshTokenHeaderName: 'x-tensei-refresh-token',
twoFactorAuth: false,
verifyEmails: false,
skipWelcomeEmail: false,
providers: {}
}
private TwoFactorAuth: any = null
private teamsInstance: any = new Teams(this)
public __resources: AuthResources = {} as any
public constructor() {
this.refreshResources()
}
public separateSocialLoginAndRegister() {
this.config.separateSocialLoginAndRegister = true
return this
}
public cookieSessions() {
this.config.httpOnlyCookiesAuth = true
return this
}
public registered(registered: AuthPluginConfig['registered']) {
this.config.registered = registered
return this
}
public refreshTokens() {
this.config.enableRefreshTokens = true
return this
}
private refreshResources() {
this.__resources.user = this.userResource()
this.__resources.token = this.tokenResource()
this.__resources.oauthIdentity = this.oauthResource()
this.__resources.passwordReset = this.passwordResetResource()
this.teamsInstance = new Teams(this)
this.__resources.team = this.teamsInstance.teamResource()
this.__resources.membership = this.teamsInstance.teamMembershipResource()
this.config.setupFn(this.__resources)
}
private resolveApiPath(plugins: PluginContract[]) {
const restAPiPlugin = plugins.find(
plugin => plugin.config.name === 'Rest API'
)
if (
restAPiPlugin &&
restAPiPlugin.config.extra?.path &&
restAPiPlugin.config.extra?.path !== 'api'
) {
this.config.apiPath = restAPiPlugin.config.extra?.path
return restAPiPlugin.config.extra?.path
}
return this.config.apiPath
}
public setup(fn: AuthSetupFn) {
this.config.setupFn = fn
return this
}
public beforeLogin(fn: AuthHookFunction) {
this.config.beforeLogin = fn
return this
}
public afterLogin(fn: AuthHookFunction) {
this.config.afterLogin = fn
return this
}
public beforeRegister(fn: AuthHookFunction) {
this.config.beforeRegister = fn
return this
}
public afterRegister(fn: AuthHookFunction) {
this.config.afterRegister = fn
return this
}
public beforePasswordReset(fn: AuthHookFunction) {
this.config.beforePasswordReset = fn
return this
}
public afterPasswordReset(fn: AuthHookFunction) {
this.config.afterPasswordReset = fn
return this
}
public user(name: string) {
this.config.userResource = name
return this
}
public verifyEmails() {
this.config.verifyEmails = true
return this
}
public configureTokens(config: Partial<AuthPluginConfig['tokensConfig']>) {
this.config.tokensConfig = {
...this.config.tokensConfig,
...config
}
return this
}
public apiPath(path: string) {
this.config.apiPath = path
return this
}
public fields(fields: AuthPluginConfig['fields']) {
this.config.fields = fields
return this
}
public twoFactorAuth() {
this.TwoFactorAuth = require('@tensei/two-factor-auth')
this.config.twoFactorAuth = true
return this
}
public token(name: string) {
this.config.tokenResource = name
return this
}
public teams() {
this.config.teams = true
this.teamsInstance = new Teams(this)
return this
}
public teamPermissions(permissions: PermissionContract[]) {
this.config.teamPermissions = [
...this.config.teamPermissions,
...permissions
]
return this
}
public roles(roles: RoleContract[]) {
this.config.roles = roles
return this
}
private userResource() {
let passwordField = password('Password')
let socialFields: FieldContract[] = []
let teamFields: FieldContract[] = []
if (Object.keys(this.config.providers).length === 0) {
passwordField = passwordField.notNullable()
} else {
socialFields = [
hasMany(this.__resources.oauthIdentity.data.name)
.hideOnCreateApi()
.hideOnUpdateApi()
]
passwordField = passwordField.nullable()
}
if (this.config.teams) {
teamFields = [
hasOne(this.config.teamResource, 'currentTeam')
.label(`Current ${this.config.teamResource}`)
.nullable(),
hasMany(this.config.teamResource, 'ownTeams')
]
}
const userResource = resource(this.config.userResource)
.canUpdate(({ authUser, params, body, isGraphqlRequest }) => {
if (!authUser) {
return false
}
if (isGraphqlRequest) {
return authUser.id.toString() === body.id
}
return (params?.id as string) === authUser.id.toString()
})
.fields([
array('Roles')
.default([])
.of('string')
.type('[RoleString!]')
.arrayRules(
'required',
`in:${this.config.roles.map(role => role.config.slug).join(',')}`
)
.nullable(),
text('Email')
.unique()
.searchable()
.notNullable()
.creationRules('required', 'email', 'unique:email'),
passwordField
.hidden()
.htmlAttributes({
type: 'password'
})
.creationRules('required')
.onlyOnForms()
.hideOnUpdateApi(),
array('All Roles')
.type('[Role]')
.virtual(function (this: any) {
return this.getAllRoles().map((role: RoleContract) => ({
slug: role.config.slug,
name: role.config.name,
description: role.config.description,
permissions: role.config.permissions.map(permission => ({
name: permission.config.name,
slug: permission.config.slug,
description: permission.config.description
}))
}))
}),
array('All Permissions')
.type('[Permission]')
.virtual(function (this: any) {
return this.getAllPermissions().map(
(permission: PermissionContract) => ({
slug: permission.config.slug,
name: permission.config.name,
description: permission.config.description
})
)
}),
boolean('Blocked')
.nullable()
.default(false)
.trueLabel('No')
.falseLabel('Yes')
.positiveValues(['false', false])
.defaultFormValue(false)
.hideOnApi(),
...socialFields,
...teamFields,
...(this.config.twoFactorAuth
? [
boolean('Two Factor Enabled')
.hideOnCreate()
.hideOnUpdate()
.hideOnCreateApi()
.hideOnUpdateApi()
.nullable(),
text('Two Factor Secret')
.hidden()
.hideOnApi()
.hideOnDetail()
.hideOnIndex()
.hideOnCreate()
.hideOnUpdate()
.nullable()
]
: []),
...this.config.fields,
...(this.config.verifyEmails
? [
timestamp('Email Verified At')
.hideOnIndex()
.hideOnDetail()
.hideOnCreateApi()
.hideOnUpdateApi()
.nullable(),
text('Email Verification Token')
.hidden()
.nullable()
.hideOnApi()
.hideOnCreate()
.hideOnIndex()
.hideOnUpdate()
.hideOnDetail()
]
: [])
])
.hideOnFetchApi()
.hideOnDeleteApi()
.beforeCreate(async ({ entity, em }) => {
const payload: DataPayload = {
password: entity.password
? Bcrypt.hashSync(entity.password)
: undefined
}
if (this.config.verifyEmails) {
if (!entity.emailVerifiedAt) {
payload.emailVerifiedAt = null
}
payload.emailVerificationToken = this.generateRandomToken(72)
}
em.assign(entity, payload)
})
.beforeCreate(async ({ entity, em }, ctx) => {
if (this.socialAuthEnabled() && ctx.request?.body?.object?.extra) {
em.assign(entity, ctx.request.body.object.extra)
}
})
.beforeUpdate(async ({ entity, em, changeSet }) => {
if (changeSet?.payload.password) {
em.assign(entity, {
password: Bcrypt.hashSync(changeSet.payload.password)
})
}
})
.icon('database-manager')
.group('Authentication')
if (this.config.teams) {
this.teamsInstance.defineUserResourceMethods(userResource)
}
// Roles and permissions methods.
userResource.method(
'hasRole',
function (this: any, roleNameOrSlug: string) {
const roles: RoleContract[] = this.getAllRoles()
return [
...roles.map(role => role.config.name),
...roles.map(role => role.config.slug)
].includes(roleNameOrSlug)
}
)
userResource.method(
'hasPermission',
function (this: any, permissionNameOrSlug: string) {
const permissions: PermissionContract[] = this.getAllPermissions()
return [
...permissions.map(permission => permission.config.name),
...permissions.map(permission => permission.config.slug)
].includes(permissionNameOrSlug)
}
)
const self = this
userResource.method(
'assignRole',
async function (this: any, roleNameOrSlug: string) {
// check if role actually exists
const role = self.config.roles.find(r =>
[r.config.name, r.config.slug].includes(roleNameOrSlug)
)
if (!role) {
throw new Error(`Role ${roleNameOrSlug} does not exist.`)
}
const roles: RoleContract[] = this.getAllRoles()
// check if already has role
const hasRole = roles.find(r =>
[r.config.name, r.config.slug].includes(roleNameOrSlug)
)
if (hasRole) {
return
}
// persist role for user
const { manager } = this.ctx
manager.assign(this, {
roles: [...roles.map(role => role.config.slug), role.config.slug]
})
await manager.persistAndFlush(this)
}
)
userResource.method(
'removeRole',
async function (this: any, roleNameOrSlug: string) {
// check if role actually exists
const role = self.config.roles.find(r =>
[r.config.name, r.config.slug].includes(roleNameOrSlug)
)
if (!role) {
throw new Error(`Role ${role} does not exist.`)
}
const roles: RoleContract[] = this.getAllRoles()
// check if already has role
const hasRole = roles.find(r =>
[r.config.name, r.config.slug].includes(roleNameOrSlug)
)
if (!hasRole) {
return
}
const { manager } = this.ctx
manager.assign(this, {
roles: roles
.filter(
role =>
![role.config.name, role.config.slug].includes(roleNameOrSlug)
)
.map(role => role.config.slug)
})
await manager.persistAndFlush(this)
}
)
userResource.method('getAllPermissions', function (this: any) {
const roles = this.getAllRoles()
return (roles.reduce(
(permissions: PermissionContract[], role: RoleContract) => [
...permissions,
...role.config.permissions
],
[]
) as PermissionContract[]).filter(
(permission, idx: number, items) =>
items.findIndex(t => t.config.slug === permission.config.slug) === idx
)
})
userResource.method('getAllRoles', function (this: any) {
return ((this.roles || []).map((role: string) =>
self.config.roles.find(r =>
[r.config.name, r.config.slug].includes(role)
)
) as RoleContract[])
.filter(Boolean)
.filter(
(role, idx: number, items) =>
items.findIndex(t => t.config.slug === role.config.slug) === idx
)
})
return userResource
}
private tokenResource() {
const tokenTypes = []
if (this.config.enableRefreshTokens) {
tokenTypes.push({
label: 'Refresh Token',
value: TokenTypes.REFRESH
})
}
return resource(this.config.tokenResource)
.fields([
text('Token').notNullable().hidden().searchable().unique(),
text('Name').searchable().nullable(),
select('Type').options(tokenTypes).searchable().nullable(),
dateTime('Last Used At').nullable(),
dateTime('Compromised At').nullable(),
dateTime('Expires At').hidden(),
belongsTo(this.config.userResource).nullable()
])
.hideFromNavigation()
.hideOnApi()
}
private passwordResetResource() {
return resource(this.config.passwordResetResource)
.hideFromNavigation()
.fields([
text('Email').searchable().unique().notNullable(),
text('Token').unique().notNullable().hidden(),
dateTime('Expires At')
])
.hideOnApi()
}
private oauthResource() {
return resource('Oauth Identity')
.hideFromNavigation()
.fields([
belongsTo(this.config.userResource).nullable(),
textarea('Access Token').hidden().hideOnApi(),
text('Email').hidden().hideOnApi(),
textarea('Temporal Token').nullable().hidden().hideOnApi(),
json('Payload').hidden().hideOnApi(),
text('Provider').rules('required'),
text('Provider User ID').hidden().hideOnApi()
])
.hideFromNavigation()
.hideOnApi()
}
private forceRemoveInsertUserQueries(queries: GraphQlQueryContract[]) {
const insert_user_index = queries.findIndex(
q => q.config.path === `create${this.__resources.user.data.camelCaseName}`
)
if (insert_user_index !== -1) {
queries.splice(insert_user_index, 1)
}
const insert_users_index = queries.findIndex(
q =>
q.config.path ===
`createMany${this.__resources.user.data.camelCaseNamePlural}`
)
if (insert_users_index !== -1) {
queries.splice(insert_users_index, 1)
}
}
public excludePathsFromCsrf(paths: string[]) {
this.config.excludedPathsFromCsrf = paths
return this
}
public noAutofillUser() {
this.config.autoFillUser = false
return this
}
public noAutoFilters() {
this.config.autoFilterForUser = false
return this
}
private registerAutofillUserHooks(resources: ResourceContract[]) {
resources
.filter(
resource =>
resource.data.fields.find(
field =>
field.relatedProperty.reference === ReferenceType.MANY_TO_ONE &&
field.relatedProperty.type === this.config.userResource
) && resource.data.enableAutoFills
)
.forEach(resource => {
resource.beforeCreate(({ entity, em }, { request }) => {
if (request.authUser && request.authUser.id) {
em.assign(entity, {
user: request.authUser.id
})
}
})
})
}
private registerAutoFilterUserHooks(resources: ResourceContract[]) {
resources
.filter(
resource =>
resource.data.fields.find(
field =>
field.relatedProperty.reference === ReferenceType.MANY_TO_ONE &&
field.relatedProperty.type === this.config.userResource
) && resource.data.enableAutoFilters
)
.forEach(resource => {
resource.filters([
filter(`${this.__resources.user.data.label} ${resource.data.label}`)
.default()
.noArgs()
.query((args, request) =>
request.authUser && request.authUser.id
? {
[this.__resources.user.data.camelCaseName]:
request.authUser.id
}
: resource.data.noTimestamps
? false
: {
createdAt: Dayjs().add(1, 'month').toDate()
}
)
])
})
}
public plugin() {
return plugin('Auth')
.extra(this.config)
.register(
({
gql,
resources,
currentCtx,
extendRoutes,
databaseConfig,
extendResources,
extendGraphQlTypeDefs,
extendGraphQlQueries
}) => {
this.refreshResources()
extendResources([
this.__resources.user,
this.__resources.passwordReset
])
if (this.config.teams) {
extendResources([
this.__resources.team,
this.__resources.membership
])
}
if (this.config.enableRefreshTokens) {
extendResources([this.__resources.token])
}
if (Object.keys(this.config.providers).length > 0) {
extendResources([this.__resources.oauthIdentity])
}
if (this.socialAuthEnabled() || this.config.httpOnlyCookiesAuth) {
databaseConfig.entities = [
...(databaseConfig.entities || []),
require('express-session-mikro-orm').generateSessionEntity({
entityName: `${this.__resources.user.data.pascalCaseName}Session`,
tableName: `${this.__resources.user.data.camelCaseNamePlural}_sessions`,
collection: `${this.__resources.user.data.camelCaseNamePlural}_sessions`
})
]
}
extendGraphQlTypeDefs([this.extendGraphQLTypeDefs(gql)])
extendGraphQlQueries(
this.extendGraphQlQueries(
(currentCtx()
.resources as unknown) as ResourceContract<'graphql'>[]
)
)
extendRoutes(this.extendRoutes())
if (this.config.teams) {
extendGraphQlTypeDefs([this.teamsInstance.types(gql)])
extendGraphQlQueries(
this.teamsInstance.queries(currentCtx().resources)
)
}
if (this.config.roles.length) {
extendGraphQlQueries([
graphQlQuery('RoleString')
.custom()
.path('RoleString')
.handle(() =>
this.config.roles.reduce(
(values, role) => ({
...values,
[role.formatForEnum()]: role.config.slug
}),
{}
)
)
])
}
if (this.config.autoFillUser) {
this.registerAutofillUserHooks(currentCtx().resources)
}
if (this.config.autoFilterForUser) {
this.registerAutoFilterUserHooks(currentCtx().resources)
}
}
)
.boot(async config => {
this.refreshResources()
this.resolveApiPath(config.plugins)
if (this.config.twoFactorAuth) {
config.app.use((request, response, next) => {
request.verifyTwoFactorAuthToken = (token: string | number) =>
this.TwoFactorAuth.verifyTwoFactorAuthToken(request, token)
next()
})
}
const {
app,
serverUrl,
clientUrl,
currentCtx,
routes,
setPluginConfig
} = config
this.forceRemoveInsertUserQueries(config.graphQlQueries)
setPluginConfig('auth', {
user: this.__resources.user.serialize()
})
if (this.config.httpOnlyCookiesAuth) {
const excludedRoutes = routes.filter(route => !route.config.csrf)
this.config.excludedPathsFromCsrf = [
...this.config.excludedPathsFromCsrf,
...excludedRoutes.map(route => route.config.path)
]
require('@tensei/cookie-sessions').register({
app,
excludedPaths: this.config.excludedPathsFromCsrf
})
}
if (this.config.httpOnlyCookiesAuth || this.socialAuthEnabled()) {
const ExpressSession = require('express-session')
const ExpressSessionMikroORMStore = require('express-session-mikro-orm')
.default
const Store = ExpressSessionMikroORMStore(ExpressSession, {
entityName: `${this.__resources.user.data.pascalCaseName}Session`,
tableName: `${this.__resources.user.data.camelCaseNamePlural}_sessions`,
collection: `${this.__resources.user.data.camelCaseNamePlural}_sessions`
})
app.use(
ExpressSession({
store: new Store({
orm: config.orm
}) as any,
resave: false,
saveUninitialized: false,
cookie: this.config.cookieOptions,
secret: process.env.SESSION_SECRET || '__sessions__secret__'
})
)
}
if (this.socialAuthEnabled()) {
const { register } = require('@tensei/social-auth')
register({
app,
clientUrl,
serverUrl,
orm: config.orm,
authConfig: this.config,
resourcesMap: this.__resources,
apiPath: this.config.apiPath,
getUserPayloadFromProviderData: this.config
.getUserPayloadFromProviderData
})
}
currentCtx().graphQlQueries.forEach(query => {
query.config.middleware = [
async (resolve, parent, args, context, info) => {
await this.getAuthUserFromContext(context)
await this.getCurrentTeamFromContext(
context,
currentCtx().plugins
)
await this.ensureAuthUserIsNotBlocked(context)
return resolve(parent, args, context, info)
},
...query.config.middleware
]
})
currentCtx().routes.forEach(route => {
route.config.middleware = [
async (request, response, next) => {
await this.getAuthUserFromContext(request as any)
await this.getCurrentTeamFromContext(
request as any,
currentCtx().plugins
)
await this.ensureAuthUserIsNotBlocked(request as any)
return next()
},
...route.config.middleware
]
})
})
}
private extendRoutes() {
const name = this.__resources.user.data.slugSingular
return [
route(`Login ${name}`)
.group('Auth')
.path(this.__getApiPath('login'))
.id(this.getRouteId(`login_${name}`))
.post()
.description(`Login an existing ${name}.`)
.parameters([
{
in: 'body',
validation: ['required', 'email'],
description: `The email of the ${name}`,
name: 'email',
type: 'string'
},
{
in: 'body',
validation: ['required'],
description: `The password of the ${name}`,
name: 'password',
type: 'string'
}
])
.handle(async (request, { formatter: { ok } }) =>
ok(await this.login(request as any))
),
...(this.config.httpOnlyCookiesAuth
? [
route(`Logout ${name}`)
.group('Auth')
.path(this.__getApiPath('logout'))
.id(this.getRouteId(`logout_${name}`))
.post()
.description(`Logout a currently logged in ${name}.`)
.handle(async (request, { formatter: { noContent } }) => {
noContent(await this.logout(request as any))
})
]
: []),
route(`Register ${name}`)
.path(this.__getApiPath('register'))
.description(`Register a new ${name}`)
.group('Auth')
.post()
.parameters([
{
in: 'body',
validation: ['required', 'email'],
description: `The email of the ${name}`,
name: 'email',
type: 'string'
},
{
in: 'body',
validation: ['required'],
description: `The password of the ${name}`,
name: 'password',
type: 'string'
}
])
.id(this.getRouteId(`register_${name}`))
.handle(async (request, { formatter: { created } }) => {
return created(await this.register(request as any))
}),
route(`Request password reset`)
.path(this.__getApiPath('passwords/email'))
.post()
.group('Auth')
.parameters([
{
in: 'body',
validation: ['required', 'email'],
description: `The email of the ${name}`,
name: 'email',
type: 'string'
}
])
.id(this.getRouteId(`request_password_reset_${name}`))
.description(
`Request a password reset for a ${name} using the ${name} email.`
)
.handle(async (request, response) =>
response.formatter.ok(await this.forgotPassword(request as any))
),
route(`Reset password`)
.path(this.__getApiPath('passwords/reset'))
.post()
.group('Auth')
.id(this.getRouteId(`reset_password_${name}`))
.description(`Reset a ${name} password using a password reset token.`)
.parameters([
{
in: 'body',
validation: ['required'],
description: `This token was sent to the ${name}'s email. Provide it here to reset the ${name}'s password.`,
name: 'token',
type: 'string'
},
{
in: 'body',
validation: ['required'],
description: `The password of the ${name}`,
name: 'password',
type: 'string'
}
])
.handle(async (request, response) =>
response.formatter.ok(await this.resetPassword(request as any))
),
...(this.config.twoFactorAuth
? [
route(`Enable Two Factor Auth`)
.path(this.__getApiPath('two-factor/enable'))
.post()
.group('Two Factor Auth')
.description(
`Enable two factor authentication for an existing ${name}.`
)
.authorize(({ authUser }) => !!authUser)
.handle(async (request, response) => {
const {
dataURL,
user
} = await this.TwoFactorAuth.enableTwoFactorAuth(request as any)
response.formatter.ok({
dataURL,
[this.__resources.user.data.camelCaseName]: user
})
}),
route(`Confirm Enable Two Factor Auth`)
.path(this.__getApiPath('two-factor/confirm'))
.post()
.group('Two Factor Auth')
.parameters([
{
in: 'body',
validation: ['required'],
description: `The two-factor code from the authentication application such as Google Authenticator ${name}`,
name: 'password',
type: 'string'
}
])
.description(
`This endpoint confirms enabling 2fa for an account. A previous call to /${this.config.apiPath}/two-factor/enable is required to generate a 2fa secret for the ${name}'s account.`
)
.authorize(({ authUser }) => !!authUser)
.handle(async (request, response) => {
const user = await this.TwoFactorAuth.confirmEnableTwoFactorAuth(
request as any
)
response.formatter.ok({
[this.__resources.user.data.camelCaseName]: user
})
}),
route(`Disable Two Factor Auth`)
.path(this.__getApiPath('two-factor/disable'))
.post()
.group('Two Factor Auth')
.parameters([
{
in: 'body',
validation: ['required'],
description: `The two-factor code from the authentication application such as Google Authenticator ${name}`,
name: 'password',
type: 'string'
}
])
.description(
`Disable two factor authentication for an existing ${name}.`
)
.authorize(({ authUser }) => !!authUser)
.handle(async (request, response) => {
const user = await this.TwoFactorAuth.disableTwoFactorAuth(
request as any
)
response.formatter.ok({
[this.__resources.user.data.camelCaseName]: user
})
})
]
: []),
route(`Get authenticated ${name}`)
.path(this.__getApiPath('me'))
.group('Auth')
.get()
.id(this.getRouteId(`get_authenticated_${name}`))
.authorize(({ authUser }) => !!authUser)
.description(
`Get the authenticated ${name} from a valid JWT or session.`
)
.handle(async ({ authUser }, { formatter: { ok } }) => ok(authUser)),
...(this.config.verifyEmails
? [
route(`Resend Verification email`)
.group('Verify Emails')
.path(this.__getApiPath('emails/verification/resend'))
.post()
.id(this.getRouteId(`resend_${name}_verification_email`))
.authorize(({ authUser }) => !!authUser)
.description(`Resend verification email to ${name} email.`)
.handle(async (request, response) =>
response.formatter.ok(
await this.resendVerificationEmail(request as any)
)
),
route(`Confirm ${name} email`)
.path(this.__getApiPath('emails/verification/confirm'))
.post()
.group('Verify Emails')
.authorize(({ authUser }) => !!authUser)
.parameters([
{
in: 'body',
validation: ['required'],
description: `This email confirmation token was sent to the ${name}'s email. Provide it here to confirm the ${name}'s email.`,
name: 'token',
type: 'string'
}
])
.id(this.getRouteId(`confirm_${name}_email`))
.description(
`Confirm ${name} email with email verification token.`
)
.handle(async (request, response) =>
response.formatter.ok(await this.confirmEmail(request as any))
)
]
: []),
...(this.socialAuthEnabled()
? this.config.separateSocialLoginAndRegister
? [
route(`Social Auth Login`)
.path(this.__getApiPath('social/login'))
.post()
.id('social_login')
.description(`Login a ${name} via a social provider.`)
.group('Social Auth')
.handle(async (request, response) =>
response.formatter.ok(
await this.socialAuth(request as any, 'login')
)
),
route(`Social Auth Register`)
.path(this.__getApiPath('social/register'))
.id('social_register')
.post()
.group('Social Auth')
.description(`Register a ${name} via a social provider.`)
.handle(async (request, response) =>
response.formatter.ok(
await this.socialAuth(request as any, 'register')
)
)
]
: [
route(`Social Auth Confirm`)
.path(this.__getApiPath(`social/confirm`))
.id('social_confirm')
.post()
.description(
`Confirm a ${name} (login or register) via a social provider. If this user is already registered, it'll login the user. If not, it'll register a new account for the user and login that user.`
)
.handle(async (request, response) =>
response.formatter.ok(await this.socialAuth(request as any))
)
]
: []),
...(this.config.enableRefreshTokens
? [
route('Refresh Token')
.path(this.__getApiPath('refresh-token'))
.get()
.group('Auth')
.id(this.getRouteId(`refreshToken_${name}`))
.handle(async (request, { formatter: { ok, unauthorized } }) => {
try {
return ok(await this.handleRefreshTokens(request as any))
} catch (error: any) {
return unauthorized({
message: error.message || 'Invalid refresh token.'
})
}
})
]
: []),
...(this.config.httpOnlyCookiesAuth
? [
route('Get CSRF Token')
.path(this.__getApiPath('csrf'))
.handle(async (request, { formatter: { noContent } }) =>
noContent([])
)
]
: []),
...(this.config.teams ? this.teamsInstance.routes() : [])
]
}
cookieOptions(cookieOptions: AuthPluginConfig['cookieOptions']) {
this.config.cookieOptions = {
...this.config.cookieOptions,
...cookieOptions
}
return this
}
private extendGraphQlQueries(resources: ResourceContract<'graphql'>[]) {
const name = this.__resources.user.data.camelCaseName
const pascalName = this.__resources.user.data.pascalCaseName
return [
graphQlQuery(`Login ${name}`)
.path('login')
.mutation()
.handle(async (_, args, ctx, info) => {
const payload = await this.login(ctx)
const { authUser } = ctx
await Utils.graphql.populateFromResolvedNodes(
resources,
ctx.manager,
ctx.databaseConfig.type!,
(this.__resources.user as unknown) as ResourceContract<'graphql'>,
Utils.graphql.getParsedInfo(info)[name]?.['fieldsByTypeName']?.[
pascalName
],
[authUser]
)
return {
...payload,
[this.__resources.user.data.camelCaseName]: authUser
}
}),
...(this.config.httpOnlyCookiesAuth
? [
graphQlQuery(`Logout ${name}`)
.path('logout')
.mutation()
.handle(async (_, args, ctx) => {
return true
})
]
: []),
graphQlQuery(`Register ${name}`)
.path('register')
.mutation()
.handle(async (_, args, ctx, info) => {
const payload = await this.register(ctx)
const { authUser } = ctx
await Utils.graphql.populateFromResolvedNodes(
resources,
ctx.manager,
ctx.databaseConfig.type!,
(this.__resources.user as unknown) as ResourceContract<'graphql'>,
Utils.graphql.getParsedInfo(info),
[authUser]
)
return {
...payload,
[this.__resources.user.data.camelCaseName]: authUser
}
}),
graphQlQuery(`Request ${name} password reset`)
.path('requestPasswordReset')
.mutation()
.handle(async (_, args, ctx, info) => this.forgotPassword(ctx)),
graphQlQuery(`Reset ${name} password`)
.path('resetPassword')
.mutation()
.handle(async (_, args, ctx, info) => this.resetPassword(ctx)),
graphQlQuery(
`Get authenticated ${this.__resources.user.data.camelCaseName}`
)
.path(`authenticated`)
.query()
.authorize(({ authUser }) => !!authUser)
.handle(async (_, args, ctx, info) => {
const { authUser } = ctx
await Utils.graphql.populateFromResolvedNodes(
resources,
ctx.manager,
ctx.databaseConfig.type!,
(this.__resources.user as unknown) as ResourceContract<'graphql'>,
Utils.graphql.getParsedInfo(info),
[authUser]
)
return authUser
}),
...(this.config.twoFactorAuth
? [
graphQlQuery(`Enable Two Factor Auth`)
.path('enableTwoFactorAuth')
.mutation()
.handle(async (_, args, ctx, info) =>
this.TwoFactorAuth.enableTwoFactorAuth(ctx)
)
.authorize(({ authUser }) => !!authUser),
graphQlQuery('Confirm Enable Two Factor Auth')
.path('confirmEnableTwoFactorAuth')
.mutation()
.handle(async (_, args, ctx, info) => {
await this.TwoFactorAuth.confirmEnableTwoFactorAuth(ctx)
const { authUser } = ctx
await Utils.graphql.populateFromResolvedNodes(
resources,
ctx.manager,
ctx.databaseConfig.type!,
(this.__resources
.user as unknown) as ResourceContract<'graphql'>,
Utils.graphql.getParsedInfo(info),
[authUser]
)
return authUser
})
.authorize(({ authUser }) => !!authUser),
graphQlQuery(`Disable Two Factor Auth`)
.path('disableTwoFactorAuth')
.mutation()
.handle(async (_, args, ctx, info) => {
await this.TwoFactorAuth.disableTwoFactorAuth(ctx)
const { authUser } = ctx
await Utils.graphql.populateFromResolvedNodes(
resources,
ctx.manager,
ctx.databaseConfig.type!,
(this.__resources
.user as unknown) as ResourceContract<'graphql'>,
Utils.graphql.getParsedInfo(info),
[authUser]
)
return authUser
})
.authorize(({ authUser }) => !!authUser)
]
: []),
...(this.config.verifyEmails
? [
graphQlQuery(`Confirm ${name} Email`)
.path('confirmEmail')
.mutation()
.handle(async (_, args, ctx, info) => {
await this.confirmEmail(ctx)
const { authUser } = ctx
await Utils.graphql.populateFromResolvedNodes(
resources,
ctx.manager,
ctx.databaseConfig.type!,
(this.__resources
.user as unknown) as ResourceContract<'graphql'>,
Utils.graphql.getParsedInfo(info),
[authUser]
)
return authUser
})
.authorize(({ authUser }) => !!authUser),
graphQlQuery(`Resend ${name} Verification Email`)
.path('resendVerificationEmail')
.mutation()
.handle(async (_, args, ctx, info) =>
this.resendVerificationEmail(ctx)
)
]
: []),
...(this.socialAuthEnabled()
? this.config.separateSocialLoginAndRegister
? [
graphQlQuery('Social auth login')
.path('socialAuthLogin')
.mutation()
.handle(async (_, args, ctx, info) => {
const payload = await this.socialAuth(ctx, 'login')
const { authUser } = ctx
await Utils.graphql.populateFromResolvedNodes(
resources,
ctx.manager,
ctx.databaseConfig.type!,
(this.__resources
.user as unknown) as ResourceContract<'graphql'>,
Utils.graphql.getParsedInfo(info),
[authUser]
)
return {
...payload,
[this.__resources.user.data.camelCaseName]: authUser
}
}),
graphQlQuery('Social auth register')
.path('socialAuthRegister')
.mutation()
.handle(async (_, args, ctx, info) => {
const payload = await this.socialAuth(ctx, 'register')
const { authUser } = ctx
await Utils.graphql.populateFromResolvedNodes(
resources,
ctx.manager,
ctx.databaseConfig.type!,
(this.__resources
.user as unknown) as ResourceContract<'graphql'>,
Utils.graphql.getParsedInfo(info),
[authUser]
)
return {
...payload,
[this.__resources.user.data.camelCaseName]: authUser
}
})
]
: [
graphQlQuery('Social auth confirm')
.path('socialAuthConfirm')
.mutation()
.handle(async (_, args, ctx, info) => {
const payload = await this.socialAuth(ctx)
const { authUser } = ctx
await Utils.graphql.populateFromResolvedNodes(
resources,
ctx.manager,
ctx.databaseConfig.type!,
(this.__resources
.user as unknown) as ResourceContract<'graphql'>,
Utils.graphql.getParsedInfo(info),
[authUser]
)
return {
...payload,
[this.__resources.user.data.camelCaseName]: authUser
}
})
]
: []),
...(this.config.enableRefreshTokens
? [
graphQlQuery('Refresh token')
.path('refreshToken')
.mutation()
.handle(async (_, args, ctx, info) =>
this.handleRefreshTokens(ctx)
)
]
: []),
...(this.config.httpOnlyCookiesAuth
? [
graphQlQuery('Get CSRF Token')
.path(`csrfToken`)
.query()
.handle(async (_, args, ctx, info) => {
ctx.res.cookie(
'xsrf-token',
// @ts-ignore
ctx.req.csrfToken()
)
return true
})
]
: [])
]
}
private async handleRefreshTokens(ctx: ApiContext) {
if (!this.config.enableRefreshTokens) {
return undefined
}
if (this.config.httpOnlyCookiesAuth) {
return undefined
}
const { body } = ctx
const userField = this.__resources.user.data.camelCaseName
const tokenName = this.__resources.token.data.pascalCaseName
const refreshToken =
ctx.req.headers[this.config.refreshTokenHeaderName] ||
(body
? body.object
? body.object.refreshToken
: body.refreshToken
: undefined)
if (!refreshToken) {
throw ctx.authenticationError('Invalid refresh token.')
}
const token: any = await ctx.manager.findOne(
tokenName,
{
token: refreshToken,
type: TokenTypes.REFRESH
},
{
populate: [userField]
}
)
if (!token) {
throw ctx.authenticationError('Invalid refresh token.')
}
if (token.lastUsedAt) {
// This token has been used before.
// We'll block the user's access to the API by marking this refresh token as compromised.
// Human interaction is required to lift this limit, something like deleting the compromised tokens.
ctx.manager.assign(token, {
compromised_at: Dayjs().format()
})
ctx.manager.assign(token[userField], {
blocked: true
})
ctx.manager.persist(token)
ctx.manager.persist(token[userField])
await ctx.manager.flush()
throw ctx.authenticationError('Invalid refresh token.')
}
if (!token[userField] || Dayjs(token.expiresOn).isBefore(Dayjs())) {
token && (await ctx.manager.removeAndFlush(token))
throw ctx.authenticationError('Invalid refresh token.')
}
ctx.manager.assign(token, {
lastUsedAt: Dayjs().format(),
expiresAt: Dayjs().subtract(1, 'second').format()
})
await ctx.manager.persistAndFlush(token)
// TODO: Delete all refresh tokens older than a 24 hours. This will be custom and calculated in future.
ctx.authUser = token[userField]
return this.getUserPayload(
ctx,
await this.generateRefreshToken(ctx, token.expiresOn)
)
}
private getUserPayload(ctx: ApiContext, refreshToken?: string) {
let userPayload: any = {
[this.__resources.user.data.camelCaseName]: ctx.authUser
}
if (!this.config.httpOnlyCookiesAuth) {
userPayload.accessToken = this.generateJwt({
id: ctx.authUser.id
})
userPayload.expiresIn = this.config.tokensConfig.accessTokenExpiresIn
}
if (this.config.enableRefreshTokens) {
userPayload.refreshToken = refreshToken
}
if (this.config.httpOnlyCookiesAuth) {
if (ctx.req) {
ctx.req.session.user = {
id: ctx.authUser.id
}
} else {
// @ts-ignore
ctx.session.user = {
id: ctx.authUser.id
}
}
}
return userPayload
}
private extendGraphQLTypeDefs(gql: any) {
const { camelCaseName, pascalCaseName } = this.__resources.user.data
const cookies = this.config.httpOnlyCookiesAuth
return gql`
type RegisterResponse {
${
cookies
? ''
: `
accessToken: String!
${this.config.enableRefreshTokens ? 'refreshToken: String!' : ''}
expiresIn: Int!
`
}
${camelCaseName}: ${pascalCaseName}!
}
enum RoleString {
${this.config.roles.map(role => role.formatForEnum())}
${this.config.roles.length === 0 ? 'NOOB' : ''}
}
type Permission {
name: String
slug: String
description: String
}
type Role {
name: String
slug: String
description: String
permissions: [Permission]
}
type LoginResponse {
${
cookies
? ''
: `
accessToken: String!
${this.config.enableRefreshTokens ? 'refreshToken: String!' : ''}
expiresIn: Int!
`
}
${camelCaseName}: ${pascalCaseName}!
}
input LoginInput {
email: String!
password: String!
twoFactorToken: String
}
input RequestPasswordResetInput {
email: String!
}
input ResetPasswordInput {
email: String!
""" The reset password token sent to ${camelCaseName}'s email """
token: String!
password: String!
}
${
this.config.twoFactorAuth
? `
type EnableTwoFactorAuthResponse {
""" The data url for the qr code. Display this in an <img /> tag to be scanned on the authenticator app """
dataURL: String!
}
input ConfirmEnableTwoFactorAuthInput {
""" The two factor auth token from the ${camelCaseName}'s authenticator app """
token: String!
}
input DisableTwoFactorAuthInput {
""" The two factor auth token from the ${camelCaseName}'s authenticator app """
token: Int!
}
`
: ''
}
${
this.config.verifyEmails
? `
input ConfirmEmailInput {
""" The email verification token sent to the ${camelCaseName}'s email """
emailVerificationToken: String!
}
`
: ''
}
${
this.socialAuthEnabled()
? this.config.separateSocialLoginAndRegister
? `
input SocialAuthRegisterInput {
""" The temporal access token received in query parameter when user is redirected """
accessToken: String!
extra: JSONObject
}
input SocialAuthLoginInput {
""" The temporal access token received in query parameter when user is redirected """
accessToken: String!
}
`
: `
input SocialAuthConfirm {
""" The temporal access token received in query parameter when user is redirected """
accessToken: String!
}
`
: ''
}
extend input Create${pascalCaseName}Input {
password: String!
}
${
this.config.enableRefreshTokens
? `
input RefreshTokenInput {
refreshToken: String
}
`
: ''
}
extend type Mutation {
login(object: LoginInput!): LoginResponse!
${
cookies
? `
logout: Boolean!
`
: ''
}
register(object: Create${pascalCaseName}Input!): RegisterResponse!
requestPasswordReset(object: RequestPasswordResetInput!): Boolean!
resetPassword(object: ResetPasswordInput!): Boolean!
${
this.config.twoFactorAuth
? `
enableTwoFactorAuth: EnableTwoFactorAuthResponse!
disableTwoFactorAuth(object: DisableTwoFactorAuthInput!): ${pascalCaseName}!
confirmEnableTwoFactorAuth(object: ConfirmEnableTwoFactorAuthInput!): ${pascalCaseName}!
`
: ''
}
${
this.config.verifyEmails
? `
confirmEmail(object: ConfirmEmailInput!): ${pascalCaseName}!
resendVerificationEmail: Boolean
`
: ''
}
${
this.socialAuthEnabled()
? this.config.separateSocialLoginAndRegister
? `
socialAuthRegister(object: SocialAuthRegisterInput!): RegisterResponse!
socialAuthLogin(object: SocialAuthLoginInput!): LoginResponse!
`
: `
socialAuthConfirm(object: SocialAuthConfirm): LoginResponse!
`
: ''
}
${
this.config.enableRefreshTokens
? `
refreshToken(object: RefreshTokenInput): LoginResponse!
`
: ''
}
}
extend type Query {
authenticated: ${pascalCaseName}!
}
`
}
private socialAuthEnabled() {
return Object.keys(this.config.providers).length > 0
}
__getApiPath(path: string) {
return `/${this.config.apiPath}/${path}`
}
private getRouteId(id: string) {
return this.config.prefix ? `${this.config.prefix}_${id}` : id
}
prefix(prefix: string) {
this.config.prefix = prefix
return this
}
private register = async (ctx: ApiContext) => {
const { manager, body, emitter } = ctx
const validator = Utils.validator(
this.__resources.user,
ctx.manager,
ctx.req.resources
)
let [success, createUserPayload] = await validator.validate(
body.object ? body.object : body
)
if (!success) {
throw ctx.userInputError('Validation failed.', {
errors: createUserPayload
})
}
const UserResource = this.__resources.user
await this.config.beforeRegister(ctx, createUserPayload)
const user: any = manager.create(
UserResource.data.pascalCaseName,
createUserPayload
)
let currentTeam = null
const toPersist = [user]
if (this.config.teams) {
// Create a new team
currentTeam = manager.create(this.config.teamResource, {
name: 'Personal',
owner: user
})
user.currentTeam = currentTeam
toPersist.push(currentTeam)
}
await manager.persistAndFlush(toPersist)
const populates = []
if (this.config.teams) {
populates.push('currentTeam')
}
await manager.populate([user], populates)
ctx.authUser = user
await this.config.afterRegister(ctx, user)
emitter.emit(USER_EVENTS.REGISTERED, user)
return this.getUserPayload(ctx, await this.generateRefreshToken(ctx))
}
private resendVerificationEmail = async ({
manager,
authUser,
emitter
}: ApiContext) => {
if (!authUser.emailVerificationToken) {
return false
}
manager.assign(authUser, {
emailVerificationToken: this.generateRandomToken(72)
})
await manager.persistAndFlush(authUser)
emitter.emit(USER_EVENTS.RESENT_VERIFICATION_EMAIL, authUser)
return true
}
private confirmEmail = async (ctx: ApiContext) => {
const { manager, body, authUser } = ctx
if (
authUser.emailVerificationToken ===
(body.object
? body.object.emailVerificationToken
: body.emailVerificationToken)
) {
manager.assign(authUser, {
emailVerificationToken: null,
emailVerifiedAt: Dayjs().format()
})
await manager.persistAndFlush(authUser)
ctx.emitter.emit(USER_EVENTS.VERIFIED_EMAIL, authUser)
return authUser.toJSON()
}
throw ctx.userInputError('Invalid email verification token.')
}
public getUserPayloadFromProviderData(
getUserPayloadFromProviderData: AuthPluginConfig['getUserPayloadFromProviderData']
) {
this.config.getUserPayloadFromProviderData = getUserPayloadFromProviderData
return this
}
private socialAuth = async (
ctx: ApiContext,
action?: 'login' | 'register'
) => {
const { body, manager } = ctx
const accessToken = body.object ? body.object.accessToken : body.accessToken
if (!accessToken) {
throw ctx.userInputError('Validation failed.', {
errors: [
{
field: 'accessToken',
message: 'Invalid access token provided.'
}
]
})
}
let oauthIdentity: any = await manager.findOne(
this.__resources.oauthIdentity.data.pascalCaseName,
{
temporalToken: accessToken
}
)
if (!oauthIdentity) {
throw ctx.userInputError('Validation failed.', {
errors: [
{
field: 'accessToken',
message: 'Invalid access token provided.'
}
]
})
}
const oauthPayload = JSON.parse(oauthIdentity.payload)
let user: any = await manager.findOne(
this.__resources.user.data.pascalCaseName,
{
email: oauthPayload.email
}
)
if (
!user &&
action === 'login' &&
this.config.separateSocialLoginAndRegister
) {
throw ctx.userInputError('Validation failed.', {
errors: [
{
field: 'email',
message: 'Cannot find a user with these credentials.'
}
]
})
}
if (
user &&
action === 'register' &&
this.config.separateSocialLoginAndRegister
) {
throw ctx.userInputError('Validation failed.', {
errors: [
{
field: 'email',
message: `A ${this.__resources.user.data.camelCaseName.toLowerCase()} already exists with email ${
oauthIdentity.email
}.`
}
]
})
}
if (
!user &&
(action === 'register' || !this.config.separateSocialLoginAndRegister)
) {
let createPayload: DataPayload = {
...oauthPayload
}
if (this.config.verifyEmails) {
createPayload.emailVerifiedAt = Dayjs().format()
createPayload.emailVerificationToken = null
}
await this.config.beforeRegister(ctx, createPayload as any)
user = manager.create(
this.__resources.user.data.pascalCaseName,
createPayload
)
await manager.persistAndFlush(user)
await this.config.afterRegister(ctx, user)
} else {
await this.config.beforeLogin(ctx, oauthPayload)
}
const belongsToField = this.__resources.oauthIdentity.data.fields.find(
field => field.name === this.__resources.user.data.pascalCaseName
)!
manager.assign(oauthIdentity, {
temporalToken: null,
[belongsToField.databaseField]: user.id
})
await manager.flush()
await this.config.afterLogin(ctx, user)
ctx.authUser = user
return this.getUserPayload(ctx, await this.generateRefreshToken(ctx))
}
private logout = async (ctx: ApiContext) => {
let request = (ctx.req ? ctx.req : ctx) as Request
return new Promise(resolve => {
request.session.destroy(error => {
if (error) {
return resolve(false)
}
ctx.res.clearCookie('connect.sid')
return resolve(true)
})
})
}
private login = async (ctx: ApiContext) => {
const { manager, body } = ctx
const [passed, payload] = await this.validate(
body.object ? body.object : body
)
if (!passed) {
throw ctx.userInputError('Validation failed.', {
errors: payload
})
}
const { email, password, two_factor_token } = payload
const user: any = await manager.findOne(
this.__resources.user.data.pascalCaseName,
{
email
}
)
if (!user) {
throw ctx.authenticationError('Invalid credentials.')
}
if (user.blocked) {
throw ctx.forbiddenError('Your account is temporarily disabled.')
}
if (!Bcrypt.compareSync(password, user.password)) {
throw ctx.authenticationError('Invalid credentials.')
}
await this.config.beforeLogin(ctx, user)
if (this.config.twoFactorAuth && user.two_factor_enabled) {
const Speakeasy = require('speakeasy')
if (!two_factor_token) {
throw ctx.userInputError(
'The two factor authentication token is required.',
{
twoFactorAuthRequired: true
}
)
}
const verified = Speakeasy.totp.verify({
token: two_factor_token,
encoding: 'base32',
secret: user.two_factor_secret
})
if (!verified) {
throw ctx.userInputError('Invalid two factor authentication token.')
}
}
ctx.authUser = user
await this.config.afterLogin(ctx, user)
return this.getUserPayload(ctx, await this.generateRefreshToken(ctx))
}
private ensureAuthUserIsNotBlocked = async (ctx: ApiContext) => {
if (!ctx.authUser) {
return
}
if (ctx.authUser.blocked) {
throw ctx.forbiddenError('Your account is temporarily disabled.')
}
}
private populateContextFromToken = async (
token: string | undefined,
ctx: ApiContext
) => {
const { manager } = ctx
try {
let id
if (!this.config.httpOnlyCookiesAuth) {
const payload = Jwt.verify(
token!,
this.config.tokensConfig.secretKey
) as JwtPayload
id = payload.id
} else {
id = ctx.req.session?.user?.id
}
if (!id) {
return
}
const populate = []
if (this.config.teams) {
populate.push('currentTeam')
}
const user: any = await manager.findOne(
this.__resources.user.data.pascalCaseName,
{
id
},
{
populate
}
)
ctx.authUser = user
} catch (error) {}
}
public getCurrentTeamFromContext = async (
ctx: ApiContext,
plugins: PluginContract[]
) => {
if (!this.config.teams) {
return
}
const { req, body } = ctx
const { headers, params } = req
let currentTeamId =
(headers['x-current-team'] as any) || params.team || body.teamId
if (
!currentTeamId &&
req.originalUrl.startsWith(
`/${this.resolveApiPath(plugins)}/${
this.__resources.team.data.slugPlural
}`
) &&
['GET', 'PATCH', 'PUT', 'DELETE'].includes(req.method)
) {
currentTeamId = params.id
}
if (!currentTeamId) {
return
}
const team = await (ctx.repositories as any).teams().findOne({
id: currentTeamId
})
if (!team) {
return
}
ctx.team = team
}
public getAuthUserFromContext = async (ctx: ApiContext) => {
const { req } = ctx
const { headers } = req
const [, token] = (headers['authorization'] || '').split('Bearer ')
return this.populateContextFromToken(token, ctx)
}
private validateForgotPassword = async (
payload: DataPayload
): Promise<[boolean, DataPayload]> => {
try {
const { email } = await validateAll(payload, {
email: 'required|email'
})
return [true, { email }]
} catch (errors: any) {
return [false, errors]
}
}
protected forgotPassword = async ({
body,
manager,
userInputError
}: ApiContext) => {
const [passed, payload] = await this.validateForgotPassword(
body.object ? body.object : body
)
if (!passed) {
throw userInputError('Validation failed.', {
errors: payload
})
}
const { email } = payload
const existingUser: any = await manager.findOne(
this.__resources.user.data.pascalCaseName,
{
email
}
)
const existingPasswordReset = await manager.findOne(
this.__resources.passwordReset.data.pascalCaseName,
{
email
}
)
if (!existingUser) {
throw userInputError('Validation failed.', {
errors: [
{
field: 'email',
message: 'Invalid email address.'
}
]
})
}
const token = this.generateRandomToken()
const expiresAt = Dayjs().add(1, 'hour').format('YYYY-MM-DD HH:mm:ss')
if (existingPasswordReset) {
// make sure it has not expired
manager.assign(existingPasswordReset, {
token,
expiresAt
})
manager.persist(existingPasswordReset)
} else {
manager.persist(
manager.create(this.__resources.passwordReset.data.pascalCaseName, {
email,
token,
expiresAt
})
)
}
await manager.flush()
return true
}
private validateResetPassword = async (
payload: DataPayload
): Promise<[boolean, DataPayload]> => {
try {
const { token, password } = await validateAll(payload, {
token: 'required|string',
password: 'required|string|min:8'
})
return [true, { token, password }]
} catch (errors: any) {
return [false, errors]
}
}
protected resetPassword = async ({
body,
manager,
userInputError
}: ApiContext) => {
const [passed, payload] = await this.validateResetPassword(
body.object ? body.object : body
)
if (!passed) {
throw userInputError('Validation failed.', {
errors: payload
})
}
const { token, password } = payload
let existingPasswordReset: any = await manager.findOne(
this.__resources.passwordReset.data.pascalCaseName,
{
token
}
)
if (!existingPasswordReset) {
throw userInputError('Validation failed.', {
errors: [
{
field: 'token',
message: 'Invalid reset token.'
}
]
})
}
if (Dayjs(existingPasswordReset.expiresAt).isBefore(Dayjs())) {
throw userInputError('Validation failed.', {
errors: [
{
field: 'token',
message: 'Invalid reset token.'
}
]
})
}
let user: any = await manager.findOne(
this.__resources.user.data.pascalCaseName,
{
email: existingPasswordReset.email
}
)
if (!user) {
manager.removeAndFlush(existingPasswordReset)
return false
}
manager.assign(user, {
password
})
manager.persist(user)
manager.remove(existingPasswordReset)
await manager.flush()
// TODO: Send an email to the user notifying them
// that their password was reset.
return true
}
protected validate = async (data: AuthData, registration = false) => {
let rules: {
[key: string]: string
} = {
email: 'required|email',
password: 'required|min:8',
two_factor_token: 'string|min:6|max:6'
}
try {
const payload = await validateAll(data, rules, {
'email.required': 'The email is required.',
'password.required': 'The password is required.'
})
return [true, payload]
} catch (errors) {
return [false, errors]
}
}
public async generateRefreshToken(
ctx: GraphQLPluginContext,
previousTokenExpiry?: string
): Promise<string | undefined> {
if (!this.config.enableRefreshTokens) {
return undefined
}
if (this.config.httpOnlyCookiesAuth) {
return undefined
}
const plainTextToken = this.generateRandomToken(64)
// Expire all existing refresh tokens for this user.
await ctx.manager.nativeUpdate(
this.__resources.token.data.pascalCaseName,
{
[this.__resources.user.data.camelCaseName]: ctx.authUser.id
} as any,
{
expiresAt: Dayjs().subtract(1, 'second').format(),
lastUsedAt: Dayjs().subtract(1, 'second').format()
}
)
const entity = ctx.manager.create(
this.__resources.token.data.pascalCaseName,
{
token: plainTextToken,
[this.__resources.user.data.camelCaseName]: ctx.authUser.id,
type: TokenTypes.REFRESH,
expiresAt: previousTokenExpiry
? previousTokenExpiry
: Dayjs()
.add(this.config.tokensConfig.refreshTokenExpiresIn, 'second')
.format()
}
)
await ctx.manager.persistAndFlush(entity)
// TODO:
// 1. Encrypt the token using application key
// 2. Create JWT with token as payload
// 3. Save Token to database.
// 4. To verify token, decode JWT
// 5. Decrypt token from JWT
// 6. Query the database for the refresh token
return plainTextToken
}
private generateJwt(payload: DataPayload) {
return Jwt.sign(payload, this.config.tokensConfig.secretKey, {
expiresIn: this.config.tokensConfig.accessTokenExpiresIn
})
}
public generateRandomToken(length = 32) {
return crypto.randomBytes(length).toString('hex')
}
public social(provider: SupportedSocialProviders, config: GrantConfig) {
this.config.providers[provider] = {
...config,
callback: config.callback
? config.callback
: `/${this.config.apiPath}/${provider}/callback`,
scope:
config.scope && config.scope.length > 0
? config.scope
: defaultProviderScopes(provider)
}
return this
}
}
export {
role,
permission,
PermissionConfig,
PermissionContract,
Role,
RoleConfig,
RoleContract
} from './teams/Permission'
export const auth = () => new Auth()
export { USER_EVENTS } from './config' | the_stack |
import { Link } from "@fluentui/react";
import * as React from "react";
import AddDatabaseIcon from "../../../images/AddDatabase.svg";
import NewQueryIcon from "../../../images/AddSqlQuery_16x16.svg";
import NewStoredProcedureIcon from "../../../images/AddStoredProcedure.svg";
import OpenQueryIcon from "../../../images/BrowseQuery.svg";
import NewContainerIcon from "../../../images/Hero-new-container.svg";
import NewNotebookIcon from "../../../images/Hero-new-notebook.svg";
import SampleIcon from "../../../images/Hero-sample.svg";
import NotebookIcon from "../../../images/notebook/Notebook-resource.svg";
import ScaleAndSettingsIcon from "../../../images/Scale_15x15.svg";
import CollectionIcon from "../../../images/tree-collection.svg";
import { AuthType } from "../../AuthType";
import * as Constants from "../../Common/Constants";
import * as ViewModels from "../../Contracts/ViewModels";
import { useSidePanel } from "../../hooks/useSidePanel";
import { userContext } from "../../UserContext";
import { getCollectionName, getDatabaseName } from "../../Utils/APITypeUtils";
import { FeaturePanelLauncher } from "../Controls/FeaturePanel/FeaturePanelLauncher";
import { DataSamplesUtil } from "../DataSamples/DataSamplesUtil";
import Explorer from "../Explorer";
import * as MostRecentActivity from "../MostRecentActivity/MostRecentActivity";
import { useNotebook } from "../Notebook/useNotebook";
import { AddDatabasePanel } from "../Panes/AddDatabasePanel/AddDatabasePanel";
import { BrowseQueriesPane } from "../Panes/BrowseQueriesPane/BrowseQueriesPane";
import { useDatabases } from "../useDatabases";
import { useSelectedNode } from "../useSelectedNode";
export interface SplashScreenItem {
iconSrc: string;
title: string;
info?: string;
description: string;
onClick: () => void;
}
export interface SplashScreenProps {
explorer: Explorer;
}
export class SplashScreen extends React.Component<SplashScreenProps> {
private static readonly seeMoreItemTitle: string = "See more Cosmos DB documentation";
private static readonly seeMoreItemUrl: string = "https://aka.ms/cosmosdbdocument";
private static readonly dataModelingUrl = "https://docs.microsoft.com/azure/cosmos-db/modeling-data";
private static readonly throughputEstimatorUrl = "https://cosmos.azure.com/capacitycalculator";
private static readonly failoverUrl = "https://docs.microsoft.com/azure/cosmos-db/high-availability";
private readonly container: Explorer;
private subscriptions: Array<{ dispose: () => void }>;
constructor(props: SplashScreenProps) {
super(props);
this.container = props.explorer;
this.subscriptions = [];
}
public componentWillUnmount() {
while (this.subscriptions.length) {
this.subscriptions.pop().dispose();
}
}
public componentDidMount() {
this.subscriptions.push(
{
dispose: useNotebook.subscribe(
() => this.setState({}),
(state) => state.isNotebookEnabled
),
},
{ dispose: useSelectedNode.subscribe(() => this.setState({})) }
);
}
private clearMostRecent = (): void => {
MostRecentActivity.mostRecentActivity.clear(userContext.databaseAccount?.id);
this.setState({});
};
public render(): JSX.Element {
const mainItems = this.createMainItems();
const commonTaskItems = this.createCommonTaskItems();
let recentItems = this.createRecentItems();
if (userContext.features.notebooksTemporarilyDown) {
recentItems = recentItems.filter((item) => item.description !== "Notebook");
}
const tipsItems = this.createTipsItems();
const onClearRecent = this.clearMostRecent;
const formContainer = (jsx: JSX.Element) => (
<div className="connectExplorerContainer">
<form className="connectExplorerFormContainer">{jsx}</form>
</div>
);
return formContainer(
<div className="splashScreenContainer">
<div className="splashScreen">
<div className="title">
Welcome to Cosmos DB
<FeaturePanelLauncher />
</div>
<div className="subtitle">Globally distributed, multi-model database service for any scale</div>
<div className="mainButtonsContainer">
{mainItems.map((item) => (
<div
className="mainButton focusable"
key={`${item.title}`}
onClick={item.onClick}
onKeyPress={(event: React.KeyboardEvent) => this.onSplashScreenItemKeyPress(event, item.onClick)}
tabIndex={0}
role="button"
>
<img src={item.iconSrc} alt="" />
<div className="legendContainer">
<div className="legend">{item.title}</div>
<div className="description">{item.description}</div>
</div>
</div>
))}
</div>
<div className="moreStuffContainer">
<div className="moreStuffColumn commonTasks">
<div className="title">Common Tasks</div>
<ul>
{commonTaskItems.map((item) => (
<li
className="focusable"
key={`${item.title}${item.description}`}
onClick={item.onClick}
onKeyPress={(event: React.KeyboardEvent) => this.onSplashScreenItemKeyPress(event, item.onClick)}
tabIndex={0}
role="button"
>
<img src={item.iconSrc} alt="" />
<span className="oneLineContent" title={item.info}>
{item.title}
</span>
</li>
))}
</ul>
</div>
<div className="moreStuffColumn">
<div className="title">Recents</div>
<ul>
{recentItems.map((item, index) => (
<li key={`${item.title}${item.description}${index}`}>
<img src={item.iconSrc} alt="" />
<span className="twoLineContent">
<Link onClick={item.onClick} title={item.info}>
{item.title}
</Link>
<div className="description">{item.description}</div>
</span>
</li>
))}
</ul>
{recentItems.length > 0 && <Link onClick={() => onClearRecent()}>Clear Recents</Link>}
</div>
<div className="moreStuffColumn tipsContainer">
<div className="title">Tips</div>
<ul>
{tipsItems.map((item) => (
<li
className="tipContainer focusable"
key={`${item.title}${item.description}`}
onClick={item.onClick}
onKeyPress={(event: React.KeyboardEvent) => this.onSplashScreenItemKeyPress(event, item.onClick)}
tabIndex={0}
role="link"
>
<div className="title" title={item.info}>
{item.title}
</div>
<div className="description">{item.description}</div>
</li>
))}
<li>
<a role="link" href={SplashScreen.seeMoreItemUrl} rel="noreferrer" target="_blank" tabIndex={0}>
{SplashScreen.seeMoreItemTitle}
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
);
}
/**
* This exists to enable unit testing
*/
public createDataSampleUtil(): DataSamplesUtil {
return new DataSamplesUtil(this.container);
}
/**
* public for testing purposes
*/
public createMainItems(): SplashScreenItem[] {
const dataSampleUtil = this.createDataSampleUtil();
const heroes: SplashScreenItem[] = [
{
iconSrc: NewContainerIcon,
title: `New ${getCollectionName()}`,
description: "Create a new container for storage and throughput",
onClick: () => this.container.onNewCollectionClicked(),
},
];
if (dataSampleUtil.isSampleContainerCreationSupported()) {
// Insert at the front
heroes.unshift({
iconSrc: SampleIcon,
title: "Start with Sample",
description: "Get started with a sample provided by Cosmos DB",
onClick: () => dataSampleUtil.createSampleContainerAsync(),
});
}
if (useNotebook.getState().isNotebookEnabled && !userContext.features.notebooksTemporarilyDown) {
heroes.push({
iconSrc: NewNotebookIcon,
title: "New Notebook",
description: "Create a notebook to start querying, visualizing, and modeling your data",
onClick: () => this.container.onNewNotebookClicked(),
});
}
return heroes;
}
private createCommonTaskItems(): SplashScreenItem[] {
const items: SplashScreenItem[] = [];
if (userContext.authType === AuthType.ResourceToken) {
return items;
}
if (!useSelectedNode.getState().isDatabaseNodeOrNoneSelected()) {
if (userContext.apiType === "SQL" || userContext.apiType === "Gremlin") {
items.push({
iconSrc: NewQueryIcon,
onClick: () => {
const selectedCollection: ViewModels.Collection = useSelectedNode.getState().findSelectedCollection();
selectedCollection && selectedCollection.onNewQueryClick(selectedCollection, undefined);
},
title: "New SQL Query",
description: undefined,
});
} else if (userContext.apiType === "Mongo") {
items.push({
iconSrc: NewQueryIcon,
onClick: () => {
const selectedCollection: ViewModels.Collection = useSelectedNode.getState().findSelectedCollection();
selectedCollection && selectedCollection.onNewMongoQueryClick(selectedCollection, undefined);
},
title: "New Query",
description: undefined,
});
}
if (userContext.apiType === "SQL") {
items.push({
iconSrc: OpenQueryIcon,
title: "Open Query",
description: undefined,
onClick: () =>
useSidePanel
.getState()
.openSidePanel("Open Saved Queries", <BrowseQueriesPane explorer={this.container} />),
});
}
if (userContext.apiType !== "Cassandra") {
items.push({
iconSrc: NewStoredProcedureIcon,
title: "New Stored Procedure",
description: undefined,
onClick: () => {
const selectedCollection: ViewModels.Collection = useSelectedNode.getState().findSelectedCollection();
selectedCollection && selectedCollection.onNewStoredProcedureClick(selectedCollection, undefined);
},
});
}
/* Scale & Settings */
const isShared = useDatabases.getState().findSelectedDatabase()?.isDatabaseShared();
const label = isShared ? "Settings" : "Scale & Settings";
items.push({
iconSrc: ScaleAndSettingsIcon,
title: label,
description: undefined,
onClick: () => {
const selectedCollection: ViewModels.Collection = useSelectedNode.getState().findSelectedCollection();
selectedCollection && selectedCollection.onSettingsClick();
},
});
} else {
items.push({
iconSrc: AddDatabaseIcon,
title: "New " + getDatabaseName(),
description: undefined,
onClick: () =>
useSidePanel
.getState()
.openSidePanel("New " + getDatabaseName(), <AddDatabasePanel explorer={this.container} />),
});
}
return items;
}
private decorateOpenCollectionActivity({ databaseId, collectionId }: MostRecentActivity.OpenCollectionItem) {
return {
iconSrc: NotebookIcon,
title: collectionId,
description: "Data",
onClick: () => {
const collection = useDatabases.getState().findCollection(databaseId, collectionId);
collection?.openTab();
},
};
}
private decorateOpenNotebookActivity({ name, path }: MostRecentActivity.OpenNotebookItem) {
return {
info: path,
iconSrc: CollectionIcon,
title: name,
description: "Notebook",
onClick: () => {
const notebookItem = this.container.createNotebookContentItemFile(name, path);
notebookItem && this.container.openNotebook(notebookItem);
},
};
}
private createRecentItems(): SplashScreenItem[] {
return MostRecentActivity.mostRecentActivity.getItems(userContext.databaseAccount?.id).map((activity) => {
switch (activity.type) {
default: {
const unknownActivity: never = activity;
throw new Error(`Unknown activity: ${unknownActivity}`);
}
case MostRecentActivity.Type.OpenNotebook:
return this.decorateOpenNotebookActivity(activity);
case MostRecentActivity.Type.OpenCollection:
return this.decorateOpenCollectionActivity(activity);
}
});
}
private createTipsItems(): SplashScreenItem[] {
return [
{
iconSrc: undefined,
title: "Data Modeling",
description: "Learn more about modeling",
onClick: () => window.open(SplashScreen.dataModelingUrl),
},
{
iconSrc: undefined,
title: "Cost & Throughput Calculation",
description: "Learn more about cost calculation",
onClick: () => window.open(SplashScreen.throughputEstimatorUrl),
},
{
iconSrc: undefined,
title: "Configure automatic failover",
description: "Learn more about Cosmos DB high-availability",
onClick: () => window.open(SplashScreen.failoverUrl),
},
];
}
private onSplashScreenItemKeyPress(event: React.KeyboardEvent, callback: () => void) {
if (event.charCode === Constants.KeyCodes.Space || event.charCode === Constants.KeyCodes.Enter) {
callback();
event.stopPropagation();
}
}
} | the_stack |
import React, { useEffect, useCallback, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import {
READ_POST,
SinglePost,
REMOVE_POST,
LIKE_POST,
UNLIKE_POST,
LinkedPost,
POST_VIEW,
} from '../../lib/graphql/post';
import PostHead from '../../components/post/PostHead';
import PostContent from '../../components/post/PostContent';
import PostComments from './PostComments';
import postSlice from '../../modules/post';
import PostViewerProvider from '../../components/post/PostViewerProvider';
import useUser, { useUserId } from '../../lib/hooks/useUser';
import { useQuery, useMutation, useApolloClient } from '@apollo/react-hooks';
import { withRouter, RouteComponentProps } from 'react-router-dom';
import { prepareEdit } from '../../modules/write';
import PostLikeShareButtons from '../../components/post/PostLikeShareButtons';
import gql from 'graphql-tag';
import { shareFacebook, shareTwitter, copyText } from '../../lib/share';
import PostToc from '../../components/post/PostToc';
import LinkedPostList from '../../components/post/LinkedPostList';
import { getScrollTop, ssrEnabled } from '../../lib/utils';
import UserProfile from '../../components/common/UserProfile';
import VelogResponsive from '../../components/velog/VelogResponsive';
import styled from 'styled-components';
import PostSkeleton from '../../components/post/PostSkeleton';
import media from '../../lib/styles/media';
import useNotFound from '../../lib/hooks/useNotFound';
import { Helmet } from 'react-helmet-async';
import { toast } from 'react-toastify';
import MobileLikeButton from '../../components/post/MobileLikeButton';
import RelatedPost from './RelatedPost';
import optimizeImage from '../../lib/optimizeImage';
import RelatedPostsForGuest from './RelatedPostsForGuest';
const UserProfileWrapper = styled(VelogResponsive)`
margin-top: 16rem;
margin-bottom: 6rem;
${media.medium} {
margin-top: 8rem;
margin-bottom: 3rem;
}
${media.small} {
margin-top: 2rem;
}
`;
export interface PostViewerOwnProps {
username: string;
urlSlug: string;
}
export interface PostViewerProps
extends PostViewerOwnProps,
RouteComponentProps {}
const PostViewer: React.FC<PostViewerProps> = ({
username,
urlSlug,
history,
match,
}) => {
const [showRecommends, setShowRecommends] = useState(false);
useEffect(() => {
window.scrollTo(0, 0);
}, [username, urlSlug]);
const userId = useUserId();
const dispatch = useDispatch();
const readPost = useQuery<{ post: SinglePost }>(READ_POST, {
variables: {
username,
url_slug: urlSlug,
},
});
const client = useApolloClient();
const prefetchPost = useCallback(
({ username, urlSlug }: { username: string; urlSlug: string }) => {
client.query({
query: READ_POST,
variables: {
username,
url_slug: urlSlug,
},
});
},
[client],
);
const prefetched = useRef(false);
const [removePost] = useMutation(REMOVE_POST);
const [postView] = useMutation(POST_VIEW);
const [likePost, { loading: loadingLike }] = useMutation(LIKE_POST);
const [unlikePost, { loading: loadingUnlike }] = useMutation(UNLIKE_POST);
const { showNotFound } = useNotFound();
// const userLogo = useSelector((state: RootState) => state.header.userLogo);
// const velogTitle = useMemo(() => {
// if (!userLogo || !userLogo.title) return `${username}.log`;
// return userLogo.title;
// }, [userLogo, username]);
const user = useUser();
const { error, data } = readPost;
useEffect(() => {
if (data && data.post === null) {
showNotFound();
return;
}
if (!data || !data.post) return;
postView({
variables: {
id: data.post.id,
},
});
}, [data, postView, showNotFound]);
if (ssrEnabled && data && data.post === null) {
showNotFound();
}
const prefetchLinkedPosts = useCallback(() => {
if (!data || !data.post) return;
if (prefetched.current) return;
prefetched.current = true;
const { linked_posts: linkedPosts } = data.post;
const { next, previous } = linkedPosts;
const getVariables = (post: LinkedPost) => ({
username: post.user.username,
urlSlug: post.url_slug,
});
if (next) {
prefetchPost(getVariables(next));
}
if (previous) {
prefetchPost(getVariables(previous));
}
}, [data, prefetchPost]);
const postReady = !!data?.post;
const onScroll = useCallback(() => {
const scrollTop = getScrollTop();
const { scrollHeight } = document.body;
const { innerHeight } = window;
const percentage = ((scrollTop + innerHeight) / scrollHeight) * 100;
if (percentage > 50) {
prefetchLinkedPosts();
}
if (percentage > 50 && postReady) {
setShowRecommends(true);
}
}, [prefetchLinkedPosts, postReady]);
useEffect(() => {
if (!data) return;
if (!data.post) return;
// schedule post prefetch
const timeoutId = setTimeout(prefetchLinkedPosts, 1000 * 5);
dispatch(postSlice.actions.setPostId(data.post.id));
prefetched.current = false;
return () => {
clearTimeout(timeoutId);
};
}, [data, dispatch, prefetchLinkedPosts]);
useEffect(() => {
window.addEventListener('scroll', onScroll);
return () => {
window.removeEventListener('scroll', onScroll);
};
}, [onScroll]);
const onRemove = async () => {
if (!data || !data.post) return;
try {
await removePost({
variables: {
id: data.post.id,
},
});
history.push('/');
await client.resetStore();
} catch (e) {}
};
if (error) {
console.log(error);
return null;
}
const onEdit = () => {
if (!data) return;
const { post } = data;
dispatch(
prepareEdit({
id: post.id,
body: post.body,
description: post.short_description,
isMarkdown: post.is_markdown,
isPrivate: post.is_private,
series: post.series
? {
id: post.series.id,
name: post.series.name,
}
: null,
tags: post.tags,
title: post.title,
urlSlug: post.url_slug,
thumbnail: post.thumbnail,
}),
);
history.push(`/write?id=${post.id}`);
};
const onOpenStats = () => {
history.push(`/post-stats/${post.id}`);
};
const onLikeToggle = async () => {
if (loadingLike || loadingUnlike) return;
const variables = {
id: post.id,
};
const likeFragment = gql`
fragment post on Post {
liked
likes
}
`;
// IF SPLITTED TO ANOTHER CONTAINER
// const data = client.readFragment<{ liked: boolean; likes: number }>({
// id: `Post:${post.id}`,
// fragment: likeFragment
// });
try {
if (!user) {
toast.error('로그인 후 이용해주세요.');
return;
}
if (post.liked) {
client.writeFragment({
id: `Post:${post.id}`,
fragment: likeFragment,
data: {
liked: false,
likes: post.likes - 1,
__typename: 'Post',
},
});
await unlikePost({
variables,
});
} else {
client.writeFragment({
id: `Post:${post.id}`,
fragment: likeFragment,
data: {
liked: true,
likes: post.likes + 1,
__typename: 'Post',
},
});
await likePost({
variables,
});
}
} catch (e) {
console.log(e);
}
};
const onShareClick = (type: 'facebook' | 'twitter' | 'clipboard') => {
const { url } = match;
const link = `https://velog.io${url}`;
switch (type) {
case 'facebook':
shareFacebook(link);
break;
case 'twitter':
const ownPost = post.user.id === userId;
const message = ownPost
? `제가 velog 에 게재한 "${post.title}" 포스트를 읽어보세요.`
: `${post.user.username}님이 velog 에 게재한 "${post.title}" 포스트를 읽어보세요.`;
shareTwitter(link, message);
break;
case 'clipboard':
copyText(link);
toast.success('링크가 복사되었습니다.');
break;
default:
}
};
if (!data || !data.post) return <PostSkeleton />;
const { post } = data;
const url = `https://velog.io/@${username}/${post.url_slug}`;
return (
<PostViewerProvider prefetchLinkedPosts={prefetchLinkedPosts}>
<Helmet>
<title>{post.title}</title>
{post.short_description && (
<meta name="description" content={post.short_description} />
)}
<link rel="canonical" href={url} />
<meta property="og:url" content={url} />
<meta property="og:type" content="article" />
<meta property="og:title" content={post.title} />
<meta property="og:description" content={post.short_description} />
{post.thumbnail && (
<meta
property="og:image"
content={optimizeImage(post.thumbnail, 768)}
/>
)}
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content={post.title} />
<meta name="twitter:description" content={post.short_description} />
{post.thumbnail && (
<meta name="twitter:image" content={post.thumbnail} />
)}
</Helmet>
<PostHead
title={post.title}
tags={post.tags}
username={username}
date={post.released_at}
thumbnail={
post.thumbnail &&
(post.body.includes(encodeURI(post.thumbnail))
? null
: post.thumbnail)
}
series={post.series}
hideThumbnail={!!post.thumbnail && post.body.includes(post.thumbnail)}
postId={post.id}
ownPost={post.user.id === userId}
onRemove={onRemove}
onEdit={onEdit}
onOpenStats={onOpenStats}
shareButtons={
<PostLikeShareButtons
onLikeToggle={onLikeToggle}
onShareClick={onShareClick}
likes={post.likes}
liked={post.liked}
postId={post.id}
/>
}
toc={<PostToc />}
isPrivate={post.is_private}
mobileLikeButton={
<MobileLikeButton
likes={post.likes}
liked={post.liked}
onToggle={onLikeToggle}
/>
}
/>
<PostContent isMarkdown={post.is_markdown} body={post.body} />
<UserProfileWrapper>
<UserProfile
thumbnail={post.user.profile.thumbnail}
displayName={post.user.profile.display_name}
description={post.user.profile.short_bio}
profileLinks={post.user.profile.profile_links}
username={post.user.username}
/>
</UserProfileWrapper>
<LinkedPostList linkedPosts={post.linked_posts} />
{showRecommends && userId === null && (
<RelatedPostsForGuest
postId={post.id}
showAds={
Date.now() - new Date(post.released_at).getTime() >
1000 * 60 * 60 * 24 * 21
}
/>
)}
<PostComments
count={post.comments_count}
comments={post.comments}
postId={post.id}
/>
{showRecommends && userId !== null && (
<RelatedPost
postId={post.id}
showAds={
post.user.id !== userId &&
Date.now() - new Date(post.released_at).getTime() >
1000 * 60 * 60 * 24 * 30
}
/>
)}
</PostViewerProvider>
);
};
export default withRouter(PostViewer); | the_stack |
import { _FirebaseService, FirebaseApp } from '@firebase/app';
import {
Auth,
AuthErrorMap,
AuthSettings,
EmulatorConfig,
NextOrObserver,
Persistence,
PopupRedirectResolver,
User,
UserCredential,
CompleteFn,
ErrorFn,
NextFn,
Unsubscribe
} from '../../model/public_types';
import {
createSubscribe,
ErrorFactory,
getModularInstance,
Observer,
Subscribe
} from '@firebase/util';
import { AuthInternal, ConfigInternal } from '../../model/auth';
import { PopupRedirectResolverInternal } from '../../model/popup_redirect';
import { UserInternal } from '../../model/user';
import {
AuthErrorCode,
AuthErrorParams,
ErrorMapRetriever,
_DEFAULT_AUTH_ERROR_FACTORY
} from '../errors';
import { PersistenceInternal } from '../persistence';
import {
KeyName,
PersistenceUserManager
} from '../persistence/persistence_user_manager';
import { _reloadWithoutSaving } from '../user/reload';
import { _assert } from '../util/assert';
import { _getInstance } from '../util/instantiator';
import { _getUserLanguage } from '../util/navigator';
import { _getClientVersion } from '../util/version';
interface AsyncAction {
(): Promise<void>;
}
export const enum DefaultConfig {
TOKEN_API_HOST = 'securetoken.googleapis.com',
API_HOST = 'identitytoolkit.googleapis.com',
API_SCHEME = 'https'
}
export class AuthImpl implements AuthInternal, _FirebaseService {
currentUser: User | null = null;
emulatorConfig: EmulatorConfig | null = null;
private operations = Promise.resolve();
private persistenceManager?: PersistenceUserManager;
private redirectPersistenceManager?: PersistenceUserManager;
private authStateSubscription = new Subscription<User>(this);
private idTokenSubscription = new Subscription<User>(this);
private redirectUser: UserInternal | null = null;
private isProactiveRefreshEnabled = false;
// Any network calls will set this to true and prevent subsequent emulator
// initialization
_canInitEmulator = true;
_isInitialized = false;
_deleted = false;
_initializationPromise: Promise<void> | null = null;
_popupRedirectResolver: PopupRedirectResolverInternal | null = null;
_errorFactory: ErrorFactory<AuthErrorCode, AuthErrorParams> =
_DEFAULT_AUTH_ERROR_FACTORY;
readonly name: string;
// Tracks the last notified UID for state change listeners to prevent
// repeated calls to the callbacks. Undefined means it's never been
// called, whereas null means it's been called with a signed out user
private lastNotifiedUid: string | null | undefined = undefined;
languageCode: string | null = null;
tenantId: string | null = null;
settings: AuthSettings = { appVerificationDisabledForTesting: false };
constructor(
public readonly app: FirebaseApp,
public readonly config: ConfigInternal
) {
this.name = app.name;
this.clientVersion = config.sdkClientVersion;
}
_initializeWithPersistence(
persistenceHierarchy: PersistenceInternal[],
popupRedirectResolver?: PopupRedirectResolver
): Promise<void> {
if (popupRedirectResolver) {
this._popupRedirectResolver = _getInstance(popupRedirectResolver);
}
// Have to check for app deletion throughout initialization (after each
// promise resolution)
this._initializationPromise = this.queue(async () => {
if (this._deleted) {
return;
}
this.persistenceManager = await PersistenceUserManager.create(
this,
persistenceHierarchy
);
if (this._deleted) {
return;
}
// Initialize the resolver early if necessary (only applicable to web:
// this will cause the iframe to load immediately in certain cases)
if (this._popupRedirectResolver?._shouldInitProactively) {
await this._popupRedirectResolver._initialize(this);
}
await this.initializeCurrentUser(popupRedirectResolver);
if (this._deleted) {
return;
}
this._isInitialized = true;
});
return this._initializationPromise;
}
/**
* If the persistence is changed in another window, the user manager will let us know
*/
async _onStorageEvent(): Promise<void> {
if (this._deleted) {
return;
}
const user = await this.assertedPersistence.getCurrentUser();
if (!this.currentUser && !user) {
// No change, do nothing (was signed out and remained signed out).
return;
}
// If the same user is to be synchronized.
if (this.currentUser && user && this.currentUser.uid === user.uid) {
// Data update, simply copy data changes.
this._currentUser._assign(user);
// If tokens changed from previous user tokens, this will trigger
// notifyAuthListeners_.
await this.currentUser.getIdToken();
return;
}
// Update current Auth state. Either a new login or logout.
await this._updateCurrentUser(user);
}
private async initializeCurrentUser(
popupRedirectResolver?: PopupRedirectResolver
): Promise<void> {
// First check to see if we have a pending redirect event.
let storedUser =
(await this.assertedPersistence.getCurrentUser()) as UserInternal | null;
if (popupRedirectResolver && this.config.authDomain) {
await this.getOrInitRedirectPersistenceManager();
const redirectUserEventId = this.redirectUser?._redirectEventId;
const storedUserEventId = storedUser?._redirectEventId;
const result = await this.tryRedirectSignIn(popupRedirectResolver);
// If the stored user (i.e. the old "currentUser") has a redirectId that
// matches the redirect user, then we want to initially sign in with the
// new user object from result.
// TODO(samgho): More thoroughly test all of this
if (
(!redirectUserEventId || redirectUserEventId === storedUserEventId) &&
result?.user
) {
storedUser = result.user as UserInternal;
}
}
// If no user in persistence, there is no current user. Set to null.
if (!storedUser) {
return this.directlySetCurrentUser(null);
}
if (!storedUser._redirectEventId) {
// This isn't a redirect user, we can reload and bail
// This will also catch the redirected user, if available, as that method
// strips the _redirectEventId
return this.reloadAndSetCurrentUserOrClear(storedUser);
}
_assert(this._popupRedirectResolver, this, AuthErrorCode.ARGUMENT_ERROR);
await this.getOrInitRedirectPersistenceManager();
// If the redirect user's event ID matches the current user's event ID,
// DO NOT reload the current user, otherwise they'll be cleared from storage.
// This is important for the reauthenticateWithRedirect() flow.
if (
this.redirectUser &&
this.redirectUser._redirectEventId === storedUser._redirectEventId
) {
return this.directlySetCurrentUser(storedUser);
}
return this.reloadAndSetCurrentUserOrClear(storedUser);
}
private async tryRedirectSignIn(
redirectResolver: PopupRedirectResolver
): Promise<UserCredential | null> {
// The redirect user needs to be checked (and signed in if available)
// during auth initialization. All of the normal sign in and link/reauth
// flows call back into auth and push things onto the promise queue. We
// need to await the result of the redirect sign in *inside the promise
// queue*. This presents a problem: we run into deadlock. See:
// ┌> [Initialization] ─────┐
// ┌> [<other queue tasks>] │
// └─ [getRedirectResult] <─┘
// where [] are tasks on the queue and arrows denote awaits
// Initialization will never complete because it's waiting on something
// that's waiting for initialization to complete!
//
// Instead, this method calls getRedirectResult() (stored in
// _completeRedirectFn) with an optional parameter that instructs all of
// the underlying auth operations to skip anything that mutates auth state.
let result: UserCredential | null = null;
try {
// We know this._popupRedirectResolver is set since redirectResolver
// is passed in. The _completeRedirectFn expects the unwrapped extern.
result = await this._popupRedirectResolver!._completeRedirectFn(
this,
redirectResolver,
true
);
} catch (e) {
// Swallow any errors here; the code can retrieve them in
// getRedirectResult().
await this._setRedirectUser(null);
}
return result;
}
private async reloadAndSetCurrentUserOrClear(
user: UserInternal
): Promise<void> {
try {
await _reloadWithoutSaving(user);
} catch (e) {
if (e.code !== `auth/${AuthErrorCode.NETWORK_REQUEST_FAILED}`) {
// Something's wrong with the user's token. Log them out and remove
// them from storage
return this.directlySetCurrentUser(null);
}
}
return this.directlySetCurrentUser(user);
}
useDeviceLanguage(): void {
this.languageCode = _getUserLanguage();
}
async _delete(): Promise<void> {
this._deleted = true;
}
async updateCurrentUser(userExtern: User | null): Promise<void> {
// The public updateCurrentUser method needs to make a copy of the user,
// and also check that the project matches
const user = userExtern
? (getModularInstance(userExtern) as UserInternal)
: null;
if (user) {
_assert(
user.auth.config.apiKey === this.config.apiKey,
this,
AuthErrorCode.INVALID_AUTH
);
}
return this._updateCurrentUser(user && user._clone(this));
}
async _updateCurrentUser(user: User | null): Promise<void> {
if (this._deleted) {
return;
}
if (user) {
_assert(
this.tenantId === user.tenantId,
this,
AuthErrorCode.TENANT_ID_MISMATCH
);
}
return this.queue(async () => {
await this.directlySetCurrentUser(user as UserInternal | null);
this.notifyAuthListeners();
});
}
async signOut(): Promise<void> {
// Clear the redirect user when signOut is called
if (this.redirectPersistenceManager || this._popupRedirectResolver) {
await this._setRedirectUser(null);
}
return this._updateCurrentUser(null);
}
setPersistence(persistence: Persistence): Promise<void> {
return this.queue(async () => {
await this.assertedPersistence.setPersistence(_getInstance(persistence));
});
}
_getPersistence(): string {
return this.assertedPersistence.persistence.type;
}
_updateErrorMap(errorMap: AuthErrorMap): void {
this._errorFactory = new ErrorFactory<AuthErrorCode, AuthErrorParams>(
'auth',
'Firebase',
(errorMap as ErrorMapRetriever)()
);
}
onAuthStateChanged(
nextOrObserver: NextOrObserver<User>,
error?: ErrorFn,
completed?: CompleteFn
): Unsubscribe {
return this.registerStateListener(
this.authStateSubscription,
nextOrObserver,
error,
completed
);
}
onIdTokenChanged(
nextOrObserver: NextOrObserver<User>,
error?: ErrorFn,
completed?: CompleteFn
): Unsubscribe {
return this.registerStateListener(
this.idTokenSubscription,
nextOrObserver,
error,
completed
);
}
toJSON(): object {
return {
apiKey: this.config.apiKey,
authDomain: this.config.authDomain,
appName: this.name,
currentUser: this._currentUser?.toJSON()
};
}
async _setRedirectUser(
user: UserInternal | null,
popupRedirectResolver?: PopupRedirectResolver
): Promise<void> {
const redirectManager = await this.getOrInitRedirectPersistenceManager(
popupRedirectResolver
);
return user === null
? redirectManager.removeCurrentUser()
: redirectManager.setCurrentUser(user);
}
private async getOrInitRedirectPersistenceManager(
popupRedirectResolver?: PopupRedirectResolver
): Promise<PersistenceUserManager> {
if (!this.redirectPersistenceManager) {
const resolver: PopupRedirectResolverInternal | null =
(popupRedirectResolver && _getInstance(popupRedirectResolver)) ||
this._popupRedirectResolver;
_assert(resolver, this, AuthErrorCode.ARGUMENT_ERROR);
this.redirectPersistenceManager = await PersistenceUserManager.create(
this,
[_getInstance(resolver._redirectPersistence)],
KeyName.REDIRECT_USER
);
this.redirectUser =
await this.redirectPersistenceManager.getCurrentUser();
}
return this.redirectPersistenceManager;
}
async _redirectUserForId(id: string): Promise<UserInternal | null> {
// Make sure we've cleared any pending persistence actions if we're not in
// the initializer
if (this._isInitialized) {
await this.queue(async () => {});
}
if (this._currentUser?._redirectEventId === id) {
return this._currentUser;
}
if (this.redirectUser?._redirectEventId === id) {
return this.redirectUser;
}
return null;
}
async _persistUserIfCurrent(user: UserInternal): Promise<void> {
if (user === this.currentUser) {
return this.queue(async () => this.directlySetCurrentUser(user));
}
}
/** Notifies listeners only if the user is current */
_notifyListenersIfCurrent(user: UserInternal): void {
if (user === this.currentUser) {
this.notifyAuthListeners();
}
}
_key(): string {
return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;
}
_startProactiveRefresh(): void {
this.isProactiveRefreshEnabled = true;
if (this.currentUser) {
this._currentUser._startProactiveRefresh();
}
}
_stopProactiveRefresh(): void {
this.isProactiveRefreshEnabled = false;
if (this.currentUser) {
this._currentUser._stopProactiveRefresh();
}
}
/** Returns the current user cast as the internal type */
get _currentUser(): UserInternal {
return this.currentUser as UserInternal;
}
private notifyAuthListeners(): void {
if (!this._isInitialized) {
return;
}
this.idTokenSubscription.next(this.currentUser);
const currentUid = this.currentUser?.uid ?? null;
if (this.lastNotifiedUid !== currentUid) {
this.lastNotifiedUid = currentUid;
this.authStateSubscription.next(this.currentUser);
}
}
private registerStateListener(
subscription: Subscription<User>,
nextOrObserver: NextOrObserver<User>,
error?: ErrorFn,
completed?: CompleteFn
): Unsubscribe {
if (this._deleted) {
return () => {};
}
const cb =
typeof nextOrObserver === 'function'
? nextOrObserver
: nextOrObserver.next.bind(nextOrObserver);
const promise = this._isInitialized
? Promise.resolve()
: this._initializationPromise;
_assert(promise, this, AuthErrorCode.INTERNAL_ERROR);
// The callback needs to be called asynchronously per the spec.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
promise.then(() => cb(this.currentUser));
if (typeof nextOrObserver === 'function') {
return subscription.addObserver(nextOrObserver, error, completed);
} else {
return subscription.addObserver(nextOrObserver);
}
}
/**
* Unprotected (from race conditions) method to set the current user. This
* should only be called from within a queued callback. This is necessary
* because the queue shouldn't rely on another queued callback.
*/
private async directlySetCurrentUser(
user: UserInternal | null
): Promise<void> {
if (this.currentUser && this.currentUser !== user) {
this._currentUser._stopProactiveRefresh();
if (user && this.isProactiveRefreshEnabled) {
user._startProactiveRefresh();
}
}
this.currentUser = user;
if (user) {
await this.assertedPersistence.setCurrentUser(user);
} else {
await this.assertedPersistence.removeCurrentUser();
}
}
private queue(action: AsyncAction): Promise<void> {
// In case something errors, the callback still should be called in order
// to keep the promise chain alive
this.operations = this.operations.then(action, action);
return this.operations;
}
private get assertedPersistence(): PersistenceUserManager {
_assert(this.persistenceManager, this, AuthErrorCode.INTERNAL_ERROR);
return this.persistenceManager;
}
private frameworks: string[] = [];
private clientVersion: string;
_logFramework(framework: string): void {
if (!framework || this.frameworks.includes(framework)) {
return;
}
this.frameworks.push(framework);
// Sort alphabetically so that "FirebaseCore-web,FirebaseUI-web" and
// "FirebaseUI-web,FirebaseCore-web" aren't viewed as different.
this.frameworks.sort();
this.clientVersion = _getClientVersion(
this.config.clientPlatform,
this._getFrameworks()
);
}
_getFrameworks(): readonly string[] {
return this.frameworks;
}
_getSdkClientVersion(): string {
return this.clientVersion;
}
}
/**
* Method to be used to cast down to our private implmentation of Auth.
* It will also handle unwrapping from the compat type if necessary
*
* @param auth Auth object passed in from developer
*/
export function _castAuth(auth: Auth): AuthInternal {
return getModularInstance(auth) as AuthInternal;
}
/** Helper class to wrap subscriber logic */
class Subscription<T> {
private observer: Observer<T | null> | null = null;
readonly addObserver: Subscribe<T | null> = createSubscribe(
observer => (this.observer = observer)
);
constructor(readonly auth: AuthInternal) {}
get next(): NextFn<T | null> {
_assert(this.observer, this.auth, AuthErrorCode.INTERNAL_ERROR);
return this.observer.next.bind(this.observer);
}
} | the_stack |
import { bootstrap } from '../../../src/bootstrap';
import fastify, { FastifyInstance } from 'fastify';
import { controllerFactory } from '../../support/controllerFactory';
import methodsDefinitions from '../../data/controllerMethodsDefinitions';
describe('@Controller decorator', () => {
let server: FastifyInstance;
beforeEach(async () => { server = fastify(); });
afterEach(() => { server.close(); });
describe('Controller register', () => {
test('Should register controller on specific route', async () => {
// arrange
const TestController = controllerFactory('/example', [{ route: '/', method: 'GET', handler: () => [] }]);
await bootstrap(server, { controllers: [TestController] });
// act
await server.listen(4000);
// assert
expect(server.printRoutes()).toBe(
'└── /example (GET)\n' +
' └── / (GET)\n'
);
});
test('Should register controller without "route" option', async () => {
// arrange
const TestController = controllerFactory(undefined, [{ route: '/my-route', method: 'GET', handler: () => [] }]);
await bootstrap(server, { controllers: [TestController] });
// act
await server.listen(4000);
// assert
expect(server.printRoutes()).toBe('└── /my-route (GET)\n');
});
});
describe('Controller hooks', () => {
test('Should handle @OnRequest hook', async () => {
// arrange
const hookHandler = jest.fn((request, reply, done) => done());
const routeHandler = jest.fn().mockResolvedValue([]);
const TestController = controllerFactory(
'/hooks-on-request',
[{ route: '/', method: 'GET', handler: routeHandler }],
[{ hook: 'OnRequest', handler: hookHandler }]
);
await bootstrap(server, { controllers: [TestController] });
// act
const response = await server.inject({ method: 'GET', url: '/hooks-on-request/' });
// assert
expect(response.statusCode).toBe(200);
expect(response.statusMessage).toBe('OK');
expect(hookHandler).toBeCalledTimes(1);
});
test('Should handle @PreParsing hook', async () => {
// arrange
const hookHandler = jest.fn((request, reply, payload, done) => done(null, payload));
const routeHandler = jest.fn().mockResolvedValue([]);
const TestController = controllerFactory(
'/hooks-pre-parsing',
[{ route: '/', method: 'POST', handler: routeHandler }],
[{ hook: 'PreParsing', handler: hookHandler }]
);
await bootstrap(server, { controllers: [TestController] });
// act
const response = await server.inject({ method: 'POST', url: '/hooks-pre-parsing/', body: { title: 'Testing' } } as any);
// assert
expect(response.statusCode).toBe(200);
expect(response.statusMessage).toBe('OK');
expect(hookHandler).toBeCalledTimes(1);
});
test('Should handle @PreValidation hook', async () => {
// arrange
const hookHandler = jest.fn((request, reply, done) => done());
const routeHandler = jest.fn().mockResolvedValue([]);
const TestController = controllerFactory(
'/hooks-pre-validation',
[{ route: '/', method: 'GET', handler: routeHandler }],
[{ hook: 'PreValidation', handler: hookHandler }]
);
await bootstrap(server, { controllers: [TestController] });
// act
const response = await server.inject({ method: 'GET', url: '/hooks-pre-validation/' });
// assert
expect(response.statusCode).toBe(200);
expect(response.statusMessage).toBe('OK');
expect(hookHandler).toBeCalledTimes(1);
});
// TODO: add 'preHandler', 'preSerialization', 'onError', 'onSend', 'onResponse', 'onTimeout';
// with the next pattern:
//
// test('Should handle @PreValidation hook', async () => {});
});
describe('Request decorators', () => {
describe('@GET', () => {
test('Should register @GET endpoint', async () => {
// arrange
const { response } = methodsDefinitions.get;
const handler = jest.fn().mockResolvedValue(response);
const TestController = controllerFactory('/test-get', [{ route: '/:id', method: 'GET', handler }]);
await bootstrap(server, { controllers: [TestController] });
// act
const result = await server.inject({ method: 'GET', url: '/test-get/965?$limit=20&$results=true' });
// assert
expect(result.statusCode).toBe(200);
expect(result.statusMessage).toBe('OK');
expect(result.body).toBe(JSON.stringify(response));
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0].length).toBe(2);
expect(handler.mock.calls[0][0].params.id).toBe('965');
expect(handler.mock.calls[0][0].query.$limit).toBe('20');
expect(handler.mock.calls[0][0].query.$results).toBe('true');
});
test('Should register @GET endpoint with schema and hooks', async () => {
// arrange
const { response, schema } = methodsDefinitions.get;
const handler = jest.fn().mockResolvedValue(response);
const preValidation = jest.fn().mockImplementation((request, reply, done) => done());
const TestController = controllerFactory('/test-get', [{ route: '/:id', method: 'GET', handler, options: { schema, preValidation } }]);
await bootstrap(server, { controllers: [TestController] });
// act
const result = await server.inject({ method: 'GET', url: '/test-get/965?$limit=20&$results=true' });
// assert
expect(result.statusCode).toBe(200);
expect(result.statusMessage).toBe('OK');
expect(result.body).toBe(JSON.stringify({ data: response.data, total: response.total }));
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0].length).toBe(2);
expect(handler.mock.calls[0][0].params.id).toBe(965);
expect(handler.mock.calls[0][0].query.$limit).toBe(20);
expect(handler.mock.calls[0][0].query.$results).toBe(true);
expect(preValidation).toBeCalledTimes(1);
});
});
describe('@POST', () => {
test('Should register @POST endpoint', async () => {
// arrange
const { response, body } = methodsDefinitions.post;
const handler = jest.fn().mockResolvedValue(response);
const TestController = controllerFactory('/test-post', [{ route: '/', method: 'POST', handler }]);
await bootstrap(server, { controllers: [TestController] });
// act
const result = await server.inject({ method: 'POST', url: '/test-post/?$results=true', body } as any);
// assert
expect(result.statusCode).toBe(200);
expect(result.statusMessage).toBe('OK');
expect(result.body).toBe(JSON.stringify(response));
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0].length).toBe(2);
expect(handler.mock.calls[0][0].query.$results).toBe('true');
expect(handler.mock.calls[0][0].body).toMatchObject(body);
});
test('Should register @POST endpoint with schema and hooks', async () => {
// arrange
const { response, body, schema } = methodsDefinitions.post;
const handler = jest.fn().mockResolvedValue(response);
const preParsing = jest.fn().mockImplementation((request, reply, payload, done) => done(null, payload));
const TestController = controllerFactory('/test-post', [{ route: '/', method: 'POST', handler, options: { schema, preParsing } }]);
await bootstrap(server, { controllers: [TestController] });
// act
const result = await server.inject({ method: 'POST', url: '/test-post/?$results=true', body } as any);
// assert
expect(result.statusCode).toBe(200);
expect(result.statusMessage).toBe('OK');
expect(result.body).toBe(JSON.stringify({ createdAt: response.createdAt }));
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0].length).toBe(2);
expect(handler.mock.calls[0][0].query.$results).toBe(true);
expect(handler.mock.calls[0][0].body).toMatchObject(body);
expect(preParsing).toBeCalledTimes(1);
});
});
describe('@PATCH', () => {
test('Should register @PATCH endpoint', async () => {
// arrange
const { response, body } = methodsDefinitions.patch;
const handler = jest.fn().mockResolvedValue(response);
const TestController = controllerFactory('/test-patch', [{ route: '/:ref', method: 'PATCH', handler }]);
await bootstrap(server, { controllers: [TestController] });
// act
const result = await server.inject({ method: 'PATCH', url: '/test-patch/sample?times=9', body } as any);
// assert
expect(result.statusCode).toBe(200);
expect(result.statusMessage).toBe('OK');
expect(result.body).toBe(JSON.stringify(response));
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0].length).toBe(2);
expect(handler.mock.calls[0][0].params.ref).toBe('sample');
expect(handler.mock.calls[0][0].query.times).toBe('9');
expect(handler.mock.calls[0][0].body).toMatchObject(body);
});
test('Should register @PATCH endpoint with schema and hooks', async () => {
// arrange
const { response, body, schema } = methodsDefinitions.patch;
const handler = jest.fn().mockResolvedValue(response);
const preHandler = jest.fn().mockImplementation((request, reply, done) => done());
const TestController = controllerFactory('/test-patch', [{ route: '/:ref', method: 'PATCH', handler, options: { schema, preHandler } }]);
await bootstrap(server, { controllers: [TestController] });
// act
const result = await server.inject({ method: 'PATCH', url: '/test-patch/sample?times=9', body } as any);
// assert
expect(result.statusCode).toBe(200);
expect(result.statusMessage).toBe('OK');
expect(result.body).toBe(JSON.stringify(response));
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0].length).toBe(2);
expect(handler.mock.calls[0][0].params.ref).toBe('sample');
expect(handler.mock.calls[0][0].query.times).toBe(9);
expect(handler.mock.calls[0][0].body).toMatchObject(body);
expect(preHandler).toHaveBeenCalledTimes(1);
});
});
// TODO: add UPDATE, DELETE, HEAD, PUT, OPTIONS, ALL (all + custom methods)
// with the next pattern:
//
// describe('@POST', () => {
// test('Should register @POST endpoint', async () => {});
// test('Should register @POST endpoint with schema and hooks', async () => {});
// });
});
}); | the_stack |
import { Chart, registerInteraction } from '@antv/g2'
import { AdjustOption, AnnotationPosition, ArcOption, AxisOption, ChartCfg, CoordinateActions, CoordinateOption, DataMarkerOption, DataRegionOption, GeometryOption, LineOption, RegionOption, ScaleOption, TextOption } from '@antv/g2/lib/interface'
import { B, Dict, F, Model, parseI, parseU, Rec, S, unpack, V } from 'h2o-wave'
import React from 'react'
import { stylesheet } from 'typestyle'
import { Fmt, parseFormat } from './intl'
import { cards, grid } from './layout'
import { cssVar, cssVarValue, formItemWidth } from './theme'
import { bond, wave } from './ui'
let
cat10 = [
'$gray',
'$blue',
'$green',
'$amber',
'$tangerine',
'$purple',
'$cyan',
'$mint',
'$pink',
'$brown',
]
type AnnotationOption = ArcOption | LineOption | TextOption | RegionOption | DataMarkerOption | DataRegionOption
enum SpaceT { CC, DD, TT, CD, DC, TC, CT, TD, DT }
/**
* Create a specification for a layer of graphical marks such as bars, lines, points for a plot.
* A plot can contain multiple such layers of marks.
*/
interface Mark {
/** Coordinate system. `rect` is synonymous to `cartesian`. `theta` is transposed `polar`. */
coord?: 'rect' | 'cartesian' | 'polar' | 'theta' | 'helix'
/** Graphical geometry. */
type?: 'interval' | 'line' | 'path' | 'point' | 'area' | 'polygon' | 'schema' | 'edge' | 'heatmap'
/** X field or value. */
x?: V
/** X base field or value. */
x0?: V
/** X bin lower bound field or value. For histograms. */
x1?: V
/** X bin upper bound field or value. For histograms. */
x2?: V
/** X axis scale minimum. */
x_min?: F
/** X axis scale maximum. */
x_max?: F
/** Whether to nice X axis scale ticks. */
x_nice?: B
/** X axis scale type. */
x_scale?: 'linear' | 'cat' | 'category' | 'identity' | 'log' | 'pow' | 'power' | 'time' | 'time-category' | 'quantize' | 'quantile'
/** X axis title. */
x_title?: S
/** Y field or value. */
y?: V
/** Y base field or value. */
y0?: V
/** Y bin lower bound field or value. For histograms. */
y1?: V
/** Y bin upper bound field or value. For histograms. */
y2?: V
/** Y axis scale minimum. */
y_min?: F
/** Y axis scale maximum. */
y_max?: F
/** Whether to nice Y axis scale ticks. */
y_nice?: B
/** Y axis scale type. */
y_scale?: 'linear' | 'cat' | 'category' | 'identity' | 'log' | 'pow' | 'power' | 'time' | 'time-category' | 'quantize' | 'quantile'
/** Y axis title. */
y_title?: S
/** Mark color field or value. */
color?: S
/** Mark color range for multi-series plots. A string containing space-separated colors, e.g. `'#fee8c8 #fdbb84 #e34a33'` */
color_range?: S
/** The unique values in the data (labels or categories or classes) to map colors to, e.g. `['high', 'medium', 'low']`. If this is not provided, the unique values are automatically inferred from the `color` attribute. */
color_domain?: S[]
/** Mark shape field or value for `point` mark types. Possible values are 'circle', 'square', 'bowtie', 'diamond', 'hexagon', 'triangle', 'triangle-down', 'cross', 'tick', 'plus', 'hyphen', 'line'. */
shape?: S
/** Mark shape range for multi-series plots using `point` mark types. A string containing space-separated shapes, e.g. `'circle square diamond'` */
shape_range?: S
/** Mark size field or value. */
size?: V
/** Mark size range. A string containing space-separated integers, e.g. `'4 30'` */
size_range?: S
/** Field to stack marks by, or 'auto' to infer. */
stack?: S
/** Field to dodge marks by, or 'auto' to infer. */
dodge?: S
/** Curve type for `line` and `area` mark types. */
curve?: 'none' | 'smooth' | 'step-before' | 'step' | 'step-after'
/** Mark fill color. */
fill_color?: S
/** Mark fill opacity. */
fill_opacity?: F
/** Mark stroke color. */
stroke_color?: S
/** Mark stroke opacity. */
stroke_opacity?: F
/** Mark stroke size. */
stroke_size?: F
/** Mark stroke dash style. A string containing space-separated integers that specify distances to alternately draw a line and a gap (in coordinate space units). If the number of elements in the array is odd, the elements of the array get copied and concatenated. For example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25]. */
stroke_dash?: S
/** Label field or value. */
label?: S
/** Distance between label and mark. */
label_offset?: F
/** Horizontal distance between label and mark. */
label_offset_x?: F
/** Vertical distance between label and mark. */
label_offset_y?: F
/** Label rotation angle, in degrees, or 'none' to disable automatic rotation. The default behavior is 'auto' for automatic rotation. */
label_rotation?: S
/** Label position relative to the mark. */
label_position?: 'top' | 'bottom' | 'middle' | 'left' | 'right'
/** Strategy to use if labels overlap. */
label_overlap?: 'hide' | 'overlap' | 'constrain'
/** Label fill color. */
label_fill_color?: S
/** Label fill opacity. */
label_fill_opacity?: F
/** Label stroke color. */
label_stroke_color?: S
/** Label stroke opacity. */
label_stroke_opacity?: F
/** Label stroke size (line width or pen thickness). */
label_stroke_size?: F
/** Label font size. */
label_font_size?: F
/** Label font weight. */
label_font_weight?: S
/** Label line height. */
label_line_height?: F
/** Label text alignment. */
label_align?: 'left' | 'right' | 'center' | 'start' | 'end'
/** Reference line stroke color. */
ref_stroke_color?: S
/** Reference line stroke opacity. */
ref_stroke_opacity?: F
/** Reference line stroke size (line width or pen thickness). */
ref_stroke_size?: F
/** Reference line stroke dash style. A string containing space-separated integers that specify distances to alternately draw a line and a gap (in coordinate space units). If the number of elements in the array is odd, the elements of the array get copied and concatenated. For example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25]. */
ref_stroke_dash?: S
}
/** Extended mark attributes. Not exposed to API. */
interface MarkExt extends Mark {
/** Field. */
x_field?: S
/** Format string. */
x_format?: Fmt
/** Field. */
x0_field?: S
/** Format string. */
x0_format?: Fmt
/** Field. */
x1_field?: S
/** Format string. */
x1_format?: Fmt
/** Field. */
x2_field?: S
/** Format string. */
x2_format?: Fmt
/** Field. */
y_field?: S
/** Format string. */
y_format?: Fmt
/** Field. */
y0_field?: S
/** Format string. */
y0_format?: Fmt
/** Field. */
y1_field?: S
/** Format string. */
y1_format?: Fmt
/** Field. */
y2_field?: S
/** Format string. */
y2_format?: Fmt
/** Field. */
color_field?: S
/** Format string. */
color_format?: Fmt
/** Field. */
shape_field?: S
/** Format string. */
shape_format?: Fmt
/** Format string. */
size_format?: Fmt
/** Field. */
size_field?: S
/** Field. */
dodge_field?: S
/** Field. */
label_field?: S
/** Format string. */
label_format?: Fmt
}
/** Create a plot. A plot is composed of one or more graphical mark layers. */
export interface Plot {
/** The graphical mark layers contained in this plot. */
marks: Mark[];
}
registerInteraction('drag-move', {
start: [{ trigger: 'plot:mousedown', action: 'scale-translate:start' }],
processing: [{ trigger: 'plot:mousemove', action: 'scale-translate:translate', throttle: { wait: 100, leading: true, trailing: false } }],
end: [{ trigger: 'plot:mouseup', action: 'scale-translate:end' }],
})
// TODO not in use
export const
spaceTypeOf = (ds: any[], marks: Mark[]): SpaceT => spaceTypes[scaleTypeOf(ds, marks, 'x') + scaleTypeOf(ds, marks, 'y')],
crosshairFor = (t: SpaceT): 'x' | 'y' | 'xy' => {
switch (t) {
case SpaceT.CC:
case SpaceT.DD:
case SpaceT.TT:
return 'xy'
case SpaceT.DC:
case SpaceT.TC:
case SpaceT.TD:
return 'x'
case SpaceT.CD:
case SpaceT.CT:
case SpaceT.DT:
return 'y'
}
}
const
isF = (x: any): x is number => typeof x === 'number',
isB = (x: any): x is boolean => typeof x === 'boolean',
isS = (x: any): x is string => typeof x === 'string',
split = (s: S) => s.trim().split(/\s+/g),
parseInts = (s: S) => split(s).map(s => parseInt(s, 10)),
convertToDates = (ds: any[], f: S) => {
for (const d of ds) {
if (d) {
const s = d[f]
if (s && isS(s)) d[f] = new Date(s) // must be ISO string
}
}
},
convertToPairs = (ds: any[], f0: S, f1: S, f: S) => {
for (const d of ds) if (d) d[f] = [d[f0], d[f1]]
},
xyVariants = ' 0 1 2'.split(' '),
xyExtra = split('min max nice scale title'),
makeXYProps = (p: S) => xyVariants.map(s => p + s),
makeXYExtraProps = (p: S) => xyExtra.map(s => `${p}_${s}`),
makeFormattables = (xs: S[]) => xs.map(f => ([f, f + '_field', f + '_format'])),
xProps = makeFormattables(makeXYProps('x')),
yProps = makeFormattables(makeXYProps('y')),
xExtraProps = makeXYExtraProps('x'),
yExtraProps = makeXYExtraProps('y'),
otherProps = makeFormattables(split('color shape size dodge label')),
formattables = [...xProps, ...yProps, ...otherProps],
scaleTypeOf = (ds: any[], marks: Mark[], attr: S): 'c' | 'd' | 't' => {
const f = attr + '_field', s = attr + '_scale'
for (const mark of marks) {
const m = mark as any, field = m[f], scale = m[s]
if (scale === 'time') return 't'
if (isS(field)) {
for (const d of ds) {
const v = d[field]
if (isF(v)) return 'c'
if (isS(v)) return 'd'
}
}
}
return 'c'
},
spaceTypes: Dict<SpaceT> = {
cc: SpaceT.CC, dd: SpaceT.DD, tt: SpaceT.TT,
dc: SpaceT.DC, cd: SpaceT.CD,
tc: SpaceT.TC, ct: SpaceT.CT,
td: SpaceT.TD, dt: SpaceT.DT,
},
dummyDatum: any = {},
makeFormatFunc = (field: S, render: HandlebarsTemplateDelegate<any>) => (datum: any, value?: any) => {
const x = datum ? datum[field] : value
if (x != null) {
dummyDatum[field] = x
return render(dummyDatum)
}
return ''
},
transposeMark = (mark: Mark) => { // WARNING: Can modify marks in-place!
const m: any = mark
for (let k = 0; k < xProps.length; k++) {
const x = xProps[k], y = yProps[k]
for (let i = 0; i < x.length; i++) {
const tmp = m[x[i]]
m[x[i]] = m[y[i]]
m[y[i]] = tmp
}
}
for (let i = 0; i < xExtraProps.length; i++) {
const x = xExtraProps[i], y = yExtraProps[i]
const tmp = m[x]
m[x] = m[y]
m[y] = tmp
}
},
refactorMark = (mark: Mark): MarkExt => {
// if any fields are passed in as format expressions, separate them out into _field and _format
const m = mark as any
for (const [plainAttr, fieldAttr, formatAttr] of formattables) {
const expr = m[plainAttr]
if (isS(expr)) {
const fmts = parseFormat(expr)
if (fmts) {
const [field, fmt] = fmts
m[plainAttr] = undefined
m[fieldAttr] = field
if (fmt) m[formatAttr] = makeFormatFunc(field, fmt)
}
}
}
return mark
},
refactorData = (ds: any[], marks: MarkExt[]): any[] => {
for (const m of marks) {
if (m.x_scale === 'time') {
for (const { x_field, x0_field } of marks) {
if (isS(x_field)) convertToDates(ds, x_field)
if (isS(x0_field)) convertToDates(ds, x0_field)
}
if (isS(m.x)) m.x = new Date(m.x)
if (isS(m.x0)) m.x0 = new Date(m.x0)
break
}
}
for (const m of marks) {
if (m.y_scale === 'time') {
for (const { y_field, y0_field } of marks) {
if (isS(y_field)) convertToDates(ds, y_field)
if (isS(y0_field)) convertToDates(ds, y0_field)
}
if (isS(m.y)) m.y = new Date(m.y)
if (isS(m.y0)) m.y0 = new Date(m.y0)
break
}
}
for (const { x_field, x0_field } of marks) {
if (isS(x_field) && isS(x0_field)) {
convertToPairs(ds, x0_field, x_field, x_field)
}
}
for (const { y_field, y0_field } of marks) {
if (isS(y_field) && isS(y0_field)) {
convertToPairs(ds, y0_field, y_field, y_field)
}
}
for (const mark of marks) {
const { type, x1_field, x2_field, y_field } = mark
if (type === 'interval' && isS(x1_field) && isS(x2_field) && isS(y_field)) { // histogram on x
mark.x_field = x1_field + ' - ' + x2_field
convertToPairs(ds, x1_field, x2_field, mark.x_field)
}
}
for (const mark of marks) {
const { type, y1_field, y2_field, x_field } = mark
if (type === 'interval' && isS(y1_field) && isS(y2_field) && isS(x_field)) { // histogram on y
mark.y_field = y1_field + ' - ' + y2_field
convertToPairs(ds, y1_field, y2_field, mark.y_field)
}
}
return ds
},
makeNote = ({
x, x0, y, y0, label,
fill_color, fill_opacity, stroke_color, stroke_opacity, stroke_size, stroke_dash,
ref_stroke_color, ref_stroke_opacity, ref_stroke_dash, ref_stroke_size,
label_fill_color, label_fill_opacity, label_stroke_color, label_stroke_opacity, label_stroke_size,
label_font_size, label_font_weight, label_line_height, label_align,
}: Mark): AnnotationOption[] => {
// XXX pass 'start'/'end' if axis is categorical
const
labelStyle = makeTextStyle(
label_fill_color, label_fill_opacity, label_stroke_color, label_stroke_opacity, label_stroke_size,
label_font_size, label_font_weight, label_line_height, label_align,
),
shapeStyle = makeShapeStyle(fill_color, fill_opacity, stroke_color, stroke_opacity, stroke_size, stroke_dash),
lineStyle = makeShapeStyle(undefined, undefined, ref_stroke_color, ref_stroke_opacity, ref_stroke_size, ref_stroke_dash)
if (x != null && y != null) {
if (x0 != null && y0 != null) {
const region: DataRegionOption = {
type: 'region',
start: [x0, y0] as AnnotationPosition,
end: [x, y] as AnnotationPosition,
text: isS(label) ? { content: label, style: labelStyle } : undefined,
style: shapeStyle,
}
return [region]
} else {
const marker: DataMarkerOption = {
type: 'dataMarker',
position: [x, y] as AnnotationPosition,
text: isS(label) ? { content: label, style: labelStyle } : null,
point: { style: shapeStyle },
line: { style: lineStyle }
}
return [marker]
}
} else if (x != null) {
if (x0 != null) {
const region: DataRegionOption = {
type: 'region',
start: [x0, 'min'] as AnnotationPosition,
end: [x, 'max'] as AnnotationPosition,
text: isS(label) ? { content: label, style: labelStyle } : null,
style: shapeStyle,
}
return [region]
} else {
const line: LineOption = {
type: 'line',
start: [x, 'min'] as AnnotationPosition,
end: [x, 'max'] as AnnotationPosition,
text: isS(label) ? { content: label, style: labelStyle, position: 'start' } : undefined,
style: lineStyle,
}
return [line]
}
} else { // y != null
if (y0 != null) {
const region: DataRegionOption = {
type: 'region',
start: ['min', y0] as AnnotationPosition,
end: ['max', y] as AnnotationPosition,
text: isS(label) ? { content: label, style: labelStyle } : null,
style: shapeStyle,
}
return [region]
} else {
const line: LineOption = {
type: 'line',
start: ['min', y] as AnnotationPosition,
end: ['max', y] as AnnotationPosition,
text: isS(label) ? { content: label, style: labelStyle, position: 'start' } : undefined,
style: lineStyle,
}
return [line]
}
}
},
makeGeom = ({
type, x_field, y_field,
color_field, color_range, color_domain, color,
shape_field, shape_range, shape,
size_field, size_range, size,
stack,
dodge, dodge_field,
curve,
fill_color, fill_opacity, stroke_color, stroke_opacity, stroke_dash, stroke_size,
label_field, label_format, label_offset, label_offset_x, label_offset_y, label_rotation, label_position, label_overlap,
label_fill_color, label_fill_opacity, label_stroke_color, label_stroke_opacity, label_stroke_size,
label_font_size, label_font_weight, label_line_height, label_align,
}: MarkExt): GeometryOption => {
const o: GeometryOption = {}
if (isS(type)) o.type = type
const adjust: AdjustOption[] = []
// TODO set marginRatio=1 polar coords
if (isS(dodge_field)) {
adjust.push({ type: 'dodge', marginRatio: 0, dodgeBy: dodge_field })
} else if (dodge === 'auto') {
adjust.push({ type: 'dodge', marginRatio: 0 })
}
if (stack === 'auto') adjust.push({ type: 'stack' })
if (adjust.length) o.adjust = adjust
if (isS(x_field) && isS(y_field)) o.position = { fields: [x_field, y_field] }
if (isS(color_field)) {
const colors = isS(color_range) ? split(color_range).map(cssVarValue) : cat10
o.color = { fields: [color_field], values: colors }
if (color_domain && color_domain.length == colors.length) {
const domain_colors = color_domain.reduce((acc, value, i) => {
acc[value] = colors[i]
return acc
}, {} as Dict<S>)
o.color.callback = (x: S) => domain_colors[x]
}
} else {
o.color = cssVar(isS(color) ? color : '$themePrimary')
}
if (isS(shape_field)) {
if (isS(shape_range)) {
o.shape = { fields: [shape_field], values: split(shape_range) }
} else {
o.shape = { fields: [shape_field] }
}
} else if (isS(shape)) {
o.shape = shape
}
if (isS(size_field)) {
if (isS(size_range)) {
o.size = { fields: [size_field], values: parseInts(size_range) }
} else {
o.size = { fields: [size_field] }
}
} else if (isF(size)) {
o.size = size
}
if (isS(label_field)) {
const styles = makeTextStyle(
label_fill_color, label_fill_opacity, label_stroke_color, label_stroke_opacity, label_stroke_size,
label_font_size, label_font_weight, label_line_height, label_align,
)
const c: Dict<any> = {}
if (styles) c.style = styles
switch (label_overlap) {
case 'hide': c.layout = { type: 'overlap' }; break
case 'overlap': c.layout = { type: 'fixedOverlap' }; break
case 'constrain': c.layout = { type: 'limitInShape' }; break
}
if (isF(label_offset)) c.offset = label_offset
if (isF(label_offset_x)) c.offsetX = label_offset_x
if (isF(label_offset_y)) c.offsetY = label_offset_y
if (isS(label_rotation)) {
const i_label_rotation = parseI(label_rotation)
if (isNaN(i_label_rotation)) {
c.autoRotate = label_rotation === 'none' ? false : true
} else {
c.rotate = i_label_rotation * Math.PI / 180
}
}
switch (label_position) {
case 'top': case 'bottom': case 'middle': case 'left': case 'right': c.position = label_position as any
}
if (label_format) {
o.label = {
fields: [label_field],
callback: (label) => ({ content: label_format(null, label) })
}
} else {
o.label = { fields: [label_field] }
}
if (Object.keys(c).length) o.label.cfg = c
}
if (isS(curve)) {
switch (curve) {
case 'smooth': o.shape = 'smooth'; break
case 'step-before': o.shape = 'vh'; break
case 'step': o.shape = 'hvh'; break
case 'step-after': o.shape = 'hv'; break
}
}
const style = makeShapeStyle(fill_color, fill_opacity, stroke_color, stroke_opacity, stroke_size, stroke_dash)
if (style) o.style = style
return o
},
makeShapeStyle = (fill_color?: S, fill_opacity?: F, stroke_color?: S, stroke_opacity?: F, stroke_size?: F, stroke_dash?: S): Dict<any> | undefined => {
const s: Dict<any> = {}
if (isS(fill_color)) s.fill = cssVarValue(fill_color)
if (isF(fill_opacity)) s.fillOpacity = fill_opacity
if (isS(stroke_color)) s.stroke = cssVarValue(stroke_color)
if (isF(stroke_opacity)) s.strokeOpacity = stroke_opacity
if (isF(stroke_size)) s.lineWidth = stroke_size
if (isS(stroke_dash)) s.lineDash = parseInts(stroke_dash)
return Object.keys(s).length ? s : undefined
},
makeTextStyle = (fill_color?: S, fill_opacity?: F, stroke_color?: S, stroke_opacity?: F, stroke_size?: F, font_size?: F, font_weight?: S, line_height?: F, align?: S): Dict<any> | undefined => {
const s: Dict<any> = {}
s.fill = cssVar(isS(fill_color) ? fill_color : '$neutralPrimaryAlt')
if (isF(fill_opacity)) s.fillOpacity = fill_opacity
if (isS(stroke_color)) s.stroke = cssVarValue(stroke_color)
if (isF(stroke_opacity)) s.strokeOpacity = stroke_opacity
if (isF(stroke_size)) s.lineWidth = stroke_size
if (isF(font_size)) s.fontSize = font_size
if (isS(font_weight)) {
const u_font_weight = parseU(font_weight)
s.fontWeight = isNaN(u_font_weight) ? font_weight : u_font_weight
}
if (isF(line_height)) s.lineHeight = line_height
if (isS(align)) s.textAlign = align
return Object.keys(s).length ? s : undefined
},
makeScales = (marks: MarkExt[]): [Record<S, ScaleOption>, Record<S, AxisOption>] => {
const
scales: Record<S, ScaleOption> = {},
axes: Record<S, AxisOption> = {}
for (const m of marks) {
if (m.x_field) {
const [x_scale, x_axis] = makeScale(m.x_scale, m.x_format, m.x_title, m.x_min, m.x_max, m.x_nice)
scales[m.x_field] = x_scale
if (x_axis) axes[m.x_field] = x_axis
break
}
}
for (const m of marks) {
if (m.y_field) {
const [y_scale, y_axis] = makeScale(m.y_scale, m.y_format, m.y_title, m.y_min, m.y_max, m.y_nice)
scales[m.y_field] = y_scale
if (y_axis) axes[m.y_field] = y_axis
break
}
}
return [scales, axes]
},
fixScaleType = (t: S): S => {
switch (t) {
case 'time-category': return 'timeCat'
case 'power': return 'pow'
}
return t
},
makeScale = (typ: S | undefined, format: Fmt | undefined, title: S | undefined, min: S | F | undefined, max: S | F | undefined, nice: B | undefined): [ScaleOption, AxisOption | null] => {
const
scale: ScaleOption = {},
axis: AxisOption = { label: { autoHide: false } } // Bug in G2? `autoHide` should be set to false by default (it is not).
if (isS(typ)) scale.type = fixScaleType(typ) as any
if (format) scale.formatter = (v: any) => format(undefined, v)
if (isS(title)) {
scale.alias = title
// HACK ALERT!
// The scale alias is not rendered by G2 unless the axis title is non-empty.
axis.title = {}
}
if (isF(min)) scale.min = min
if (isF(max)) scale.max = max
scale.nice = isB(nice) ? nice : true
return [scale, axis]
},
getCoordType = (marks: Mark[]): S | undefined => {
for (const { coord } of marks) if (isS(coord)) return coord
return undefined
},
makeCoord = (space: SpaceT, marks: Mark[]): CoordinateOption | undefined => {
// HACK ALERT!
// Flip all x* and y* properties if the x-variable is continuous.
// This is because the underlying lib expects x-variables to be always discrete.
// So if the coord space is continuous-discrete, flip x/y and set a transpose transform on the coords.
const
type = getCoordType(marks) as any,
transpose = space === SpaceT.CD,
actions: CoordinateActions[] | undefined = transpose ? [['transpose']] : undefined
if (transpose) for (const mark of marks) transposeMark(mark)
return (
type
? actions ? { type, actions } : { type }
: actions ? { actions } : undefined
)
},
makeMarks = (marks: Mark[]): [GeometryOption[], AnnotationOption[]] => {
const
geometries: GeometryOption[] = [],
annotations: AnnotationOption[] = []
for (const m of marks) {
const { x, y } = m
if (x != null || y != null) {
annotations.push(...makeNote(m))
} else {
geometries.push(makeGeom(m))
}
}
return [geometries, annotations]
},
makeChart = (el: HTMLElement, space: SpaceT, marks: Mark[]): ChartCfg => {
// WARNING: makeCoord() must be called before other functions.
const
coordinate = makeCoord(space, marks), // WARNING: this call may transpose x/y in-place.
[scales, axes] = makeScales(marks),
[geometries, annotations] = makeMarks(marks)
return {
container: el,
autoFit: true,
renderer: 'svg', // Use SVG to allow use of CSS vars which don't work with canvas.
theme: { // Referrence: https://theme-set.antv.vision/ https://g2.antv.vision/en/docs/api/advanced/register-theme
defaultColor: cssVar('$themePrimary'),
geometries: {
point: {
'hollow-circle': {
default: {
style: {
fill: 'transparent'
}
}
}
},
interval: {
rect: {
selected: {
style: {
stroke: cssVar('$text'),
}
}
},
}
},
components: {
annotation: {
dataMarker: {
point: {
style: {
stroke: cssVar('$themePrimary'),
fill: cssVar('$card'),
}
}
},
line: {
style: {
fill: cssVar('$neutralPrimaryAlt'),
}
},
region: {
style: {
fill: cssVar('$themePrimary'),
fillOpacity: 0.3
}
},
},
legend: {
common: {
pageNavigator: {
marker: {
style: {
fill: cssVar('$themePrimary'),
inactiveFill: cssVar('$themePrimary')
}
},
}
},
continuous: {
handler: {
style: {
fill: cssVar('$neutralPrimaryAlt'),
}
},
}
},
axis: {
common: {
grid: {
line: {
style: {
stroke: cssVar('$neutralPrimaryAlt'),
strokeOpacity: 0.2
}
}
},
line: {
style: {
stroke: cssVar('$neutralPrimaryAlt'),
strokeOpacity: 0.6
}
},
tickLine: {
style: {
stroke: cssVar('$neutralPrimaryAlt'),
strokeOpacity: 0.6
}
},
}
},
}
},
options: {
animate: false,
coordinate,
scales,
axes,
geometries,
annotations,
interactions: [
{ type: 'drag-move' }, // custom
],
tooltip: {
showCrosshairs: true,
crosshairs: { type: 'xy' }
// XXX pass container element
}
}
}
}
const
css = stylesheet({
card: {
display: 'flex',
flexDirection: 'column',
padding: grid.gap,
},
body: {
flexGrow: 1,
display: 'flex',
},
plot: {
$nest: {
'svg': {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
overflow: 'visible'
},
'text': {
fill: `${cssVar('$text')} !important`
}
}
}
})
/** Create a visualization for display inside a form. */
export interface Visualization {
/** The plot to be rendered in this visualization. */
plot: Plot
/** Data for this visualization. */
data: Rec
/** The width of the visualization. Defaults to '100%'. */
width?: S
/** The hight of the visualization. Defaults to '300px'. */
height?: S
/** An identifying name for this component. */
name?: S
/** True if the component should be visible. Defaults to true. */
visible?: B
/** The events to capture on this visualization. */
events?: S[]
}
export const
XVisualization = ({ model }: { model: Visualization }) => {
const
container = React.useRef<HTMLDivElement>(null),
currentChart = React.useRef<Chart | null>(null),
currentPlot = React.useRef<Plot | null>(null),
checkDimensionsPostInit = (w: F, h: F) => { // Safari fix
const el = container.current
if (!el) return
if (el.clientHeight !== h || el.clientWidth !== w) {
currentChart.current?.destroy()
init()
}
},
init = () => {
// Map CSS var colors to their hex values.
cat10 = cat10.map(cssVarValue)
const el = container.current
if (!el) return
// If card does not have specified height, it uses content. Since the wrapper is empty, it takes very little space - set to 300px by default.
if (el.clientHeight < 30) el.style.height = '300px'
const
raw_data = unpack<any[]>(model.data),
raw_plot = unpack<Plot>(model.plot),
marks = raw_plot.marks.map(refactorMark),
plot: Plot = { marks },
space = spaceTypeOf(raw_data, marks),
data = refactorData(raw_data, plot.marks),
chart = plot.marks ? new Chart(makeChart(el, space, plot.marks)) : null
currentPlot.current = plot
if (chart) {
currentChart.current = chart
chart.data(data)
if (model.events) {
for (const event of model.events) {
switch (event) {
case 'select_marks': {
chart.interaction('element-single-selected')
chart.on('element:statechange', (ev: any) => {
const e = ev.gEvent.originalEvent
if (e.stateStatus && e.state === 'selected') {
if (model.name) wave.emit(model.name, event, [e.element?.data])
}
})
}
}
}
}
chart.render()
// React fires mount lifecycle hook before Safari finishes Layout phase so we need recheck if original card dimensions are the
// same as after Layout phase. If not, rerender the plot again.
setTimeout(() => checkDimensionsPostInit(el.clientWidth, el.clientHeight), 300)
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
React.useEffect(init, [])
React.useEffect(() => {
const el = container.current
if (!el || !currentChart.current || !currentPlot.current) return
const
raw_data = unpack<any[]>(model.data),
data = refactorData(raw_data, currentPlot.current.marks)
currentChart.current.changeData(data)
}, [currentChart, currentPlot, model])
const
{ width = 'auto', height = 'auto', name } = model,
style: React.CSSProperties = (width === 'auto' && height === 'auto')
? { flexGrow: 1 }
: { width: formItemWidth(width), height }
return <div data-test={name} style={style} className={css.plot} ref={container} />
}
/** Create a card displaying a plot. */
interface State {
/** The title for this card. */
title: S
/** Data for this card. */
data: Rec
/** The plot to be displayed in this card. */
plot: Plot
/** The events to capture on this card. */
events?: S[]
}
export const
View = bond(({ name, state, changed }: Model<State>) => {
const
render = () => {
const { title = 'Untitled', plot, data, events } = state
return (
<div className={css.card}>
<div className='wave-s12 wave-w6'>{title}</div>
<div className={css.body}>
<XVisualization model={{ name, plot, data, events }} />
</div>
</div>
)
}
return { render, changed }
})
cards.register('plot', View) | the_stack |
import React, { Component } from 'react'
import {
StyleSheet,
Text,
View,
Animated,
TouchableWithoutFeedback,
StatusBar,
ViewPagerAndroid
} from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
import { connect } from 'react-redux'
import { changeSegmentIndex, changeCommunityType, changeGeneType } from '../redux/action/app'
import { getRecommend } from '../redux/action/recommend'
import { standardColor } from '../constant/colorConfig'
import { routes } from './Tab'
let title = 'PSNINE'
const searchAction = { title: '搜索', iconName: 'md-search', value: '', show: 'always' }
let recommendActions = [
searchAction
]
let communityActions = [
{ title: '新建', iconName: 'md-create', value: '', show: 'always', iconSize: 22 },
searchAction,
{ title: '全部', value: '', show: 'never' },
{ title: '新闻', value: 'news', show: 'never' },
{ title: '攻略', value: 'guide', show: 'never' },
{ title: '测评', value: 'review', show: 'never' },
{ title: '心得', value: 'exp', show: 'never' },
{ title: 'Plus', value: 'plus', show: 'never' },
{ title: '开箱', value: 'openbox', show: 'never' },
{ title: '游列', value: 'gamelist', show: 'never' },
{ title: '活动', value: 'event', show: 'never' }
]
let qaActions = [
{ title: '新建', iconName: 'md-create', value: '', show: 'always', iconSize: 22 },
searchAction
]
let gameActions = [
searchAction
]
let rankActions = [
searchAction
]
let battleActions = [
{ title: '新建', iconName: 'md-create', value: '', show: 'always', iconSize: 22 }
]
let geneActions = [
{ title: '新建', iconName: 'md-create', value: '', show: 'always', iconSize: 22 },
searchAction,
{ title: '综合排序', value: 'obdate', show: 'never' },
{ title: '最新', value: 'date', show: 'never' }
]
let storeActions = [
searchAction
]
let tradeActions = [
{ title: '新建', iconName: 'md-create', value: '', show: 'always', iconSize: 22 },
searchAction
]
let discountActions = [
searchAction
]
let toolbarActions = [
recommendActions,
communityActions,
qaActions,
geneActions,
gameActions,
discountActions,
battleActions,
rankActions,
/*circleActions,*/
storeActions,
tradeActions
]
let toolbarHeight = 56
import {
AppBarLayoutAndroid,
CoordinatorLayoutAndroid,
TabLayoutAndroid,
PopupWindowAndroid
} from 'mao-rn-android-kit'
class Toolbar extends Component<any, any> {
constructor(props) {
super(props)
this.state = {
search: '',
rotation: new Animated.Value(1),
scale: new Animated.Value(1),
opacity: new Animated.Value(1),
marginTop: new Animated.Value(0),
openVal: new Animated.Value(0),
innerMarginTop: new Animated.Value(0),
modalVisible: false,
modalOpenVal: new Animated.Value(0),
topicMarginTop: new Animated.Value(0),
tabMode: this.props.modeInfo.settingInfo.tabMode,
_scrollHeight: this.props.modeInfo.height - (StatusBar.currentHeight || 0) - 38 + 1
// _scrollHeight:
}
}
searchMapper = Object.keys(routes).reduce((prev, curr) => (prev[curr] = '', prev), {})
afterEachHooks = []
componentWillMount() {
this.props.dispatch(getRecommend())
this._pages.length = 0
}
componentWillReceiveProps(nextProps) {
if (this.state.tabMode !== nextProps.modeInfo.settingInfo.tabMode) {
this.setState({
tabMode: nextProps.modeInfo.settingInfo.tabMode
})
} else if (this.props.modeInfo.width !== nextProps.modeInfo.width) {
this.setState({
_scrollHeight: nextProps.modeInfo.height - (StatusBar.currentHeight || 0) - 38 + 1
})
}
}
_onSearch = (text) => {
this.setState({
search: text
})
const currentIndex = this.props.app.segmentedIndex
const callback = this.afterEachHooks[currentIndex]
typeof callback === 'function' && callback(text)
const currentRouteName = Object.keys(routes)[currentIndex]
this.searchMapper[currentRouteName] = text
}
_onSearchClicked = () => {
this.props.navigation.navigate('Search', {
shouldSeeBackground: true,
content: this.state.search,
callback: this._onSearch
})
}
onActionSelected = (index) => {
const { segmentedIndex, communityType } = this.props.app
// console.log(segmentedIndex)
const { dispatch } = this.props
if (segmentedIndex === 1) {
if (index !== 0 && index !== 1) {
let type = toolbarActions[segmentedIndex][index].value
dispatch(changeCommunityType(type))
} else {
index === 1 && this._onSearchClicked()
const obj: any = {}
if (communityType) {
obj.URL = `https://psnine.com/node/${communityType}/add`
}
index === 0 && this.props.navigation.navigate('NewTopic', obj)
}
} else if (segmentedIndex === 2) {
index === 0 && this.props.navigation.navigate('NewQa', {})
index === 1 && this._onSearchClicked()
} else if (segmentedIndex === 3) {
if (index !== 0 && index !== 1) {
let type = toolbarActions[segmentedIndex][index].value
dispatch(changeGeneType(type))
} else {
index === 1 && this._onSearchClicked()
index === 0 && this.props.navigation.navigate('NewGene', {})
}
} else if (segmentedIndex === 6) {
this.props.navigation.navigate('NewBattle', {})
} else if (segmentedIndex === 9) {
index === 0 && this.props.navigation.navigate('NewTrade', {})
index === 1 && this._onSearchClicked()
} else {
this._onSearchClicked()
}
}
render() {
const { app: appReducer, modeInfo } = this.props
// alert(appReducer.segmentedIndex)
return (
<View style={{ flex: 1 }}>
<CoordinatorLayoutAndroid
fitsSystemWindows={false}
ref={this._setCoordinatorLayout}>
<AppBarLayoutAndroid
ref={this._setAppBarLayout}
layoutParams={{
height: 94 // required
}}
style={styles.appbar} >
<View
style={styles.navbar}
layoutParams={{
height: 56, // required
scrollFlags: (
AppBarLayoutAndroid.SCROLL_FLAG_SCROLL |
AppBarLayoutAndroid.SCROLL_FLAG_ENTRY_ALWAYS
)
}}>
<View style={styles.toolbar}>
<Icon.ToolbarAndroid
navIconName='md-menu'
style={[styles.toolbar, { backgroundColor: modeInfo.standardColor, elevation: 0 }]}
overflowIconName='md-more'
iconColor={modeInfo.isNightMode ? '#000' : '#fff'}
actions={toolbarActions[appReducer.segmentedIndex]}
key={appReducer.segmentedIndex}
origin
onActionSelected={this.onActionSelected}
onIconClicked={this.props._callDrawer()}
>
<TouchableWithoutFeedback>
<View style={{ height: 56, flex: 1, flexDirection: 'column', justifyContent: 'center' }}>
<Text style={{ fontSize: 20, fontWeight: '500', color: modeInfo.isNightMode ? '#000' : '#fff' }} onPress={() => {
const index = this._currentViewPagerPageIndex
const callback = this.afterEachHooks[index]
{/*log(callback, this.state.afterEachHooks, index)*/ }
typeof callback === 'function' && callback()
}}>
{title}
</Text>
{this.state.search && <Text
onPress={() => {
this._onSearch('')
}}
style={{ fontSize: 15, color: modeInfo.isNightMode ? '#000' : '#fff' }}>
{`当前搜索: ${this.state.search}`}
</Text> || undefined}
</View>
</TouchableWithoutFeedback>
</Icon.ToolbarAndroid>
</View>
<View style={styles.actionBar}>
</View>
</View>
<View
style={styles.tabBar}>
<TabLayoutAndroid
tabMode='scrollable'
tabSelectedTextColor='#fff'
tabIndicatorColor='#fff'
tabTextColor='rgba(255, 255, 255, .6)'
tabIndicatorHeight={2}
tabSidePadding={22}
tabGravity='center'
tabHeight={38}
ref={this._setTabLayout}
style={{
backgroundColor: modeInfo.standardColor
}} />
</View>
</AppBarLayoutAndroid>
<View
style={[styles.scrollView, { height: this.state._scrollHeight }]}
ref={this._setScrollView}>
<ViewPagerAndroid
onPageScroll={this._handleViewPagerPageScroll}
onPageScrollStateChanged={this._handleViewPagerPageScrollStateChanged}
onPageSelected={this._handleViewPagerPageSelected}
style={[styles.viewPager, { height: this.state._scrollHeight }]}
initialPage={this._currentViewPagerPageIndex}
ref={this._setViewPager}>
{this._getPages({
height: this.state._scrollHeight,
initialPage: this._currentViewPagerPageIndex
})}
</ViewPagerAndroid>
</View>
</CoordinatorLayoutAndroid>
<PopupWindowAndroid
ref={this._setMenuPopup}>
<View style={styles.menu}>
</View>
</PopupWindowAndroid>
</View>
)
}
_tabTexts = Object.keys(routes).map(name => ({ text: routes[name].screen.navigationOptions.tabBarLabel }))
_coordinatorLayout: any = null
_appBarLayout: any = null
_scrollView: any = null
_viewPager: any = null
_menuPopup: any = null
_menuBtn: any = null
_tabLayout: any = null
_pages: JSX.Element[] = []
_currentViewPagerPageIndex: number = 0
_handleMenuButtonPess = () => {
this._menuPopup.showAsDropdown(this._menuBtn, 0, -10)
}
_setMenuBtn = component => {
this._menuBtn = component
}
_handleMenuItemPress = () => {
this._menuPopup.hide()
}
_setMenuPopup = component => {
this._menuPopup = component
}
_setCoordinatorLayout = component => {
this._coordinatorLayout = component
}
_setAppBarLayout = component => {
this._appBarLayout = component
}
_setTabLayout = component => {
this._tabLayout = component
}
_setScrollView = component => {
this._scrollView = component
}
_setViewPager = component => {
this._viewPager = component
}
_addPage = component => {
this._pages.push(component)
}
_handleViewPagerPageScroll = event => {
let nativeEvent = event.nativeEvent
const { position, offset } = nativeEvent
const targetLimit = position === this._currentViewPagerPageIndex ? 0.60 : 0.40
if (offset >= targetLimit) {
this._currentViewPagerPageIndex = nativeEvent.position + 1
} else {
this._currentViewPagerPageIndex = nativeEvent.position
}
}
_handleViewPagerPageScrollStateChanged = scrollState => {
if (scrollState === 'settling') {
this._loadPage(this._currentViewPagerPageIndex)
}
}
_handleViewPagerPageSelected = event => {
let nativeEvent = event.nativeEvent
this._loadPage(nativeEvent.position)
}
_loadPage(index) {
let page: any = this.refs['page_' + index]
if (page && !page.isLoaded()) {
page.load()
}
if (index !== this.props.app.segmentedIndex) {
this.props.dispatch(changeSegmentIndex(index))
setTimeout(() => {
const callback = this.afterEachHooks[index]
const currentRouteName = Object.keys(routes)[index]
if (this.searchMapper[currentRouteName] !== this.state.search) {
typeof callback === 'function' && callback(this.state.search)
this.searchMapper[currentRouteName] = this.state.search
}
})
}
}
_getPages({ height, initialPage = 1 }) {
const { modeInfo } = this.props
// console.log(this.props.app.communityType, '===========outter')
return this._tabTexts.map((tab, index) => {
return (
<View
key={index}
style={{ backgroundColor: modeInfo.background }}>
<Page
ref={'page_' + index}
tab={tab}
pageIndex={index}
index={index}
height={height}
initialPage={initialPage}
screenProps={{
communityType: this.props.app.communityType,
geneType: this.props.app.geneType,
circleType: this.props.app.circleType,
navigation: this.props.navigation,
toolbarDispatch: this.props.dispatch,
segmentedIndex: this.props.app.segmentedIndex,
modeInfo: this.props.modeInfo,
modalVisible: this.state.modalVisible,
searchTitle: this.state.search,
registerAfterEach: componentDidFocus => {
if (componentDidFocus) {
const { index, handler } = componentDidFocus
this.afterEachHooks = [...this.afterEachHooks]
this.afterEachHooks[index] = handler
}
}
}}
navigation={{
navigate: (name) => {
if (name === 'Community') {
this._currentViewPagerPageIndex = 1
this._viewPager.setPage(1)
this._loadPage(1)
}
}
}}
key={index} />
</View>
)
})
}
componentDidMount() {
this._coordinatorLayout.setScrollingViewBehavior(this._scrollView)
this._tabLayout.setViewPager(this._viewPager, this._tabTexts)
this._viewPager.setPageWithoutAnimation(1)
// this._viewPager.setViewSize
this.refs.page_1.load()
this._currentViewPagerPageIndex = 1
// this.props.navigation.navigate('Home', {
// title: 'secondlife_xhm',
// id: 'secondlife_xhm',
// URL: `https://psnine.com/psnid/${'secondlife_xhm'}`
// })
}
}
class Page extends Component<any, any> {
constructor(props) {
super(props)
this.state = {
loaded: false
}
}
shouldComponentUpdate(nextProps) {
if (nextProps.screenProps.segmentedIndex !== this.props.screenProps.segmentedIndex) {
if (nextProps.screenProps.segmentedIndex === this.props.index) return true
return false
}
return true
}
render() {
let content: any = null
if (this.state.loaded) {
content = this._getContent()
} else {
content = <View></View>
}
return content
}
isLoaded() {
return this.state.loaded
}
load() {
if (this.state.loaded) return
this.state.loaded = true
this.setState({
loaded: true
})
}
_getContent() {
const Name = Object.keys(routes)[this.props.index]
const TargetRoute = routes[Name]
if (!TargetRoute) return null
let Target = TargetRoute.screen
let items = (
<Target
{...this.props}
/>
)
return items
// return <NestedScrollViewAndroid showVerticalScrollIndicator={true} showsVerticalScrollIndicator={true}>{items}</NestedScrollViewAndroid>
}
}
function mapStateToProps(state) {
return {
app: state.app
}
}
export default connect(
mapStateToProps
)(Toolbar)
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: '#F5FCFF'
},
toolbar: {
backgroundColor: standardColor,
height: toolbarHeight,
elevation: 0
},
segmentedView: {
backgroundColor: '#F5FCFF'
},
selectedTitle: {},
appbar: {
backgroundColor: '#2278F6'
},
avatar: {
width: 50,
height: 50
},
navbar: {
height: 56
// alignItems: "center",
// justifyContent: "center",
// backgroundColor: "transparent",
// position: 'relative'
},
backBtn: {
top: 0,
left: 0,
height: 56,
position: 'absolute'
},
caption: {
color: '#fff',
fontSize: 20
},
actionBar: {
position: 'absolute',
top: 0,
right: 0,
height: 56,
flexDirection: 'column',
flexWrap: 'nowrap',
justifyContent: 'center',
paddingLeft: 10
},
actionBtn: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
menuBtn: {
width: 34,
paddingRight: 10
},
menuBtnIcon: {
width: 16,
height: 16,
tintColor: 'rgba(255, 255, 255, .8)'
},
menu: {
width: 150,
backgroundColor: 'rgba(0, 0, 0, 0.8)'
},
tabBar: {
height: 38,
backgroundColor: '#4889F1'
},
scrollView: {
backgroundColor: '#f2f2f2'
},
viewPager: {
flex: 1,
backgroundColor: 'transparent'
},
pageItem: {
borderRadius: 2,
height: 200,
marginLeft: 10,
marginRight: 10,
marginTop: 5,
marginBottom: 5,
justifyContent: 'center',
alignItems: 'center'
},
pageItemContent: {
fontSize: 30,
color: '#FFF'
}
}) | the_stack |
import {getScrollingElement} from "../../util/scrolling-element";
// tslint:disable
interface IVisualViewport {
height: number;
width: number;
}
declare var visualViewport: IVisualViewport;
interface VisualViewportable {
visualViewport?: {
height: number;
width: number;
};
}
/**
* Find out which edge to align against when logical scroll position is "nearest"
* Interesting fact: "nearest" works similarly to "if-needed", if the element is fully visible it will not scroll it
*
* Legends:
* ┌────────┐ ┏ ━ ━ ━ ┓
* │ target │ frame
* └────────┘ ┗ ━ ━ ━ ┛
*/
function alignNearest(
scrollingEdgeStart: number,
scrollingEdgeEnd: number,
scrollingSize: number,
scrollingBorderStart: number,
scrollingBorderEnd: number,
elementEdgeStart: number,
elementEdgeEnd: number,
elementSize: number
) {
/**
* If element edge A and element edge B are both outside scrolling box edge A and scrolling box edge B
*
* ┌──┐
* ┏━│━━│━┓
* │ │
* ┃ │ │ ┃ do nothing
* │ │
* ┗━│━━│━┛
* └──┘
*
* If element edge C and element edge D are both outside scrolling box edge C and scrolling box edge D
*
* ┏ ━ ━ ━ ━ ┓
* ┌───────────┐
* │┃ ┃│ do nothing
* └───────────┘
* ┗ ━ ━ ━ ━ ┛
*/
if (
(elementEdgeStart < scrollingEdgeStart && elementEdgeEnd > scrollingEdgeEnd) ||
(elementEdgeStart > scrollingEdgeStart && elementEdgeEnd < scrollingEdgeEnd)
) {
return 0;
}
/**
* If element edge A is outside scrolling box edge A and element height is less than scrolling box height
*
* ┌──┐
* ┏━│━━│━┓ ┏━┌━━┐━┓
* └──┘ │ │
* from ┃ ┃ to ┃ └──┘ ┃
*
* ┗━ ━━ ━┛ ┗━ ━━ ━┛
*
* If element edge B is outside scrolling box edge B and element height is greater than scrolling box height
*
* ┏━ ━━ ━┓ ┏━┌━━┐━┓
* │ │
* from ┃ ┌──┐ ┃ to ┃ │ │ ┃
* │ │ │ │
* ┗━│━━│━┛ ┗━│━━│━┛
* │ │ └──┘
* │ │
* └──┘
*
* If element edge C is outside scrolling box edge C and element width is less than scrolling box width
*
* from to
* ┏ ━ ━ ━ ━ ┓ ┏ ━ ━ ━ ━ ┓
* ┌───┐ ┌───┐
* │ ┃ │ ┃ ┃ │ ┃
* └───┘ └───┘
* ┗ ━ ━ ━ ━ ┛ ┗ ━ ━ ━ ━ ┛
*
* If element edge D is outside scrolling box edge D and element width is greater than scrolling box width
*
* from to
* ┏ ━ ━ ━ ━ ┓ ┏ ━ ━ ━ ━ ┓
* ┌───────────┐ ┌───────────┐
* ┃ │ ┃ │ ┃ ┃ │
* └───────────┘ └───────────┘
* ┗ ━ ━ ━ ━ ┛ ┗ ━ ━ ━ ━ ┛
*/
if (
(elementEdgeStart <= scrollingEdgeStart && elementSize <= scrollingSize) ||
(elementEdgeEnd >= scrollingEdgeEnd && elementSize >= scrollingSize)
) {
return elementEdgeStart - scrollingEdgeStart - scrollingBorderStart;
}
/**
* If element edge B is outside scrolling box edge B and element height is less than scrolling box height
*
* ┏━ ━━ ━┓ ┏━ ━━ ━┓
*
* from ┃ ┃ to ┃ ┌──┐ ┃
* ┌──┐ │ │
* ┗━│━━│━┛ ┗━└━━┘━┛
* └──┘
*
* If element edge A is outside scrolling box edge A and element height is greater than scrolling box height
*
* ┌──┐
* │ │
* │ │ ┌──┐
* ┏━│━━│━┓ ┏━│━━│━┓
* │ │ │ │
* from ┃ └──┘ ┃ to ┃ │ │ ┃
* │ │
* ┗━ ━━ ━┛ ┗━└━━┘━┛
*
* If element edge C is outside scrolling box edge C and element width is greater than scrolling box width
*
* from to
* ┏ ━ ━ ━ ━ ┓ ┏ ━ ━ ━ ━ ┓
* ┌───────────┐ ┌───────────┐
* │ ┃ │ ┃ │ ┃ ┃
* └───────────┘ └───────────┘
* ┗ ━ ━ ━ ━ ┛ ┗ ━ ━ ━ ━ ┛
*
* If element edge D is outside scrolling box edge D and element width is less than scrolling box width
*
* from to
* ┏ ━ ━ ━ ━ ┓ ┏ ━ ━ ━ ━ ┓
* ┌───┐ ┌───┐
* ┃ │ ┃ │ ┃ │ ┃
* └───┘ └───┘
* ┗ ━ ━ ━ ━ ┛ ┗ ━ ━ ━ ━ ┛
*
*/
if ((elementEdgeEnd > scrollingEdgeEnd && elementSize < scrollingSize) || (elementEdgeStart < scrollingEdgeStart && elementSize > scrollingSize)) {
return elementEdgeEnd - scrollingEdgeEnd + scrollingBorderEnd;
}
return 0;
}
export function computeScrollIntoView(target: Element, scroller: Element, options: ScrollIntoViewOptions): Pick<ScrollToOptions, "top" | "left"> {
const {block, inline} = options;
// Used to handle the top most element that can be scrolled
const scrollingElement = getScrollingElement();
// Support pinch-zooming properly, making sure elements scroll into the visual viewport
// Browsers that don't support visualViewport will report the layout viewport dimensions on document.documentElement.clientWidth/Height
// and viewport dimensions on window.innerWidth/Height
// https://www.quirksmode.org/mobile/viewports2.html
// https://bokand.github.io/viewport/index.html
const viewportWidth = (window as VisualViewportable).visualViewport != null ? visualViewport.width : innerWidth;
const viewportHeight = (window as VisualViewportable).visualViewport != null ? visualViewport.height : innerHeight;
const viewportX = window.scrollX != null ? window.scrollX : window.pageXOffset;
const viewportY = window.scrollY != null ? window.scrollY : window.pageYOffset;
const {
height: targetHeight,
width: targetWidth,
top: targetTop,
right: targetRight,
bottom: targetBottom,
left: targetLeft
} = target.getBoundingClientRect();
// These values mutate as we loop through and generate scroll coordinates
const targetBlock: number = block === "start" || block === "nearest" ? targetTop : block === "end" ? targetBottom : targetTop + targetHeight / 2; // block === 'center
const targetInline: number = inline === "center" ? targetLeft + targetWidth / 2 : inline === "end" ? targetRight : targetLeft; // inline === 'start || inline === 'nearest
const {height, width, top, right, bottom, left} = scroller.getBoundingClientRect();
const frameStyle = getComputedStyle(scroller);
const borderLeft = parseInt(frameStyle.borderLeftWidth as string, 10);
const borderTop = parseInt(frameStyle.borderTopWidth as string, 10);
const borderRight = parseInt(frameStyle.borderRightWidth as string, 10);
const borderBottom = parseInt(frameStyle.borderBottomWidth as string, 10);
let blockScroll: number = 0;
let inlineScroll: number = 0;
// The property existance checks for offset[Width|Height] is because only HTMLElement objects have them, but any Element might pass by here
// @TODO find out if the "as HTMLElement" overrides can be dropped
const scrollbarWidth =
"offsetWidth" in scroller ? (scroller as HTMLElement).offsetWidth - (scroller as HTMLElement).clientWidth - borderLeft - borderRight : 0;
const scrollbarHeight =
"offsetHeight" in scroller ? (scroller as HTMLElement).offsetHeight - (scroller as HTMLElement).clientHeight - borderTop - borderBottom : 0;
if (scrollingElement === scroller) {
// Handle viewport logic (document.documentElement or document.body)
if (block === "start") {
blockScroll = targetBlock;
} else if (block === "end") {
blockScroll = targetBlock - viewportHeight;
} else if (block === "nearest") {
blockScroll = alignNearest(
viewportY,
viewportY + viewportHeight,
viewportHeight,
borderTop,
borderBottom,
viewportY + targetBlock,
viewportY + targetBlock + targetHeight,
targetHeight
);
} else {
// block === 'center' is the default
blockScroll = targetBlock - viewportHeight / 2;
}
if (inline === "start") {
inlineScroll = targetInline;
} else if (inline === "center") {
inlineScroll = targetInline - viewportWidth / 2;
} else if (inline === "end") {
inlineScroll = targetInline - viewportWidth;
} else {
// inline === 'nearest' is the default
inlineScroll = alignNearest(
viewportX,
viewportX + viewportWidth,
viewportWidth,
borderLeft,
borderRight,
viewportX + targetInline,
viewportX + targetInline + targetWidth,
targetWidth
);
}
// Apply scroll position offsets and ensure they are within bounds
// @TODO add more test cases to cover this 100%
blockScroll = Math.max(0, blockScroll + viewportY);
inlineScroll = Math.max(0, inlineScroll + viewportX);
} else {
// Handle each scrolling frame that might exist between the target and the viewport
if (block === "start") {
blockScroll = targetBlock - top - borderTop;
} else if (block === "end") {
blockScroll = targetBlock - bottom + borderBottom + scrollbarHeight;
} else if (block === "nearest") {
blockScroll = alignNearest(
top,
bottom,
height,
borderTop,
borderBottom + scrollbarHeight,
targetBlock,
targetBlock + targetHeight,
targetHeight
);
} else {
// block === 'center' is the default
blockScroll = targetBlock - (top + height / 2) + scrollbarHeight / 2;
}
if (inline === "start") {
inlineScroll = targetInline - left - borderLeft;
} else if (inline === "center") {
inlineScroll = targetInline - (left + width / 2) + scrollbarWidth / 2;
} else if (inline === "end") {
inlineScroll = targetInline - right + borderRight + scrollbarWidth;
} else {
// inline === 'nearest' is the default
inlineScroll = alignNearest(
left,
right,
width,
borderLeft,
borderRight + scrollbarWidth,
targetInline,
targetInline + targetWidth,
targetWidth
);
}
const {scrollLeft, scrollTop} = scroller;
// Ensure scroll coordinates are not out of bounds while applying scroll offsets
blockScroll = Math.max(0, Math.min(scrollTop + blockScroll, scroller.scrollHeight - height + scrollbarHeight));
inlineScroll = Math.max(0, Math.min(scrollLeft + inlineScroll, scroller.scrollWidth - width + scrollbarWidth));
}
return {
top: blockScroll,
left: inlineScroll
};
} | the_stack |
'use strict';
import * as jsdoc from './jsdoc'
import * as dom5 from 'dom5'
import {
FeatureDescriptor, FunctionDescriptor, PropertyDescriptor, Descriptor,
ElementDescriptor, BehaviorsByName, EventDescriptor, BehaviorDescriptor
} from './descriptors'
/** Properties on element prototypes that are purely configuration. */
const ELEMENT_CONFIGURATION = [
'attached',
'attributeChanged',
'beforeRegister',
'configure',
'constructor',
'created',
'detached',
'enableCustomStyleProperties',
'extends',
'hostAttributes',
'is',
'listeners',
'mixins',
'properties',
'ready',
'registered'
];
/** Tags understood by the annotation process, to be removed during `clean`. */
const HANDLED_TAGS = [
'param',
'return',
'type',
];
/**
* Annotates Hydrolysis descriptors, processing any `desc` properties as JSDoc.
*
* You probably want to use a more specialized version of this, such as
* `annotateElement`.
*
* Processed JSDoc values will be made available via the `jsdoc` property on a
* descriptor node.
*
* @param {Object} descriptor The descriptor node to process.
* @return {Object} The descriptor that was given.
*/
export function annotate(descriptor: Descriptor): Descriptor{
if (!descriptor || descriptor.jsdoc) return descriptor;
if (typeof descriptor.desc === 'string') {
descriptor.jsdoc = jsdoc.parseJsdoc(descriptor.desc);
// We want to present the normalized form of a descriptor.
descriptor.jsdoc.orig = descriptor.desc;
descriptor.desc = descriptor.jsdoc.description;
}
return descriptor;
}
/**
* Annotates @event, @hero, & @demo tags
*/
export function annotateElementHeader(descriptor: ElementDescriptor) {
if (descriptor.events) {
descriptor.events.forEach(function(event) {
_annotateEvent(event);
});
descriptor.events.sort( function(a,b) {
return a.name.localeCompare(b.name);
});
}
descriptor.demos = [];
if (descriptor.jsdoc && descriptor.jsdoc.tags) {
descriptor.jsdoc.tags.forEach( function(tag) {
switch(tag.tag) {
case 'hero':
descriptor.hero = tag.name || 'hero.png';
break;
case 'demo':
descriptor.demos.push({
desc: tag.description || 'demo',
path: tag.name || 'demo/index.html'
});
break;
}
});
}
}
function copyProperties(
from:ElementDescriptor, to:ElementDescriptor,
behaviorsByName:BehaviorsByName) {
if (from.properties) {
from.properties.forEach(function(fromProp){
for (var toProp:PropertyDescriptor, i = 0;
i < to.properties.length; i++) {
toProp = to.properties[i];
if (fromProp.name === toProp.name) {
return;
}
}
var newProp = {__fromBehavior: from.is};
if (fromProp.__fromBehavior) {
return;
}
Object.keys(fromProp).forEach(function(propertyField){
newProp[propertyField] = fromProp[propertyField];
});
to.properties.push(<any>newProp);
});
from.events.forEach(function(fromEvent){
for (var toEvent:EventDescriptor, i = 0; i < to.events.length; i++) {
toEvent = to.events[i];
if (fromEvent.name === toEvent.name) {
return;
}
}
if (fromEvent.__fromBehavior) {
return;
}
var newEvent = {__fromBehavior: from.is};
Object.keys(fromEvent).forEach(function(eventField){
newEvent[eventField] = fromEvent[eventField];
});
to.events.push(newEvent);
});
}
if (!from.behaviors) {
return;
}
for (let i = from.behaviors.length - 1; i >= 0; i--) {
// TODO: what's up with behaviors sometimes being a literal, and sometimes
// being a descriptor object?
const localBehavior: any = from.behaviors[i];
var definedBehavior =
behaviorsByName[localBehavior] || behaviorsByName[localBehavior.symbol];
if (!definedBehavior) {
console.warn("Behavior " + localBehavior + " not found when mixing " +
"properties into " + to.is + "!");
return;
}
copyProperties(definedBehavior, to, behaviorsByName);
}
}
function mixinBehaviors(
descriptor:ElementDescriptor, behaviorsByName: BehaviorsByName) {
if (descriptor.behaviors) {
for (let i = descriptor.behaviors.length - 1; i >= 0; i--) {
const behavior = <string>descriptor.behaviors[i];
if (!behaviorsByName[behavior]) {
console.warn("Behavior " + behavior + " not found when mixing " +
"properties into " + descriptor.is + "!");
break;
}
var definedBehavior = behaviorsByName[<string>behavior];
copyProperties(definedBehavior, descriptor, behaviorsByName);
}
}
}
/**
* Annotates documentation found within a Hydrolysis element descriptor. Also
* supports behaviors.
*
* If the element was processed via `hydrolize`, the element's documentation
* will also be extracted via its <dom-module>.
*
* @param {Object} descriptor The element descriptor.
* @return {Object} The descriptor that was given.
*/
export function annotateElement(
descriptor: ElementDescriptor,
behaviorsByName: BehaviorsByName): ElementDescriptor {
if (!descriptor.desc && descriptor.type === 'element') {
descriptor.desc = _findElementDocs(descriptor.is,
descriptor.domModule,
descriptor.scriptElement);
}
annotate(descriptor);
// The `<dom-module>` is too low level for most needs, and it is _not_
// serializable. So we drop it now that we've extracted all the useful bits
// from it.
// TODO: Don't worry about serializability here, provide an API to get JSON.
delete descriptor.domModule;
mixinBehaviors(descriptor, behaviorsByName);
// Descriptors that should have their `desc` properties parsed as JSDoc.
descriptor.properties.forEach(function(property) {
// Feature properties are special, configuration is really just a matter of
// inheritance...
annotateProperty(property, descriptor.abstract);
});
// It may seem like overkill to always sort, but we have an assumption that
// these properties are typically being consumed by user-visible tooling.
// As such, it's good to have consistent output/ordering to aid the user.
descriptor.properties.sort(function(a, b) {
// Private properties are always last.
if (a.private && !b.private) {
return 1;
} else if (!a.private && b.private) {
return -1;
// Otherwise, we're just sorting alphabetically.
} else {
return a.name.localeCompare(b.name);
}
});
annotateElementHeader(descriptor);
return descriptor;
}
/**
* Annotates behavior descriptor.
* @param {Object} descriptor behavior descriptor
* @return {Object} descriptor passed in as param
*/
export function annotateBehavior(
descriptor:BehaviorDescriptor): BehaviorDescriptor {
annotate(descriptor);
annotateElementHeader(descriptor);
return descriptor;
}
/**
* Annotates event documentation
*/
function _annotateEvent(descriptor:EventDescriptor): EventDescriptor {
annotate(descriptor);
// process @event
var eventTag = jsdoc.getTag(descriptor.jsdoc, 'event');
descriptor.name = eventTag ? eventTag.description : "N/A";
// process @params
descriptor.params = (descriptor.jsdoc.tags || [])
.filter(function(tag) {
return tag.tag === 'param';
})
.map(function(tag) {
return {
type: tag.type || "N/A",
desc: tag.description,
name: tag.name || "N/A"
};
});
// process @params
return descriptor;
}
/**
* Annotates documentation found about a Hydrolysis property descriptor.
*
* @param {Object} descriptor The property descriptor.
* @param {boolean} ignoreConfiguration If true, `configuration` is not set.
* @return {Object} The descriptior that was given.
*/
function annotateProperty(
descriptor:PropertyDescriptor,
ignoreConfiguration:boolean): PropertyDescriptor {
annotate(descriptor);
if (descriptor.name[0] === '_' || jsdoc.hasTag(descriptor.jsdoc, 'private')) {
descriptor.private = true;
}
if (!ignoreConfiguration &&
ELEMENT_CONFIGURATION.indexOf(descriptor.name) !== -1) {
descriptor.private = true;
descriptor.configuration = true;
}
// @type JSDoc wins
descriptor.type =
jsdoc.getTag(descriptor.jsdoc, 'type', 'type') || descriptor.type;
if (descriptor.type.match(/^function/i)) {
_annotateFunctionProperty(<FunctionDescriptor>descriptor);
}
// @default JSDoc wins
var defaultTag = jsdoc.getTag(descriptor.jsdoc, 'default');
if (defaultTag !== null) {
var newDefault = (defaultTag.name || '') + (defaultTag.description || '');
if (newDefault !== '') {
descriptor.default = newDefault;
}
}
return descriptor;
}
function _annotateFunctionProperty(descriptor:FunctionDescriptor) {
descriptor.function = true;
var returnTag = jsdoc.getTag(descriptor.jsdoc, 'return');
if (returnTag) {
descriptor.return = {
type: returnTag.type,
desc: returnTag.description,
};
}
var paramsByName = {};
(descriptor.params || []).forEach(function(param) {
paramsByName[param.name] = param;
});
(descriptor.jsdoc && descriptor.jsdoc.tags || []).forEach(function(tag) {
if (tag.tag !== 'param') return;
var param = paramsByName[tag.name];
if (!param) {
return;
}
param.type = tag.type || param.type;
param.desc = tag.description;
});
}
/**
* Converts raw features into an abstract `Polymer.Base` element.
*
* Note that docs on this element _are not processed_. You must call
* `annotateElement` on it yourself if you wish that.
*
* @param {Array<FeatureDescriptor>} features
* @return {ElementDescriptor}
*/
export function featureElement(
features:FeatureDescriptor[]): ElementDescriptor {
var properties = features.reduce<PropertyDescriptor[]>((result, feature) => {
return result.concat(feature.properties);
}, []);
return {
type: 'element',
is: 'Polymer.Base',
abstract: true,
properties: properties,
desc: '`Polymer.Base` acts as a base prototype for all Polymer ' +
'elements. It is composed via various calls to ' +
'`Polymer.Base._addFeature()`.\n' +
'\n' +
'The properties reflected here are the combined view of all ' +
'features found in this library. There may be more properties ' +
'added via other libraries, as well.',
};
}
/**
* Cleans redundant properties from a descriptor, assuming that you have already
* called `annotate`.
*
* @param {Object} descriptor
*/
export function clean(descriptor:Descriptor) {
if (!descriptor.jsdoc) return;
// The doctext was written to `descriptor.desc`
delete descriptor.jsdoc.description;
delete descriptor.jsdoc.orig;
var cleanTags:jsdoc.Tag[] = [];
(descriptor.jsdoc.tags || []).forEach(function(tag) {
// Drop any tags we've consumed.
if (HANDLED_TAGS.indexOf(tag.tag) !== -1) return;
cleanTags.push(tag);
});
if (cleanTags.length === 0) {
// No tags? no docs left!
delete descriptor.jsdoc;
} else {
descriptor.jsdoc.tags = cleanTags;
}
}
/**
* Cleans redundant properties from an element, assuming that you have already
* called `annotateElement`.
*
* @param {ElementDescriptor|BehaviorDescriptor} element
*/
export function cleanElement(element:ElementDescriptor) {
clean(element);
element.properties.forEach(cleanProperty);
}
/**
* Cleans redundant properties from a property, assuming that you have already
* called `annotateProperty`.
*
* @param {PropertyDescriptor} property
*/
function cleanProperty(property:PropertyDescriptor) {
clean(property);
}
/**
* Parse elements defined only in comments.
* @param {comments} Array<string> A list of comments to parse.
* @return {ElementDescriptor} A list of pseudo-elements.
*/
export function parsePseudoElements(comments: string[]):ElementDescriptor[] {
var elements: ElementDescriptor[] = [];
comments.forEach(function(comment) {
var parsedJsdoc = jsdoc.parseJsdoc(comment);
var pseudoTag = jsdoc.getTag(parsedJsdoc, 'pseudoElement', 'name');
if (pseudoTag) {
let element: ElementDescriptor = {
is: pseudoTag,
type: 'element',
jsdoc: {description: parsedJsdoc.description, tags: parsedJsdoc.tags},
properties: [],
desc: parsedJsdoc.description,
}
annotateElementHeader(element);
elements.push(element);
}
});
return elements;
}
/**
* @param {string} elementId
* @param {DocumentAST} domModule
* @param {DocumentAST} scriptElement The script that the element was
* defined in.
*/
function _findElementDocs(
elementId:string, domModule:dom5.Node, scriptElement:dom5.Node) {
// Note that we concatenate docs from all sources if we find them.
// element can be defined in:
// html comment right before dom-module
// html commnet right before script defining the module,
// if dom-module is empty
var found:string[] = [];
// Do we have a HTML comment on the `<dom-module>` or `<script>`?
//
// Confusingly, with our current style, the comment will be attached to
// `<head>`, rather than being a sibling to the `<dom-module>`
var searchRoot = domModule || scriptElement;
var parents = dom5.nodeWalkAllPrior(searchRoot, dom5.isCommentNode);
var comment = parents.length > 0 ? parents[0] : null;
if (comment && comment.data) {
found.push(comment.data);
}
if (found.length === 0) return null;
return found
.filter(function(comment) {
// skip @license comments
if (comment && comment.indexOf('@license') === -1) {
return true;
}
else {
return false;
}
})
.map(jsdoc.unindent).join('\n');
}
function _findLastChildNamed(name:string, parent:dom5.Node) {
var children = parent.childNodes;
for (var i = children.length - 1; i >= 0; i--) {
let child = children[i];
if (child.nodeName === name) return child;
}
return null;
}
// TODO(nevir): parse5-utils!
function _getNodeAttribute(node:dom5.Node, name:string) {
for (var i = 0; i < node.attrs.length; i++) {
let attr = node.attrs[i];
if (attr.name === name) {
return attr.value;
}
}
} | the_stack |
* WARNING: This file has been deprecated and should now be considered locked against further changes. Its contents
* have been partially or wholely superceded by functionality included in the @salesforce/core npm package, and exists
* now to service prior uses in this repository only until they can be ported to use the new @salesforce/core library.
*
* If you need or want help deciding where to add new functionality or how to migrate to the new library, please
* contact the CLI team at alm-cli@salesforce.com.
* ----------------------------------------------------------------------------------------------------------------- */
// Node
import * as os from 'os';
import * as util from 'util';
import * as path from 'path';
import * as crypto from 'crypto';
import * as mkdirp from 'mkdirp';
import * as archiver from 'archiver';
// Thirdparty
import * as BBPromise from 'bluebird';
import { Org } from '@salesforce/core';
import { parseJson } from '@salesforce/kit';
import { AnyJson } from '@salesforce/ts-types';
import * as _ from 'lodash';
const fs = BBPromise.promisifyAll(require('fs-extra'));
// Local
import Messages = require('../messages');
import * as errors from './errors';
import consts = require('./constants');
const messages = Messages();
import logger = require('./logApi');
// The hidden folder that we keep all SFDX's state in.
const STATE_FOLDER = '.sfdx';
const SFDX_CONFIG_FILE_NAME = 'sfdx-config.json';
// For 208 this needs to be 'sfdx toolbelt'
const SfdxCLIClientId = 'sfdx toolbelt';
const SFDX_HTTP_HEADERS = {
'content-type': 'application/json',
'user-agent': SfdxCLIClientId,
};
const DEV_HUB_SOQL = "SELECT CreatedDate,Edition,ExpirationDate FROM ActiveScratchOrg WHERE ScratchOrg='%s'";
let zipDirPath: string;
const _getHomeDir = function () {
return os.homedir();
};
const _getGlobalHiddenFolder = function () {
return path.join(_getHomeDir(), STATE_FOLDER);
};
const _toLowerCase = (val, key) => key.toLowerCase();
const _checkEmptyContent = function (data, jsonPath, throwOnEmpty = true) {
// REVIEWME: why throw? shouldn't the caller handle?
if (!data.length) {
if (throwOnEmpty) {
throw new Error(messages.getMessage('JsonParseError', [jsonPath, 1, 'FILE HAS NO CONTENT']));
} else {
data = {};
}
}
return data;
};
/**
*
* @param data JSON data as a string to parse
* @param jsonPath path to the json file used for error reporting
* @param throwOnEmpty throw a JsonParseError when the content is empty
*/
function parseJSON(data, jsonPath, throwOnEmpty = true): AnyJson {
const _data = _checkEmptyContent(data, jsonPath, throwOnEmpty);
return parseJson(_data, jsonPath, throwOnEmpty);
}
const self = {
queryOrgInfoFromDevHub(hubOrg, orgId) {
return hubOrg.force.query(hubOrg, util.format(DEV_HUB_SOQL, this.trimTo15(orgId)));
},
/**
* Returns whether the org has source tracking ability.
*
* @param {string} username the org username
* @returns {boolean}
*/
async isSourceTrackedOrg(username) {
let isSourceTracked = false;
try {
const org = await Org.create(username);
await org.getConnection().tooling.query('select id from SourceMember');
isSourceTracked = true;
} catch (e) {
/* ignore */
}
return isSourceTracked;
},
/**
* Read a file and convert it to JSON
*
* @param {string} jsonPath The path of the file
* @return promise The contents of the file as a JSON object
*/
async readJSON(jsonPath, throwOnEmpty = true) {
const data = await fs.readFile(jsonPath, 'utf8');
return parseJSON(data, jsonPath, throwOnEmpty);
},
parseJSON,
/**
* Helper for handling errors resulting from reading and then parsing a JSON file
*
* @param e - the error
* @param filePath - the filePath to the JSON file being read
*/
processReadAndParseJsonFileError(e, filePath) {
if (e.name === 'SyntaxError') {
e.message = messages.getMessage('InvalidJson', filePath);
}
return e;
},
/**
* simple helper for creating an error with a name.
*
* @param message - the message for the error
* @param name - the name of the error. preferably containing no spaces, starting with a capital letter, and camel-case.
* @returns {Error}
*/
getError(message, name) {
let error = new Error(message);
error['name'] = name;
if (util.isNullOrUndefined(message) || util.isNullOrUndefined(name)) {
error = new Error('Both name and message are required for sf toolbelt errors.');
error['name'] = 'NameAndMessageRequired';
}
return error;
},
/**
* function that normalizes cli args between yargs and heroku toolbelt
*
* @param context - the cli context
* @returns {object}
*/
fixCliContext(context) {
// This can be called from heroku or appconfig.
let fixedContext = context;
if (!util.isNullOrUndefined(context.flags)) {
fixedContext = context.flags;
}
return fixedContext;
},
/**
* Simple helper method to determine that the path is a file (all SFDX files have an extension)
*
* @param localPath
* @returns {boolean}
*/
containsFileExt(localPath) {
const typeExtension = path.extname(localPath);
return typeExtension && typeExtension !== '';
},
/**
* Simple helper method to determine if a fs path exists.
*
* @param localPath The path to check. Either a file or directory.
* @returns {boolean} true if the path exists false otherwise.
*/
pathExistsSync(localPath) {
try {
return fs.statSync(localPath);
} catch (err) {
return false;
}
},
/**
* Ensure that a directory exists, creating as necessary
*
* @param localPath The path to the directory
*/
ensureDirectoryExistsSync(localPath) {
if (!self.pathExistsSync(localPath)) {
mkdirp.sync(localPath);
}
},
/**
* If a file exists, delete it
*
* @param localPath - Path of the file to delete.
*/
deleteIfExistsSync(localPath) {
if (self.pathExistsSync(localPath)) {
const stats = fs.statSync(localPath);
if (stats.isDirectory()) {
fs.rmdirSync(localPath);
} else {
fs.unlinkSync(localPath);
}
}
},
/**
* If a directory exists, force remove it and anything inside
*
* @param localPath - Path of the directory to delete.
*/
deleteDirIfExistsSync(localPath) {
fs.removeSync(localPath);
},
/**
* If a directory exists, return all the items inside of it
*
* @param localPath - Path of the directory
* @param deep{boolean} - Whether to include files in all subdirectories recursively
* @param excludeDirs{boolean} - Whether to exclude directories in the returned list
* @returns {Array} - files in directory
*/
getDirectoryItems(localPath: string, deep?: boolean, excludeDirs?: boolean) {
let dirItems = [];
if (self.pathExistsSync(localPath)) {
fs.readdirSync(localPath).forEach((file) => {
const curPath = path.join(localPath, file);
const isDir = fs.statSync(curPath).isDirectory();
if (!isDir || (isDir && !excludeDirs)) {
dirItems.push(curPath);
}
if (deep && isDir) {
dirItems = [...dirItems, ...this.getDirectoryItems(curPath, true, excludeDirs)];
}
});
}
return dirItems;
},
getGlobalHiddenFolder() {
return _getGlobalHiddenFolder();
},
/**
* Helper method for removing config file data from .sfdx.
*
* @param jsonConfigFileName The name of the config file stored in .sfdx.
* @returns BBPromise
*/
deleteGlobalConfig(jsonConfigFileName) {
if (util.isNullOrUndefined(jsonConfigFileName)) {
throw new errors.MissingRequiredParameter('jsonConfigFileName');
}
const filepath = path.join(_getGlobalHiddenFolder(), jsonConfigFileName);
return fs.unlinkAsync(filepath);
},
/**
* Helper method for getting config file data from $HOME/.sfdx.
*
* @param {string} jsonConfigFileName The name of the config file stored in .sfdx.
* @param {object} defaultIfNotExist A value returned if the files doesn't exist. It not set, an error would be thrown.
* @returns {BBPromise<object>} The resolved content as a json object.
*/
getGlobalConfig(jsonConfigFileName, defaultIfNotExist?) {
if (util.isNullOrUndefined(jsonConfigFileName)) {
throw new errors.MissingRequiredParameter('jsonConfigFileName');
}
const configFilePath = path.join(_getGlobalHiddenFolder(), jsonConfigFileName);
return this.readJSON(configFilePath).catch((err) => {
if (err.code === 'ENOENT' && _.isObject(defaultIfNotExist)) {
return BBPromise.resolve(defaultIfNotExist);
}
return BBPromise.reject(err);
});
},
/**
* Synchronous version of getAppConfig.
*
* @deprecated
*/
getGlobalConfigSync(jsonConfigFileName) {
if (util.isNullOrUndefined(jsonConfigFileName)) {
throw new errors.MissingRequiredParameter('jsonConfigFileName');
}
const configPath = path.join(_getGlobalHiddenFolder(), jsonConfigFileName);
try {
return JSON.parse(fs.readFileSync(configPath, 'utf8'));
} catch (e) {
throw this.processReadAndParseJsonFileError(e, configPath);
}
},
/**
* Helper method for saving config files to .sfdx.
*
* @param config The config.json configuration object.
* @param jsonConfigFileName The name for the config file to store in .sfdx.
* @param jsonConfigObject The json object to store in .sfdx/[jsonConfigFileName]
* @returns BBPromise
*/
saveGlobalConfig(jsonConfigFileName, jsonConfigObject) {
if (util.isNullOrUndefined(jsonConfigFileName)) {
throw new errors.MissingRequiredParameter('jsonConfigFileName');
}
if (util.isNullOrUndefined(jsonConfigObject)) {
throw new errors.MissingRequiredParameter('jsonConfigObject');
}
return (
fs
.mkdirAsync(path.join(_getGlobalHiddenFolder()), consts.DEFAULT_USER_DIR_MODE)
.error((err) => {
// This directory already existing is a normal and expected thing.
if (err.code !== 'EEXIST') {
throw err;
}
})
// Handle the login result and persist the access token.
.then(() => {
const configFilePath = path.join(_getGlobalHiddenFolder(), jsonConfigFileName);
return fs.writeFileAsync(configFilePath, JSON.stringify(jsonConfigObject, undefined, 4), {
encoding: 'utf8',
flag: 'w+',
mode: consts.DEFAULT_USER_FILE_MODE,
});
})
);
},
/**
* Get the name of the directory containing workspace state
*
* @returns {string}
*/
getWorkspaceStateFolderName() {
return STATE_FOLDER;
},
getConfigFileName() {
return SFDX_CONFIG_FILE_NAME;
},
/**
* Get the full path to the file storing the workspace org config information
*
* @param wsPath - The root path of the workspace
* @returns {*}
*/
getWorkspaceOrgConfigPath(wsPath) {
return path.join(wsPath, STATE_FOLDER, this.getConfigFileName());
},
/**
* Helper function that returns true if a value is an integer.
*
* @param value the value to compare
* @returns {boolean} true if value is an integer. this is not a mathematical definition. that is -0 returns true.
* this is in intended to be followed up with parseInt.
*/
isInt(value) {
return (
!isNaN(value) &&
(function (x) {
return (x | 0) === x;
})(parseFloat(value))
);
},
/**
* Execute each function in the array sequentially.
*
* @param promiseFactories An array of functions to be executed that return BBPromises.
* @returns {BBPromise.<T>}
*/
sequentialExecute(promiseFactories) {
let result = BBPromise.resolve();
promiseFactories.forEach((promiseFactory) => {
result = result.then(promiseFactory);
});
return result;
},
/**
* Execute each function in the array in parallel.
*
* @param promiseFactories An array of functions to be executed that return BBPromises.
* @returns {BBPromise.<*>}
*/
parallelExecute(promiseFactories) {
return BBPromise.all(promiseFactories.map((factory) => factory()));
},
/**
* Given a request object or string url a request object is returned with the additional http headers needed by force.com
*
* @param {(string|object)} request - A string url or javascript object.
* @param options - {object} that may contain headers to add to request
* @returns {object} a request object containing {method, url, headers}
*/
setSfdxRequestHeaders(request, options: any = {}) {
if (!request) {
return undefined;
}
// if request is simple string, regard it as url in GET method
const _request = _.isString(request) ? { method: 'GET', url: request } : request;
// normalize header keys
const reqHeaders = _.mapKeys(request.headers, _toLowerCase);
const optHeaders = _.mapKeys(options.headers, _toLowerCase);
// set headers, overriding as appropriate
_request.headers = Object.assign({}, this.getSfdxRequestHeaders(), reqHeaders, optHeaders);
return _request;
},
getSfdxRequestHeaders() {
return SFDX_HTTP_HEADERS;
},
getSfdxCLIClientId() {
if (process.env.SFDX_SET_CLIENT_IDS) {
return `${SfdxCLIClientId}:${process.env.SFDX_SET_CLIENT_IDS}`;
}
return SfdxCLIClientId;
},
isVerbose() {
return process.argv.indexOf('--verbose') > 0;
},
trimTo15(id) {
// FIXME: remove once 18-char orgid is figured out
if (!util.isNullOrUndefined(id) && id.length && id.length > 15) {
id = id.substring(0, 15);
}
return id;
},
/**
* @returns {boolean} returns true if process.env.SFDX_USE_GENERIC_UNIX_KEYCHAIN is set to true.
*/
useGenericUnixKeychain() {
// Support the old env var name
const useGenericUnixKeychain = process.env.SFDX_USE_GENERIC_UNIX_KEYCHAIN || process.env.USE_GENERIC_UNIX_KEYCHAIN;
return !_.isNil(useGenericUnixKeychain) && useGenericUnixKeychain.toLowerCase() === 'true';
},
/**
* Zips directory to given zipfile.
*
* https://github.com/archiverjs/node-archiver
*
* @param dir to zip
* @param zipfile
* @param options
*/
zipDir(dir, zipfile, options = {}) {
const file = path.parse(dir);
const outFile = zipfile || path.join(os.tmpdir() || '.', `${file.base}.zip`);
const output = fs.createWriteStream(outFile);
this.setZipDirPath(outFile);
const timer = process.hrtime();
return new BBPromise((resolve, reject) => {
const archive = archiver('zip', options);
archive.on('finish', () => {
logger.debug(`${archive.pointer()} bytes written to ${outFile} using ${this.getElapsedTime(timer)}ms`);
// zip file returned once stream is closed, see 'close' listener below
});
archive.on('error', (err) => {
reject(err);
});
output.on('close', () => {
resolve(outFile);
});
archive.pipe(output);
archive.directory(dir, '');
archive.finalize();
});
},
setZipDirPath(path: string) {
zipDirPath = path;
},
getZipDirPath() {
return zipDirPath;
},
getElapsedTime(timer) {
const elapsed = process.hrtime(timer);
return (elapsed[0] * 1000 + elapsed[1] / 1000000).toFixed(3);
},
/**
* Uses Lodash _.mapKeys to convert object keys to another format using the specified conversion function.
*
* E.g., to deep convert all object keys to camelCase: mapKeys(myObj, _.camelCase, true)
* to shallow convert object keys to lower case: mapKeys(myObj, _.toLower)
*
* NOTE: This mutates the object passed in for conversion.
*
* @param obj - {Object} The object to convert the keys
* @param converterFn - {Function} The function that converts the object key
* @param deep - {boolean} Whether to do a deep object key conversion
* @return {Object} - the object with the converted keys
*/
mapKeys(obj, converterFn, deep?) {
return _.mapKeys(obj, (val, key, o) => {
const _key = converterFn.call(null, key);
if (deep) {
let _val = val;
if (_.isArray(val)) {
_.forEach(val, (v1) => {
if (_.isPlainObject(v1)) {
_val = this.mapKeys(v1, converterFn, deep);
}
});
} else if (_.isPlainObject(val)) {
_val = this.mapKeys(val, converterFn, deep);
}
o[_key] = _val;
if (key !== _key) {
delete o[key];
}
}
return _key;
});
},
// A very common usecase of mapKeys.
toLowerCaseKeys(obj, deep?) {
return this.mapKeys(obj, _.toLower, deep);
},
/**
* Returns the first key within the object that has an upper case first letter.
*
* @param obj - {Object} The object to check key casing
* @param blocklist - don't include results in this array
* @return {string} - the key that starts with upper case
*/
findUpperCaseKeys(obj, blocklist = []) {
let _key;
_.findKey(obj, (val, key) => {
if (blocklist.includes(key)) {
return _key;
}
if (key[0] === key[0].toUpperCase()) {
_key = key;
} else if (_.isPlainObject(val)) {
_key = this.findUpperCaseKeys(val);
}
return _key;
});
return _key;
},
/**
* Helper to make a nodejs base64 encoded string compatible with rfc4648 alternative encoding for urls.
*
* @param {string} base64Encoded - a nodejs base64 encoded string
* @returns {string} returns the string escaped.
*/
base64UrlEscape(base64Encoded?) {
// builtin node js base 64 encoding is not 64 url compatible.
// See - https://toolsn.ietf.org/html/rfc4648#section-5
return _.replace(base64Encoded, /\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
},
/**
* Helper that will un-escape a base64 url encoded string.
*
* @param {string} base64EncodedAndEscaped - the based 64 escaped and encoded string.
* @returns {string} returns the string un-escaped.
*/
base64UrlUnEscape(base64EncodedAndEscaped) {
// builtin node js base 64 encoding is not 64 url compatible.
// See - https://toolsn.ietf.org/html/rfc4648#section-5
const _unescaped = _.replace(base64EncodedAndEscaped, /-/g, '+').replace(/_/g, '/');
return _unescaped + '==='.slice((_unescaped.length + 3) % 4);
},
getContentHash(contents) {
return crypto.createHash('sha1').update(contents).digest('hex');
},
/**
* Logs the collection of unsupported mime types to the server
*
* @param unsupportedMimeTypes
* @param _logger
* @param force
*/
async logUnsupportedMimeTypeError(unsupportedMimeTypes, _logger, force) {
if (unsupportedMimeTypes.length > 0) {
const errName = 'UnsupportedMimeTypes';
const unsupportedMimeTypeError = new Error();
unsupportedMimeTypeError.name = errName;
unsupportedMimeTypeError.message = messages.getMessage(errName, [...new Set(unsupportedMimeTypes)]);
unsupportedMimeTypeError.stack = '';
_.set(unsupportedMimeTypeError, 'errAllowlist', errName);
try {
// TODO Use new telemetry exception throwing.
} catch (err) {
// Ignore; Don't fail source commands if logServerError fails
}
}
return BBPromise.resolve();
},
};
export = self; | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type ArtistAboutShowsTestsQueryVariables = {
artistID: string;
};
export type ArtistAboutShowsTestsQueryResponse = {
readonly artist: {
readonly currentShows: {
readonly edges: ReadonlyArray<{
readonly node: {
readonly id: string;
} | null;
} | null> | null;
} | null;
readonly " $fragmentRefs": FragmentRefs<"ArtistAboutShows_artist">;
} | null;
};
export type ArtistAboutShowsTestsQuery = {
readonly response: ArtistAboutShowsTestsQueryResponse;
readonly variables: ArtistAboutShowsTestsQueryVariables;
};
/*
query ArtistAboutShowsTestsQuery(
$artistID: String!
) {
artist(id: $artistID) {
...ArtistAboutShows_artist
currentShows: showsConnection(status: "running", first: 10) {
edges {
node {
id
}
}
}
id
}
}
fragment ArtistAboutShows_artist on Artist {
name
slug
currentShows: showsConnection(status: "running", first: 10) {
edges {
node {
id
...ArtistShow_show
}
}
}
upcomingShows: showsConnection(status: "upcoming", first: 10) {
edges {
node {
id
...ArtistShow_show
}
}
}
pastShows: showsConnection(status: "closed", first: 3) {
edges {
node {
id
...ArtistShow_show
}
}
}
}
fragment ArtistShow_show on Show {
slug
href
is_fair_booth: isFairBooth
cover_image: coverImage {
url(version: "large")
}
...Metadata_show
}
fragment Metadata_show on Show {
kind
name
exhibition_period: exhibitionPeriod(format: SHORT)
status_update: statusUpdate
status
partner {
__typename
... on Partner {
name
}
... on ExternalPartner {
name
id
}
... on Node {
__isNode: __typename
id
}
}
location {
city
id
}
}
*/
const node: ConcreteRequest = (function(){
var v0 = [
{
"defaultValue": null,
"kind": "LocalArgument",
"name": "artistID"
}
],
v1 = [
{
"kind": "Variable",
"name": "id",
"variableName": "artistID"
}
],
v2 = {
"kind": "Literal",
"name": "first",
"value": 10
},
v3 = [
(v2/*: any*/),
{
"kind": "Literal",
"name": "status",
"value": "running"
}
],
v4 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v5 = [
(v4/*: any*/)
],
v6 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
},
v7 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "slug",
"storageKey": null
},
v8 = [
{
"alias": null,
"args": null,
"concreteType": "ShowEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Show",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v4/*: any*/),
(v7/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "href",
"storageKey": null
},
{
"alias": "is_fair_booth",
"args": null,
"kind": "ScalarField",
"name": "isFairBooth",
"storageKey": null
},
{
"alias": "cover_image",
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "coverImage",
"plural": false,
"selections": [
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "version",
"value": "large"
}
],
"kind": "ScalarField",
"name": "url",
"storageKey": "url(version:\"large\")"
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "kind",
"storageKey": null
},
(v6/*: any*/),
{
"alias": "exhibition_period",
"args": [
{
"kind": "Literal",
"name": "format",
"value": "SHORT"
}
],
"kind": "ScalarField",
"name": "exhibitionPeriod",
"storageKey": "exhibitionPeriod(format:\"SHORT\")"
},
{
"alias": "status_update",
"args": null,
"kind": "ScalarField",
"name": "statusUpdate",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "status",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "partner",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
{
"kind": "InlineFragment",
"selections": [
(v6/*: any*/)
],
"type": "Partner",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": [
(v6/*: any*/),
(v4/*: any*/)
],
"type": "ExternalPartner",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": (v5/*: any*/),
"type": "Node",
"abstractKey": "__isNode"
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Location",
"kind": "LinkedField",
"name": "location",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "city",
"storageKey": null
},
(v4/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
}
],
v9 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "ShowConnection"
},
v10 = {
"enumValues": null,
"nullable": true,
"plural": true,
"type": "ShowEdge"
},
v11 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Show"
},
v12 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Image"
},
v13 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "String"
},
v14 = {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "ID"
},
v15 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Boolean"
},
v16 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Location"
},
v17 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "PartnerTypes"
},
v18 = {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "String"
};
return {
"fragment": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Fragment",
"metadata": null,
"name": "ArtistAboutShowsTestsQuery",
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "Artist",
"kind": "LinkedField",
"name": "artist",
"plural": false,
"selections": [
{
"alias": "currentShows",
"args": (v3/*: any*/),
"concreteType": "ShowConnection",
"kind": "LinkedField",
"name": "showsConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "ShowEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Show",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": (v5/*: any*/),
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "showsConnection(first:10,status:\"running\")"
},
{
"args": null,
"kind": "FragmentSpread",
"name": "ArtistAboutShows_artist"
}
],
"storageKey": null
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Operation",
"name": "ArtistAboutShowsTestsQuery",
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "Artist",
"kind": "LinkedField",
"name": "artist",
"plural": false,
"selections": [
(v6/*: any*/),
(v7/*: any*/),
{
"alias": "currentShows",
"args": (v3/*: any*/),
"concreteType": "ShowConnection",
"kind": "LinkedField",
"name": "showsConnection",
"plural": false,
"selections": (v8/*: any*/),
"storageKey": "showsConnection(first:10,status:\"running\")"
},
{
"alias": "upcomingShows",
"args": [
(v2/*: any*/),
{
"kind": "Literal",
"name": "status",
"value": "upcoming"
}
],
"concreteType": "ShowConnection",
"kind": "LinkedField",
"name": "showsConnection",
"plural": false,
"selections": (v8/*: any*/),
"storageKey": "showsConnection(first:10,status:\"upcoming\")"
},
{
"alias": "pastShows",
"args": [
{
"kind": "Literal",
"name": "first",
"value": 3
},
{
"kind": "Literal",
"name": "status",
"value": "closed"
}
],
"concreteType": "ShowConnection",
"kind": "LinkedField",
"name": "showsConnection",
"plural": false,
"selections": (v8/*: any*/),
"storageKey": "showsConnection(first:3,status:\"closed\")"
},
(v4/*: any*/)
],
"storageKey": null
}
]
},
"params": {
"id": "7675ceb9b827757d5e2bf572d0a525d5",
"metadata": {
"relayTestingSelectionTypeInfo": {
"artist": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Artist"
},
"artist.currentShows": (v9/*: any*/),
"artist.currentShows.edges": (v10/*: any*/),
"artist.currentShows.edges.node": (v11/*: any*/),
"artist.currentShows.edges.node.cover_image": (v12/*: any*/),
"artist.currentShows.edges.node.cover_image.url": (v13/*: any*/),
"artist.currentShows.edges.node.exhibition_period": (v13/*: any*/),
"artist.currentShows.edges.node.href": (v13/*: any*/),
"artist.currentShows.edges.node.id": (v14/*: any*/),
"artist.currentShows.edges.node.is_fair_booth": (v15/*: any*/),
"artist.currentShows.edges.node.kind": (v13/*: any*/),
"artist.currentShows.edges.node.location": (v16/*: any*/),
"artist.currentShows.edges.node.location.city": (v13/*: any*/),
"artist.currentShows.edges.node.location.id": (v14/*: any*/),
"artist.currentShows.edges.node.name": (v13/*: any*/),
"artist.currentShows.edges.node.partner": (v17/*: any*/),
"artist.currentShows.edges.node.partner.__isNode": (v18/*: any*/),
"artist.currentShows.edges.node.partner.__typename": (v18/*: any*/),
"artist.currentShows.edges.node.partner.id": (v14/*: any*/),
"artist.currentShows.edges.node.partner.name": (v13/*: any*/),
"artist.currentShows.edges.node.slug": (v14/*: any*/),
"artist.currentShows.edges.node.status": (v13/*: any*/),
"artist.currentShows.edges.node.status_update": (v13/*: any*/),
"artist.id": (v14/*: any*/),
"artist.name": (v13/*: any*/),
"artist.pastShows": (v9/*: any*/),
"artist.pastShows.edges": (v10/*: any*/),
"artist.pastShows.edges.node": (v11/*: any*/),
"artist.pastShows.edges.node.cover_image": (v12/*: any*/),
"artist.pastShows.edges.node.cover_image.url": (v13/*: any*/),
"artist.pastShows.edges.node.exhibition_period": (v13/*: any*/),
"artist.pastShows.edges.node.href": (v13/*: any*/),
"artist.pastShows.edges.node.id": (v14/*: any*/),
"artist.pastShows.edges.node.is_fair_booth": (v15/*: any*/),
"artist.pastShows.edges.node.kind": (v13/*: any*/),
"artist.pastShows.edges.node.location": (v16/*: any*/),
"artist.pastShows.edges.node.location.city": (v13/*: any*/),
"artist.pastShows.edges.node.location.id": (v14/*: any*/),
"artist.pastShows.edges.node.name": (v13/*: any*/),
"artist.pastShows.edges.node.partner": (v17/*: any*/),
"artist.pastShows.edges.node.partner.__isNode": (v18/*: any*/),
"artist.pastShows.edges.node.partner.__typename": (v18/*: any*/),
"artist.pastShows.edges.node.partner.id": (v14/*: any*/),
"artist.pastShows.edges.node.partner.name": (v13/*: any*/),
"artist.pastShows.edges.node.slug": (v14/*: any*/),
"artist.pastShows.edges.node.status": (v13/*: any*/),
"artist.pastShows.edges.node.status_update": (v13/*: any*/),
"artist.slug": (v14/*: any*/),
"artist.upcomingShows": (v9/*: any*/),
"artist.upcomingShows.edges": (v10/*: any*/),
"artist.upcomingShows.edges.node": (v11/*: any*/),
"artist.upcomingShows.edges.node.cover_image": (v12/*: any*/),
"artist.upcomingShows.edges.node.cover_image.url": (v13/*: any*/),
"artist.upcomingShows.edges.node.exhibition_period": (v13/*: any*/),
"artist.upcomingShows.edges.node.href": (v13/*: any*/),
"artist.upcomingShows.edges.node.id": (v14/*: any*/),
"artist.upcomingShows.edges.node.is_fair_booth": (v15/*: any*/),
"artist.upcomingShows.edges.node.kind": (v13/*: any*/),
"artist.upcomingShows.edges.node.location": (v16/*: any*/),
"artist.upcomingShows.edges.node.location.city": (v13/*: any*/),
"artist.upcomingShows.edges.node.location.id": (v14/*: any*/),
"artist.upcomingShows.edges.node.name": (v13/*: any*/),
"artist.upcomingShows.edges.node.partner": (v17/*: any*/),
"artist.upcomingShows.edges.node.partner.__isNode": (v18/*: any*/),
"artist.upcomingShows.edges.node.partner.__typename": (v18/*: any*/),
"artist.upcomingShows.edges.node.partner.id": (v14/*: any*/),
"artist.upcomingShows.edges.node.partner.name": (v13/*: any*/),
"artist.upcomingShows.edges.node.slug": (v14/*: any*/),
"artist.upcomingShows.edges.node.status": (v13/*: any*/),
"artist.upcomingShows.edges.node.status_update": (v13/*: any*/)
}
},
"name": "ArtistAboutShowsTestsQuery",
"operationKind": "query",
"text": null
}
};
})();
(node as any).hash = 'c2d2e97277ce92e509fcef8e50f81253';
export default node; | the_stack |
import { DATEPICKER_DIALOG_NAME, DATEPICKER_NAME } from '../../constants.js';
import type { DatepickerDialog } from '../../datepicker-dialog.js';
import type { Datepicker } from '../../datepicker.js';
import { APP_INDEX_URL } from '../constants.js';
import type { PrepareOptions } from '../custom_typings.js';
import { cleanHtml } from '../helpers/clean-html.js';
import { prettyHtml } from '../helpers/pretty-html.js';
import { toSelector } from '../helpers/to-selector.js';
import {
allStrictEqual,
deepStrictEqual,
ok,
strictEqual,
} from '../helpers/typed-assert.js';
describe(`${DATEPICKER_DIALOG_NAME}::mouses`, () => {
const isSafari = browser.capabilities.browserName === 'Safari';
const clickElements = async (classes: string[], prepareOptions?: PrepareOptions) => {
if (prepareOptions) {
await browser.executeAsync(async (a, b, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const { props, attrs }: PrepareOptions = b;
if (props) {
Object.keys(props).forEach((o) => {
(n as any)[o] = (props as any)[o];
});
}
if (attrs) {
Object.keys(attrs).forEach((o) => {
n.setAttribute(o.toLowerCase(), String((attrs as any)[o]));
});
}
await n.updateComplete;
done();
}, DATEPICKER_DIALOG_NAME, prepareOptions);
}
/**
* NOTE: [20191229] Due to a bug in Safari 13, Safari is not able
* to recognize any clicks but it has yet to release the patch to
* stable Safari and any older versions of Safari. As of writing,
* only Safari TP has it fixed.
*
* Therefore, this helper is here to imperatively calling `.click()`
* in the browser the tests run when it detects a Safari browser.
*
* @see https://bugs.webkit.org/show_bug.cgi?id=202589
*/
for (const cls of classes) {
if (isSafari) {
await browser.executeAsync(async (a, b, c, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const n2 = n.shadowRoot!.querySelector<Datepicker>(b)!;
const n3 = n2.shadowRoot!.querySelector<HTMLElement>(c)!;
if (n3 instanceof HTMLButtonElement || n3.tagName === 'MWC-BUTTON') {
n3.click();
} else {
// Simulate click event on non natively focusable elements.
// This is for selecting new focused date in the table.
['touchstart', 'touchend'].forEach((o) => {
n3.dispatchEvent(new CustomEvent(o, { bubbles: true, composed: true }));
});
}
await n.updateComplete;
done();
}, DATEPICKER_DIALOG_NAME, DATEPICKER_NAME, cls);
} else {
const el = await $(DATEPICKER_DIALOG_NAME);
const el2 = (await el.shadow$(DATEPICKER_NAME)) as unknown as WebdriverIOAsync.Element;
const el3 = (await el2.shadow$(cls)) as unknown as WebdriverIOAsync.Element;
await el3.click();
}
}
};
before(async () => {
await browser.url(APP_INDEX_URL);
});
beforeEach(async () => {
await browser.executeAsync(async (a, done) => {
const el: DatepickerDialog = document.createElement(a);
el.locale = 'en-US';
// Reset `min` and `value` here before running tests
el.min = '2000-01-01';
el.value = '2020-02-20';
document.body.appendChild(el);
await el.open();
await el.updateComplete;
done();
}, DATEPICKER_DIALOG_NAME);
});
afterEach(async () => {
await browser.executeAsync((a, done) => {
const el = document.body.querySelector<DatepickerDialog>(a);
if (el) document.body.removeChild(el);
done();
}, DATEPICKER_DIALOG_NAME);
});
it(`switches to year list view`, async () => {
await clickElements(['.btn__year-selector']);
const hasYearListView: boolean = await browser.executeAsync(async (a, b, c, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const n2 = n.shadowRoot!.querySelector<Datepicker>(b)!;
const yearListView = n2.shadowRoot!.querySelector<HTMLDivElement>(c);
done(yearListView != null);
}, DATEPICKER_DIALOG_NAME, DATEPICKER_NAME, '.datepicker-body__year-list-view');
ok(hasYearListView);
});
it(`switches to calendar view`, async () => {
await clickElements(['.btn__calendar-selector'], {
props: {
startView: 'yearList',
},
});
const hasCalendarView: boolean = await browser.executeAsync(async (a, b, c, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const n2 = n.shadowRoot!.querySelector<Datepicker>(b)!;
const calendarView = n2.shadowRoot!.querySelector<HTMLDivElement>(c);
done(calendarView != null);
}, DATEPICKER_DIALOG_NAME, DATEPICKER_NAME, '.datepicker-body__calendar-view');
ok(hasCalendarView);
});
it(`selects new year`, async () => {
type A = [string, string, string, string, string[]];
await clickElements([
'.btn__year-selector',
[
`.year-list-view__list-item.year--selected`,
`+ .year-list-view__list-item`,
`+ .year-list-view__list-item`,
].join(' '),
]);
const [
prop,
prop2,
yearSelectorButtonContent,
calendarLabelContent,
calendarDaysContents,
]: A = await browser.executeAsync(async (a, b, c, d, e, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const n2 = n.shadowRoot!.querySelector<Datepicker>(b)!;
const root = n2.shadowRoot!;
const yearSelectorButton = root.querySelector<HTMLButtonElement>(c)!;
const calendarLabel = root.querySelector<HTMLDivElement>(d)!;
const calendarDays = Array.from(
root.querySelectorAll<HTMLTableCellElement>(e), o => o.textContent);
done([
n.value,
n2.value,
yearSelectorButton.outerHTML,
calendarLabel.outerHTML,
calendarDays,
] as A);
},
DATEPICKER_DIALOG_NAME,
DATEPICKER_NAME,
'.btn__year-selector',
toSelector('.calendar-label'),
toSelector('.full-calendar__day'));
strictEqual(prop, '2020-02-20');
strictEqual(prop2, '2022-02-20');
strictEqual(cleanHtml(yearSelectorButtonContent), prettyHtml`
<button class="btn__year-selector" data-view="yearList">2022</button>
`);
strictEqual(cleanHtml(calendarLabelContent), prettyHtml`
<div class="calendar-label">February 2022</div>
`);
deepStrictEqual(calendarDaysContents.map(n => cleanHtml(n.trim())), [
'', '', 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26,
27, 28, '', '', '', '', '',
'', '', '', '', '', '', '',
].map(String));
});
it(`navigates to next month`, async () => {
type A = [string, string[]];
await clickElements([`.btn__month-selector[aria-label="Next month"]`]);
const [
calendarLabelContent,
calendarDaysContents,
]: A = await browser.executeAsync(async (a, b, c, d, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const n2 = n.shadowRoot!.querySelector<Datepicker>(b)!;
const root = n2.shadowRoot!;
const calendarLabel = root.querySelector<HTMLDivElement>(c)!;
const calendarDays = Array.from(
root.querySelectorAll<HTMLTableCellElement>(d), o => o.textContent);
done([
calendarLabel.outerHTML,
calendarDays,
] as A);
},
DATEPICKER_DIALOG_NAME,
DATEPICKER_NAME,
toSelector('.calendar-label'),
toSelector('.full-calendar__day'));
strictEqual(
cleanHtml(calendarLabelContent),
prettyHtml`<div class="calendar-label">March 2020</div>`
);
deepStrictEqual(calendarDaysContents.map(n => cleanHtml(n.trim())), [
1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 26, 27, 28,
29, 30, 31, '', '', '', '',
'', '', '', '', '', '', '',
].map(String));
});
it(`navigates to previous month`, async () => {
type A = [string, string[]];
await clickElements([`.btn__month-selector[aria-label="Previous month"]`]);
const [
calendarLabelContent,
calendarDaysContents,
]: A = await browser.executeAsync(async (a, b, c, d, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const n2 = n.shadowRoot!.querySelector<Datepicker>(b)!;
const root = n2.shadowRoot!;
const calendarLabel = root.querySelector<HTMLDivElement>(c)!;
const calendarDays = Array.from(
root.querySelectorAll<HTMLTableCellElement>(d), o => o.textContent);
done([
calendarLabel.outerHTML,
calendarDays,
] as A);
},
DATEPICKER_DIALOG_NAME,
DATEPICKER_NAME,
toSelector('.calendar-label'),
toSelector('.full-calendar__day'));
strictEqual(
cleanHtml(calendarLabelContent),
prettyHtml`<div class="calendar-label">January 2020</div>`
);
deepStrictEqual(calendarDaysContents.map(n => cleanHtml(n.trim())), [
'', '', '', 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, '',
'', '', '', '', '', '', '',
].map(String));
});
it(`selects new focused date`, async () => {
type A = [string, string, string];
await clickElements([
toSelector(`.full-calendar__day[aria-label="Feb 13, 2020"]`),
]);
const [
prop,
prop2,
focusedDateContent,
]: A = await browser.executeAsync(async (a, b, c, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const n2 = n.shadowRoot!.querySelector<Datepicker>(b)!;
const root = n2.shadowRoot!;
const focusedDate = root.querySelector<HTMLTableCellElement>(c)!;
done([
n.value,
n2.value,
focusedDate.outerHTML,
] as A);
},
DATEPICKER_DIALOG_NAME,
DATEPICKER_NAME,
toSelector('.day--focused'));
strictEqual(prop, '2020-02-20');
strictEqual(prop2, '2020-02-13');
strictEqual(cleanHtml(focusedDateContent), prettyHtml`
<td class="full-calendar__day day--focused" aria-disabled="false" aria-label="Feb 13, 2020" aria-selected="true">
<div class="calendar-day">13</div>
</td>
`);
});
it(`closes dialog when dismiss button is clicked`, async () => {
type A = [string, string];
const [
cssDisplay,
ariaHiddenAttr,
]: A = await browser.executeAsync(async (a, b, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const dialogDismissButton = n.shadowRoot!.querySelector<HTMLElement>(b)!;
const dialogClosed = new Promise((yay) => {
let timer = -1;
function handler() {
clearTimeout(timer);
yay(true);
n.removeEventListener('datepicker-dialog-closed', handler);
}
n.addEventListener('datepicker-dialog-closed', handler);
timer = window.setTimeout(() => yay(false), 15e3);
});
dialogDismissButton.click();
await n.updateComplete;
await dialogClosed;
done([
getComputedStyle(n).display,
n.getAttribute('aria-hidden'),
] as A);
}, DATEPICKER_DIALOG_NAME, `.actions-container > mwc-button[dialog-dismiss]`);
strictEqual(cssDisplay, 'none');
strictEqual(ariaHiddenAttr, 'true');
});
it(`closes dialog with new focused date when confirm button is clicked`, async () => {
type A = [string, string, string, string, string, string];
await clickElements([
toSelector(`.full-calendar__day[aria-label="Feb 13, 2020"]`),
]);
const [
prop,
prop2,
prop3,
cssDisplay,
ariaHiddenAttr,
focusedDateContent,
]: A = await browser.executeAsync(async (a, b, c, d, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const root = n.shadowRoot!;
const dialogConfirmButton = root.querySelector<HTMLElement>(c)!;
const n2 = root.querySelector<Datepicker>(b)!;
const focusedDate = n2.shadowRoot!.querySelector<HTMLTableCellElement>(d)!;
const propVal = n.value;
const propVal2 = n2.value;
const focusedDateVal = focusedDate.outerHTML;
const dialogClosed = new Promise((yay) => {
let timer = -1;
function handler() {
clearTimeout(timer);
yay(true);
n.removeEventListener('datepicker-dialog-closed', handler);
}
n.addEventListener('datepicker-dialog-closed', handler);
timer = window.setTimeout(() => yay(false), 15e3);
});
dialogConfirmButton.click();
await n.updateComplete;
await dialogClosed;
done([
propVal,
propVal2,
n.value,
getComputedStyle(n).display,
n.getAttribute('aria-hidden'),
focusedDateVal,
] as A);
},
DATEPICKER_DIALOG_NAME,
DATEPICKER_NAME,
`.actions-container > mwc-button[dialog-confirm]`,
toSelector('.day--focused'));
strictEqual(prop, '2020-02-20');
allStrictEqual([prop2, prop3], '2020-02-13');
strictEqual(cssDisplay, 'none');
strictEqual(ariaHiddenAttr, 'true');
strictEqual(cleanHtml(focusedDateContent), prettyHtml`
<td class="full-calendar__day day--focused" aria-disabled="false" aria-label="Feb 13, 2020" aria-selected="true">
<div class="calendar-day">13</div>
</td>
`);
});
it(`reset value when clear button is clicked`, async () => {
type A = [string, string, string];
const [
initialProp,
prop,
todayValue,
]: A = await browser.executeAsync(async (a, b, c, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const root = n.shadowRoot!;
const n2 = root.querySelector<Datepicker>(b)!;
const padStart = (v: number) => `0${v}`.slice(-2);
const today = new Date();
const fy = today.getFullYear();
const m = today.getMonth();
const d = today.getDate();
const todayVal = [`${fy}`].concat([1 + m, d].map(padStart)).join('-');
n.min = `${fy - 10}-01-01`;
n2.value = `${fy - 1}-01-01`;
n.max = `${fy + 10}-01-01`;
await n2.updateComplete;
await n.updateComplete;
const propVal = n2.value;
const clearButton = root.querySelector<HTMLElement>(c)!;
clearButton.click();
const propVal2 = n2.value;
done([
propVal,
propVal2,
todayVal,
] as A);
}, DATEPICKER_DIALOG_NAME, DATEPICKER_NAME, 'mwc-button.clear');
strictEqual(initialProp, `${Number(todayValue.slice(0, 4)) - 1}-01-01`);
strictEqual(prop, todayValue);
});
}); | the_stack |
import first from "lodash/first"
import isEmpty from "lodash/isEmpty"
import drop from "lodash/drop"
import flatten from "lodash/flatten"
import filter from "lodash/filter"
import reject from "lodash/reject"
import difference from "lodash/difference"
import map from "lodash/map"
import forEach from "lodash/forEach"
import groupBy from "lodash/groupBy"
import reduce from "lodash/reduce"
import pickBy from "lodash/pickBy"
import values from "lodash/values"
import includes from "lodash/includes"
import flatMap from "lodash/flatMap"
import clone from "lodash/clone"
import {
IParserAmbiguousAlternativesDefinitionError,
IParserDuplicatesDefinitionError,
IParserEmptyAlternativeDefinitionError,
ParserDefinitionErrorType
} from "../parser/parser"
import { getProductionDslName, isOptionalProd } from "./gast/gast"
import {
Alternative,
containsPath,
getLookaheadPathsForOptionalProd,
getLookaheadPathsForOr,
getProdType,
isStrictPrefixOfPath
} from "./lookahead"
import { nextPossibleTokensAfter } from "./interpreter"
import {
Alternation,
Alternative as AlternativeGAST,
NonTerminal,
Option,
Repetition,
RepetitionMandatory,
RepetitionMandatoryWithSeparator,
RepetitionWithSeparator,
Rule,
Terminal
} from "./gast/gast_public"
import { GAstVisitor } from "./gast/gast_visitor_public"
import {
IProduction,
IProductionWithOccurrence,
TokenType
} from "@chevrotain/types"
import {
IGrammarValidatorErrorMessageProvider,
IParserDefinitionError
} from "./types"
import dropRight from "lodash/dropRight"
import compact from "lodash/compact"
import { tokenStructuredMatcher } from "../../scan/tokens"
export function validateGrammar(
topLevels: Rule[],
globalMaxLookahead: number,
tokenTypes: TokenType[],
errMsgProvider: IGrammarValidatorErrorMessageProvider,
grammarName: string
): IParserDefinitionError[] {
const duplicateErrors = flatMap(topLevels, (currTopLevel) =>
validateDuplicateProductions(currTopLevel, errMsgProvider)
)
const leftRecursionErrors = flatMap(topLevels, (currTopRule) =>
validateNoLeftRecursion(currTopRule, currTopRule, errMsgProvider)
)
let emptyAltErrors: IParserEmptyAlternativeDefinitionError[] = []
let ambiguousAltsErrors: IParserAmbiguousAlternativesDefinitionError[] = []
let emptyRepetitionErrors: IParserDefinitionError[] = []
// left recursion could cause infinite loops in the following validations.
// It is safest to first have the user fix the left recursion errors first and only then examine Further issues.
if (isEmpty(leftRecursionErrors)) {
emptyAltErrors = flatMap(topLevels, (currTopRule) =>
validateEmptyOrAlternative(currTopRule, errMsgProvider)
)
ambiguousAltsErrors = flatMap(topLevels, (currTopRule) =>
validateAmbiguousAlternationAlternatives(
currTopRule,
globalMaxLookahead,
errMsgProvider
)
)
emptyRepetitionErrors = validateSomeNonEmptyLookaheadPath(
topLevels,
globalMaxLookahead,
errMsgProvider
)
}
const termsNamespaceConflictErrors = checkTerminalAndNoneTerminalsNameSpace(
topLevels,
tokenTypes,
errMsgProvider
)
const tooManyAltsErrors = flatMap(topLevels, (curRule) =>
validateTooManyAlts(curRule, errMsgProvider)
)
const duplicateRulesError = flatMap(topLevels, (curRule) =>
validateRuleDoesNotAlreadyExist(
curRule,
topLevels,
grammarName,
errMsgProvider
)
)
return (duplicateErrors as IParserDefinitionError[]).concat(
emptyRepetitionErrors,
leftRecursionErrors,
emptyAltErrors,
ambiguousAltsErrors,
termsNamespaceConflictErrors,
tooManyAltsErrors,
duplicateRulesError
)
}
function validateDuplicateProductions(
topLevelRule: Rule,
errMsgProvider: IGrammarValidatorErrorMessageProvider
): IParserDuplicatesDefinitionError[] {
const collectorVisitor = new OccurrenceValidationCollector()
topLevelRule.accept(collectorVisitor)
const allRuleProductions = collectorVisitor.allProductions
const productionGroups = groupBy(
allRuleProductions,
identifyProductionForDuplicates
)
const duplicates: any = pickBy(productionGroups, (currGroup) => {
return currGroup.length > 1
})
const errors = map(values(duplicates), (currDuplicates: any) => {
const firstProd: any = first(currDuplicates)
const msg = errMsgProvider.buildDuplicateFoundError(
topLevelRule,
currDuplicates
)
const dslName = getProductionDslName(firstProd)
const defError: IParserDuplicatesDefinitionError = {
message: msg,
type: ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS,
ruleName: topLevelRule.name,
dslName: dslName,
occurrence: firstProd.idx
}
const param = getExtraProductionArgument(firstProd)
if (param) {
defError.parameter = param
}
return defError
})
return errors
}
export function identifyProductionForDuplicates(
prod: IProductionWithOccurrence
): string {
return `${getProductionDslName(prod)}_#_${
prod.idx
}_#_${getExtraProductionArgument(prod)}`
}
function getExtraProductionArgument(prod: IProductionWithOccurrence): string {
if (prod instanceof Terminal) {
return prod.terminalType.name
} else if (prod instanceof NonTerminal) {
return prod.nonTerminalName
} else {
return ""
}
}
export class OccurrenceValidationCollector extends GAstVisitor {
public allProductions: IProductionWithOccurrence[] = []
public visitNonTerminal(subrule: NonTerminal): void {
this.allProductions.push(subrule)
}
public visitOption(option: Option): void {
this.allProductions.push(option)
}
public visitRepetitionWithSeparator(manySep: RepetitionWithSeparator): void {
this.allProductions.push(manySep)
}
public visitRepetitionMandatory(atLeastOne: RepetitionMandatory): void {
this.allProductions.push(atLeastOne)
}
public visitRepetitionMandatoryWithSeparator(
atLeastOneSep: RepetitionMandatoryWithSeparator
): void {
this.allProductions.push(atLeastOneSep)
}
public visitRepetition(many: Repetition): void {
this.allProductions.push(many)
}
public visitAlternation(or: Alternation): void {
this.allProductions.push(or)
}
public visitTerminal(terminal: Terminal): void {
this.allProductions.push(terminal)
}
}
export function validateRuleDoesNotAlreadyExist(
rule: Rule,
allRules: Rule[],
className: string,
errMsgProvider: IGrammarValidatorErrorMessageProvider
): IParserDefinitionError[] {
const errors = []
const occurrences = reduce(
allRules,
(result, curRule) => {
if (curRule.name === rule.name) {
return result + 1
}
return result
},
0
)
if (occurrences > 1) {
const errMsg = errMsgProvider.buildDuplicateRuleNameError({
topLevelRule: rule,
grammarName: className
})
errors.push({
message: errMsg,
type: ParserDefinitionErrorType.DUPLICATE_RULE_NAME,
ruleName: rule.name
})
}
return errors
}
// TODO: is there anyway to get only the rule names of rules inherited from the super grammars?
// This is not part of the IGrammarErrorProvider because the validation cannot be performed on
// The grammar structure, only at runtime.
export function validateRuleIsOverridden(
ruleName: string,
definedRulesNames: string[],
className: string
): IParserDefinitionError[] {
const errors = []
let errMsg
if (!includes(definedRulesNames, ruleName)) {
errMsg =
`Invalid rule override, rule: ->${ruleName}<- cannot be overridden in the grammar: ->${className}<-` +
`as it is not defined in any of the super grammars `
errors.push({
message: errMsg,
type: ParserDefinitionErrorType.INVALID_RULE_OVERRIDE,
ruleName: ruleName
})
}
return errors
}
export function validateNoLeftRecursion(
topRule: Rule,
currRule: Rule,
errMsgProvider: IGrammarValidatorErrorMessageProvider,
path: Rule[] = []
): IParserDefinitionError[] {
const errors: IParserDefinitionError[] = []
const nextNonTerminals = getFirstNoneTerminal(currRule.definition)
if (isEmpty(nextNonTerminals)) {
return []
} else {
const ruleName = topRule.name
const foundLeftRecursion = includes(<any>nextNonTerminals, topRule)
if (foundLeftRecursion) {
errors.push({
message: errMsgProvider.buildLeftRecursionError({
topLevelRule: topRule,
leftRecursionPath: path
}),
type: ParserDefinitionErrorType.LEFT_RECURSION,
ruleName: ruleName
})
}
// we are only looking for cyclic paths leading back to the specific topRule
// other cyclic paths are ignored, we still need this difference to avoid infinite loops...
const validNextSteps = difference(nextNonTerminals, path.concat([topRule]))
const errorsFromNextSteps = flatMap(validNextSteps, (currRefRule) => {
const newPath = clone(path)
newPath.push(currRefRule)
return validateNoLeftRecursion(
topRule,
currRefRule,
errMsgProvider,
newPath
)
})
return errors.concat(errorsFromNextSteps)
}
}
export function getFirstNoneTerminal(definition: IProduction[]): Rule[] {
let result: Rule[] = []
if (isEmpty(definition)) {
return result
}
const firstProd = first(definition)
/* istanbul ignore else */
if (firstProd instanceof NonTerminal) {
result.push(firstProd.referencedRule)
} else if (
firstProd instanceof AlternativeGAST ||
firstProd instanceof Option ||
firstProd instanceof RepetitionMandatory ||
firstProd instanceof RepetitionMandatoryWithSeparator ||
firstProd instanceof RepetitionWithSeparator ||
firstProd instanceof Repetition
) {
result = result.concat(
getFirstNoneTerminal(<IProduction[]>firstProd.definition)
)
} else if (firstProd instanceof Alternation) {
// each sub definition in alternation is a FLAT
result = flatten(
map(firstProd.definition, (currSubDef) =>
getFirstNoneTerminal((<AlternativeGAST>currSubDef).definition)
)
)
} else if (firstProd instanceof Terminal) {
// nothing to see, move along
} else {
throw Error("non exhaustive match")
}
const isFirstOptional = isOptionalProd(firstProd)
const hasMore = definition.length > 1
if (isFirstOptional && hasMore) {
const rest = drop(definition)
return result.concat(getFirstNoneTerminal(rest))
} else {
return result
}
}
class OrCollector extends GAstVisitor {
public alternations: Alternation[] = []
public visitAlternation(node: Alternation): void {
this.alternations.push(node)
}
}
export function validateEmptyOrAlternative(
topLevelRule: Rule,
errMsgProvider: IGrammarValidatorErrorMessageProvider
): IParserEmptyAlternativeDefinitionError[] {
const orCollector = new OrCollector()
topLevelRule.accept(orCollector)
const ors = orCollector.alternations
const errors = flatMap<Alternation, IParserEmptyAlternativeDefinitionError>(
ors,
(currOr) => {
const exceptLast = dropRight(currOr.definition)
return flatMap(exceptLast, (currAlternative, currAltIdx) => {
const possibleFirstInAlt = nextPossibleTokensAfter(
[currAlternative],
[],
tokenStructuredMatcher,
1
)
if (isEmpty(possibleFirstInAlt)) {
return [
{
message: errMsgProvider.buildEmptyAlternationError({
topLevelRule: topLevelRule,
alternation: currOr,
emptyChoiceIdx: currAltIdx
}),
type: ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT,
ruleName: topLevelRule.name,
occurrence: currOr.idx,
alternative: currAltIdx + 1
}
]
} else {
return []
}
})
}
)
return errors
}
export function validateAmbiguousAlternationAlternatives(
topLevelRule: Rule,
globalMaxLookahead: number,
errMsgProvider: IGrammarValidatorErrorMessageProvider
): IParserAmbiguousAlternativesDefinitionError[] {
const orCollector = new OrCollector()
topLevelRule.accept(orCollector)
let ors = orCollector.alternations
// New Handling of ignoring ambiguities
// - https://github.com/chevrotain/chevrotain/issues/869
ors = reject(ors, (currOr) => currOr.ignoreAmbiguities === true)
const errors = flatMap(ors, (currOr: Alternation) => {
const currOccurrence = currOr.idx
const actualMaxLookahead = currOr.maxLookahead || globalMaxLookahead
const alternatives = getLookaheadPathsForOr(
currOccurrence,
topLevelRule,
actualMaxLookahead,
currOr
)
const altsAmbiguityErrors = checkAlternativesAmbiguities(
alternatives,
currOr,
topLevelRule,
errMsgProvider
)
const altsPrefixAmbiguityErrors = checkPrefixAlternativesAmbiguities(
alternatives,
currOr,
topLevelRule,
errMsgProvider
)
return altsAmbiguityErrors.concat(altsPrefixAmbiguityErrors)
})
return errors
}
export class RepetitionCollector extends GAstVisitor {
public allProductions: (IProductionWithOccurrence & {
maxLookahead?: number
})[] = []
public visitRepetitionWithSeparator(manySep: RepetitionWithSeparator): void {
this.allProductions.push(manySep)
}
public visitRepetitionMandatory(atLeastOne: RepetitionMandatory): void {
this.allProductions.push(atLeastOne)
}
public visitRepetitionMandatoryWithSeparator(
atLeastOneSep: RepetitionMandatoryWithSeparator
): void {
this.allProductions.push(atLeastOneSep)
}
public visitRepetition(many: Repetition): void {
this.allProductions.push(many)
}
}
export function validateTooManyAlts(
topLevelRule: Rule,
errMsgProvider: IGrammarValidatorErrorMessageProvider
): IParserDefinitionError[] {
const orCollector = new OrCollector()
topLevelRule.accept(orCollector)
const ors = orCollector.alternations
const errors = flatMap(ors, (currOr) => {
if (currOr.definition.length > 255) {
return [
{
message: errMsgProvider.buildTooManyAlternativesError({
topLevelRule: topLevelRule,
alternation: currOr
}),
type: ParserDefinitionErrorType.TOO_MANY_ALTS,
ruleName: topLevelRule.name,
occurrence: currOr.idx
}
]
} else {
return []
}
})
return errors
}
export function validateSomeNonEmptyLookaheadPath(
topLevelRules: Rule[],
maxLookahead: number,
errMsgProvider: IGrammarValidatorErrorMessageProvider
): IParserDefinitionError[] {
const errors: IParserDefinitionError[] = []
forEach(topLevelRules, (currTopRule) => {
const collectorVisitor = new RepetitionCollector()
currTopRule.accept(collectorVisitor)
const allRuleProductions = collectorVisitor.allProductions
forEach(allRuleProductions, (currProd) => {
const prodType = getProdType(currProd)
const actualMaxLookahead = currProd.maxLookahead || maxLookahead
const currOccurrence = currProd.idx
const paths = getLookaheadPathsForOptionalProd(
currOccurrence,
currTopRule,
prodType,
actualMaxLookahead
)
const pathsInsideProduction = paths[0]
if (isEmpty(flatten(pathsInsideProduction))) {
const errMsg = errMsgProvider.buildEmptyRepetitionError({
topLevelRule: currTopRule,
repetition: currProd
})
errors.push({
message: errMsg,
type: ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD,
ruleName: currTopRule.name
})
}
})
})
return errors
}
export interface IAmbiguityDescriptor {
alts: number[]
path: TokenType[]
}
function checkAlternativesAmbiguities(
alternatives: Alternative[],
alternation: Alternation,
rule: Rule,
errMsgProvider: IGrammarValidatorErrorMessageProvider
): IParserAmbiguousAlternativesDefinitionError[] {
const foundAmbiguousPaths: Alternative = []
const identicalAmbiguities = reduce(
alternatives,
(result, currAlt, currAltIdx) => {
// ignore (skip) ambiguities with this alternative
if (alternation.definition[currAltIdx].ignoreAmbiguities === true) {
return result
}
forEach(currAlt, (currPath) => {
const altsCurrPathAppearsIn = [currAltIdx]
forEach(alternatives, (currOtherAlt, currOtherAltIdx) => {
if (
currAltIdx !== currOtherAltIdx &&
containsPath(currOtherAlt, currPath) &&
// ignore (skip) ambiguities with this "other" alternative
alternation.definition[currOtherAltIdx].ignoreAmbiguities !== true
) {
altsCurrPathAppearsIn.push(currOtherAltIdx)
}
})
if (
altsCurrPathAppearsIn.length > 1 &&
!containsPath(foundAmbiguousPaths, currPath)
) {
foundAmbiguousPaths.push(currPath)
result.push({
alts: altsCurrPathAppearsIn,
path: currPath
})
}
})
return result
},
[] as { alts: number[]; path: TokenType[] }[]
)
const currErrors = map(identicalAmbiguities, (currAmbDescriptor) => {
const ambgIndices = map(
currAmbDescriptor.alts,
(currAltIdx) => currAltIdx + 1
)
const currMessage = errMsgProvider.buildAlternationAmbiguityError({
topLevelRule: rule,
alternation: alternation,
ambiguityIndices: ambgIndices,
prefixPath: currAmbDescriptor.path
})
return {
message: currMessage,
type: ParserDefinitionErrorType.AMBIGUOUS_ALTS,
ruleName: rule.name,
occurrence: alternation.idx,
alternatives: currAmbDescriptor.alts
}
})
return currErrors
}
export function checkPrefixAlternativesAmbiguities(
alternatives: Alternative[],
alternation: Alternation,
rule: Rule,
errMsgProvider: IGrammarValidatorErrorMessageProvider
): IParserAmbiguousAlternativesDefinitionError[] {
// flatten
const pathsAndIndices = reduce(
alternatives,
(result, currAlt, idx) => {
const currPathsAndIdx = map(currAlt, (currPath) => {
return { idx: idx, path: currPath }
})
return result.concat(currPathsAndIdx)
},
[] as { idx: number; path: TokenType[] }[]
)
const errors = compact(
flatMap(pathsAndIndices, (currPathAndIdx) => {
const alternativeGast = alternation.definition[currPathAndIdx.idx]
// ignore (skip) ambiguities with this alternative
if (alternativeGast.ignoreAmbiguities === true) {
return []
}
const targetIdx = currPathAndIdx.idx
const targetPath = currPathAndIdx.path
const prefixAmbiguitiesPathsAndIndices = filter(
pathsAndIndices,
(searchPathAndIdx) => {
// prefix ambiguity can only be created from lower idx (higher priority) path
return (
// ignore (skip) ambiguities with this "other" alternative
alternation.definition[searchPathAndIdx.idx].ignoreAmbiguities !==
true &&
searchPathAndIdx.idx < targetIdx &&
// checking for strict prefix because identical lookaheads
// will be be detected using a different validation.
isStrictPrefixOfPath(searchPathAndIdx.path, targetPath)
)
}
)
const currPathPrefixErrors = map(
prefixAmbiguitiesPathsAndIndices,
(currAmbPathAndIdx): IParserAmbiguousAlternativesDefinitionError => {
const ambgIndices = [currAmbPathAndIdx.idx + 1, targetIdx + 1]
const occurrence = alternation.idx === 0 ? "" : alternation.idx
const message = errMsgProvider.buildAlternationPrefixAmbiguityError({
topLevelRule: rule,
alternation: alternation,
ambiguityIndices: ambgIndices,
prefixPath: currAmbPathAndIdx.path
})
return {
message: message,
type: ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS,
ruleName: rule.name,
occurrence: occurrence,
alternatives: ambgIndices
}
}
)
return currPathPrefixErrors
})
)
return errors
}
function checkTerminalAndNoneTerminalsNameSpace(
topLevels: Rule[],
tokenTypes: TokenType[],
errMsgProvider: IGrammarValidatorErrorMessageProvider
): IParserDefinitionError[] {
const errors: IParserDefinitionError[] = []
const tokenNames = map(tokenTypes, (currToken) => currToken.name)
forEach(topLevels, (currRule) => {
const currRuleName = currRule.name
if (includes(tokenNames, currRuleName)) {
const errMsg = errMsgProvider.buildNamespaceConflictError(currRule)
errors.push({
message: errMsg,
type: ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE,
ruleName: currRuleName
})
}
})
return errors
} | the_stack |
import Browserslist from "browserslist";
import {feature as caniuseFeature, features as caniuseFeatures} from "caniuse-lite";
import compatData from "@mdn/browser-compat-data";
import {get} from "object-path";
import {gt, gte, lt, lte} from "semver";
import {
getClosestMatchingBrowserVersion,
getNextVersionOfBrowser,
getOldestVersionOfBrowser,
getPreviousVersionOfBrowser,
getSortedBrowserVersionsWithLeadingVersion,
normalizeBrowserVersion
} from "./browser-version";
import {UNKNOWN_CANIUSE_BROWSER} from "./constant";
import {ensureSemver, coerceToString} from "./ensure-semver";
import {compareVersions} from "./compare-versions";
import {ComparisonOperator} from "./comparison-operator";
import {
EcmaVersion,
ES2015_FEATURES,
ES2016_FEATURES,
ES2017_FEATURES,
ES2018_FEATURES,
ES2019_FEATURES,
ES2020_FEATURES,
ES2021_FEATURES,
ES2022_FEATURES,
ES5_FEATURES
} from "./ecma-version";
import {rangeCorrection} from "./range-correction";
import {BrowserSupportForFeaturesCommonResult} from "./browser-support-for-features-common-result";
import {CaniuseBrowser, CaniuseStats, CaniuseStatsNormalized, CaniuseSupportKind, CaniuseBrowserCorrection, CaniuseFeature, VersionedCaniuseBrowser} from "./i-caniuse";
import {Mdn, MdnBrowserName} from "./mdn";
import {NORMALIZE_BROWSER_VERSION_REGEXP} from "./normalize-browser-version-regexp";
import {UaParserWrapper} from "./ua-parser-wrapper";
import {UseragentBrowser, UseragentEngine, UseragentOs} from "./useragent/useragent-typed";
/**
* A Cache between user agent names and generated Browserslists
*/
const userAgentToBrowserslistCache: Map<string, string[]> = new Map();
/**
* A Cache for retrieving browser support for some features
* @type {Map<string, BrowserSupportForFeaturesCommonResult>}
*/
const browserSupportForFeaturesCache: Map<string, BrowserSupportForFeaturesCommonResult> = new Map();
/**
* A Cache between feature names and their CaniuseStats
* @type {Map<string, CaniuseStatsNormalized>}
*/
const featureToCaniuseStatsCache: Map<string, CaniuseStatsNormalized> = new Map();
/**
* A Cache between user agents with any amount of features and whether or not they are supported by the user agent
* @type {Map<string, boolean>}
*/
const userAgentWithFeaturesToSupportCache: Map<string, boolean> = new Map();
// tslint:disable:no-magic-numbers
/**
* A Map between features and browsers that has partial support for them but should be allowed anyway
* @type {Map<string, string[]>}
*/
const PARTIAL_SUPPORT_ALLOWANCES = new Map([
["shadowdomv1", "*"],
["custom-elementsv1", "*"],
["web-animation", "*"]
]) as Map<string, CaniuseBrowser[] | "*">;
/**
* These browsers will be ignored all-together since they only report the latest
* version from Caniuse and is considered unreliable because of it
* @type {Set<string>}
*/
const IGNORED_BROWSERS_INPUT: CaniuseBrowser[] = ["and_chr", "and_ff", "and_uc", "and_qq", "baidu", "op_mini"];
const IGNORED_BROWSERS: Set<CaniuseBrowser> = new Set(IGNORED_BROWSERS_INPUT);
const TYPED_ARRAY_BASE_DATA_CORRECTIONS_INPUT: CaniuseBrowserCorrection = {
/* eslint-disable @typescript-eslint/naming-convention */
android: rangeCorrection("android", CaniuseSupportKind.AVAILABLE, `4`),
chrome: rangeCorrection("and_chr", CaniuseSupportKind.AVAILABLE, `7`),
and_chr: rangeCorrection("and_chr", CaniuseSupportKind.AVAILABLE, `7`),
edge: rangeCorrection("edge", CaniuseSupportKind.AVAILABLE, "12"),
samsung: rangeCorrection("samsung", CaniuseSupportKind.AVAILABLE, `4`),
opera: rangeCorrection("opera", CaniuseSupportKind.AVAILABLE, `12`),
op_mob: rangeCorrection("op_mob", CaniuseSupportKind.AVAILABLE, `12`),
firefox: rangeCorrection("firefox", CaniuseSupportKind.AVAILABLE, `4`),
and_ff: rangeCorrection("and_ff", CaniuseSupportKind.AVAILABLE, `4`),
safari: rangeCorrection("safari", CaniuseSupportKind.AVAILABLE, `6`),
ios_saf: rangeCorrection("safari", CaniuseSupportKind.AVAILABLE, `5`),
ie: rangeCorrection("ie", CaniuseSupportKind.AVAILABLE, `11`),
op_mini: rangeCorrection("op_mini", CaniuseSupportKind.AVAILABLE, `all`),
bb: rangeCorrection("bb", CaniuseSupportKind.AVAILABLE, `10`),
and_uc: rangeCorrection("and_uc", CaniuseSupportKind.AVAILABLE, `11.8`),
and_qq: rangeCorrection("and_qq", CaniuseSupportKind.AVAILABLE, `1.2`),
baidu: rangeCorrection("baidu", CaniuseSupportKind.AVAILABLE, `7.12`)
/* eslint-enable @typescript-eslint/naming-convention */
};
const TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT: CaniuseBrowserCorrection = {
/* eslint-disable @typescript-eslint/naming-convention */
android: rangeCorrection("android", CaniuseSupportKind.AVAILABLE, `45`),
chrome: rangeCorrection("and_chr", CaniuseSupportKind.AVAILABLE, `45`),
and_chr: rangeCorrection("and_chr", CaniuseSupportKind.AVAILABLE, `45`),
edge: rangeCorrection("edge", CaniuseSupportKind.AVAILABLE, "12"),
samsung: rangeCorrection("samsung", CaniuseSupportKind.AVAILABLE, `5`),
opera: rangeCorrection("opera", CaniuseSupportKind.AVAILABLE, `32`),
op_mob: rangeCorrection("op_mob", CaniuseSupportKind.AVAILABLE, `32`),
firefox: rangeCorrection("firefox", CaniuseSupportKind.AVAILABLE, `38`),
and_ff: rangeCorrection("and_ff", CaniuseSupportKind.AVAILABLE, `38`),
safari: rangeCorrection("safari", CaniuseSupportKind.AVAILABLE, `10`),
ios_saf: rangeCorrection("safari", CaniuseSupportKind.AVAILABLE, `10`),
ie: rangeCorrection("ie", CaniuseSupportKind.AVAILABLE, `11`),
ie_mob: rangeCorrection("ie", CaniuseSupportKind.AVAILABLE, `11`)
/* eslint-enable @typescript-eslint/naming-convention */
};
const TYPED_ARRAY_ES2016_DATA_CORRECTIONS_INPUT: CaniuseBrowserCorrection = {
/* eslint-disable @typescript-eslint/naming-convention */
android: rangeCorrection("android", CaniuseSupportKind.AVAILABLE, `47`),
chrome: rangeCorrection("and_chr", CaniuseSupportKind.AVAILABLE, `47`),
and_chr: rangeCorrection("and_chr", CaniuseSupportKind.AVAILABLE, `47`),
edge: rangeCorrection("edge", CaniuseSupportKind.AVAILABLE, "14"),
samsung: rangeCorrection("samsung", CaniuseSupportKind.AVAILABLE, `5`),
opera: rangeCorrection("opera", CaniuseSupportKind.AVAILABLE, `34`),
op_mob: rangeCorrection("op_mob", CaniuseSupportKind.AVAILABLE, `34`),
firefox: rangeCorrection("firefox", CaniuseSupportKind.AVAILABLE, `43`),
and_ff: rangeCorrection("and_ff", CaniuseSupportKind.AVAILABLE, `43`),
safari: rangeCorrection("safari", CaniuseSupportKind.AVAILABLE, `10`),
ios_saf: rangeCorrection("safari", CaniuseSupportKind.AVAILABLE, `10`)
/* eslint-enable @typescript-eslint/naming-convention */
};
const TYPED_ARRAY_KEYS_VALUES_ENTRIES_ITERATOR_DATA_CORRECTIONS_INPUT: CaniuseBrowserCorrection = {
/* eslint-disable @typescript-eslint/naming-convention */
android: rangeCorrection("android", CaniuseSupportKind.AVAILABLE, `38`),
chrome: rangeCorrection("and_chr", CaniuseSupportKind.AVAILABLE, `38`),
and_chr: rangeCorrection("and_chr", CaniuseSupportKind.AVAILABLE, `38`),
edge: rangeCorrection("edge", CaniuseSupportKind.AVAILABLE, "12"),
samsung: rangeCorrection("samsung", CaniuseSupportKind.AVAILABLE, `5`),
opera: rangeCorrection("opera", CaniuseSupportKind.AVAILABLE, `26`),
op_mob: rangeCorrection("op_mob", CaniuseSupportKind.AVAILABLE, `26`),
firefox: rangeCorrection("firefox", CaniuseSupportKind.AVAILABLE, `37`),
and_ff: rangeCorrection("and_ff", CaniuseSupportKind.AVAILABLE, `37`),
safari: rangeCorrection("safari", CaniuseSupportKind.AVAILABLE, `10`),
ios_saf: rangeCorrection("safari", CaniuseSupportKind.AVAILABLE, `10`)
/* eslint-enable @typescript-eslint/naming-convention */
};
const TYPED_ARRAY_SPECIES_DATA_CORRECTIONS_INPUT: CaniuseBrowserCorrection = {
/* eslint-disable @typescript-eslint/naming-convention */
android: rangeCorrection("android", CaniuseSupportKind.AVAILABLE, `51`),
chrome: rangeCorrection("and_chr", CaniuseSupportKind.AVAILABLE, `51`),
and_chr: rangeCorrection("and_chr", CaniuseSupportKind.AVAILABLE, `51`),
edge: rangeCorrection("edge", CaniuseSupportKind.AVAILABLE, "13"),
samsung: rangeCorrection("samsung", CaniuseSupportKind.AVAILABLE, `5`),
opera: rangeCorrection("opera", CaniuseSupportKind.AVAILABLE, `38`),
op_mob: rangeCorrection("op_mob", CaniuseSupportKind.AVAILABLE, `38`),
firefox: rangeCorrection("firefox", CaniuseSupportKind.AVAILABLE, `48`),
and_ff: rangeCorrection("and_ff", CaniuseSupportKind.AVAILABLE, `48`),
safari: rangeCorrection("safari", CaniuseSupportKind.AVAILABLE, `10`),
ios_saf: rangeCorrection("safari", CaniuseSupportKind.AVAILABLE, `10`)
/* eslint-enable @typescript-eslint/naming-convention */
};
/**
* Not all Caniuse data is entirely correct. For some features, the data on https://kangax.github.io/compat-table/es6/
* is more correct. When a Browserslist is generated based on support for specific features, it is really important
* that it is correct, especially if the browserslist will be used as an input to tools such as @babel/preset-env.
* This table provides some corrections to the Caniuse data that makes it align better with actual availability
* @type {[string, CaniuseBrowserCorrection][]}
*/
const FEATURE_TO_BROWSER_DATA_CORRECTIONS_INPUT: [string, CaniuseBrowserCorrection][] = [
/* eslint-disable @typescript-eslint/naming-convention */
[
"xhr2",
{
ie: [
{
// Caniuse reports that XMLHttpRequest support is partial in Internet Explorer 11, but it is in fact properly supported
kind: CaniuseSupportKind.AVAILABLE,
version: "11"
}
]
}
],
[
// Caniuse reports that Safari 12.1 and iOS Safari 12.2 has partial support for Web Animations,
// but they do not - They require enabling it as an experimental feature
"web-animation",
{
safari: rangeCorrection("safari", CaniuseSupportKind.UNAVAILABLE, `0`, "13.4"),
ios_saf: rangeCorrection("ios_saf", CaniuseSupportKind.UNAVAILABLE, `0`, "13.4")
}
],
[
"es6-class",
{
edge: [
{
// Caniuse reports that Microsoft Edge has been supporting classes since v12, but it was prefixed until v13
kind: CaniuseSupportKind.PREFIXED,
version: "12"
}
],
ios_saf: [
{
// Caniuse reports that iOS Safari has been supporting classes since v9, but the implementation was only partial
kind: CaniuseSupportKind.PARTIAL_SUPPORT,
version: "9"
},
{
// Caniuse reports that iOS Safari has been supporting classes since v9, but the implementation was only partial
kind: CaniuseSupportKind.PARTIAL_SUPPORT,
version: "9.2"
},
{
// Caniuse reports that iOS Safari has been supporting classes since v9, but the implementation was only partial
kind: CaniuseSupportKind.PARTIAL_SUPPORT,
version: "9.3"
}
],
safari: [
{
// Caniuse reports that Safari has been supporting classes since v9, but the implementation was only partial
kind: CaniuseSupportKind.PARTIAL_SUPPORT,
version: "9"
},
{
// Caniuse reports that Safari has been supporting classes since v9, but the implementation was only partial
kind: CaniuseSupportKind.PARTIAL_SUPPORT,
version: "9.1"
}
]
}
],
[
"api.Element.classList",
{
edge: [
{
// Caniuse reports that Microsoft Edge v15 has only partial support for class-list since it doesn't support SVG elements,
// but we don't want feature detections to return false for that browser
kind: CaniuseSupportKind.AVAILABLE,
version: "15"
}
],
ie: [
{
// Caniuse reports that IE 10 has only partial support for class-list since it doesn't support SVG elements,
// but we don't want feature detections to return false for that browser
kind: CaniuseSupportKind.AVAILABLE,
version: "10"
},
{
// Caniuse reports that IE 11 has only partial support for class-list since it doesn't support SVG elements,
// but we don't want feature detections to return false for that browser
kind: CaniuseSupportKind.AVAILABLE,
version: "11"
}
]
}
],
["javascript.builtins.TypedArray.from", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.of", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.subarray", TYPED_ARRAY_BASE_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.copyWithin", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.every", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.fill", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.filter", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.find", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.findIndex", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.forEach", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.indexOf", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.join", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.lastIndexOf", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.map", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.reduce", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.reduceRight", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.reverse", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.some", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.sort", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.toLocaleString", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.toString", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.slice", TYPED_ARRAY_ES2015_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.includes", TYPED_ARRAY_ES2016_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.keys", TYPED_ARRAY_KEYS_VALUES_ENTRIES_ITERATOR_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.values", TYPED_ARRAY_KEYS_VALUES_ENTRIES_ITERATOR_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.entries", TYPED_ARRAY_KEYS_VALUES_ENTRIES_ITERATOR_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.@@iterator", TYPED_ARRAY_KEYS_VALUES_ENTRIES_ITERATOR_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray.@@species", TYPED_ARRAY_SPECIES_DATA_CORRECTIONS_INPUT],
["javascript.builtins.TypedArray", TYPED_ARRAY_BASE_DATA_CORRECTIONS_INPUT],
["javascript.builtins.Int8Array", TYPED_ARRAY_BASE_DATA_CORRECTIONS_INPUT],
["javascript.builtins.Int16Array", TYPED_ARRAY_BASE_DATA_CORRECTIONS_INPUT],
["javascript.builtins.Int32Array", TYPED_ARRAY_BASE_DATA_CORRECTIONS_INPUT],
["javascript.builtins.Float32Array", TYPED_ARRAY_BASE_DATA_CORRECTIONS_INPUT],
["javascript.builtins.Float64Array", TYPED_ARRAY_BASE_DATA_CORRECTIONS_INPUT],
["javascript.builtins.Uint8Array", TYPED_ARRAY_BASE_DATA_CORRECTIONS_INPUT],
["javascript.builtins.Uint8ClampedArray", TYPED_ARRAY_BASE_DATA_CORRECTIONS_INPUT],
["javascript.builtins.Uint16ClampedArray", TYPED_ARRAY_BASE_DATA_CORRECTIONS_INPUT],
["javascript.builtins.Uint32ClampedArray", TYPED_ARRAY_BASE_DATA_CORRECTIONS_INPUT],
[
"javascript.builtins.String.@@iterator",
{
android: rangeCorrection("chrome", CaniuseSupportKind.AVAILABLE, `38`),
chrome: rangeCorrection("chrome", CaniuseSupportKind.AVAILABLE, `38`),
and_chr: rangeCorrection("and_chr", CaniuseSupportKind.AVAILABLE, `38`),
edge: rangeCorrection("edge", CaniuseSupportKind.AVAILABLE, `12`),
opera: rangeCorrection("opera", CaniuseSupportKind.AVAILABLE, `25`),
op_mob: rangeCorrection("op_mob", CaniuseSupportKind.AVAILABLE, `25`),
firefox: rangeCorrection("firefox", CaniuseSupportKind.AVAILABLE, `36`),
and_ff: rangeCorrection("and_ff", CaniuseSupportKind.AVAILABLE, `36`),
safari: rangeCorrection("safari", CaniuseSupportKind.AVAILABLE, `9`),
ios_saf: rangeCorrection("ios_saf", CaniuseSupportKind.AVAILABLE, `9`),
samsung: rangeCorrection("samsung", CaniuseSupportKind.AVAILABLE, `3`)
}
],
[
"javascript.builtins.Symbol.asyncIterator",
{
android: rangeCorrection("android", CaniuseSupportKind.AVAILABLE, `63`),
chrome: rangeCorrection("chrome", CaniuseSupportKind.AVAILABLE, `63`),
and_chr: rangeCorrection("and_chr", CaniuseSupportKind.AVAILABLE, `63`),
opera: rangeCorrection("opera", CaniuseSupportKind.AVAILABLE, `50`),
op_mob: rangeCorrection("op_mob", CaniuseSupportKind.AVAILABLE, `50`),
firefox: rangeCorrection("firefox", CaniuseSupportKind.AVAILABLE, `57`),
and_ff: rangeCorrection("and_ff", CaniuseSupportKind.AVAILABLE, `57`),
safari: rangeCorrection("safari", CaniuseSupportKind.AVAILABLE, `11.1`),
ios_saf: rangeCorrection("ios_saf", CaniuseSupportKind.AVAILABLE, `11.1`)
}
],
[
"javascript.builtins.Array.@@species",
{
android: rangeCorrection("android", CaniuseSupportKind.AVAILABLE, `51`),
// MDN reports that it doesn't support Array.@@species, but it does and has done since Chrome v51
chrome: rangeCorrection("chrome", CaniuseSupportKind.AVAILABLE, `51`),
// MDN reports that it doesn't support Array.@@species, but it does and has done since Chrome for Android v51
and_chr: rangeCorrection("and_chr", CaniuseSupportKind.AVAILABLE, `51`),
// MDN reports that it doesn't support Array.@@species, but it does and has done since Edge v14
edge: rangeCorrection("edge", CaniuseSupportKind.AVAILABLE, `14`),
// MDN reports that it doesn't support Array.@@species, but it does and has done since Firefox v41
firefox: rangeCorrection("firefox", CaniuseSupportKind.AVAILABLE, `41`),
// MDN reports that it doesn't support Array.@@species, but it does and has done since Firefox for Android v41
and_ff: rangeCorrection("and_ff", CaniuseSupportKind.AVAILABLE, `41`),
// MDN reports that it doesn't support Array.@@species, but it does and has done since Opera v38
opera: rangeCorrection("opera", CaniuseSupportKind.AVAILABLE, `38`),
// MDN reports that it doesn't support Array.@@species, but it does and has done since Opera for Android v38
op_mob: rangeCorrection("op_mob", CaniuseSupportKind.AVAILABLE, `38`),
// MDN reports that it doesn't support Array.@@species, but it does and has done since Safari v10
safari: rangeCorrection("safari", CaniuseSupportKind.AVAILABLE, `10`),
// MDN reports that it doesn't support Array.@@species, but it does and has done since Safari for iOS v10
ios_saf: rangeCorrection("ios_saf", CaniuseSupportKind.AVAILABLE, `10`)
}
],
[
"javascript.builtins.Date.@@toPrimitive",
{
android: rangeCorrection("android", CaniuseSupportKind.AVAILABLE, `48`),
// MDN reports that it doesn't support Date.@@toPrimitive, but it does and has done since Chrome v48
chrome: rangeCorrection("chrome", CaniuseSupportKind.AVAILABLE, `48`),
// MDN reports that it doesn't support Date.@@toPrimitive, but it does and has done since Chrome for Android v48
and_chr: rangeCorrection("and_chr", CaniuseSupportKind.AVAILABLE, `48`),
// MDN reports that it doesn't support Date.@@toPrimitive, but it does and has done in all Edge versions
edge: rangeCorrection("edge", CaniuseSupportKind.AVAILABLE),
// MDN reports that it doesn't support Date.@@toPrimitive, but it does and has done since Firefox v44
firefox: rangeCorrection("firefox", CaniuseSupportKind.AVAILABLE, `44`),
// MDN reports that it doesn't support Date.@@toPrimitive, but it does and has done since Firefox for Android v44
and_ff: rangeCorrection("and_ff", CaniuseSupportKind.AVAILABLE, `44`),
// MDN reports that it doesn't support Date.@@toPrimitive, but it does and has done since Opera v35
opera: rangeCorrection("opera", CaniuseSupportKind.AVAILABLE, `35`),
// MDN reports that it doesn't support Date.@@toPrimitive, but it does and has done since Opera for Android v35
op_mob: rangeCorrection("op_mob", CaniuseSupportKind.AVAILABLE, `35`),
// MDN reports that it doesn't support Date.@@toPrimitive, but it does and has done since Safari v10
safari: rangeCorrection("safari", CaniuseSupportKind.AVAILABLE, `10`),
// MDN reports that it doesn't support Date.@@toPrimitive, but it does and has done since Safari for iOS v10
ios_saf: rangeCorrection("ios_saf", CaniuseSupportKind.AVAILABLE, `10`),
// MDN reports that it doesn't support the Date.@@toPrimitive method, but it does and has done for all Samsung Internet versions
samsung: rangeCorrection("samsung", CaniuseSupportKind.AVAILABLE)
}
],
[
"fetch",
{
edge: [
{
// Caniuse reports that Microsoft Edge has been supporting fetch since v14, but the implementation was quite unstable until v15
kind: CaniuseSupportKind.UNAVAILABLE,
version: "14"
}
]
}
],
[
"api.Window",
{
chrome: rangeCorrection("chrome", CaniuseSupportKind.UNAVAILABLE, `0`, `18`),
safari: rangeCorrection("safari", CaniuseSupportKind.UNAVAILABLE, `0`, `5.1`),
ie: rangeCorrection("ie", CaniuseSupportKind.UNAVAILABLE, `0`, `7`),
opera: rangeCorrection("safari", CaniuseSupportKind.UNAVAILABLE, `0`, `11.1`)
}
],
[
"javascript.builtins.String.matchAll",
{
samsung: rangeCorrection("samsung", CaniuseSupportKind.UNAVAILABLE, `0`, `9.4`)
}
],
[
"resizeobserver",
{
safari: rangeCorrection("safari", CaniuseSupportKind.UNAVAILABLE, `0`)
}
]
/* eslint-enable @typescript-eslint/naming-convention */
];
/**
* A Map between caniuse features and corrections to apply (see above)
* @type {Map<string, CaniuseBrowserCorrection>}
*/
const FEATURE_TO_BROWSER_DATA_CORRECTIONS_MAP: Map<string, CaniuseBrowserCorrection> = new Map(FEATURE_TO_BROWSER_DATA_CORRECTIONS_INPUT);
/**
* Returns the input query, but extended with the given options
*/
function extendQueryWith(query: string[], extendWith: string | string[]): string[] {
const normalizedExtendWith = Array.isArray(extendWith) ? extendWith : [extendWith];
return [...new Set([...query, ...normalizedExtendWith])];
}
/**
* Normalizes the given Browserslist
*/
export function normalizeBrowserslist(browserslist: string | string[]): string[] {
return Browserslist(browserslist);
}
/**
* Returns the input query, but extended with 'unreleased versions'
*
* @param query
* @param browsers
* @returns
*/
function extendQueryWithUnreleasedVersions(query: string[], browsers: Iterable<CaniuseBrowser>): string[] {
return extendQueryWith(
query,
Array.from(browsers).map(browser => `unreleased ${browser} versions`)
);
}
/**
* Generates a Browserslist based on browser support for the given features
*
* @param features
* @returns
*/
export function browsersWithSupportForFeatures(...features: string[]): string[] {
const {query, browsers} = browserSupportForFeaturesCommon(">=", ...features);
return extendQueryWithUnreleasedVersions(query, browsers);
}
/**
* Returns true if the given Browserslist supports the given EcmaVersion
* @param browserslist
* @param version
*/
export function browserslistSupportsEcmaVersion(browserslist: string[], version: EcmaVersion): boolean {
switch (version) {
case "es3":
// ES3 is the lowest possible target and will always be treated as supported
return true;
case "es5":
return browserslistSupportsFeatures(browserslist, ...ES5_FEATURES);
case "es2015":
return browserslistSupportsFeatures(browserslist, ...ES2015_FEATURES);
case "es2016":
return browserslistSupportsFeatures(browserslist, ...ES2016_FEATURES);
case "es2017":
return browserslistSupportsFeatures(browserslist, ...ES2017_FEATURES);
case "es2018":
return browserslistSupportsFeatures(browserslist, ...ES2018_FEATURES);
case "es2019":
return browserslistSupportsFeatures(browserslist, ...ES2019_FEATURES);
case "es2020":
return browserslistSupportsFeatures(browserslist, ...ES2020_FEATURES);
case "es2021":
return browserslistSupportsFeatures(browserslist, ...ES2021_FEATURES);
case "es2022":
return browserslistSupportsFeatures(browserslist, ...ES2022_FEATURES);
}
}
/**
* Returns the appropriate Ecma version for the given Browserslist
*/
export function getAppropriateEcmaVersionForBrowserslist(browserslist: string[]): EcmaVersion {
if (browserslistSupportsEcmaVersion(browserslist, "es2022")) return "es2022";
if (browserslistSupportsEcmaVersion(browserslist, "es2021")) return "es2021";
if (browserslistSupportsEcmaVersion(browserslist, "es2020")) return "es2020";
if (browserslistSupportsEcmaVersion(browserslist, "es2019")) return "es2019";
if (browserslistSupportsEcmaVersion(browserslist, "es2018")) return "es2018";
else if (browserslistSupportsEcmaVersion(browserslist, "es2017")) return "es2017";
else if (browserslistSupportsEcmaVersion(browserslist, "es2016")) return "es2016";
else if (browserslistSupportsEcmaVersion(browserslist, "es2015")) return "es2015";
else if (browserslistSupportsEcmaVersion(browserslist, "es5")) return "es5";
else return "es3";
}
/**
* Generates a Browserslist based on browser support for the given ECMA version
*/
export function browsersWithSupportForEcmaVersion(version: EcmaVersion): string[] {
switch (version) {
case "es3":
return browsersWithoutSupportForFeatures(...ES5_FEATURES);
case "es5":
return browsersWithSupportForFeatures(...ES5_FEATURES);
case "es2015":
return browsersWithSupportForFeatures(...ES2015_FEATURES);
case "es2016":
return browsersWithSupportForFeatures(...ES2016_FEATURES);
case "es2017":
return browsersWithSupportForFeatures(...ES2017_FEATURES);
case "es2018":
return browsersWithSupportForFeatures(...ES2018_FEATURES);
case "es2019":
return browsersWithSupportForFeatures(...ES2019_FEATURES);
case "es2020":
return browsersWithSupportForFeatures(...ES2020_FEATURES);
case "es2021":
return browsersWithSupportForFeatures(...ES2021_FEATURES);
case "es2022":
return browsersWithSupportForFeatures(...ES2022_FEATURES);
}
}
/**
* Returns true if the given browserslist support all of the given features
*
* @param browserslist
* @param features
* @returns
*/
export function browserslistSupportsFeatures(browserslist: string[], ...features: string[]): boolean {
// First, generate an ideal browserslist that would target the given features exactly
const normalizedIdealBrowserslist: string[] = normalizeBrowserslist(browsersWithSupportForFeatures(...features));
// Now, normalize the input browserslist
const normalizedInputBrowserslist: string[] = normalizeBrowserslist(browserslist);
// Now, compare the two and see if they align. If they do, the input browserslist *does* support all of the given features.
// They align if all members of the input browserslist are included in the ideal browserslist
return normalizedInputBrowserslist.every(option => normalizedIdealBrowserslist.includes(option));
}
/**
* Generates a Browserslist based on browsers that *doesn't* support the given features
*
* @param features
* @returns
*/
export function browsersWithoutSupportForFeatures(...features: string[]): string[] {
return browserSupportForFeaturesCommon("<", ...features).query;
}
/**
* Returns true if the given browser should be ignored. The data reported from Caniuse is a bit lacking.
* For example, only the latest version of and_ff, and_qq, and_uc and baidu is reported, and since
* android went to use Chromium for the WebView, it has only reported the latest Chromium version
*
* @param browser
* @param version
* @returns
*/
function shouldIgnoreBrowser(browser: CaniuseBrowser, version: string): boolean {
return (
(browser === "android" && gt(coerceToString(browser, version), coerceToString(browser, "4.4.4"))) ||
(browser === "op_mob" && gt(coerceToString(browser, version), coerceToString(browser, "12.1"))) ||
IGNORED_BROWSERS.has(browser)
);
}
/**
* Normalizes the given ICaniuseLiteFeature
*
* @param stats
* @param featureName
* @returns
*/
function getCaniuseLiteFeatureNormalized(stats: CaniuseStats, featureName: string): CaniuseStatsNormalized {
// Check if a correction exists for this browser
const featureCorrectionMatch = FEATURE_TO_BROWSER_DATA_CORRECTIONS_MAP.get(featureName);
const keys = Object.keys(stats) as (keyof CaniuseStats & string)[];
keys.forEach(browser => {
const browserDict = stats[browser];
Object.entries(browserDict).forEach(([version, support]: [string, string]) => {
const versionMatch = version.match(NORMALIZE_BROWSER_VERSION_REGEXP);
const normalizedVersion = versionMatch == null ? version : versionMatch[1];
let supportKind: CaniuseSupportKind;
if (
support === CaniuseSupportKind.AVAILABLE ||
support === CaniuseSupportKind.UNAVAILABLE ||
support === CaniuseSupportKind.PARTIAL_SUPPORT ||
support === CaniuseSupportKind.PREFIXED
) {
supportKind = support;
} else if (support.startsWith("y")) {
supportKind = CaniuseSupportKind.AVAILABLE;
} else if (support.startsWith("n")) {
supportKind = CaniuseSupportKind.UNAVAILABLE;
} else if (support.startsWith("a")) {
supportKind = CaniuseSupportKind.PARTIAL_SUPPORT;
} else {
supportKind = CaniuseSupportKind.PREFIXED;
}
// Delete the rewritten version
if (version !== normalizedVersion) {
delete browserDict[version];
}
if (support !== supportKind) {
browserDict[normalizedVersion] = supportKind;
}
// If a feature correction exists for this feature, apply applicable corrections
if (featureCorrectionMatch != null) {
// Check if the browser has some corrections
const browserMatch = featureCorrectionMatch[browser];
if (browserMatch != null) {
// Apply all corrections
browserMatch.forEach(correction => {
browserDict[correction.version] = correction.kind;
});
}
}
});
});
return stats as CaniuseStatsNormalized;
}
/**
* Gets the support from caniuse for the given feature
*
* @param feature
* @returns
*/
function getCaniuseFeatureSupport(feature: string): CaniuseStatsNormalized {
const rawStats = (caniuseFeature(caniuseFeatures[feature]) as CaniuseFeature).stats;
for (const browser of Object.keys(rawStats)) {
const browserDict = rawStats[browser as keyof CaniuseStatsNormalized];
for (const version of Object.keys(browserDict)) {
// If browser is Android and version is greater than "4.4.4", or if the browser is Chrome, Firefox, UC, QQ for Android, or Baidu,
// strip it entirely from the data, since Caniuse only reports the latest versions of those browsers
if (shouldIgnoreBrowser(browser as keyof CaniuseStatsNormalized, version)) {
delete browserDict[version];
}
}
}
return getCaniuseLiteFeatureNormalized(rawStats, feature);
}
/**
* Returns true if the given feature is a Caniuse feature
* @param feature
*/
function isCaniuseFeature(feature: string): boolean {
return caniuseFeatures[feature] != null;
}
/**
* Returns true if the given feature is a MDN feature
* @param feature
*/
function isMdnFeature(feature: string): boolean {
return get(compatData, feature) != null;
}
/**
* Asserts that the given feature is a valid Caniuse or MDN feature name
*
* @param feature
*/
function assertKnownFeature(feature: string): void {
if (!isCaniuseFeature(feature) && !isMdnFeature(feature)) {
throw new TypeError(`The given feature: '${feature}' is unknown. It must be a valid Caniuse or MDN feature!`);
}
}
/**
* Gets the feature support for the given feature
*
* @param feature
* @returns
*/
function getFeatureSupport(feature: string): CaniuseStatsNormalized {
// First check if the cache has a match and return it if so
const cacheHit = featureToCaniuseStatsCache.get(feature);
if (cacheHit != null) return cacheHit;
// Assert that the feature is in fact known
assertKnownFeature(feature);
const result = isMdnFeature(feature) ? getMdnFeatureSupport(feature) : getCaniuseFeatureSupport(feature);
// Store it in the cache before returning it
featureToCaniuseStatsCache.set(feature, result);
return result;
}
/**
* Gets the support from caniuse for the given feature
*
* @param feature
* @returns
*/
function getMdnFeatureSupport(feature: string): CaniuseStatsNormalized {
const match: Mdn = get(compatData, feature);
const supportMap = match.__compat.support;
const formatBrowser = (mdnBrowser: MdnBrowserName, caniuseBrowser: CaniuseBrowser): {[key: string]: CaniuseSupportKind} => {
const versionMap = supportMap[mdnBrowser];
const versionAdded =
versionMap == null
? false
: Array.isArray(versionMap)
? // If there are multiple entries, take the one that hasn't been removed yet, if any
(() => {
const versionStillInBrowser = versionMap.filter(element => element.version_removed == null)[0];
return versionStillInBrowser == null || versionStillInBrowser.version_added == null ? false : (versionStillInBrowser.version_added as string | boolean);
})()
: versionMap.version_added;
const dict: {[key: string]: CaniuseSupportKind} = {};
const supportedSince: string | null = versionAdded === false ? null : versionAdded === true ? getOldestVersionOfBrowser(caniuseBrowser) : versionAdded;
getSortedBrowserVersionsWithLeadingVersion(caniuseBrowser, typeof versionAdded === "string" ? versionAdded : undefined).forEach(version => {
// If the features has never been supported, mark the feature as unavailable
if (supportedSince == null) {
dict[version] = CaniuseSupportKind.UNAVAILABLE;
} else {
dict[version] =
version === "TP" || version === "all" || gte(coerceToString(caniuseBrowser, version), coerceToString(caniuseBrowser, supportedSince))
? CaniuseSupportKind.AVAILABLE
: CaniuseSupportKind.UNAVAILABLE;
}
});
return dict;
};
const stats: CaniuseStatsNormalized = {
/* eslint-disable @typescript-eslint/naming-convention */
and_chr: formatBrowser("chrome_android", "and_chr"),
chrome: formatBrowser("chrome", "chrome"),
and_ff: formatBrowser("firefox_android", "and_ff"),
and_qq: {},
and_uc: {},
android: formatBrowser("webview_android", "android"),
baidu: {},
bb: {},
edge: formatBrowser("edge", "edge"),
samsung: formatBrowser("samsunginternet_android", "samsung"),
ie: formatBrowser("ie", "ie"),
ie_mob: formatBrowser("ie", "ie_mob"),
safari: formatBrowser("safari", "safari"),
ios_saf: formatBrowser("safari_ios", "ios_saf"),
opera: formatBrowser("opera", "opera"),
op_mini: {},
op_mob: {},
firefox: formatBrowser("firefox", "firefox")
/* eslint-enable @typescript-eslint/naming-convention */
};
return getCaniuseLiteFeatureNormalized(stats, feature);
}
/**
* Gets the first version that matches the given CaniuseSupportKind
*
* @param kind
* @param stats
* @returns
*/
function getFirstVersionWithSupportKind(kind: CaniuseSupportKind, stats: {[key: string]: CaniuseSupportKind}): string | undefined {
// Sort all keys of the object
const sortedKeys = Object.keys(stats).sort(compareVersions);
for (const key of sortedKeys) {
if (stats[key] === kind) {
return key;
}
}
return undefined;
}
/**
* Sorts the given browserslist. Ensures that 'not' expressions come last
*
* @param a
* @param b
* @returns
*/
function sortBrowserslist(a: string, b: string): number {
if (a.startsWith("not") && !b.startsWith("not")) return 1;
if (!a.startsWith("not") && b.startsWith("not")) return -1;
return 0;
}
/**
* Gets a Map between browser names and the first version of them that supported the given feature
*
* @param feature
* @returns
*/
export function getFirstVersionsWithFullSupport(feature: string): Map<CaniuseBrowser, string> {
const support = getFeatureSupport(feature);
// A map between browser names and their required versions
const browserMap: Map<CaniuseBrowser, string> = new Map();
const entries = Object.entries(support) as [CaniuseBrowser, Record<string, CaniuseSupportKind>][];
entries.forEach(([browser, stats]) => {
const fullSupportVersion = getFirstVersionWithSupportKind(CaniuseSupportKind.AVAILABLE, stats);
if (fullSupportVersion != null) {
browserMap.set(browser, fullSupportVersion);
}
});
return browserMap;
}
/**
* Gets the Cache key for the given combination of a comparison operator and any amount of features
*
* @param comparisonOperator
* @param features
*/
function getBrowserSupportForFeaturesCacheKey(comparisonOperator: ComparisonOperator, features: string[]): string {
return `${comparisonOperator}.${features.sort().join(",")}`;
}
/**
* Common logic for the functions that generate browserslists based on feature support
*/
function browserSupportForFeaturesCommon(comparisonOperator: ComparisonOperator, ...features: string[]): BrowserSupportForFeaturesCommonResult {
const cacheKey = getBrowserSupportForFeaturesCacheKey(comparisonOperator, features);
// First check if the cache has a hit and return it if so
const cacheHit = browserSupportForFeaturesCache.get(cacheKey);
if (cacheHit != null) {
return cacheHit;
}
// All of the generated browser maps
const browserMaps: Map<CaniuseBrowser, string>[] = [];
for (const feature of features) {
const support = getFeatureSupport(feature);
// A map between browser names and their required versions
const browserMap: Map<CaniuseBrowser, string> = new Map();
const entries = Object.entries(support) as [CaniuseBrowser, Record<string, CaniuseSupportKind>][];
entries.forEach(([browser, stats]) => {
const fullSupportVersion = getFirstVersionWithSupportKind(CaniuseSupportKind.AVAILABLE, stats);
const partialSupportVersion = getFirstVersionWithSupportKind(CaniuseSupportKind.PARTIAL_SUPPORT, stats);
let versionToSet: string | undefined;
if (fullSupportVersion != null) {
versionToSet = fullSupportVersion;
}
// Otherwise, check if partial support exists and should be allowed
if (partialSupportVersion != null) {
// Get all partial support allowances for this specific feature
const partialSupportMatch = PARTIAL_SUPPORT_ALLOWANCES.get(feature);
// Check if partial support exists for the browser. // If no full supported version exists or if the partial supported version has a lower version number than the full supported one, use that one instead
if (
partialSupportMatch != null &&
(partialSupportMatch === "*" || partialSupportMatch.includes(browser)) &&
(fullSupportVersion == null || compareVersions(partialSupportVersion, fullSupportVersion) < 0)
) {
versionToSet = partialSupportVersion;
}
}
if (versionToSet == null) {
// Apply additional checks depending on the comparison operator
switch (comparisonOperator) {
case "<":
case "<=":
// Add all browsers with no support whatsoever, or those that require prefixing or flags
versionToSet = "-1";
}
}
if (versionToSet != null) {
browserMap.set(browser, versionToSet);
}
});
browserMaps.push(browserMap);
}
// Now, remove all browsers that isn't part of all generated browser maps
for (const browserMap of browserMaps) {
for (const browser of browserMap.keys()) {
if (!browserMaps.every(map => map.has(browser))) {
// Delete the browser if it isn't included in all of the browser maps
browserMap.delete(browser);
}
}
}
// Now, prepare a combined browser map
const combinedBrowserMap: Map<CaniuseBrowser, string> = new Map();
for (const browserMap of browserMaps) {
for (const [browser, version] of browserMap.entries()) {
// Take the existing entry from the combined map
const existingVersion = combinedBrowserMap.get(browser);
// The browser should be set in the map if it has no entry already
const shouldSet = existingVersion !== "-1" && (existingVersion == null || version === "-1" || compareVersions(version, existingVersion) >= 0);
if (shouldSet) {
// Set the version in the map
combinedBrowserMap.set(browser, version);
}
}
}
// Finally, generate a string array of the browsers
// Make sure that 'not' expressions come last
const query: string[] = ([] as string[]).concat
.apply(
[],
Array.from(combinedBrowserMap.entries()).map(([browser, version]) => {
// The version is not a number, so we can't do comparisons on it.
if (isNaN(parseFloat(version))) {
switch (comparisonOperator) {
case "<":
case "<=": {
const previousVersion = getPreviousVersionOfBrowser(browser, version);
return [`not ${browser} ${version}`, ...(previousVersion == null ? [] : [`${browser} ${comparisonOperator} ${previousVersion}`])];
}
case ">":
case ">=": {
const nextVersion = getNextVersionOfBrowser(browser, version);
return [`${browser} ${version}`, ...(nextVersion == null ? [] : [`${browser} ${comparisonOperator} ${nextVersion}`])];
}
}
}
return parseInt(version) === -1
? [
`${comparisonOperator === ">" || comparisonOperator === ">=" ? "not " : ""}${browser} ${browser === "op_mini" ? "all" : "> 0"}`,
`${comparisonOperator === ">" || comparisonOperator === ">=" ? "not " : ""}unreleased ${browser} versions`
]
: [`${browser} ${comparisonOperator} ${version}`];
})
)
.sort(sortBrowserslist);
const returnObject = {
query,
browsers: new Set(combinedBrowserMap.keys())
};
// Store it in the cache before returning it
browserSupportForFeaturesCache.set(cacheKey, returnObject);
return returnObject;
}
/**
* Gets the matching CaniuseBrowser for the given UseragentBrowser. Not all are supported, so it may return undefined
*/
function getCaniuseBrowserForUseragentBrowser(parser: UaParserWrapper): Partial<VersionedCaniuseBrowser> {
const browser = parser.getBrowser();
const device = parser.getDevice();
const os = parser.getOS();
const engine = parser.getEngine();
// If the OS is iOS, it is actually Safari that drives the WebView
if (os.name === "iOS") {
// Opera Mini with the Presto runtime actually works around
// the restrictions os the Safari WebView
if (browser.name === "Opera Mini" && engine.name === "Presto") {
return {
browser: "op_mini",
version: browser.version
};
}
// In all other cases, it is always Safari driving the WebView
return {
browser: "ios_saf",
version: os.version ?? browser.version
};
}
// First, if it is a Blackberry device, it will always be the 'bb' browser
if (device.vendor === "BlackBerry" || os.name === "BlackBerry") {
return {
browser: "bb",
version: browser.version
};
}
// For platforms where the HeyTapBrowser doesn't report which Chrome version
// it is based on, we'll have to rely on knowledge from similar user agent strings.
// as far as we know, HeyTapBrowser on non-iOS is always based on Chrome 70 or 77,
// seemingly at random. So we'll have to assume Chrome 70 here.
if (browser.name === "HeyTapBrowser" && engine.name === "WebKit") {
return {
browser: "chrome",
version: "70"
};
}
// Unfortunately, since Caniuse doesn't support PaleMoon,
// we will have to remap it to its closest equivalent Firefox
// version (which it is similar to and a fork of).
// This is less than ideal, but unfortunately a requirement for the time being
if (browser.name === "PaleMoon" && engine.name === "Goanna" && browser.version != null) {
const semver = ensureSemver(undefined, browser.version);
// The data comes from this table: https://en.wikipedia.org/wiki/Pale_Moon_(web_browser)#Releases
if (lte(semver, "5.0.0")) {
return {
browser: "firefox",
version: "2"
};
}
// Between these two versions, the version numbers followed Firefox/Gecko
else if (lte(semver, "24.0.0")) {
return {
browser: "firefox",
version: browser.version
};
}
// It kept staying at Firefox 24 for all we know
else if (lt(semver, "27.0.0")) {
return {
browser: "firefox",
version: "24.0.0"
};
}
// Then, from v27, it was based on a re-fork of Firefox 38.
// Unfortunately, we don't have fresh data as for the versions
// in between 27 and 29, so we'll have to stay at version 38 in
// this range
else if (lt(semver, "29.0.0")) {
return {
browser: "firefox",
version: "38"
};
}
// We know that v29 points to Firefox 68 in some of its user agents
else {
return {
browser: "firefox",
version: "68"
};
}
}
// For the MIUIBrowser, there are some rare instances for major versions 8 and 9 where they'll have no declared Chromium engine.
// as part of the UA. Under these circumstances, we have to rely on knowledge gathered from scraping related User Agents
// to determine the equivalent Chromium version
if (browser.name === "MIUI Browser" && browser.version != null && os.name === "Android" && engine.name == null) {
const semver = ensureSemver(undefined, browser.version);
if (semver.major === 8 || semver.major === 9) {
return {
browser: "chrome",
version: "53"
};
}
}
switch (browser.name) {
case "Samsung Browser":
if (browser.version != null) {
return {
browser: "samsung",
version: browser.version
};
} else if (engine.name === "Blink" && engine.version != null) {
return {
browser: "chrome",
version: engine.version
};
} else {
break;
}
case "Android Browser": {
// If the vendor is Samsung, the default browser is Samsung Internet
if (device.vendor === "Samsung") {
return {
browser: "samsung",
version: browser.version
};
}
// Default to the stock android browser
return {
browser: "android",
version: browser.version
};
}
case "WebKit":
// This will be the case if we're in an iOS Safari WebView
if (device.type === "mobile" || device.type === "tablet" || device.type === "smarttv" || device.type === "wearable" || device.type === "embedded") {
return {
browser: "ios_saf",
version: os.version
};
}
// Otherwise, fall back to Safari
return {
browser: "safari",
version: browser.version
};
case "Baidu":
return {
browser: "baidu",
version: browser.version
};
case "Chrome Headless":
case "Chrome WebView":
return {
browser: "chrome",
version: browser.version
};
case "Facebook":
// We've already asserted that this isn't iOS above, so we must be on Android and inside of a WebView
return {
browser: "chrome",
version: browser.version
};
case "Chrome": {
// Check if the OS is Android, in which case this is actually Chrome for Android. Make it report as regular Chrome
if (os.name === "Android") {
// Handle a special case on Android where the Chrome version
// is actually the WebKit version, and it is actually the stock
// Android browser.
if (os.version != null && browser.version != null) {
const browserSemver = ensureSemver("chrome", browser.version);
const osSemver = ensureSemver(undefined, os.version);
if (lte(osSemver, "4.4.4") && gte(browserSemver, "400.0.0")) {
return {
browser: "android",
version: os.version
};
}
}
return {
browser: "chrome",
version: browser.version
};
}
// Otherwise, fall back to chrome
return {
browser: "chrome",
version: browser.version
};
}
case "Edge": {
// If the Engine is Blink, it's Chrome-based
if (engine.name === "Blink") {
// If there is no browser version, fall back to Chrome
if (browser.version == null) {
return {
browser: "chrome",
version: engine.version
};
}
const semverVersion = ensureSemver("edge", browser.version);
// If the Major version is in between 18 and 79, this will be Edge Mobile on Android,
// which is Chromium based but has no related Caniuse browser name. Treat it as Chrome
if (semverVersion.major > 18 && semverVersion.major < 79) {
return {
browser: "chrome",
version: engine.version
};
}
}
return {
browser: "edge",
version: browser.version
};
}
case "Firefox":
// Check if the OS is Android, in which case this is actually Firefox for Android.
if (os.name === "Android") {
return {
browser: "and_ff",
version: browser.version
};
}
// Default to Firefox
return {
browser: "firefox",
version: browser.version
};
case "IE":
return {
browser: "ie",
version: browser.version
};
case "IE Mobile":
case "IEMobile":
return {
browser: "ie_mob",
version: browser.version
};
case "Safari":
// If no browser version is reported, and it is based on WebKit,
// we will have to attempt to "guess" the Safari version with mapping the
// WebKit version to an equivalent Safari version based on the data
// here: https://en.wikipedia.org/wiki/Safari_version_history, even
// though this doesn't seem to map correctly to real-world data
if (browser.version == null && engine.name === "WebKit" && engine.version != null) {
const semver = ensureSemver(undefined, engine.version);
if (lt(semver, "412.0.0")) {
return {
browser: "safari",
version: "1.0"
};
}
if (lt(semver, "522.0.0")) {
return {
browser: "safari",
version: "2.0"
};
}
if (lt(semver, "526.0.0")) {
return {
browser: "safari",
version: "3.0"
};
}
if (lt(semver, "533.0.0")) {
return {
browser: "safari",
version: "4.0"
};
}
if (lt(semver, "536.0.0")) {
return {
browser: "safari",
version: "5.0"
};
}
if (lt(semver, "537.71.0")) {
return {
browser: "safari",
version: "6.0"
};
}
if (lt(semver, "600.0.0")) {
return {
browser: "safari",
version: "7.0"
};
}
if (lt(semver, "601.0.0")) {
return {
browser: "safari",
version: "8.0"
};
}
if (lt(semver, "602.0.0")) {
return {
browser: "safari",
version: "9.0"
};
}
if (lt(semver, "604.0.0")) {
return {
browser: "safari",
version: "10.0"
};
}
if (lt(semver, "606.0.0")) {
return {
browser: "safari",
version: "11.0"
};
}
if (lt(semver, "608.0.0")) {
return {
browser: "safari",
version: "12.0"
};
}
if (lt(semver, "610.0.0")) {
return {
browser: "safari",
version: "13.0"
};
}
// Else it is the current Safari version.
// Keep this updated regularly
return {
browser: "safari",
version: "14.0"
};
}
return {
browser: "safari",
version: browser.version
};
case "Mobile Safari":
case "MobileSafari":
case "Safari Mobile":
case "SafariMobile":
return {
browser: "ios_saf",
version: os.version ?? browser.version
};
case "Opera":
return {
browser: "opera",
version: browser.version
};
case "Opera Mini":
return {
browser: "op_mini",
version: browser.version
};
case "Opera Mobi":
return {
browser: "op_mob",
version: browser.version
};
case "QQBrowser":
return {
browser: "and_qq",
version: browser.version
};
case "UCBrowser":
return {
browser: "and_uc",
version: browser.version
};
default:
switch (engine.name) {
// If the Engine is Blink, it's Chrome
case "Blink":
return {
browser: "chrome",
version: engine.version
};
case "WebKit":
return {
browser: "safari",
version: browser.version
};
case "EdgeHTML":
return {
browser: "edge",
version: browser.version
};
case "Gecko":
return {
browser: "firefox",
version: engine.version
};
case "Presto":
return {
browser: "opera",
version: browser.version
};
}
}
// Fall back to the unknown Caniuse browser when all
// we received was the name of the OS
if (browser.name == null && engine.name == null && device.type == null && os.name != null) {
return UNKNOWN_CANIUSE_BROWSER;
}
return {};
}
/**
* Normalizes the version of the browser such that it plays well with Caniuse
*/
function getCaniuseVersionForUseragentVersion(
{browser, version}: VersionedCaniuseBrowser,
useragentBrowser: UseragentBrowser,
useragentOs: UseragentOs,
useragentEngine: UseragentEngine
): string {
// Always use 'all' with Opera Mini
if (browser === "op_mini") {
return "all";
} else if (browser === "safari") {
// Check if there is a newer version of the browser
const nextBrowserVersion = getNextVersionOfBrowser(browser, version);
// If there isn't we're in the Technology Preview
if (nextBrowserVersion == null) {
return "TP";
}
}
const coerced = ensureSemver(browser, version);
// Make sure that we have a proper Semver version to work with
if (coerced == null) throw new TypeError(`Could not detect the version of: '${version}' for browser: ${browser}`);
// Unpack the semver version
const {major, minor, patch} = coerced;
// Generates a Semver version
const buildSemverVersion = (majorVersion: number, minorVersion?: number, patchVersion?: number): string =>
`${majorVersion}${minorVersion == null || minorVersion === 0 ? "" : `.${minorVersion}`}${patchVersion == null || patchVersion === 0 ? "" : `.${patchVersion}`}`;
switch (browser) {
case "chrome":
if (useragentEngine.name === "Blink") {
return buildSemverVersion(ensureSemver(browser, getClosestMatchingBrowserVersion(browser, useragentEngine.version ?? version)).major);
}
return buildSemverVersion(major);
case "ie":
case "ie_mob":
case "edge":
case "bb":
case "and_chr":
case "and_ff":
// Always use the major version of these browser
return buildSemverVersion(major);
case "opera":
case "op_mob":
// Opera may have minor versions before it went to Chromium. After that, always use major versions
if (major === 10 || major === 11 || major === 12) {
return buildSemverVersion(major, minor);
}
// For anything else, only use the major version
return buildSemverVersion(major);
case "ios_saf": {
// For browsers that report as iOS safari, they may actually be other browsers using Safari's WebView.
// We want them to report as iOS safari since they will support the same browsers, but we have to apply
// some tricks in order to get the version number
// If it is in fact mobile Safari, just use the reported version
if (useragentBrowser.name === "Safari" || useragentBrowser.name === "Mobile Safari") {
// iOS may have minor releases, but never patch releases, according to caniuse
return buildSemverVersion(major, minor);
}
// Otherwise, try to get the assumed Safari version from the OS version
else {
if (useragentOs.version == null) throw new ReferenceError(`Could not detect OS version of iOS for ${useragentBrowser.name} on iOS`);
// Decide the Semver version
const osSemver = ensureSemver(undefined, getClosestMatchingBrowserVersion(browser, useragentOs.version));
// iOS may have minor releases, but never patch releases, according to caniuse
return buildSemverVersion(osSemver.major, osSemver.minor);
}
}
case "safari":
case "firefox": {
// These may have minor releases, but never patch releases, according to caniuse
return buildSemverVersion(major, minor);
}
case "android":
// Up to version 4.4.4, these could include patch releases. After that, only use major versions
if (major < 4) {
return buildSemverVersion(major, minor);
} else if (major === 4) {
return buildSemverVersion(major, minor, patch);
} else {
return buildSemverVersion(major);
}
case "and_uc":
case "samsung":
case "and_qq":
case "baidu":
// These may always contain minor versions
return buildSemverVersion(major, minor);
default:
// For anything else, just use the major version
return buildSemverVersion(major);
}
}
/**
* Generates a browserslist from the provided useragent string
*/
export function generateBrowserslistFromUseragent(useragent: string): string[] {
// Check if a user agent has been generated previously for this specific user agent
const cacheHit = userAgentToBrowserslistCache.get(useragent);
if (cacheHit != null) return cacheHit;
// Otherwise, generate a new one
const parser = new UaParserWrapper(useragent);
const browser = parser.getBrowser();
const os = parser.getOS();
const engine = parser.getEngine();
// Prepare a CaniuseBrowser name from the useragent string
let {browser: caniuseBrowserName, version: caniuseBrowserVersion} = getCaniuseBrowserForUseragentBrowser(parser);
// console.log({browser, os, engine, caniuseBrowserName, caniuseBrowserVersion});
// If the browser name or version couldn't be determined, return false immediately
if (caniuseBrowserName == null || caniuseBrowserVersion == null) {
throw new TypeError(`No caniuse browser and/or version could be determined for User Agent: ${useragent}`);
}
caniuseBrowserVersion = normalizeBrowserVersion(caniuseBrowserName, caniuseBrowserVersion);
const caniuseBrowser = {browser: caniuseBrowserName, version: caniuseBrowserVersion};
// Prepare a version from the useragent that plays well with caniuse
caniuseBrowserVersion = getCaniuseVersionForUseragentVersion(caniuseBrowser, browser, os, engine);
// Prepare a browserslist from the useragent itself
const normalizedBrowserslist = normalizeBrowserslist([`${caniuseBrowserName} ${caniuseBrowserVersion}`]);
// Store it in the cache before returning it
userAgentToBrowserslistCache.set(useragent, normalizedBrowserslist);
return normalizedBrowserslist;
}
/**
* Generates a browserslist from the provided useragent string and checks if it matches
* the given browserslist
*/
export function matchBrowserslistOnUserAgent(useragent: string, browserslist: string[]): boolean {
const useragentBrowserslist = generateBrowserslistFromUseragent(useragent);
// Pipe the input browserslist through Browserslist to normalize it
const normalizedInputBrowserslist: string[] = normalizeBrowserslist(browserslist);
// Now, compare the two, and if the normalized input browserslist includes every option from the user agent, it is matched
return useragentBrowserslist.every(option => normalizedInputBrowserslist.includes(option));
}
/**
* Returns a key to use for the cache between user agents with feature names and whether or not the user agent supports them
*/
function userAgentWithFeaturesCacheKey(useragent: string, features: string[]): string {
return `${useragent}.${features.join(",")}`;
}
/**
* Returns true if the given user agent supports the given features
*/
export function userAgentSupportsFeatures(useragent: string, ...features: string[]): boolean {
// Check if these features has been computed previously for the given user agent
const cacheKey = userAgentWithFeaturesCacheKey(useragent, features);
const cacheHit = userAgentWithFeaturesToSupportCache.get(cacheKey);
// If so, return the cache hit
if (cacheHit != null) return cacheHit;
// Prepare a browserslist from the useragent itself
const useragentBrowserslist = generateBrowserslistFromUseragent(useragent);
// Prepare a browserslist for browsers that support the given features
const supportedBrowserslist = normalizeBrowserslist(browsersWithSupportForFeatures(...features));
// Now, compare the two, and if the browserslist with supported browsers includes every option from the user agent, the user agent supports all of the given features
const support = useragentBrowserslist.every(option => supportedBrowserslist.includes(option));
// Set it in the cache and return it
userAgentWithFeaturesToSupportCache.set(cacheKey, support);
return support;
} | the_stack |
import { Component } from 'vue-property-decorator';
import _ from 'lodash';
import * as synaptic from 'synaptic';
import template from './neural-network.html';
import { injectNodeTemplate } from '../node';
import { SubsetNode } from '../subset-node';
import FormInput from '@/components/form-input/form-input';
import FormSelect from '@/components/form-select/form-select';
import ColumnSelect from '@/components/column-select/column-select';
import ColumnList from '@/components/column-list/column-list';
import { SubsetInputPort } from '../port';
import TabularDataset from '@/data/tabular-dataset';
import { SubsetPackage } from '@/data/package';
import * as history from './history';
import { ValueType } from '@/data/parser';
const EPOCH_INTERVAL_MS = 1000;
const TRAIN_ITERATIONS = 1000;
const BATCH_SIZE = 100;
export enum NeuralNetworkType {
PERCEPTRON = 'perceptron',
}
interface NeuralNetworkSave {
neuralNetworkType: NeuralNetworkType;
features: number[];
target: number | null;
epochInterval: number;
learningRate: number;
batchSize: number;
serializedNetwork: object;
outputEachEpoch: boolean;
perceptronOptions: PerceptronOptions;
}
interface PerceptronOptions {
hiddenLayerNumber: number;
hiddenLayerSize: number;
}
@Component({
template: injectNodeTemplate(template),
components: {
FormInput,
FormSelect,
ColumnSelect,
ColumnList,
},
})
export default class NeuralNetwork extends SubsetNode {
public isDataMutated = true;
protected NODE_TYPE = 'neural-network';
protected DEFAULT_WIDTH = 120;
protected RESIZABLE = true;
protected HAS_SETTINGS = true;
private neuralNetworkType: NeuralNetworkType = NeuralNetworkType.PERCEPTRON;
private features: number[] = [];
private target: number | null = null;
private trainingTimer: NodeJS.Timer | null = null;
private epochInterval = EPOCH_INTERVAL_MS;
private outputEachEpoch = true;
private learningRate = .2;
private batchSize = BATCH_SIZE; // TODO
private isFirstUpdate = true;
private network: synaptic.Network = new synaptic.Architect.Perceptron(1, 0, 1);
private serializedNetwork: object = {};
// preprocessed column domains generated on network creation
private columnDomains: Array<Array<number | string>> = [];
private perceptronOptions: PerceptronOptions = {
hiddenLayerNumber: 1,
hiddenLayerSize: 1,
};
private isTraining = false;
// first subset item index in the next batch
private batchHead = 0;
private warningMessage = '';
get neuralNetworkTypeOptions(): SelectOption[] {
return [
{ label: 'Perceptron', value: NeuralNetworkType.PERCEPTRON },
];
}
get targetName(): string {
return this.dataset && this.target !== null ? this.dataset.getColumnName(this.target) : '';
}
get featureNames(): string {
return this.dataset ? this.features.map(feature =>
this.getDataset().getColumnName(feature)).join(', ') : '';
}
public setNeuralNetworkType(type: NeuralNetworkType) {
this.neuralNetworkType = type;
}
public setFeatures(features: number[]) {
this.features = features;
this.createNetwork();
}
public setTarget(target: number | null) {
this.target = target;
this.createNetwork();
}
public setBatchSize(size: number) {
this.batchSize = size;
}
public setLearningRate(rate: number) {
this.learningRate = rate;
}
public setEpochInterval(interval: number) {
this.epochInterval = interval;
}
public setOutputEachEpoch(value: boolean) {
this.outputEachEpoch = value;
}
public setPerceptronHiddenLayerNumber(value: number) {
this.perceptronOptions.hiddenLayerNumber = value;
this.createNetwork();
}
public setPerceptronHiddenLayerSize(size: number) {
this.perceptronOptions.hiddenLayerSize = size;
this.createNetwork();
}
protected createInputPorts() {
this.inputPorts = [
new SubsetInputPort({
data: {
id: 'in', // train
node: this,
},
store: this.$store,
}),
new SubsetInputPort({
data: {
id: 'inTest',
node: this,
},
store: this.$store,
}),
];
}
protected update() {
if (!this.checkDataset()) {
return;
}
if (!this.features.length) {
this.coverText = 'No features';
this.updateNoDatasetOutput();
return;
}
if (this.target === null) {
this.coverText = 'No target';
this.updateNoDatasetOutput();
return;
}
// Create network at least once on first update
if (this.isFirstUpdate) {
this.createNetwork();
this.isFirstUpdate = false;
}
this.generateDomains();
this.test();
}
protected onDatasetChange() {
this.features = this.updateColumnsOnDatasetChange(this.features);
this.createNetwork();
}
protected created() {
this.serializationChain.push((): NeuralNetworkSave => ({
neuralNetworkType: this.neuralNetworkType,
features: this.features,
target: this.target,
learningRate: this.learningRate,
epochInterval: this.epochInterval,
serializedNetwork: this.network.toJSON(),
batchSize: this.batchSize,
outputEachEpoch: this.outputEachEpoch,
perceptronOptions: this.perceptronOptions,
}));
this.deserializationChain.push(nodeSave => {
const save = nodeSave as NeuralNetworkSave;
this.network = synaptic.Network.fromJSON(save.serializedNetwork);
this.isFirstUpdate = false; // Use deserialized network and avoid recreation.
});
}
private binarize(value: number | string, domain: Array<number | string>): number[] {
const valueIndex = domain.indexOf(value);
const binarized = new Array(domain.length).fill(0);
binarized[valueIndex] = 1;
return binarized;
}
/**
* Returns a normalized value of a cell.
*/
private normalize(column: number, itemIndex: number, dataset: TabularDataset): number[] {
const domain = this.columnDomains[column];
if (dataset.getColumnType(column) === ValueType.STRING) {
return this.binarize(dataset.getCell(itemIndex, column), domain);
} else {
const value = dataset.getCell(itemIndex, column) as number;
const [min, max] = domain as [number, number];
return [min === max ? 0 : (value - min) / (max - min)];
}
}
private normalizeTrainInput(itemIndex: number): number[] {
const values: number[] = [];
for (const column of this.features) {
values.push.apply(values, this.normalize(column, itemIndex, this.getDataset()));
}
return values;
}
private normalizeTrainOutput(itemIndex: number): number[] {
return this.normalize(this.target as number, itemIndex, this.getDataset());
}
private normalizeTestInput(itemIndex: number, features: number[]): number[] {
const testDataset = this.inputPortMap.inTest.getSubsetPackage().getDataset() as TabularDataset;
const values: number[] = [];
for (const column of features) {
values.push.apply(values, this.normalize(column, itemIndex, testDataset));
}
return values;
}
private train() {
const trainer = new synaptic.Trainer(this.network);
const pkg = this.inputPortMap.in.getSubsetPackage();
const trainingData = pkg.getItemIndices().map(itemIndex => ({
input: this.normalizeTrainInput(itemIndex),
output: this.normalizeTrainOutput(itemIndex),
}));
trainer.train(trainingData, {
rate: this.learningRate,
iterations: TRAIN_ITERATIONS,
});
if (this.outputEachEpoch) {
this.test();
this.propagate();
}
}
private startTraining() {
this.isTraining = true;
if (this.trainingTimer !== null) {
clearInterval(this.trainingTimer);
}
this.trainingTimer = setInterval(this.train, this.epochInterval);
}
private pauseTraining() {
this.isTraining = false;
if (this.trainingTimer !== null) {
clearInterval(this.trainingTimer);
}
}
private test() {
if (!this.inputPortMap.inTest.isConnected()) {
this.updateNoDatasetOutput();
return;
}
const pkg = this.inputPortMap.inTest.getSubsetPackage();
if (!pkg.hasDataset()) {
this.updateNoDatasetOutput();
return;
}
this.warningMessage = '';
const testDataset = pkg.getDataset() as TabularDataset;
const dataset = this.getDataset();
const features = this.features.map(column => dataset.getColumnName(column))
.map(columnName => {
const index = testDataset.getColumnIndex(columnName);
if (index === -1) {
this.warningMessage = `column ${columnName} not found in test dataset`;
}
return index;
});
const target = this.target as number;
const targetType = dataset.getColumnType(target);
const columns = testDataset.getColumns().map(column => column.name).concat('predicted');
const rows = pkg.getItemIndices().map(itemIndex => {
const input = this.normalizeTestInput(itemIndex, features as number[]);
const result = this.network.activate(input);
let predicted: string | number = '';
if (targetType === ValueType.STRING) { // map binarized to string
const maxIndex = result.indexOf(_.max(result) as number);
predicted = this.columnDomains[target][maxIndex];
} else {
const [min, max] = this.columnDomains[target] as [number, number];
predicted = min === max ? min : result[0] * (max - min) + min;
}
return testDataset.getRow(itemIndex).concat(predicted);
});
const newDataset = TabularDataset.fromColumnsAndRows(columns, rows);
this.updateOutput(new SubsetPackage(newDataset));
}
/**
* Resets and recreates the network.
*/
private createNetwork() {
this.isTraining = false;
if (this.trainingTimer !== null) {
clearInterval(this.trainingTimer);
}
this.generateDomains();
if (this.neuralNetworkType === NeuralNetworkType.PERCEPTRON) {
this.createPerceptron();
}
}
private createPerceptron() {
const dataset = this.getDataset();
const inputLayers: number[] = [0];
const hiddenLayers = new Array(this.perceptronOptions.hiddenLayerNumber)
.fill(this.perceptronOptions.hiddenLayerSize);
const outputLayers: number[] = [1];
for (const column of this.features) {
const domain = this.columnDomains[column];
if (dataset.getColumnType(column) === ValueType.STRING) {
inputLayers[0] += domain.length;
} else {
inputLayers[0]++;
}
}
if (dataset.getColumnType(this.target as number) === ValueType.STRING) {
// need binarization for categorical values
outputLayers[0] = dataset.getDomain(this.target as number).length;
}
const layers = inputLayers.concat(hiddenLayers).concat(outputLayers);
this.network = new synaptic.Architect.Perceptron(...layers);
}
private generateDomains() {
const dataset = this.getDataset();
this.columnDomains = dataset.getColumns().map(column => dataset.getDomain(column.index));
}
private onSelectNeuralNetworkType(type: NeuralNetworkType, prevType: NeuralNetworkType) {
this.commitHistory(history.selectNeuralNetworkTypeEvent(this, type, prevType));
this.setNeuralNetworkType(type);
}
private onSelectFeatures(features: number[], prevFeatures: number[]) {
this.commitHistory(history.selectFeaturesEvent(this, features, prevFeatures));
this.setFeatures(features);
}
private onSelectTarget(target: number | null, prevTarget: number | null) {
this.commitHistory(history.selectTargetEvent(this, target, prevTarget));
this.setTarget(target);
}
private onToggleOutputEachEpoch(value: boolean) {
this.commitHistory(history.toggleOutputEachEpoch(this, value));
this.setOutputEachEpoch(value);
}
private onInputBatchSize(size: number, prevSize: number) {
this.commitHistory(history.inputBatchSize(this, size, prevSize));
this.setBatchSize(size);
}
private onInputEpochInterval(interval: number, prevInterval: number) {
this.commitHistory(history.inputEpochIntervalEvent(this, interval, prevInterval));
this.setEpochInterval(interval);
}
private onInputPerceptronHiddenLayerNumber(value: number, prevValue: number) {
this.commitHistory(history.inputPerceptronHiddenLayerNumber(this, value, prevValue));
this.setPerceptronHiddenLayerNumber(value);
}
private onInputPerceptronHiddenLayerSize(size: number, prevSize: number) {
this.commitHistory(history.inputPerceptronHiddenLayerSize(this, size, prevSize));
this.setPerceptronHiddenLayerSize(size);
}
private onInputLearningRate(rate: number, prevRate: number) {
this.commitHistory(history.inputLearningRateEvent(this, rate, prevRate));
this.setLearningRate(rate);
}
} | the_stack |
import { defaultCss, IWebviewChannel, getVsCodeApiScript } from './common';
export class WebviewPanelManager {
private activeTheme = 'default';
private styles: { [key: string]: string };
private isHandlingScroll = false;
private updateId = 0;
private firstLoad = true;
private loadTimeout;
private pendingMessages: any[] = [];
private initialScrollProgress: number;
private ID: string | undefined;
constructor(private channel: IWebviewChannel) {
document.addEventListener('DOMContentLoaded', this.init.bind(this));
}
private init() {
const idMatch = document.location.search.match(/\bid=([\w-]+)/);
this.ID = idMatch ? idMatch[1] : undefined;
if (!document.body) {
return;
}
this.channel.onMessage('styles', (_event, data) => {
this.styles = data.styles;
this.activeTheme = data.activeTheme;
const target = this.getActiveFrame();
if (!target) {
return;
}
if (target.contentDocument) {
this.applyStyles(target.contentDocument, target.contentDocument.body);
}
});
// propagate focus
this.channel.onMessage('focus', () => {
const target = this.getActiveFrame();
if (target && target.contentWindow) {
target.contentWindow.focus();
}
});
this.channel.onMessage('content', async (_event, data) => this.setContent(data));
this.channel.onMessage('message', (_event, data) => {
const pending = this.getPendingFrame();
if (!pending) {
const target = this.getActiveFrame();
if (target) {
target.contentWindow!.postMessage(data, '*');
return;
}
}
this.pendingMessages.push(data);
});
this.trackFocus({
onFocus: () => this.channel.postMessage('did-focus'),
onBlur: () => this.channel.postMessage('did-blur'),
});
this.channel.postMessage('webview-ready', {});
}
private async setContent(data) {
const currentUpdateId = ++this.updateId;
await this.channel.ready;
if (currentUpdateId !== this.updateId) {
return;
}
const options = data.options;
const newDocument = this.toContentHtml(data);
const frame = this.getActiveFrame();
const wasFirstLoad = this.firstLoad;
// keep current scrollY around and use later
let setInitialScrollPosition;
if (this.firstLoad) {
this.firstLoad = false;
setInitialScrollPosition = (body, window) => {
if (!isNaN(this.initialScrollProgress)) {
if (window.scrollY === 0) {
window.scroll(0, body.clientHeight * this.initialScrollProgress);
}
}
};
} else {
const scrollY = frame && frame.contentDocument && frame.contentDocument.body ? frame.contentWindow!.scrollY : 0;
setInitialScrollPosition = (body, window) => {
if (window.scrollY === 0) {
window.scroll(0, scrollY);
}
};
}
// Clean up old pending frames and set current one as new one
const previousPendingFrame = this.getPendingFrame();
if (previousPendingFrame) {
previousPendingFrame.setAttribute('id', '');
document.body.removeChild(previousPendingFrame);
}
if (!wasFirstLoad) {
this.pendingMessages = [];
}
const newFrame = document.createElement('iframe');
newFrame.setAttribute('id', 'pending-frame');
newFrame.setAttribute('frameborder', '0');
newFrame.setAttribute('allow', 'autoplay');
const sandboxRules = new Set(['allow-same-origin', 'allow-pointer-lock']);
if (options.allowScripts) {
sandboxRules.add('allow-scripts');
sandboxRules.add('allow-downloads');
}
if (options.allowForms) {
sandboxRules.add('allow-forms');
}
newFrame.setAttribute('sandbox', Array.from(sandboxRules).join(' '));
if (this.channel.fakeLoad) {
// 使用service-worker时候
newFrame.src = `./fake.html?id=${this.ID}`;
}
newFrame.style.cssText =
'display: block; margin: 0; overflow: hidden; position: absolute; width: 100%; height: 100%; visibility: hidden';
document.body.appendChild(newFrame);
if (!this.channel.fakeLoad) {
// write new content onto iframe
newFrame.contentDocument!.open();
}
newFrame.contentWindow!.addEventListener('keydown', this.handleInnerKeydown.bind(this));
newFrame.contentWindow!.addEventListener('DOMContentLoaded', (e) => {
if (this.channel.fakeLoad) {
newFrame.contentDocument!.open();
newFrame.contentDocument!.write(newDocument);
newFrame.contentDocument!.close();
hookupOnLoadHandlers(newFrame);
}
const contentDocument: HTMLDocument | undefined = e.target ? (e.target as HTMLDocument) : undefined;
if (contentDocument) {
this.applyStyles(contentDocument, contentDocument.body);
}
});
const onLoad = (contentDocument, contentWindow) => {
if (contentDocument && contentDocument.body) {
// Workaround for https://github.com/Microsoft/vscode/issues/12865
// check new scrollY and reset if neccessary
setInitialScrollPosition(contentDocument.body, contentWindow);
}
const newFrame = this.getPendingFrame();
if (newFrame && newFrame.contentDocument && newFrame.contentDocument === contentDocument) {
const oldActiveFrame = this.getActiveFrame();
if (oldActiveFrame) {
document.body.removeChild(oldActiveFrame);
}
// Styles may have changed since we created the element. Make sure we re-style
this.applyStyles(newFrame.contentDocument, newFrame.contentDocument.body);
newFrame.setAttribute('id', 'active-frame');
newFrame.style.visibility = 'visible';
if (this.channel.focusIframeOnCreate) {
newFrame.contentWindow!.focus();
}
contentWindow.addEventListener('scroll', this.handleInnerScroll.bind(this));
this.pendingMessages.forEach((data) => {
contentWindow.postMessage(data, '*');
});
this.pendingMessages = [];
}
};
/**
* @param {HTMLIFrameElement} newFrame
*/
const hookupOnLoadHandlers = (newFrame) => {
clearTimeout(this.loadTimeout);
this.loadTimeout = undefined;
this.loadTimeout = setTimeout(() => {
clearTimeout(this.loadTimeout);
this.loadTimeout = undefined;
onLoad(newFrame.contentDocument, newFrame.contentWindow);
}, 1000);
// eslint-disable-next-line @typescript-eslint/no-this-alias
const _this = this;
newFrame.contentWindow.addEventListener('load', function (this: any, e) {
if (_this.loadTimeout) {
clearTimeout(_this.loadTimeout);
_this.loadTimeout = undefined;
onLoad(e.target, this);
}
});
// Bubble out link clicks
newFrame.contentWindow.addEventListener('click', this.handleInnerClick.bind(this));
if (this.channel.onIframeLoaded) {
this.channel.onIframeLoaded(newFrame);
}
};
if (!this.channel.fakeLoad) {
hookupOnLoadHandlers(newFrame);
}
if (!this.channel.fakeLoad) {
newFrame.contentDocument!.write(newDocument);
newFrame.contentDocument!.close();
}
this.channel.postMessage('did-set-content', undefined);
}
private trackFocus({ onFocus, onBlur }): void {
const interval = 50;
let isFocused = document.hasFocus();
setInterval(() => {
const isCurrentlyFocused = document.hasFocus();
if (isCurrentlyFocused === isFocused) {
return;
}
isFocused = isCurrentlyFocused;
if (isCurrentlyFocused) {
onFocus();
} else {
onBlur();
}
}, interval);
}
private getActiveFrame(): HTMLIFrameElement | undefined {
return document.getElementById('active-frame') as HTMLIFrameElement;
}
private getPendingFrame(): HTMLIFrameElement | undefined {
return document.getElementById('pending-frame') as HTMLIFrameElement;
}
private get defaultCssRules() {
return defaultCss;
}
private applyStyles(document, body) {
if (!document) {
return;
}
if (body) {
body.classList.remove('vscode-light', 'vscode-dark', 'vscode-high-contrast');
body.classList.add(this.activeTheme);
}
if (this.styles) {
for (const variable of Object.keys(this.styles)) {
document.documentElement.style.setProperty(`--${variable}`, this.styles[variable]);
}
}
}
private handleInnerClick(event: MouseEvent) {
if (!event || !event.view || !event.view.document) {
return;
}
const baseElement = event.view.document.getElementsByTagName('base')[0];
let node = event.target as any;
while (node) {
if (node.tagName && node.tagName.toLowerCase() === 'a' && node.href) {
if (node.getAttribute('href') === '#') {
event.view.scrollTo(0, 0);
} else if (
node.hash &&
(node.getAttribute('href') === node.hash || (baseElement && node.href.indexOf(baseElement.href) >= 0))
) {
const scrollTarget = event.view.document.getElementById(node.hash.substr(1, node.hash.length - 1));
if (scrollTarget) {
scrollTarget.scrollIntoView();
}
} else {
this.channel.postMessage('did-click-link', node.href.baseVal || node.href);
}
event.preventDefault();
break;
}
node = node.parentNode;
}
}
private handleInnerKeydown(e) {
this.channel.postMessage('did-keydown', {
key: e.key,
keyCode: e.keyCode,
code: e.code,
shiftKey: e.shiftKey,
altKey: e.altKey,
ctrlKey: e.ctrlKey,
metaKey: e.metaKey,
repeat: e.repeat,
});
this.channel.onKeydown && this.channel.onKeydown(e);
}
private handleInnerScroll(event) {
if (!event.target || !event.target.body) {
return;
}
if (this.isHandlingScroll) {
return;
}
const progress = event.currentTarget.scrollY / event.target.body.clientHeight;
if (isNaN(progress)) {
return;
}
this.isHandlingScroll = true;
window.requestAnimationFrame(() => {
try {
this.channel.postMessage('did-scroll', progress);
} catch (e) {
// noop
}
this.isHandlingScroll = false;
});
}
private toContentHtml(data) {
const options = data.options;
const text = data.contents;
const newDocument = new DOMParser().parseFromString(text, 'text/html');
newDocument.querySelectorAll('a').forEach((a) => {
if (!a.title) {
a.title = a.getAttribute('href')!;
}
});
// apply default script
if (options.allowScripts) {
const defaultScript = newDocument.createElement('script');
defaultScript.textContent = getVsCodeApiScript(data.state);
newDocument.head.prepend(defaultScript);
}
// apply default styles
const defaultStyles = newDocument.createElement('style');
defaultStyles.id = '_defaultStyles';
defaultStyles.innerHTML = this.defaultCssRules;
newDocument.head.prepend(defaultStyles);
this.applyStyles(newDocument, newDocument.body);
// set DOCTYPE for newDocument explicitly as DOMParser.parseFromString strips it off
// and DOCTYPE is needed in the iframe to ensure that the user agent stylesheet is correctly overridden
return '<!DOCTYPE html>\n' + newDocument.documentElement.outerHTML;
}
} | the_stack |
import { BaseEvent, PortPageHook } from "../adapter/port";
import { Commit, MsgTypes, flush } from "../events/events";
import {
VNode,
FunctionalComponent,
ComponentConstructor,
Options,
} from "preact";
import { getStringId } from "../string-table";
import {
isRoot,
getAncestor,
isSuspenseVNode,
getDisplayName,
getComponent,
getDom,
getActualChildren,
getVNodeParent,
hasDom,
setNextState,
getHookState,
createSuspenseState,
} from "./vnode";
import { shouldFilter } from "./filter";
import { ID, DevNodeType } from "../../view/store/types";
import { traverse, setIn, SerializedVNode, setInCopy } from "./utils";
import { FilterState } from "../adapter/filter";
import { Renderer } from "../renderer";
import {
createIdMappingState,
getVNodeById,
hasId,
getVNodeId,
hasVNodeId,
removeVNodeId,
IdMappingState,
createVNodeId,
updateVNodeId,
} from "./IdMapper";
import { logVNode } from "./renderer/logVNode";
import { inspectVNode } from "./renderer/inspectVNode";
import { getRenderReason, RenderReason } from "./renderer/renderReasons";
import {
UpdateRects,
measureUpdate,
startDrawing,
} from "../adapter/highlightUpdates";
import {
createStats,
DiffType,
getDiffType,
updateDiffStats,
recordComponentStats,
} from "./stats";
import { NodeType } from "../../constants";
export interface RendererConfig10 {
Fragment: FunctionalComponent;
Component?: ComponentConstructor;
}
const memoReg = /^Memo\(/;
const forwardRefReg = /^ForwardRef\(/;
/**
* Get the type of a vnode. The devtools uses these constants to differentiate
* between the various forms of components.
*/
export function getDevtoolsType(vnode: VNode): DevNodeType {
if (typeof vnode.type == "function") {
const name = vnode.type.displayName || "";
if (memoReg.test(name)) return DevNodeType.Memo;
if (forwardRefReg.test(name)) return DevNodeType.ForwardRef;
if (isSuspenseVNode(vnode)) return DevNodeType.Suspense;
// TODO: Provider and Consumer
return vnode.type.prototype && vnode.type.prototype.render
? DevNodeType.ClassComponent
: DevNodeType.FunctionComponent;
}
return DevNodeType.Element;
}
export function isVNode(x: any): x is VNode {
return x != null && x.type !== undefined && hasDom(x);
}
export function serializeVNode(
x: any,
config: RendererConfig10,
): SerializedVNode | null {
if (isVNode(x)) {
return {
type: "vnode",
name: getDisplayName(x, config),
};
}
return null;
}
export function getFilteredChildren(
vnode: VNode,
filters: FilterState,
config: RendererConfig10,
): VNode[] {
const children = getActualChildren(vnode);
const stack = children.slice();
const out: VNode[] = [];
let child;
while (stack.length) {
child = stack.pop();
if (child != null) {
if (!shouldFilter(child, filters, config)) {
out.push(child);
} else {
const nextChildren = getActualChildren(child);
if (nextChildren.length > 0) {
stack.push(...nextChildren.slice());
}
}
}
}
return out.reverse();
}
function isTextNode(dom: HTMLElement | Text | null): dom is Text {
return dom != null && dom.nodeType === NodeType.Text;
}
function updateHighlight(profiler: ProfilerState, vnode: VNode) {
if (profiler.highlightUpdates && typeof vnode.type === "function") {
let dom = getDom(vnode);
if (isTextNode(dom)) {
dom = dom.parentNode as HTMLElement;
}
if (dom && !profiler.pendingHighlightUpdates.has(dom)) {
profiler.pendingHighlightUpdates.add(dom);
measureUpdate(profiler.updateRects, dom);
}
}
}
function getHocName(name: string) {
const idx = name.indexOf("(");
if (idx === -1) return null;
const wrapper = name.slice(0, idx);
return wrapper ? wrapper : null;
}
function addHocs(commit: Commit, id: ID, hocs: string[]) {
if (hocs.length > 0) {
commit.operations.push(MsgTypes.HOC_NODES, id, hocs.length);
for (let i = 0; i < hocs.length; i++) {
const stringId = getStringId(commit.strings, hocs[i]);
commit.operations.push(stringId);
}
}
}
export function mount(
ids: IdMappingState,
commit: Commit,
vnode: VNode,
ancestorId: ID,
filters: FilterState,
domCache: WeakMap<HTMLElement | Text, VNode>,
config: RendererConfig10,
profiler: ProfilerState,
hocs: string[],
) {
if (commit.stats !== null) {
commit.stats.mounts++;
}
const root = isRoot(vnode, config);
const skip = shouldFilter(vnode, filters, config);
if (root || !skip) {
record: {
let name = getDisplayName(vnode, config);
if (filters.type.has("hoc")) {
const hocName = getHocName(name);
// Filter out HOC-Components
if (hocName) {
if (name.startsWith("ForwardRef")) {
hocs = [...hocs, hocName];
const idx = name.indexOf("(");
name = name.slice(idx + 1, -1) || "Anonymous";
} else {
hocs = [...hocs, hocName];
break record;
}
}
}
const id = hasVNodeId(ids, vnode)
? getVNodeId(ids, vnode)
: createVNodeId(ids, vnode);
if (isRoot(vnode, config)) {
commit.operations.push(MsgTypes.ADD_ROOT, id);
}
commit.operations.push(
MsgTypes.ADD_VNODE,
id,
getDevtoolsType(vnode), // Type
ancestorId,
9999, // owner
getStringId(commit.strings, name),
vnode.key ? getStringId(commit.strings, vnode.key) : 0,
// Multiply, because operations array only supports integers
// and would otherwise cut off floats
(vnode.startTime || 0) * 1000,
(vnode.endTime || 0) * 1000,
);
if (hocs.length > 0) {
addHocs(commit, id, hocs);
hocs = [];
}
// Capture render reason (mount here)
if (profiler.isProfiling && profiler.captureRenderReasons) {
commit.operations.push(
MsgTypes.RENDER_REASON,
id,
RenderReason.MOUNT,
0,
);
}
updateHighlight(profiler, vnode);
ancestorId = id;
}
}
if (skip && typeof vnode.type !== "function") {
const dom = getDom(vnode);
if (dom) domCache.set(dom, vnode);
}
let diff = DiffType.UNKNOWN;
let childCount = 0;
const children = getActualChildren(vnode);
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (child != null) {
if (commit.stats !== null) {
diff = getDiffType(child, diff);
childCount++;
}
mount(
ids,
commit,
child,
ancestorId,
filters,
domCache,
config,
profiler,
hocs,
);
}
}
if (commit.stats !== null) {
updateDiffStats(commit.stats, diff, childCount);
recordComponentStats(config, commit.stats, vnode, children);
}
}
export function resetChildren(
commit: Commit,
ids: IdMappingState,
id: ID,
vnode: VNode,
filters: FilterState,
config: RendererConfig10,
) {
const children = getActualChildren(vnode);
if (!children.length) return;
const next = getFilteredChildren(vnode, filters, config);
// Suspense internals mutate child outside of the standard render cycle.
// This leads to stale children on the devtools ends. To work around that
// We'll always reset the children of a Suspense vnode.
let forceReorder = false;
if (isSuspenseVNode(vnode)) {
forceReorder = true;
}
if (!forceReorder && next.length < 2) return;
commit.operations.push(
MsgTypes.REORDER_CHILDREN,
id,
next.length,
...next.map(x => getVNodeId(ids, x)),
);
}
export function update(
ids: IdMappingState,
commit: Commit,
vnode: VNode,
ancestorId: number,
filters: FilterState,
domCache: WeakMap<HTMLElement | Text, VNode>,
config: RendererConfig10,
profiler: ProfilerState,
hocs: string[],
) {
if (commit.stats !== null) {
commit.stats.updates++;
}
let diff = DiffType.UNKNOWN;
const skip = shouldFilter(vnode, filters, config);
if (skip) {
let childCount = 0;
const children = getActualChildren(vnode);
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (child != null) {
if (commit.stats !== null) {
diff = getDiffType(child, diff);
childCount++;
}
update(
ids,
commit,
child,
ancestorId,
filters,
domCache,
config,
profiler,
hocs,
);
}
}
if (commit.stats !== null) {
updateDiffStats(commit.stats, diff, childCount);
recordComponentStats(config, commit.stats, vnode, children);
}
return;
}
if (!hasVNodeId(ids, vnode)) {
mount(
ids,
commit,
vnode,
ancestorId,
filters,
domCache,
config,
profiler,
hocs,
);
return true;
}
const id = getVNodeId(ids, vnode);
commit.operations.push(
MsgTypes.UPDATE_VNODE_TIMINGS,
id,
(vnode.startTime || 0) * 1000,
(vnode.endTime || 0) * 1000,
);
const name = getDisplayName(vnode, config);
const hoc = getHocName(name);
if (hoc) {
hocs = [...hocs, hoc];
} else {
addHocs(commit, id, hocs);
hocs = [];
}
const oldVNode = getVNodeById(ids, id);
updateVNodeId(ids, id, vnode);
if (profiler.isProfiling && profiler.captureRenderReasons) {
const reason = getRenderReason(oldVNode, vnode);
if (reason !== null) {
const count = reason.items ? reason.items.length : 0;
commit.operations.push(MsgTypes.RENDER_REASON, id, reason.type, count);
if (reason.items && count > 0) {
commit.operations.push(
...reason.items.map(str => getStringId(commit.strings, str)),
);
}
}
}
updateHighlight(profiler, vnode);
const oldChildren = oldVNode
? getActualChildren(oldVNode).map((v: any) => v && getVNodeId(ids, v))
: [];
let shouldReorder = false;
let childCount = 0;
const children = getActualChildren(vnode);
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (child == null) {
if (oldChildren[i] != null) {
commit.unmountIds.push(oldChildren[i]);
}
} else if (hasVNodeId(ids, child) || shouldFilter(child, filters, config)) {
if (commit.stats !== null) {
diff = getDiffType(child, diff);
childCount++;
}
update(ids, commit, child, id, filters, domCache, config, profiler, hocs);
// TODO: This is only sometimes necessary
shouldReorder = true;
} else {
if (commit.stats !== null) {
diff = getDiffType(child, diff);
childCount++;
}
mount(ids, commit, child, id, filters, domCache, config, profiler, hocs);
shouldReorder = true;
}
}
if (commit.stats !== null) {
updateDiffStats(commit.stats, diff, childCount);
recordComponentStats(config, commit.stats, vnode, children);
}
if (shouldReorder) {
resetChildren(commit, ids, id, vnode, filters, config);
}
}
export function createCommit(
ids: IdMappingState,
roots: Set<VNode>,
vnode: VNode,
filters: FilterState,
domCache: WeakMap<HTMLElement | Text, VNode>,
config: RendererConfig10,
profiler: ProfilerState,
statState: StatState,
): Commit {
const commit = {
operations: [],
rootId: -1,
strings: new Map(),
unmountIds: [],
renderReasons: new Map(),
stats: statState.isRecording ? createStats() : null,
};
let parentId = -1;
const isNew = !hasVNodeId(ids, vnode);
if (isRoot(vnode, config)) {
if (commit.stats !== null) {
commit.stats.roots.total++;
const children = getActualChildren(vnode);
commit.stats.roots.children.push(children.length);
}
parentId = -1;
roots.add(vnode);
} else {
parentId = getVNodeId(ids, getAncestor(vnode)!);
}
if (isNew) {
mount(
ids,
commit,
vnode,
parentId,
filters,
domCache,
config,
profiler,
[],
);
} else {
update(
ids,
commit,
vnode,
parentId,
filters,
domCache,
config,
profiler,
[],
);
}
commit.rootId = getVNodeId(ids, vnode);
return commit;
}
const DEFAULT_FIlTERS: FilterState = {
regex: [],
// TODO: Add default hoc-filter
type: new Set(["dom", "fragment"]),
};
export interface Preact10Renderer extends Renderer {
onCommit(vnode: VNode): void;
onUnmount(vnode: VNode): void;
updateHook(id: ID, index: number, value: any): void;
}
export interface ProfilerState {
isProfiling: boolean;
highlightUpdates: boolean;
pendingHighlightUpdates: Set<HTMLElement>;
updateRects: UpdateRects;
captureRenderReasons: boolean;
}
export interface StatState {
isRecording: boolean;
}
export interface Supports {
renderReasons: boolean;
hooks: boolean;
}
export function createRenderer(
port: PortPageHook,
namespace: number,
config: RendererConfig10,
options: Options,
supports: Supports,
filters: FilterState = DEFAULT_FIlTERS,
): Preact10Renderer {
const ids = createIdMappingState(namespace);
const roots = new Set<VNode>();
let currentUnmounts: number[] = [];
const domToVNode = new WeakMap<HTMLElement | Text, VNode>();
const profiler: ProfilerState = {
isProfiling: false,
highlightUpdates: false,
updateRects: new Map(),
pendingHighlightUpdates: new Set(),
captureRenderReasons: false,
};
const statState: StatState = {
isRecording: false,
};
function onUnmount(vnode: VNode) {
if (!shouldFilter(vnode, filters, config)) {
if (hasVNodeId(ids, vnode)) {
currentUnmounts.push(getVNodeId(ids, vnode));
}
}
if (typeof vnode.type !== "function") {
const dom = getDom(vnode);
if (dom != null) domToVNode.delete(dom);
}
removeVNodeId(ids, vnode);
}
const inspect = (id: ID) =>
inspectVNode(ids, config, options, id, supports.hooks);
return {
// TODO: Deprecate
// eslint-disable-next-line @typescript-eslint/no-empty-function
flushInitial() {},
clear() {
roots.forEach(vnode => {
onUnmount(vnode);
});
},
startHighlightUpdates() {
profiler.highlightUpdates = true;
},
stopHighlightUpdates() {
profiler.highlightUpdates = false;
profiler.updateRects.clear();
profiler.pendingHighlightUpdates.clear();
},
startRecordStats: () => {
statState.isRecording = true;
},
stopRecordStats: () => {
statState.isRecording = false;
},
startProfiling: options => {
profiler.isProfiling = true;
profiler.captureRenderReasons =
!!options && !!options.captureRenderReasons;
},
stopProfiling: () => {
profiler.isProfiling = false;
},
getVNodeById: id => getVNodeById(ids, id),
has: id => hasId(ids, id),
getDisplayName(vnode) {
return getDisplayName(vnode, config);
},
getDisplayNameById: id => {
const vnode = getVNodeById(ids, id);
if (vnode) {
return getDisplayName(vnode, config);
}
return "Unknown";
},
log: (id, children) => logVNode(ids, config, id, children),
inspect,
findDomForVNode(id) {
const vnode = getVNodeById(ids, id);
if (!vnode) return null;
const first = getDom(vnode);
let last = null;
if (typeof vnode.type === "function") {
const children = getActualChildren(vnode);
for (let i = children.length - 1; i >= 0; i--) {
const child = children[i];
if (child) {
const dom = getDom(child);
if (dom === first) break;
if (dom !== null) {
last = dom;
break;
}
}
}
}
return [first, last];
},
findVNodeIdForDom(node) {
const vnode = domToVNode.get(node);
if (vnode) {
if (shouldFilter(vnode, filters, config)) {
let p: VNode | null = vnode;
let found = null;
while ((p = getVNodeParent(p)) != null) {
if (!shouldFilter(p, filters, config)) {
found = p;
break;
}
}
if (found != null) {
return getVNodeId(ids, found) || -1;
}
} else {
return getVNodeId(ids, vnode) || -1;
}
}
return -1;
},
refresh() {
this.applyFilters(filters);
},
applyFilters(nextFilters) {
/** Queue events and flush in one go */
const queue: BaseEvent<any, any>[] = [];
roots.forEach(root => {
const rootId = getVNodeId(ids, root);
traverse(root, vnode => this.onUnmount(vnode));
const commit: Commit = {
operations: [],
rootId,
strings: new Map(),
unmountIds: currentUnmounts,
stats: statState.isRecording ? createStats() : null,
};
if (commit.stats !== null) {
commit.stats.unmounts += commit.unmountIds.length;
}
const unmounts = flush(commit);
if (unmounts) {
currentUnmounts = [];
queue.push(unmounts);
}
});
filters.regex = nextFilters.regex;
filters.type = nextFilters.type;
roots.forEach(root => {
const commit = createCommit(
ids,
roots,
root,
filters,
domToVNode,
config,
profiler,
statState,
);
const ev = flush(commit);
if (!ev) return;
queue.push(ev);
});
this.flushInitial();
queue.forEach(ev => port.send(ev.type, ev.data));
},
onCommit(vnode) {
const commit = createCommit(
ids,
roots,
vnode,
filters,
domToVNode,
config,
profiler,
statState,
);
if (commit.stats !== null) {
commit.stats.unmounts += currentUnmounts.length;
}
commit.unmountIds.push(...currentUnmounts);
currentUnmounts = [];
const ev = flush(commit);
if (!ev) return;
if (profiler.updateRects.size > 0) {
startDrawing(profiler.updateRects);
profiler.pendingHighlightUpdates.clear();
}
port.send(ev.type as any, ev.data);
},
onUnmount,
update(id, type, path, value) {
const vnode = getVNodeById(ids, id);
if (vnode !== null) {
if (typeof vnode.type === "function") {
const c = getComponent(vnode);
if (c) {
if (type === "props") {
vnode.props = setInCopy(
(vnode.props as any) || {},
path.slice(),
value,
);
} else if (type === "state") {
const res = setInCopy(
(c.state as any) || {},
path.slice(),
value,
);
setNextState(c, res);
} else if (type === "context") {
// TODO: Investigate if we should disallow modifying context
// from devtools and make it readonly.
setIn((c.context as any) || {}, path.slice(), value);
}
c.forceUpdate();
}
}
}
},
updateHook(id, index, value) {
const vnode = getVNodeById(ids, id);
if (vnode !== null && typeof vnode.type === "function") {
const c = getComponent(vnode);
if (c) {
const s = getHookState(c, index);
// Only useState and useReducer hooks marked as editable so state can
// cast to more specific ReducerHookState value.
(s as [any, any])[0] = value;
c.forceUpdate();
}
}
},
suspend(id, active) {
let vnode = getVNodeById(ids, id);
while (vnode !== null) {
if (isSuspenseVNode(vnode)) {
const c = getComponent(vnode);
if (c) {
c.setState(createSuspenseState(vnode, active));
}
// Get nearest non-filtered vnode
let nearest: VNode | null = vnode;
while (nearest && shouldFilter(nearest, filters, config)) {
nearest = getVNodeParent(nearest);
}
if (nearest && hasVNodeId(ids, nearest)) {
const nearestId = getVNodeId(ids, nearest);
if (id !== nearestId) {
const inspectData = inspect(nearestId);
if (inspectData) {
inspectData.suspended = active;
port.send("inspect-result", inspectData);
}
}
}
break;
}
vnode = getVNodeParent(vnode);
}
},
};
} | the_stack |
import React, {Component} from "react";
import {Button, Col, Input, notification, Popconfirm, Row, Select, Tree} from "antd";
import {Link} from "react-router";
import {ClusterZnode, ZnodeDetailInfoVo} from "../../model/ClusterModel";
import styles from "../../../themes/Search.less";
import {SysUserVo} from "../../../sys/model/SysUserModel";
import znodeStyle from "../../../sys/view/layout/common.less";
const TreeNode = Tree.TreeNode;
export interface ClusterZnodeProps {
clusterInfoId: number;
sysUser: SysUserVo;
znodeRoots: Array<ClusterZnode>;
znodeChildren: Array<ClusterZnode>;
znodeDataDetail: ZnodeDetailInfoVo;
initChildren: any;
onDeleteZnode: any;
onSearchData: any;
onUpdateZnode: any;
onCreateZnode: any;
}
export class ClusterZnodeList extends Component<ClusterZnodeProps, any> {
constructor(props) {
super(props);
this.state = {
selectedZnode: null,
selectedKey: '',
expandedKeys: [],
znodeDataVisibility: 'hidden',
serializable: 'string',
}
}
onLoadData = (treeNode) => {
return new Promise((resolve) => {
// 拉取子节点数据,每次直接拉取节点数据,不缓存上次记录
this.props.initChildren(this.props.clusterInfoId, treeNode.props.eventKey, (data) => {
treeNode.props.dataRef.children = data;
resolve();
});
});
};
// 实时展示所选节点信息
onSelect = (selectedKeys, info) => {
this.setState({selectedZnode: info.node, selectedKey: selectedKeys[0]}, () => {
// 状态位更新成功后,设置标签显示值
document.getElementById('znodeLabel').textContent = this.state.selectedKey;
});
};
renderTreeNodes = (data) => {
return data.map((item) => {
if (item.children) {
return (
<TreeNode title={item.title} key={item.key} dataRef={item}>
{this.renderTreeNodes(item.children)}
</TreeNode>
);
}
return <TreeNode {...item} dataRef={item}/>;
});
};
deleteNode = () => {
let thisV = this;
this.props.onDeleteZnode(this.state.selectedKey, (message) => {
notification['success']({
message: message,
description: '',
});
// 前端过滤已删除的节点信息,将展开节点列表仅保留到删除节点的父节点
let end = this.state.selectedKey.lastIndexOf("/");
if (end == -1) {
end = this.state.selectedKey.length;
console.log("不存在'/'")
}
// 父节点路径
let parent = this.state.selectedKey.substring(0, end);
// 当前展开节点
let expandedKeysCurrent = thisV.state.expandedKeys.filter(bean => !bean.startsWith(parent));
thisV.setState({
expandedKeys: expandedKeysCurrent,
});
}
)
};
onExpand = (expandedKeys, info) => {
if (info.expanded) {
this.state.expandedKeys = expandedKeys;
} else {
let key = info.node.props.eventKey;
let end = key.lastIndexOf("/");
if (end == -1) {
end = key.length;
console.log("关闭节点路径不存在'/'")
}
let parent = key.substring(0, end);
let expandedKeysCurrent = this.state.expandedKeys.filter(bean => {
if (bean == parent || !bean.startsWith(parent)) {
return true;
} else {
return false;
}
});
this.setState({
expandedKeys: expandedKeysCurrent,
});
}
};
onSearchData = () => {
if (this.state.selectedKey) {
this.props.onSearchData(this.state.selectedKey, this.state.serializable);
this.setState({znodeDataVisibility: ''});
} else {
this.setState({znodeDataVisibility: 'hidden'});
notification['error']({
message: '请选择所需查询的节点!',
description: '',
});
}
};
onUpdataZnode = () => {
this.props.onUpdateZnode(this.state.selectedKey);
};
onCreateZnode = () => {
this.props.onCreateZnode(this.state.selectedKey);
};
handlsSerializableChange = (value) => {
this.setState({serializable: value})
};
getOperateProps() {
return {
sysUser: this.props.sysUser,
onSearchData: this.onSearchData,
onUpdataZnode: this.onUpdataZnode,
deleteNode: this.deleteNode,
onCreateZnode: this.onCreateZnode,
selectedKey: this.state.selectedKey,
};
}
render() {
let znodeDataDetail = this.props.znodeDataDetail ? this.props.znodeDataDetail : new ZnodeDetailInfoVo();
znodeDataDetail.data = znodeDataDetail.data ? znodeDataDetail.data : '';
return (
<div style={{
display: 'flex',
justifyContent: 'space-between',
borderBottom: '1px #d7d8d9 solid',
paddingTop: 20,
paddingBottom: 20
}}>
<div className={znodeStyle.znodeContent}>
<div style={{display: 'flex'}}>
<Tree showLine loadData={this.onLoadData}
onSelect={this.onSelect}
expandedKeys={this.state.expandedKeys}
onExpand={this.onExpand}>
{this.renderTreeNodes(this.props.znodeRoots)}
</Tree>
</div>
</div>
<div className={znodeStyle.znodeContent}>
<div>
<Row style={{marginBottom: 10}}>
<Col span={24} offset={2}>
<label style={{marginRight: 10, fontWeight: 'bold'}}>节点路径:</label>
<label id="znodeLabel"></label>
</Col>
</Row>
<Row className={znodeStyle.znodeOperate}>
<OperateManage {...this.getOperateProps()}/>
</Row>
<div style={{visibility: this.state.znodeDataVisibility}}>
<Row className={znodeStyle.znodeOperate}>
<Col span={24} offset={1} className={styles.detailCols}
style={{marginTop: 10, fontWeight: 'bold'}}>
节点状态(Stat)信息如下:
</Col>
<Col span={24} offset={2} className={styles.detailCols}>
创建该节点事务id(czxid):<span
className={styles.detailColsContent}>{znodeDataDetail.czxid}</span>
</Col>
<Col span={24} offset={2} className={styles.detailCols}>
创建该节点时间(ctime):<span
className={styles.detailColsContent}>{znodeDataDetail.ctime}</span>
</Col>
<Col span={24} offset={2} className={styles.detailCols}>
修改该节点事务id(mzxid):<span
className={styles.detailColsContent}>{znodeDataDetail.mzxid}</span>
</Col>
<Col span={24} offset={2} className={styles.detailCols}>
修改该节点时间(mtime):<span
className={styles.detailColsContent}>{znodeDataDetail.mtime}</span>
</Col>
<Col span={24} offset={2} className={styles.detailCols}>
版本号(version):<span
className={styles.detailColsContent}>{znodeDataDetail.version}</span>
</Col>
<Col span={24} offset={2} className={styles.detailCols}>
子节点版本号(cversion):<span
className={styles.detailColsContent}>{znodeDataDetail.cversion}</span>
</Col>
<Col span={24} offset={2} className={styles.detailCols}>
设置节点ACL的版本号(aversion):<span
className={styles.detailColsContent}>{znodeDataDetail.aversion}</span>
</Col>
<Col span={24} offset={2} className={styles.detailCols}>
最后一次修改该节点/子节点的事务id(pzxid):<span
className={styles.detailColsContent}>{znodeDataDetail.pzxid}</span>
</Col>
<Col span={24} offset={2} className={styles.detailCols}>
数据长度(dataLength):<span
className={styles.detailColsContent}>{znodeDataDetail.dataLength}</span>
</Col>
<Col span={24} offset={2} className={styles.detailCols}>
子节点个数(numChildren):<span
className={styles.detailColsContent}>{znodeDataDetail.numChildren}</span>
</Col>
<Col span={24} offset={2} className={styles.detailCols}>
临时节点所属sessionId(ephemeralOwner,0x0表示永久节点):<span
className={styles.detailColsContent}>{znodeDataDetail.ephemeralOwner}</span>
</Col>
<Col span={24} offset={1} className={styles.detailCols}
style={{marginTop: 10, fontWeight: 'bold'}}>
节点数据信息如下:
<Select defaultValue='string'
style={{width: '200px', marginLeft: 10, marginRight: 10}}
onChange={this.handlsSerializableChange}>
<Select.Option value="string">string序列化</Select.Option>
<Select.Option value="hessian">hessian序列化</Select.Option>
</Select>
<Button onClick={this.onSearchData}>重查数据</Button>
</Col>
<Col span={24} offset={2} className={styles.detailCols}>
<Input.TextArea style={{width: '90%'}} autosize={{minRows: 5, maxRows: 20}}
value={znodeDataDetail.data}>
</Input.TextArea>
</Col>
</Row>
</div>
</div>
</div>
</div>
);
}
}
interface ManageProps {
sysUser: SysUserVo;
onSearchData: any;
onUpdataZnode: any;
deleteNode: any;
onCreateZnode: any;
selectedKey: string;
}
const OperateManage = (props: ManageProps) => {
let role = props.sysUser.userRole;
if (role == 1 || role == 2) { // 管理员或超级管理员
return (
<Col span={24} offset={2}>
<Button type="primary" style={{marginRight: 5, marginTop: 10}}
onClick={props.onSearchData}>查询数据</Button>
<Button type="primary" style={{marginRight: 5, marginTop: 10}}
onClick={props.onUpdataZnode}>修改数据</Button>
<Popconfirm
title={'确定删除该节点以及其子节点吗?' + props.selectedKey}
onConfirm={props.deleteNode}>
<Button type="primary" style={{marginRight: 5, marginTop: 10}}>删除以及子节点</Button>
</Popconfirm>
<Button type="primary" onClick={props.onCreateZnode}>增加子节点</Button>
</Col>
)
} else {
return (
<Col span={24} offset={2}>
<Button type="primary" style={{marginTop: 10}}
onClick={props.onSearchData}>查询数据</Button>
</Col>
)
}
} | the_stack |
import { DOCUMENT } from '@angular/common';
import { Component, Inject, OnInit } from '@angular/core';
import { NavController } from '@ionic/angular';
import { filter } from 'rxjs/operators';
import { AudioName, ChatSessionType, FriendRequestStatus, MessageType, ResultCode, SocketEvent } from './common/enums';
import { success } from './common/operators';
import { WINDOW } from './common/tokens';
import { RtcComponent } from './components/modals/rtc/rtc.component';
import { RevokeMessageTipsMessage } from './models/msg.model';
import { AgreeFriendRequest, ChatRequest, ChatSession, FriendRequest, Message, Result, User } from './models/onchat.model';
import { MessageDescPipe } from './pipes/message-desc.pipe';
import { UserService } from './services/apis/user.service';
import { Application } from './services/app.service';
import { CacheService } from './services/cache.service';
import { FeedbackService } from './services/feedback.service';
import { GlobalData } from './services/global-data.service';
import { OnChatService } from './services/onchat.service';
import { Overlay } from './services/overlay.service';
import { SocketService } from './services/socket.service';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent implements OnInit {
private messageDescPipe: MessageDescPipe = new MessageDescPipe();
constructor(
public globalData: GlobalData,
private app: Application,
private overlay: Overlay,
private navCtrl: NavController,
private userService: UserService,
private cacheService: CacheService,
private socketService: SocketService,
private onChatService: OnChatService,
private feedbackService: FeedbackService,
@Inject(DOCUMENT) private document: Document,
@Inject(WINDOW) private window: Window,
) { }
ngOnInit() {
// 连接打通时
this.socketService.on(SocketEvent.Connect).subscribe(() => {
this.onChatService.init();
});
// 发起/收到好友申请时
this.socketService.on(SocketEvent.FriendRequest).subscribe(({ code, data }: Result<FriendRequest>) => {
if (code !== ResultCode.Success) { return; } //TODO
const { user } = this.globalData;
// 收到好友申请提示,如果自己是被申请人
if (data.targetId === user.id) {
const index = this.globalData.receiveFriendRequests.findIndex(o => o.id === data.id);
// 如果这条好友申请已经在列表里
if (index >= 0) {
this.globalData.receiveFriendRequests[index] = data; // 静默更改
} else {
this.globalData.receiveFriendRequests.unshift(data);
}
this.overlay.notification({
icon: data.requesterAvatarThumbnail,
title: '收到好友申请',
description: '用户 ' + data.requesterNickname + ' 申请添加你为好友',
url: '/friend/handle/' + data.requesterId
});
this.feedbackService.audio(AudioName.DingDeng).play();
} else if (data.requesterId === user.id) {
const index = this.globalData.sendFriendRequests.findIndex(o => o.id === data.id);
// 如果这条好友申请已经在列表里
if (index >= 0) {
this.globalData.sendFriendRequests[index] = data; // 静默更改
} else {
this.globalData.sendFriendRequests.unshift(data);
}
}
});
// 同意好友申请/收到同意好友申请
this.socketService.on(SocketEvent.FriendRequestAgree).pipe(success()).subscribe(({ data }: Result<AgreeFriendRequest>) => {
const { user, receiveFriendRequests } = this.globalData;
// 如果申请人是自己(我发的好友申请被同意了)
if (data.requesterId === user.id) {
// 去我发出的申请列表里面找这条FriendRequest,并删除
const request = this.globalData.sendFriendRequests.find(o => o.id === data.friendRequestId);
if (request) {
request.status = FriendRequestStatus.Agree;
request.requesterReaded = true;
}
// 去我收到的申请列表里面通过找这条FriendRequest,并删除
this.globalData.receiveFriendRequests = receiveFriendRequests.filter(o => o.requesterId !== data.targetId);
this.overlay.notification({
icon: data.targetAvatarThumbnail,
title: '好友申请已同意',
description: '已和 ' + data.targetNickname + ' 成为好友',
url: '/chat/' + data.chatroomId
});
this.feedbackService.audio(AudioName.Boo).play();
} else if (data.targetId === user.id) { // 如果自己是被申请人
const request = this.globalData.receiveFriendRequests.find(o => o.id === data.friendRequestId);
if (request) {
request.status = FriendRequestStatus.Agree;
request.targetReaded = true;
}
this.overlay.toast('成功添加新好友!');
}
// 更新一下聊天列表
this.onChatService.initChatSession().subscribe();
// 更新好友列表
// 如果不为空才更新,因为为空时,进入好友列表页会自动查询
this.globalData.privateChatrooms && this.userService.getPrivateChatrooms().subscribe(({ data }: Result<ChatSession[]>) => {
this.globalData.privateChatrooms = data;
});
});
// 拒绝好友申请/收到拒绝好友申请
this.socketService.on(SocketEvent.FriendRequestReject).pipe(success()).subscribe(({ data }: Result<FriendRequest>) => {
const { user } = this.globalData;
// 如果申请人是自己
if (data.requesterId === user.id) {
const index = this.globalData.sendFriendRequests.findIndex(o => o.id === data.id);
if (index >= 0) {
this.globalData.sendFriendRequests[index] = data;
} else {
this.globalData.sendFriendRequests.unshift(data);
}
this.overlay.notification({
icon: data.targetAvatarThumbnail,
title: '好友申请被拒绝',
description: '用户 ' + data.targetNickname + ' 拒绝了你的好友申请',
url: '/friend/request/' + data.targetId
});
this.feedbackService.audio(AudioName.DingDeng).play();
} else if (data.targetId === user.id) { // 如果自己是被申请人
const index = this.globalData.receiveFriendRequests.findIndex(o => o.id === data.id);
if (index >= 0) {
this.globalData.receiveFriendRequests[index] = data;
} else {
this.globalData.receiveFriendRequests.unshift(data);
}
this.overlay.toast('已拒绝该好友申请!');
}
});
// 收到消息时
this.socketService.on(SocketEvent.Message).pipe(success()).subscribe(({ data }: Result<Message>) => {
const { chatroomId, user } = this.globalData;
// 先去聊天列表缓存里面查,看看有没有这个房间的数据
const chatSession = this.globalData.chatSessions.find(o => o.data.chatroomId === data.chatroomId);
// 如果消息不是自己的话,就播放提示音
if (data.userId !== user.id) {
const chatroomName = chatSession ? chatSession.title : '收到新消息';
const content = this.messageDescPipe.transform(data);
// 并且不在同一个房间,就弹出通知
if (data.chatroomId !== chatroomId || this.document.hidden) {
this.overlay.notification({
icon: chatSession ? chatSession.avatarThumbnail : data.avatarThumbnail,
title: chatroomName,
description: (chatroomName !== data.nickname ? data.nickname + ':' : '') + content,
url: '/chat/' + data.chatroomId
});
}
this.feedbackService.audio(AudioName.Boo).play();
}
if (chatSession) {
// 如果用户已经进入消息所属房间
if (chatroomId === data.chatroomId) {
chatSession.unread = 0;
} else if (data.userId !== user.id) {
chatSession.unread++;
}
chatSession.content = data;
chatSession.updateTime = Date.now();
this.globalData.sortChatSessions();
} else { // 如果不存在于列表当中,就刷新数据
this.onChatService.initChatSession().subscribe();
}
});
// 撤回消息时
this.socketService.on(SocketEvent.RevokeMessage).pipe(success()).subscribe(({ data }: Result<{ chatroomId: number, msgId: number }>) => {
// 收到撤回消息的信号,去聊天列表里面找,找的到就更新一下,最新消息
const chatSession = this.globalData.chatSessions.find(o => o.data.chatroomId === data.chatroomId);
if (chatSession) {
const nickname = chatSession.content.userId === this.globalData.user.id ? '我' : chatSession.content.nickname;
chatSession.unread && chatSession.unread--;
chatSession.content.nickname = nickname;
chatSession.content.type = MessageType.Tips;
chatSession.content.data = new RevokeMessageTipsMessage();
chatSession.content = { ...chatSession.content };
chatSession.updateTime = Date.now();
this.globalData.sortChatSessions();
}
});
// 收到入群申请时
this.socketService.on(SocketEvent.ChatRequest).pipe(
success(),
// 如果申请人不是自己
filter(({ data }: Result<ChatRequest>) => data?.requesterId !== this.globalData.user.id)
).subscribe(({ data }: Result<ChatRequest>) => {
const chatSession = this.globalData.chatSessions.find(o => o.type === ChatSessionType.ChatroomNotice);
// 如果列表里没有聊天室通知会话,就需要重新拉取
if (!chatSession) {
return this.onChatService.initChatSession().subscribe(() => {
this.feedbackService.audio(AudioName.Boo).play();
});
}
const index = this.globalData.receiveChatRequests.findIndex(o => o.id === data.id);
if (index >= 0) {
this.globalData.receiveChatRequests[index] = data;
this.globalData.sortReceiveChatRequests();
} else {
this.globalData.receiveChatRequests.unshift(data);
this.feedbackService.audio(AudioName.Boo).play();
}
chatSession.updateTime = Date.now();
this.globalData.sortChatSessions();
});
// 同意别人入群/同意我入群
this.socketService.on(SocketEvent.ChatRequestAgree).subscribe(({ code, data, msg }: Result<[ChatRequest, ChatSession]>) => {
const { user } = this.globalData;
if (code !== ResultCode.Success) {
return this.overlay.toast('操作失败,原因:' + msg);
}
const [request, chatSession] = data;
// 清除这个聊天室成员的缓存
this.cacheService.revoke('/chatroom/' + request.chatroomId + '/members');
// 如果是同意我入群
if (chatSession.userId === user.id) {
this.overlay.notification({
icon: chatSession.avatarThumbnail,
title: '聊天室申请加入成功',
description: '你已加入 ' + chatSession.title,
url: '/chatroom/' + chatSession.data.chatroomId
});
this.feedbackService.audio(AudioName.Boo).play();
const index = this.globalData.sendChatRequests.findIndex(o => o.id === request.id);
if (index >= 0) {
this.globalData.sendChatRequests[index] = request;
}
this.globalData.chatSessions.push(chatSession);
return this.globalData.sortChatSessions();
}
// 同意别人入群
const index = this.globalData.receiveChatRequests.findIndex(o => o.id === request.id);
if (index >= 0) {
this.globalData.receiveChatRequests[index] = request;
}
// 如果我是处理人
if (request.handlerId === user.id) {
this.overlay.toast('操作成功,已同意该申请!');
this.navCtrl.back();
}
});
// 拒绝别人的入群申请/入群申请被拒绝
this.socketService.on(SocketEvent.ChatRequestReject).subscribe(({ code, data, msg }: Result<ChatRequest>) => {
const { user } = this.globalData;
if (code !== ResultCode.Success) {
return this.overlay.toast('操作失败,原因:' + msg);
}
// 如果我是申请人,我被拒绝了
if (data.requesterId === user.id) {
const index = this.globalData.sendChatRequests.findIndex(o => o.id === data.id);
if (index >= 0) {
this.globalData.sendChatRequests[index] = data;
}
this.overlay.notification({
icon: data.chatroomAvatarThumbnail,
title: '聊天室申请加入失败',
description: data.handlerNickname + ' 拒绝让你加入 ' + data.chatroomName,
url: '/chatroom/request/' + data.id
});
return this.feedbackService.audio(AudioName.Boo).play();
}
// 如果处理人是我自己
const index = this.globalData.receiveChatRequests.findIndex(o => o.id === data.id);
if (index >= 0) {
this.globalData.receiveChatRequests[index] = data;
}
this.overlay.toast('操作成功,已拒绝该申请!');
});
// 收到 RTC 请求
this.socketService.on<Result<[requester: User, target: User]>>(SocketEvent.RtcCall).pipe(
success(),
filter(({ data: [_, target] }) => this.globalData.user.id === target.id),
).subscribe(({ data: [requester] }) => {
// 如果我已经在实时通信中,则告诉对方我忙线中
if (this.globalData.rtcing) {
return this.window.setTimeout(() => {
this.socketService.rtcBusy(requester.id)
}, 3000);
}
this.overlay.modal({
component: RtcComponent,
componentProps: {
user: requester,
isRequester: false
}
});
});
this.app.detectUpdate();
this.app.detectNavigation();
this.app.detectSocketConnectStatus();
this.app.initNotification();
}
} | the_stack |
import { TransformBase } from './transform-base.ts';
import { _ISelection, _Transaction, IValue, _IIndex, _Explainer, _SelectExplanation, _IType, IndexKey, _ITable, Stats, AggregationComputer, AggregationGroupComputer, setId } from '../interfaces-private.ts';
import { SelectedColumn, Expr, ExprRef, ExprCall } from 'https://deno.land/x/pgsql_ast_parser@9.2.0/mod.ts';
import { buildValue, uncache } from '../expression-builder.ts';
import { ColumnNotFound, nil, NotSupported, QueryError } from '../interfaces.ts';
import { colByName, suggestColumnName } from '../utils.ts';
import hash from 'https://deno.land/x/object_hash@2.0.3.1/mod.ts';
import { Evaluator } from '../evaluator.ts';
import { buildCount } from './aggregations/count.ts';
import { buildMinMax } from './aggregations/max-min.ts';
import { buildSum } from './aggregations/sum.ts';
import { buildArrayAgg } from './aggregations/array_agg.ts';
import { buildAvg } from './aggregations/avg.ts';
import { Selection } from './selection.ts';
export const aggregationFunctions = new Set([
'array_agg',
'avg',
'bit_and',
'bit_or',
'bool_and',
'bool_or',
'count',
'every',
'json_agg',
'jsonb_agg',
'json_object_agg',
'jsonb_object_agg',
'max',
'min',
'string_agg',
'sum',
'xmlagg',
])
export function buildGroupBy(on: _ISelection, groupBy: Expr[], select: SelectedColumn[]) {
const agg = new Aggregation(on, groupBy);
return agg.select(select);
}
let idCnt = 0;
export function getAggregator(on: _ISelection | nil): Aggregation<unknown> | null {
if (!on) {
return null;
}
if (on instanceof Aggregation) {
return on;
}
if (!(on instanceof Selection)) {
return null;
}
if (!(on.base instanceof Aggregation)) {
return null;
}
return on.base;
}
type AggregItem = any;
export class Aggregation<T> extends TransformBase<T> implements _ISelection<T> {
columns: readonly IValue<any>[];
/**
* Group-by values
* - key: column in source hash
* - value: column in this, evaluated against temporary entity.
**/
private readonly symbol = Symbol();
private readonly aggId = idCnt++;
private readonly groupIndex?: _IIndex<any> | nil;
private aggregations = new Map<string, {
getter: IValue;
id: symbol;
computer: AggregationComputer;
}>();
/** How to get grouping values on the base table raw items (not on "this.enumerate()" raw items) */
private groupingValuesOnbase: IValue[];
/** How to get the grouped values on "this.enumerate()" raw items output */
private groupByMapping = new Map<string, IValue>();
constructor(on: _ISelection, _groupedBy: Expr[]) {
super(on);
// === preassign columns that are reachable (grouped by)
this.groupingValuesOnbase = _groupedBy.map(x => buildValue(on, x));
for (let _i = 0; _i < this.groupingValuesOnbase.length; _i++) {
const i = _i;
const g = this.groupingValuesOnbase[i];
this.groupByMapping.set(g.hash!, new Evaluator(
on.ownerSchema
, g.type
, g.id
, g.hash!
, [g]
// keys are stored wrapped in a symbol (because not necessarily selected)
, v => v[this.symbol][i]
));
}
// try to find an index matching our groupby clause
this.groupIndex = on.getIndex(...this.groupingValuesOnbase);
this.columns = [];
}
getColumn(column: string | ExprRef): IValue;
getColumn(column: string | ExprRef, nullIfNotFound?: boolean): IValue | nil;
getColumn(column: string | ExprRef, nullIfNotFound?: boolean): IValue<any> | nil {
return this.base.getColumn(column, nullIfNotFound);
}
checkIfIsKey(got: IValue<any>): IValue<any> {
return this.groupByMapping.get(got.hash!) ?? got;
}
entropy(t: _Transaction): number {
return this.groupByMapping.size || 1;
}
stats(): Stats | null {
// cannot be computed without iterating
return null;
}
*enumerate(t: _Transaction): Iterable<T> {
for (const item of this._enumerateAggregationKeys(t)) {
const sym = item[this.symbol];
setId(item, `agg_${this.aggId}_${hash(sym)}`)
yield item as any;
}
}
private _enumerateAggregationKeys(t: _Transaction): Iterable<AggregItem> {
// ===== try to compute directly (will only succeed when no grouping, and simple statements like count(*))
const ret = this.computeDirect(t);
if (ret) {
return [ret];
}
// ===== try to compute base on index
const fromIndex = this.iterateFromIndex(t);
if (fromIndex) {
return fromIndex;
}
// ==== seq-scan computation
return this.seqScan(t);
}
private iterateFromIndex(t: _Transaction): AggregItem[] | null {
if (!this.groupIndex) {
return null;
}
const aggs = [...this.aggregations.values()];
const allByGroup = !aggs.some(x => !x.computer.computeFromIndex);
if (!allByGroup) {
return null;
}
// iterate all index keys
const computed: AggregItem[] = []
for (const k of this.groupIndex.iterateKeys(t)!) {
const ret: any = { [this.symbol]: k };
// try to compute from index
for (const agg of aggs) {
const val = agg.computer.computeFromIndex?.(k, this.groupIndex, t);
if (typeof val === 'undefined') {
if (computed.length) {
throw new Error('Compute from index has succeeded on an index key, but failed on another (which must not happen)');
}
return null;
}
ret[agg.id] = val;
}
computed.push(ret);
}
return computed;
}
private *seqScan(t: _Transaction): Iterable<AggregItem> {
const aggs = [...this.aggregations.values()];
const groups = new Map<string, {
key: IndexKey;
aggs: {
id: symbol;
computer: AggregationGroupComputer;
}[];
}>();
// === feed all items
for (const item of this.base.enumerate(t)) {
// get group-by values
const key: IndexKey = this.groupingValuesOnbase.map(g => g.get(item, t));
// add group if necessary
const groupingKey = hash(key);
let group = groups.get(groupingKey);
if (!group) {
groups.set(groupingKey, group = {
key,
aggs: aggs.map(x => ({
id: x.id,
computer: x.computer.createGroup(t),
})),
});
}
// process aggregators in group
for (const g of group.aggs) {
g.computer.feedItem(item);
}
}
// if this.base is empty, and this is not a group by...
// 👉 Must return a result.
// ex:
// - select max(a) from empty 👉 [{max: null}]
// - select max(a) from empty group by id 👉 []
if (groups.size === 0 && !this.groupingValuesOnbase.length) {
const key: IndexKey = [];
const groupingKey = hash(key);
groups.set(groupingKey, {
key,
aggs: aggs.map(x => ({
id: x.id,
computer: x.computer.createGroup(t),
})),
});
}
// === return results
for (const g of groups.values()) {
const ret: AggregItem = {
// specify the grouping key
[this.symbol]: g.key
};
// fill aggregations values
for (const { id, computer } of g.aggs) {
ret[id] = computer.finish() ?? null;
}
yield ret;
}
}
private computeDirect(t: _Transaction): AggregItem | null {
// When there is no grouping...
if (this.groupByMapping.size) {
return null;
}
// check if all selected aggregations can be computed directly (typically: count(*))
const aggs = [...this.aggregations.values()];
const allNoGroup = !aggs.some(x => !x.computer.computeNoGroup);
if (!allNoGroup) {
return null;
}
const ret: AggregItem = {
[this.symbol]: [],
};
for (const agg of this.aggregations.values()) {
const val = agg.computer.computeNoGroup?.(t);
if (typeof val === 'undefined') {
return null;
}
ret[agg.id] = val;
}
return ret;
}
getAggregation(name: string, call: ExprCall): IValue {
const hashed = hash(call);
const agg = this.aggregations.get(hashed);
if (agg) {
return agg.getter;
}
const got = this._getAggregation(name, call);
const id = Symbol();
const getter = new Evaluator(
this.ownerSchema
, got.type
, null
, hashed
, []
, raw => raw[id]
, {
forceNotConstant: true,
});
this.aggregations.set(hashed, {
id,
getter,
computer: got,
});
return getter;
}
private _getAggregation(name: string, call: ExprCall): AggregationComputer {
switch (name) {
case 'count':
return buildCount(this.base, call);
case 'max':
case 'min':
return buildMinMax(this.base, call.args, name);
case 'sum':
return buildSum(this.base, call);
case 'array_agg':
return buildArrayAgg(this.base, call);
case 'avg':
return buildAvg(this.base, call);
default:
throw new NotSupported('aggregation function ' + name);
}
}
hasItem(value: T, t: _Transaction): boolean {
return !!(value as any)[this.symbol];
}
getIndex(forValue: IValue<any>): _IIndex<any> | nil {
// there is no index on aggregations
return null;
}
explain(e: _Explainer): _SelectExplanation {
return {
_: 'aggregate',
id: e.idFor(this),
aggregator: null as any,
}
}
} | the_stack |
import { expect } from "chai";
import * as fs from "fs";
import { Arc3d } from "../../curve/Arc3d";
import { AnyCurve, AnyRegion } from "../../curve/CurveChain";
import { CurveFactory } from "../../curve/CurveFactory";
import { CurvePrimitive } from "../../curve/CurvePrimitive";
import { GeometryQuery } from "../../curve/GeometryQuery";
import { LineSegment3d } from "../../curve/LineSegment3d";
import { LineString3d } from "../../curve/LineString3d";
import { Loop, SignedLoops } from "../../curve/Loop";
import { ParityRegion } from "../../curve/ParityRegion";
import { RegionBinaryOpType, RegionOps } from "../../curve/RegionOps";
import { Angle } from "../../geometry3d/Angle";
import { GrowableXYZArray } from "../../geometry3d/GrowableXYZArray";
import { Matrix3d } from "../../geometry3d/Matrix3d";
import { Point3d, Vector3d } from "../../geometry3d/Point3dVector3d";
import { Transform } from "../../geometry3d/Transform";
import { PolyfaceBuilder } from "../../polyface/PolyfaceBuilder";
import { DuplicateFacetClusterSelector, PolyfaceQuery } from "../../polyface/PolyfaceQuery";
import { IModelJson } from "../../serialization/IModelJsonSchema";
import { LinearSweep } from "../../solid/LinearSweep";
import { HalfEdgeGraph } from "../../topology/Graph";
import { Checker } from "../Checker";
import { GeometryCoreTestIO } from "../GeometryCoreTestIO";
import { GraphChecker } from "../topology/Graph.test";
import { Sample } from "../../serialization/GeometrySamples";
import { Range3d } from "../../geometry3d/Range";
import { PolyfaceVisitor } from "../../polyface/Polyface";
import { PolygonOps } from "../../geometry3d/PolygonOps";
import { Ray3d } from "../../geometry3d/Ray3d";
import { CurveCurve } from "../../curve/CurveCurve";
import { CurveLocationDetailPair } from "../../curve/CurveLocationDetail";
import { PointStreamXYZHandlerBase, VariantPointDataStream } from "../../geometry3d/PointStreaming";
import { MultiLineStringDataVariant } from "../../topology/Triangulation";
/* eslint-disable no-console */
describe("RegionBoolean", () => {
it("SimpleSplits", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const candidates: CurvePrimitive[] = [];
let x0 = 0;
let y0 = 0;
candidates.push(LineSegment3d.createXYXY(0, 0, 1, 0));
candidates.push(LineSegment3d.createXYXY(1, 0, 1, 1));
candidates.push(Arc3d.createCircularStartMiddleEnd(Point3d.create(0.1, -0.1), Point3d.create(0.5, 0.6), Point3d.create(1.1, 0.8))!);
for (const c of candidates)
console.log(" geometry: ", IModelJson.Writer.toIModelJson(c));
const linestringStartY = 0.5; // making this 0.5 creates partial overlap -- problem?
for (const stepData of [
{ geometry: LineSegment3d.createXYXY(0, 0.5, 1, 0.5), expectedFaces: 3 },
{ geometry: LineSegment3d.createXYXY(0.8, -0.1, 1.1, 0.2), expectedFaces: 4 },
{ geometry: LineSegment3d.createXYXY(0.5, 0, 0.4, -0.2), expectedFaces: 4 },
{ geometry: LineSegment3d.createXYXY(0.4, 0.0, 0.4, -0.2), expectedFaces: 5 },
{ geometry: LineSegment3d.createXYXY(0.4, 0.0, 1.6, 1), expectedFaces: 6 },
{ geometry: LineString3d.create([0, linestringStartY], [0.2, 0.5], [0.8, 0.3], [1.2, 0.4]), expectedFaces: -1, expectedIntersections: -1 },
]) {
candidates.push(stepData.geometry);
console.log(" add geometry: ", IModelJson.Writer.toIModelJson(stepData.geometry));
for (const c of candidates)
GeometryCoreTestIO.captureCloneGeometry(allGeometry, c, x0, y0);
const loops = RegionOps.constructAllXYRegionLoops(candidates);
y0 += 0.75;
saveShiftedLoops(allGeometry, loops, x0, y0, 1.0);
if (stepData.expectedFaces >= 0 && loops.length === 1)
ck.testExactNumber(stepData.expectedFaces, loops[0].positiveAreaLoops.length + loops[0].negativeAreaLoops.length + loops[0].slivers.length, "Face loop count");
x0 += 5.0;
y0 = 0.0;
}
GeometryCoreTestIO.saveGeometry(allGeometry, "RegionBoolean", "SimpleSplits");
expect(ck.getNumErrors()).equals(0);
});
it("Holes", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
let x0 = 0;
const delta = 15.0;
let y0 = 0;
for (const filletRadius of [undefined, 0.5]) {
for (const numHole of [1, 3]) {
const candidates: AnyCurve[] = [];
const holeStep = 0.5;
candidates.push(CurveFactory.createRectangleXY(0, 0, 10, 10, 0, filletRadius));
candidates.push(CurveFactory.createRectangleXY(5, 8, 12, 12, 0, filletRadius));
candidates.push(LineSegment3d.createXYXY(6, 5, 10, 11));
for (let holeIndex = 0; holeIndex < numHole; holeIndex++) {
const ex = holeIndex * holeStep;
const ey = holeIndex * holeStep * 0.5;
candidates.push(CurveFactory.createRectangleXY(1 + ex, 1 + ey, 2 + ex, 2 + ey, 0));
}
for (const c of candidates)
GeometryCoreTestIO.captureCloneGeometry(allGeometry, c, x0, y0);
const loops = RegionOps.constructAllXYRegionLoops(candidates);
y0 += delta;
saveShiftedLoops(allGeometry, loops, x0, y0, delta);
if (loops.length > 1) {
const negativeAreas = [];
for (const loopSet of loops) {
for (const loop of loopSet.negativeAreaLoops)
negativeAreas.push(loop);
}
const regions = RegionOps.sortOuterAndHoleLoopsXY(negativeAreas);
x0 += delta;
y0 = 0;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, regions, x0, y0);
}
x0 += delta * (loops.length + 1);
y0 = 0.0;
}
x0 += 4 * delta;
}
GeometryCoreTestIO.saveGeometry(allGeometry, "RegionBoolean", "Holes");
expect(ck.getNumErrors()).equals(0);
});
it("Overlaps", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const badGeometry: GeometryQuery[] = [];
const xMax = 10.0;
const da = 1.0;
let x0 = 0.0;
let y0 = 0;
const c = 1.0;
const c1 = 2.5;
for (const degrees of [0, 180, 0.012123389324234, 42.123213]) {
const transform = Transform.createFixedPointAndMatrix(Point3d.create(0, 0, 0),
Matrix3d.createRotationAroundAxisIndex(2, Angle.createDegrees(degrees)));
x0 = 0.0;
for (const ab of [0.6 /* , 1.1, 3.1 */]) {
for (const numCut of [1, 4, 7, 9]) {
const candidates: AnyCurve[] = [];
candidates.push(Loop.createPolygon([
Point3d.create(0, 0),
Point3d.create(xMax, 0),
Point3d.create(xMax, 2),
Point3d.create(0, 2),
Point3d.create(0, 0)]));
const a0 = 0.5;
const b0 = a0 + ab;
for (let i = 0; i < numCut; i++) {
const a = a0 + i * da;
const b = b0 + i * da;
// alternate direction of overlap bits ... maybe it will cause problems in graph sort . .
if ((i & 0x01) === 0)
candidates.push(LineSegment3d.createXYXY(a, 0, b, 0));
else
candidates.push(LineSegment3d.createXYXY(a, 0, b, 0));
candidates.push(LineSegment3d.createXYXY(a, 0, a, c));
candidates.push(LineSegment3d.createXYXY(b, 0, b, c));
candidates.push(LineSegment3d.createXYXY(a, c, b, c));
// spread around some X geometry . . .
if ((i & 0x02) !== 0 && ab > 2.0) {
candidates.push(LineSegment3d.createXYXY(a, c, b, c1));
candidates.push(LineSegment3d.createXYXY(a, c1, b, c));
}
}
let testIndex = 0;
for (const candidate of candidates) {
(candidate as any).testIndex = testIndex++;
candidate.tryTransformInPlace(transform);
}
const loops = RegionOps.constructAllXYRegionLoops(candidates);
const dy = 3.0;
saveShiftedLoops(allGeometry, loops, x0, y0 + dy, dy);
const stepData = { rotateDegrees: degrees, numCutout: numCut, cutoutStep: ab };
if (!ck.testExactNumber(1, loops.length, stepData)
|| !ck.testExactNumber(1, loops[0].negativeAreaLoops.length, stepData)) {
saveShiftedLoops(badGeometry, loops, x0, y0 + dy, dy);
}
GeometryCoreTestIO.captureCloneGeometry(allGeometry, candidates, x0, y0);
x0 += 2 * xMax;
}
x0 += 4 * xMax;
}
y0 += 100.0;
}
GeometryCoreTestIO.saveGeometry(badGeometry, "RegionBoolean", "Overlaps.BAD");
GeometryCoreTestIO.saveGeometry(allGeometry, "RegionBoolean", "Overlaps");
expect(ck.getNumErrors()).equals(0);
});
it("ParityRegionWithCoincidentEdges", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
let xBase = 0.0;
const yBase = 0;
for (const q of [0, 1, -1]) {
const a0 = -q;
const a1 = 12 + q;
const b0 = 4 - q;
const b1 = 8 + q;
for (const q1 of [0, -1, 1]) {
const pointArrayA = [[8, +q1], [4, 0], [a0, a0], [0, 4], [0, 8], [a0, 12],
[4, 11], [8, 11], [a1, 12], [12, 8], [12, 4], [a1, a0], [8, 0]];
const pointArrayB = [[8, 0], [4, 0], [b0, 4], [4, 8], [8, 8], [b1, 4], [8, 0]];
// loopB.reverseChildrenInPlace();
runRegionTest(allGeometry, pointArrayA, pointArrayB, xBase, yBase);
xBase += 100;
}
}
GeometryCoreTestIO.saveGeometry(allGeometry, "Solids", "ParityRegionWithCoincidentEdges");
expect(ck.getNumErrors()).equals(0);
});
it("ParityRegionWithBadBoundary", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
let xBase = 0.0;
let yBase = 0.0;
// q is an offset applied to corners to affect whether contiguous segments are colinear.
// q=0 makes lots of colinear edges.
// q=1 spreads corners to make all angles nonzero.
// q1,q2 is an offset applied to a single point of the interior shape to change it from
// 0,0 full edge touch
// 1,0 single point touch from inside.
// 1,1 full hole
// -1,-1 partly out.
for (const skewFactor of [0, 0.01, 0.072312]) {
for (const q1q2 of [[-1, -1], [0, 0], [0, 1], [1, 1], [-1, -1]]) {
for (const q of [1, 0]) {
const a0 = -q;
const a1 = 12 + q;
const b0 = 4 - q;
const b1 = 8 + q;
const q1 = q1q2[0];
const q2 = q1q2[1];
const pointArrayA = [[8, 0], [4, 0], [a0, a0], [0, 4], [0, 8], [a0, 12],
[4, 11], [8, 11], [a1, 12], [12, 8], [12, 4], [a1, a0], [8, 0]];
const pointArrayB = [[8, q2], [4, q1], [b0, 4], [4, 7], [8, 7], [b1, 4], [8, q2]];
for (const data of [pointArrayA, pointArrayB]) {
for (const xy of data) {
xy[1] += skewFactor * xy[0];
}
}
runRegionTest(allGeometry, pointArrayA, pointArrayB, xBase, yBase);
xBase += 100;
}
xBase += 200;
}
xBase = 0;
yBase += 100;
}
GeometryCoreTestIO.saveGeometry(allGeometry, "Solids", "ParityRegionWithBadBoundary");
expect(ck.getNumErrors()).equals(0);
});
it("SectioningExample", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
let xOut = 0.0;
const yOut0 = 0.0;
const allLines: CurvePrimitive[] = [];
const ax = 10.0;
const ax1 = ax + 1; // for mirror
const ay1 = 1.0;
const dy = 1.0;
const ay2 = ay1 + dy;
const by = 0.2;
allLines.push(LineString3d.create([[0, 0], [ax, ay1], [ax, ay2], [0, ay1]]));
for (const fraction of [0.0, 0.25, 0.5, 0.9]) {
const x = fraction * ax;
const y = fraction * ay1; // "on" the lower line
allLines.push(LineSegment3d.createXYXY(x, y- by, x, y + dy + by));
}
{
GeometryCoreTestIO.captureCloneGeometry(allGeometry, allLines, xOut, yOut0);
const regions = RegionOps.constructAllXYRegionLoops(allLines);
saveShiftedLoops(allGeometry, regions, xOut, yOut0, 1.5 * dy);
}
xOut += 3 * ax;
{
// repeat with a mirrored set of polygons
const n = allLines.length;
const transform = Transform.createFixedPointAndMatrix(Point3d.create(ax1, 0, 0),
Matrix3d.createScale(-1, 1.4, 1));
for (let i = 0; i < n; i++)
allLines.push(allLines[i].cloneTransformed(transform) as CurvePrimitive);
const regions = RegionOps.constructAllXYRegionLoops(allLines);
saveShiftedLoops(allGeometry, regions, xOut, yOut0, 10.5 * dy);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, allLines, xOut, yOut0);
}
GeometryCoreTestIO.saveGeometry(allGeometry, "RegionBoolean", "SectioningExample");
expect(ck.getNumErrors()).equals(0);
});
it("SectioningExampleFile", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
let x0 = 0.0;
let y0 = 0.0;
const dy = 2.0;
const positiveLoopOffset = 0.005;
// for (const baseName of ["sectionA", "sectionB", "sectionC", "sectionD", "sectionE", "sectionF"]) {
// sectionA has half a bridge pier
// sectionF is a mess of diagonals.
for (const baseName of ["sectionA", "sectionB", "sectionC", "sectionD", "sectionE", "sectionF"]) {
console.log({ baseName });
const stringA = fs.readFileSync(`./src/test/testInputs/ChainCollector/sectionData00/${ baseName }.imjs`, "utf8");
const jsonA = JSON.parse(stringA);
const section = IModelJson.Reader.parse(jsonA) as GeometryQuery[];
const closedAreas: LineString3d[] = [];
for (const g of section){
if (g instanceof LineString3d) {
if (g.packedPoints.front()?.isAlmostEqualMetric(g.packedPoints.back()!)) {
closedAreas.push(g);
const centroid = PolygonOps.centroidAreaNormal(g.packedPoints);
if (ck.testType (centroid, Ray3d) && Number.isFinite (centroid.a!)){
const areaNormal = PolygonOps.areaNormal(g.points);
ck.testCoordinate(centroid.a!, areaNormal.magnitude(), "compare area methods");
}
}
}
}
GeometryCoreTestIO.captureCloneGeometry(allGeometry, section, x0, y0);
const regions = RegionOps.constructAllXYRegionLoops(section as AnyRegion[]);
saveShiftedLoops(allGeometry, regions, x0, y0 + dy, dy, positiveLoopOffset, false);
x0 += 300.0;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, closedAreas, x0, y0);
const regionsB = RegionOps.constructAllXYRegionLoops((closedAreas as unknown) as AnyRegion[]);
saveShiftedLoops(allGeometry, regionsB, x0, y0 + dy, dy, positiveLoopOffset, false);
x0 = 0;
y0 += 100.0;
}
GeometryCoreTestIO.saveGeometry(allGeometry, "RegionBoolean", "SectioningExampleFile");
expect(ck.getNumErrors()).equals(0);
});
it("SectioningLineStringApproach", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
let x0 = 0.0;
let y0 = 0.0;
const dy = 3.0;
const minSearchDistance = 3.0;
const distanceDisplayFactor = 1.25;
// for (const baseName of ["sectionA", "sectionB", "sectionC", "sectionD", "sectionE", "sectionF"]) {
for (const baseName of ["sectionC"]) {
console.log({ baseName });
const stringA = fs.readFileSync(`./src/test/testInputs/ChainCollector/sectionData00/${ baseName }.imjs`, "utf8");
const jsonA = JSON.parse(stringA);
const section = IModelJson.Reader.parse(jsonA) as GeometryQuery[];
const closedAreas: LineString3d[] = [];
for (const g of section){
if (g instanceof LineString3d) {
if (g.packedPoints.front()?.isAlmostEqualMetric(g.packedPoints.back()!)) {
closedAreas.push(g);
}
}
}
GeometryCoreTestIO.captureCloneGeometry(allGeometry, section, x0, y0);
y0 += dy;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, closedAreas, x0, y0);
y0 += dy;
for (let i = 0; i < closedAreas.length; i++){
for (let j = i + 1; j < closedAreas.length; j++){
const pairs = CurveCurve.closeApproachProjectedXYPairs(closedAreas[i], closedAreas[j], minSearchDistance);
y0 += dy;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, closedAreas[i], x0, y0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, closedAreas[j], x0, y0);
let numPoint = 0;
let shortestPair: CurveLocationDetailPair | undefined;
let shortestDistance = Number.MAX_VALUE;
let numOverlap = 0;
for (const p of pairs) {
if (p.detailA.fraction1 !== undefined)
numOverlap++;
if (p.detailA.point.isAlmostEqual(p.detailB.point)){
GeometryCoreTestIO.createAndCaptureXYCircle(allGeometry, p.detailA.point, 0.05, x0, y0);
numPoint++;
} else {
const d = p.detailA.point.distance(p.detailB.point);
if (d < shortestDistance) {
shortestDistance = d;
shortestPair = p;
}
}
}
if (numOverlap > 0)
console.log({ numOverlap, i, j});
if (shortestPair && numPoint === 0)
for (const p of pairs) {
if (p.detailA.point.isAlmostEqual(p.detailB.point)){
} else {
const d = p.detailA.point.distance(p.detailB.point);
if (d < distanceDisplayFactor * shortestDistance) {
const arc = constructEllipseAroundSegment(p.detailA.point, p.detailB.point, 1.2, 0.2);
GeometryCoreTestIO.captureGeometry(allGeometry, arc, x0, y0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, [p.detailA.point, p.detailB.point], x0, y0);
}
}
}
}
}
x0 += 100.0;
}
GeometryCoreTestIO.saveGeometry(allGeometry, "RegionBoolean", "SectioningLineStringApproach");
expect(ck.getNumErrors()).equals(0);
});
// in the input directories ...
// Madhav.json is the whole input set for 5 sections.
// sectionA..sectionE are splits of the separate sections.
// Note that the corresponding .imjs files are reduced to linestrings and are accessed in other tests.
// (skip this in production builds -- it's more part of helping the user understand his data than code test)
it.skip("SectioningJson", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
// cspell:word Madhav
for (const baseName of ["sectionA", "sectionB", "sectionC", "sectionD", "sectionE", "MadhavInput"]) {
console.log({ baseName });
const stringA = fs.readFileSync(`./src/test/testInputs/ChainCollector/sectionData00/${ baseName }.json`, "utf8");
const jsonA = JSON.parse(stringA);
const parser = new SectionDataParser();
parser.parseAny(jsonA);
console.log({ baseName, linestringCount: parser.allChains.length });
let numOpen = 0;
let numClosed = 0;
for (const chain of parser.allChains) {
if (chain.length > 0) {
if (chain[0].isAlmostEqual(chain[chain.length - 1]))
numClosed++;
else
numOpen++;
}
}
console.log({ numOpen, numClosed });
}
GeometryCoreTestIO.saveGeometry(allGeometry, "RegionBoolean", "SectioningLineStringApproach");
expect(ck.getNumErrors()).equals(0);
});
});
/**
*
* @param allGeometry array to receive (cloned) geometry
* @param components geometry to output
* @param x0 x shift for positive area loops
* @param y0 y shift for positive area loops
* @param dy additional y shift for (1 step) negative loops, (2 steps) non-loop geometry, (3 step) inward offsets of positive area geometry.
* @param y1 y shift for negative loops and stray geometry
*/
function saveShiftedLoops(allGeometry: GeometryQuery[], components: SignedLoops | SignedLoops[], x0: number, y0: number, dy: number, positiveLoopOffset: number = 0.02,
doTriangulation: boolean = true) {
if (Array.isArray(components)) {
const allNegativeAreaLoops: Loop [] = [];
for (const member of components) {
saveShiftedLoops(allGeometry, member, x0, y0, dy, positiveLoopOffset);
allNegativeAreaLoops.push(...member.negativeAreaLoops);
}
if (doTriangulation && allNegativeAreaLoops.length > 1) {
const yOut = y0 + dy;
// form a triangulation of a larger area -- interior edges will be interesting relationships
const range = Range3d.createNull();
for (const loop of allNegativeAreaLoops)
range.extendRange(loop.range());
const maxSide = Math.max(range.xLength(), range.yLength());
const expansionDistance = 0.25 * maxSide;
const range1 = range.clone();
range.expandInPlace(expansionDistance);
range1.expandInPlace(0.9 * expansionDistance);
// triangulate all the way to the expanded range.
const outerLoop = Loop.createPolygon(range.rectangleXY(0.0)!);
const regionLoops = [outerLoop, ...allNegativeAreaLoops];
const region = ParityRegion.createLoops(regionLoops);
const builder = PolyfaceBuilder.create();
builder.addTriangulatedRegion(region);
const polyface = builder.claimPolyface();
// any triangle with a point outside range1 is extraneous
const isInteriorFacet = (visitor: PolyfaceVisitor): boolean => {
const facetRange = visitor.point.getRange();
return range1.containsRange(facetRange);
};
GeometryCoreTestIO.captureCloneGeometry(allGeometry, PolyfaceQuery.cloneFiltered (polyface, isInteriorFacet), x0, yOut);
}
} else {
GeometryCoreTestIO.captureCloneGeometry(allGeometry, components.positiveAreaLoops, x0, y0 + 2 * dy);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, components.negativeAreaLoops, x0, y0 + 3 * dy);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, components.slivers, x0, y0 + 4 * dy);
if (positiveLoopOffset !== 0.0) {
const yy = y0 + dy;
const zz = 0.01; // raise the tic marks above the faces
for (const loop of components.positiveAreaLoops) {
const offsetLoop = RegionOps.constructCurveXYOffset(loop, positiveLoopOffset);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, offsetLoop, x0, yy);
}
// draw a tic mark: midpoint to fractional position along an edge then leading "to the left" of the edge.
const drawEdgeTic = (curve: CurvePrimitive | undefined, loop: Loop | undefined, fraction: number) => {
if (curve) {
const curveLength = curve.quickLength();
let ticMultiplier = 3.0;
if (loop !== undefined
&& (loop as any).computedAreaInPlanarSubdivision !== undefined
&& (loop as any).computedAreaInPlanarSubdivision < 0.0)
ticMultiplier = 6.0;
const ticLength = Math.min(0.2 * curveLength, ticMultiplier * positiveLoopOffset);
const tangentRayAtTicMark = curve.fractionToPointAndUnitTangent(fraction);
const midPoint = curve.fractionToPoint(0.5);
const perp = tangentRayAtTicMark.direction.unitPerpendicularXY();
GeometryCoreTestIO.captureCloneGeometry(allGeometry,
[midPoint, tangentRayAtTicMark.origin, tangentRayAtTicMark.origin.plusScaled(perp, ticLength)],
x0, yy, zz
);
}
};
if (components.edges) {
for (const e of components.edges) {
drawEdgeTic(e.curveA, e.loopA, 0.48);
drawEdgeTic(e.curveB, e.loopB, 0.48);
}
}
}
}
}
function runRegionTest(allGeometry: GeometryQuery[], pointArrayA: number[][], pointArrayB: number[][], xBase: number, yBase: number) {
let x0 = xBase;
let y0 = yBase;
const loopA = Loop.createPolygon(GrowableXYZArray.create(pointArrayA));
// loopA.reverseChildrenInPlace();
const loopB = Loop.createPolygon(GrowableXYZArray.create(pointArrayB));
// loopB.reverseChildrenInPlace();
const region = ParityRegion.create();
region.tryAddChild(loopA);
region.tryAddChild(loopB);
// Output geometry:
// polygonXYAreaDifferenceLoopsToPolyface OffsetsOfPositives
// Mesh polygonXYAreaUnionLoopsToPolyface SliverAreas
// SweptSolid NegativeAreas
// ParityRegionA ParityRegionB PositiveAreas <repeat stack per connected component>
// Where ParityRegionA is by direct assembly of loops, let downstream sort.
// ParityRegionB is assembled by sortOuterAndHoleLoopsXY
//
const solid = LinearSweep.create(region, Vector3d.create(0, 0, 1), true)!;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, region, x0, y0);
y0 += 15;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, solid, x0, y0);
const builder = PolyfaceBuilder.create();
builder.addLinearSweep(solid);
const mesh = builder.claimPolyface();
const mesh1 = PolyfaceQuery.cloneByFacetDuplication(mesh, true, DuplicateFacetClusterSelector.SelectOneByParity);
y0 += 15;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, mesh, x0, y0);
y0 += 15;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, mesh1, x0, y0);
const sortedLoops = RegionOps.sortOuterAndHoleLoopsXY([loopA, loopB]);
x0 += 20;
y0 = yBase;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, sortedLoops, x0, y0);
y0 += 40;
let y1 = y0 + 100;
if (Checker.noisy.parityRegionAnalysis) {
RegionOps.setCheckPointFunction(
(name: string, graph: HalfEdgeGraph, _properties: string, _extraData?: any) => {
GraphChecker.captureAnnotatedGraph(allGeometry, graph, x0, y1 += 15);
const euler = graph.countVertexLoops() - graph.countNodes() / 2.0 + graph.countFaceLoops();
console.log(` Checkpoint ${name}.${_properties}`,
{ v: graph.countVertexLoops(), e: graph.countNodes(), f: graph.countFaceLoops(), eulerCharacteristic: euler });
GraphChecker.dumpGraph(graph);
});
}
const unionRegion = RegionOps.polygonXYAreaUnionLoopsToPolyface(pointArrayA, pointArrayB);
RegionOps.setCheckPointFunction();
GeometryCoreTestIO.captureCloneGeometry(allGeometry, unionRegion, x0, y0);
y0 += 20;
const diffRegion = RegionOps.polygonXYAreaDifferenceLoopsToPolyface(pointArrayA, pointArrayB);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, diffRegion, x0, y0);
x0 += 15;
y0 = yBase;
const fixedRegions = RegionOps.constructAllXYRegionLoops(region);
saveShiftedLoops(allGeometry, fixedRegions, x0, y0, 15.0);
}
/**
* Intersect a plane with each primitive of a loop.
* If any intersection is coincident, or at an endpoint, return undefined.
* Otherwise (the good case!) return the intersection sorted as in-out pairs.
function findSimpleLoopPlaneCuts(loop: Loop, plane: Plane3dByOriginAndUnitNormal, fractionTol: number = 0.001): CurveLocationDetail[] | undefined {
const cuts: CurveLocationDetail[] = [];
let farDetail: CurveLocationDetail | undefined;
const origin = plane.getOriginRef();
for (const p of loop.children) {
const num0 = cuts.length;
p.appendPlaneIntersectionPoints(plane, cuts);
for (let i = num0; i < cuts.length; i++) {
const f = cuts[i].fraction;
if (f < fractionTol || f + fractionTol > 1.0)
return undefined;
const tangentRay = cuts[i].curve?.fractionToPointAndDerivative(f)!;
if (plane.getNormalRef().isPerpendicularTo(tangentRay.direction))
return undefined;
cuts[i].a = origin.distance(cuts[i].point);
if (farDetail === undefined || cuts[i].a > farDetail.a)
farDetail = cuts[i];
}
}
if (cuts.length >= 2 && !Geometry.isOdd(cuts.length) && farDetail) {
const sortVector = Vector3d.createStartEnd(plane.getOriginRef(), farDetail.point);
for (const cut of cuts)
cut.a = sortVector.dotProductStartEnd(origin, cut.point);
cuts.sort((cutA: CurveLocationDetail, cutB: CurveLocationDetail) => (cutB.a - cutA.a));
for (let i = 0; i + 1 < cuts.length; i += 2) {
if (Geometry.isSameCoordinate(cuts[i].a, cuts[i + 1].a))
return undefined;
}
// ah, the cuts have been poked an prodded and appear to be simple pairs . .
return cuts;
}
return undefined;
}
*/
/**
* * Construct (by some unspecified means) a point that is inside the loop.
* * Pass that point to the `accept` function.
* * If the function returns a value (other than undefined) return that value.
* * If the function returns undefined, try further points.
* * The point selection process is unspecified. For instance,
* @param loop
* @param accept
function classifyLoopByAnyInternalPoint<T>(loop: Loop, accept: (loop: Loop, testPoint: Point3d) => T | undefined): T | undefined {
const testFractions = [0.321345, 0.921341276, 0.5, 0.25];
for (const f of testFractions) {
for (let primitiveIndex = 0; primitiveIndex < loop.children.length; primitiveIndex++) {
const detail = loop.primitiveIndexAndFractionToCurveLocationDetailPointAndDerivative(primitiveIndex, f, false);
if (detail) {
const cutPlane = Plane3dByOriginAndUnitNormal.create(detail.point, detail.vectorInCurveLocationDetail!);
if (cutPlane) {
const cuts = findSimpleLoopPlaneCuts(loop, cutPlane);
if (cuts && cuts.length >= 2) {
const q = accept(loop, cuts[0].point.interpolate(0.5, cuts[1].point));
if (q !== undefined)
return q;
}
}
}
}
}
return undefined;
}
/*
function classifyAreasByAnyInternalPoint(candidates: Loop[], accept: (loop: Loop, testPoint: Point3d) => boolean): Loop[] {
const acceptedLoops: Loop[] = [];
const testFractions = [0.321345, 0.921341276, 0.5, 0.25];
for (const loop of candidates) {
if (classifyLoopByAnyInternalPoint(loop, accept) !== undefined)
acceptedLoops.push(loop);
}
return acceptedLoops;
}
*/
describe("GeneralSweepBooleans", () => {
it("Rectangles", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const rectangle1A = Loop.create(LineString3d.create(Sample.createRectangle(0, 0, 5, 7, 0, true)));
const rectangle1B = Loop.create(LineString3d.create(Sample.createRectangle(-2, -2, 8, 7, 0, true)));
const rectangle2 = Loop.create(LineString3d.create(Sample.createRectangle(1, 1, 6, 2, 0, true)));
const area3 = Loop.create(
LineSegment3d.createXYXY(2, 1.5, 5, 2.5), LineSegment3d.createXYXY(5, 2.5, 5, 3),
Arc3d.createCircularStartMiddleEnd(Point3d.create(5, 3, 0), Point3d.create(4, 4, 0), Point3d.create(2, 3, 0))!,
LineSegment3d.createXYXY(2, 3, 2, 1.5));
const area4 = Loop.create(
LineSegment3d.createXYXY(-1, -1, -1, 9),
Arc3d.createCircularStartMiddleEnd(Point3d.create(-1, 9), Point3d.create(4, 4, 0), Point3d.create(-1, -1))!);
const area5 = Loop.create(
LineSegment3d.createXYXY(-1, 1, -1, 6),
Arc3d.createCircularStartMiddleEnd(Point3d.create(-1, 6), Point3d.create(1, 3.5), Point3d.create(-1, 1))!);
const xStep = 20.0;
let y0 = 0;
for (const rectangle1 of [rectangle1B, rectangle1A, rectangle1B]) {
let x0 = -xStep;
exerciseAreaBooleans([rectangle1], [area5], ck, allGeometry, x0 += xStep, y0);
exerciseAreaBooleans([rectangle1], [area5], ck, allGeometry, x0 += xStep, y0);
exerciseAreaBooleans([rectangle1], [area5], ck, allGeometry, x0 += xStep, y0);
exerciseAreaBooleans([rectangle1], [rectangle2], ck, allGeometry, x0 += xStep, y0);
exerciseAreaBooleans([rectangle1], [rectangle2, area3], ck, allGeometry, x0 += xStep, y0);
exerciseAreaBooleans([rectangle1], [area4], ck, allGeometry, x0 += xStep, y0);
y0 += 100;
}
GeometryCoreTestIO.saveGeometry(allGeometry, "sweepBooleans", "Rectangles");
expect(ck.getNumErrors()).equals(0);
});
it("HighParityRectangles", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const outerLoop = [[0, 0, 1], [0, 4, 1], [0, 4, 1], [0, 8, 1], [0, 8, 1], [0, 12, 1], [0, 12, 1], [0, 16, 1], [0, 16, 1], [0, 20, 1], [0, 20, 1], [0, 24, 1], [0, 24, 1], [4, 24, 1], [4, 24, 1], [4, 20, 1], [4, 20, 1], [4, 16, 1], [4, 16, 1], [4, 12, 1], [4, 12, 1], [4, 8, 1], [4, 8, 1], [4, 4, 1], [4, 4, 1], [4, 0, 1], [4, 0, 1], [0, 0, 1]];
const inner1 = [[0, 4, 1], [4, 4, 1], [4, 4, 1], [4, 8, 1], [4, 8, 1], [4, 12, 1], [4, 12, 1], [4, 16, 1], [4, 16, 1], [4, 20, 1], [4, 20, 1], [0, 20, 1], [0, 20, 1], [0, 16, 1], [0, 16, 1], [0, 12, 1], [0, 12, 1], [0, 8, 1], [0, 8, 1], [0, 4, 1]];
const inner2 = [[0, 8, 1], [4, 8, 1], [4, 8, 1], [4, 12, 1], [4, 12, 1], [0, 12, 1], [0, 12, 1], [0, 8, 1]];
// const inner3 = [[0, 12, 1], [4, 12, 1], [4, 12, 1], [4, 16, 1], [4, 16, 1], [0, 16, 1], [0, 16, 1], [0, 12, 1]];
const inner3 = [[0, 12, 1], [3, 12, 1], [3, 12, 1], [3, 16, 1], [3, 16, 1], [0, 16, 1], [0, 16, 1], [0, 12, 1]];
let x0 = 0;
for (const innerLoops of [[inner1], [inner2], [inner3], [inner1, inner2], [inner1, inner3], [inner1, inner2, inner3]]) {
const x1 = x0 + 10;
const x2 = x0 + 20;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, LineString3d.create(outerLoop), x0, 0);
for (const inner of innerLoops)
GeometryCoreTestIO.captureCloneGeometry(allGeometry, LineString3d.create(inner), x0, 0);
const regionDiff = RegionOps.polygonXYAreaDifferenceLoopsToPolyface(outerLoop, innerLoops);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, regionDiff, x1, 0);
const regionParity = RegionOps.polygonXYAreaDifferenceLoopsToPolyface(outerLoop, innerLoops);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, regionParity, x2, 0);
x0 += 50;
}
GeometryCoreTestIO.saveGeometry(allGeometry, "sweepBooleans", "HighParityRectangles");
expect(ck.getNumErrors()).equals(0);
});
it("Disjoints", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const lowRectangle = Loop.create(LineString3d.create(Sample.createRectangle(0, 0, 3, 1, 0, true)));
const highRectangle = Loop.create(LineString3d.create(Sample.createRectangle(0, 3, 2, 4, 0, true)));
const tallRectangleA = Loop.create(LineString3d.create(Sample.createRectangle(1, -1, 2, 5, 0, true)));
const tallRectangleB = Loop.create(LineString3d.create(Sample.createRectangle(1, -1, 1.5, 5, 0, true)));
exerciseAreaBooleans([lowRectangle], [highRectangle], ck, allGeometry, 0, 0);
exerciseAreaBooleans([tallRectangleA], [lowRectangle, highRectangle], ck, allGeometry, 10, 0);
exerciseAreaBooleans([tallRectangleB], [lowRectangle, highRectangle], ck, allGeometry, 20, 0);
GeometryCoreTestIO.saveGeometry(allGeometry, "sweepBooleans", "Disjoints");
expect(ck.getNumErrors()).equals(0);
});
it("MBDisjointCover", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const outer = IModelJson.Reader.parse(JSON.parse(fs.readFileSync(
"./src/test/testInputs/intersections/MBContainmentBoolean/outer.imjs", "utf8"))) as AnyRegion[];
const inner = IModelJson.Reader.parse(JSON.parse(fs.readFileSync(
"./src/test/testInputs/intersections/MBContainmentBoolean/inner.imjs", "utf8"))) as AnyRegion[];
let x0 = 0;
const dy = 50;
// for (const entry of outer) {
// RegionOps.consolidateAdjacentPrimitives(entry);
// }
GeometryCoreTestIO.captureCloneGeometry(allGeometry, outer, x0, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, inner, x0, 50);
const dx = 100.0;
exerciseAreaBooleans(outer, inner, ck, allGeometry, (x0 += dx), -dy);
for (const a of outer) {
GeometryCoreTestIO.captureCloneGeometry(allGeometry, a, x0 += 2 * dx, 0);
for (const b of inner) {
exerciseAreaBooleans([a], [b], ck, allGeometry, x0 += dx, 0);
}
}
GeometryCoreTestIO.saveGeometry(allGeometry, "sweepBooleans", "MBDisjointCover");
expect(ck.getNumErrors()).equals(0);
});
it("HoleInA", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const rectangle1A = Loop.create(LineString3d.create(Sample.createRectangle(0, 0, 10, 8, 0, true)));
const rectangle1B = Loop.create(LineString3d.create(Sample.createRectangle(1, 1, 9, 7, 0, true)));
const region = ParityRegion.create(rectangle1A, rectangle1B);
const dx = 20.0;
let x0 = 0;
for (const yB of [-0.5, 0.5, 6.5, 7.5, 3.0]) {
const rectangle2 = Loop.create(LineString3d.create(Sample.createRectangle(5, yB, 6, yB + 1, 0, true)));
exerciseAreaBooleans([region], [rectangle2], ck, allGeometry, x0 += dx, 0);
}
GeometryCoreTestIO.saveGeometry(allGeometry, "sweepBooleans", "HoleInA");
expect(ck.getNumErrors()).equals(0);
});
it("SharedEdgeElimination", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
let y0 = 0;
let x0 = 0;
const rectangle1A = Loop.create(LineString3d.create(Sample.createRectangle(0, 0, 10, 8, 0, true)));
const rectangle1B = Loop.create(LineString3d.create(Sample.createRectangle(10, 0, 15, 8, 0, true)));
const rectangle1C = Loop.create(LineString3d.create(Sample.createRectangle(5, 5, 12, 10, 0, true)));
y0 = 0;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, rectangle1A, x0, y0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, rectangle1B, x0, y0);
y0 += 10;
const rectangleArray = [rectangle1A.getPackedStrokes()!, rectangle1B.getPackedStrokes()!];
const fixup2 = RegionOps.polygonBooleanXYToLoops(rectangleArray, RegionBinaryOpType.Union, []);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, fixup2, x0, y0, 0);
x0 += 30;
y0 = 0;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, rectangle1A, x0, y0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, rectangle1B, x0, y0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, rectangle1C, x0, y0);
y0 += 15;
rectangleArray.push(rectangle1C.getPackedStrokes()!);
const fixup3 = RegionOps.polygonBooleanXYToLoops(rectangleArray, RegionBinaryOpType.Union, []);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, fixup3, x0, y0, 0);
GeometryCoreTestIO.saveGeometry(allGeometry, "sweepBooleans", "SharedEdgeElimination");
expect(ck.getNumErrors()).equals(0);
});
it("DocDemo", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const filletedRectangle = CurveFactory.createRectangleXY(0, 0, 5, 4, 0, 1);
const splitter = CurveFactory.createRectangleXY(1, -1, 6, 2);
const union = RegionOps.regionBooleanXY(filletedRectangle, splitter, RegionBinaryOpType.Union);
const intersection = RegionOps.regionBooleanXY(filletedRectangle, splitter, RegionBinaryOpType.Intersection);
const diff = RegionOps.regionBooleanXY(filletedRectangle, splitter, RegionBinaryOpType.AMinusB);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, filletedRectangle, 0, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, splitter, 0, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, union, 0, 10);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, intersection, 0, 20);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, diff, 0, 30);
const manyRoundedRectangles = [];
for (let a = 0; a < 5; a += 1) {
manyRoundedRectangles.push(CurveFactory.createRectangleXY(a, a, a + 4, a + 1.75, 0, 0.5));
}
const splitterB0 = CurveFactory.createRectangleXY(0.5, 0.4, 6, 2.1, 0, 0);
const splitterB1 = splitterB0.cloneTransformed(Transform.createFixedPointAndMatrix({ x: 1, y: 2, z: 0 }, Matrix3d.createRotationAroundAxisIndex(2, Angle.createDegrees(40)))) as Loop;
const splitterB = [splitterB0, splitterB1];
const unionB = RegionOps.regionBooleanXY(manyRoundedRectangles, splitterB, RegionBinaryOpType.Union);
const intersectionB = RegionOps.regionBooleanXY(manyRoundedRectangles, splitterB, RegionBinaryOpType.Intersection);
const diffB = RegionOps.regionBooleanXY(manyRoundedRectangles, splitterB, RegionBinaryOpType.AMinusB);
const xB = 10;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, manyRoundedRectangles, xB, -20);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, splitterB, xB, -10);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, manyRoundedRectangles, xB, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, splitterB, xB, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, unionB, xB, 10);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, intersectionB, xB, 20);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, diffB, xB, 30);
GeometryCoreTestIO.saveGeometry(allGeometry, "sweepBooleans", "DocDemo");
expect(ck.getNumErrors()).equals(0);
});
it("FacetPasting", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const loopA = GrowableXYZArray.create([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]]); // Missing closure !!!
const loopB = GrowableXYZArray.create([[1, 0, 0], [2, 0, 0], [2, 1, 0], [1, 1, 0]]); // Missing closure !!!
const loop = RegionOps.polygonBooleanXYToLoops([loopA, loopB], RegionBinaryOpType.Union, []);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, loopA, 0, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, loopB, 0, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, loop, 4, 0);
GeometryCoreTestIO.saveGeometry(allGeometry, "sweepBooleans", "FacetPasting");
expect(ck.getNumErrors()).equals(0);
});
});
function exerciseAreaBooleans(dataA: AnyRegion[], dataB: AnyRegion[],
ck: Checker, allGeometry: GeometryQuery[], x0: number, y0Start: number) {
const areas = [];
const range = RegionOps.curveArrayRange(dataA.concat(dataB));
const yStep = Math.max(15.0, 2.0 * range.yLength());
let y0 = y0Start;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, dataA, x0, y0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, dataB, x0, y0);
for (const opType of [RegionBinaryOpType.Union, RegionBinaryOpType.Intersection, RegionBinaryOpType.AMinusB, RegionBinaryOpType.BMinusA]) {
y0 += yStep;
const result = RegionOps.regionBooleanXY(dataA, dataB, opType);
areas.push(RegionOps.computeXYArea(result!)!);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, result, x0, y0);
}
const area0 = areas[0]; // union
const area123 = areas[1] + areas[2] + areas[3];
ck.testCoordinate(area0, area123, " UnionArea = sum of parts");
}
/**
* Return an ellipse the loops around a segment.
* @param fractionAlong = axis length in AB direction, as a multiple of distance from center to pointA
* @param fractionPerp = axis length perpendicular to AB direction, as as multiple of distance from center to pointA
*/
function constructEllipseAroundSegment(pointA: Point3d, pointB: Point3d, fractionAlong: number, fractionPerp: number) {
const center = pointA.interpolate(0.5, pointB);
const vector0 = Vector3d.createStartEnd(center, pointA);
const vector90 = vector0.rotate90CCWXY();
vector0.scaleInPlace(fractionAlong);
vector90.scaleInPlace(fractionPerp);
return Arc3d.create(center, vector0, vector90);
}
class SectionDataParser extends PointStreamXYZHandlerBase {
public allChains: Point3d[][] = [];
private _currentChain?: Point3d[];
public override startChain(_chainData: MultiLineStringDataVariant, _isLeaf: boolean): void {
this._currentChain = [];
}
public override handleXYZ(x: number, y: number, z: number): void {
this._currentChain!.push(Point3d.create(x, y, z));
}
public override endChain(_chainData: MultiLineStringDataVariant, _isLeaf: boolean): void {
if (this._currentChain !== undefined && this._currentChain.length > 0)
this.allChains.push(this._currentChain);
this._currentChain = undefined;
}
public parseGeometries(data: any[]) {
if (Array.isArray(data)) {
VariantPointDataStream.streamXYZ(data, this);
}
}
public parseElements(elements: any[]) {
for (const e of elements)
if (Array.isArray(e.geometries)) {
this.parseGeometries(e.geometries);
}
}
public parseAny(data: any, depth: number = 0) {
if (Array.isArray(data)) {
console.log({ sectionDataArrayLength: data.length, depth });
for (const d of data)
this.parseAny(d, depth + 1);
} else if (data instanceof Object) {
if (Number.isFinite(data.distanceAlong)) {
if (Array.isArray(data.elements))
console.log({
distanceAlong: data.distanceAlong, direction: data.direction,
numElements: data.elements.length,
});
this.parseElements(data.elements);
}
}
}
} | the_stack |
<?xml version="1.0" encoding="utf-8"?>
<!--
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
-->
<!DOCTYPE TS>
<TS version="2.0">
<context>
<name>BumpTopStrings</name>
<message>
<location filename="../BumpTop.cpp" line="3960"/>
<source>Sticky Note
-Double-click
to edit</source>
<translation>Sticky Note
-Double-tap
to edit</translation>
</message>
</context>
<context>
<name>BtUtilStrings</name>
<message>
<location filename="../BT_Util.cpp" line="9461"/>
<source>Double-click (or press Enter) to edit the Sticky Note again</source>
<translation>Double-tap (or press Enter) to edit the Sticky Note again</translation>
</message>
<message>
<location filename="../BT_Util.cpp" line="9466"/>
<source>Slideshow
Gesture right or press arrow keys to cycle images
Click to exit</source>
<translation>Slideshow
Gesture right or press arrow keys to cycle images
Tap to exit</translation>
</message>
<message>
<location filename="../BT_Util.cpp" line="9481"/>
<source>Use the scrollwheel or arrow keys to quickly leaf through the pile!</source>
<translation>Use the flick gestures or arrow keys to quickly leaf through the pile!</translation>
</message>
</context>
<context>
<name>Camera</name>
<message>
<location filename="../BT_Camera.cpp" line="635"/>
<source>Move the camera by using scroll wheel, double-click to focus or Ctrl + Shift W, A, S, D.</source>
<translation>Move the camera by pinching fingers in and out, double-tap to focus OR Ctrl + Shift W, A, S, D.</translation>
</message>
</context>
<context>
<name>StartPart1</name>
<message>
<location filename="../BT_Training.cpp" line="317"/>
<source>Welcome to BumpTop!
Let's take a quick tour of BumpTop's features.
To start Part 1, double-click one of the photos below.</source>
<translation>Welcome to BumpTop!
Let's take a quick tour of BumpTop's features.
To start Part 1, double-tap one of the photos below.</translation>
</message>
</context>
<context>
<name>SwipeNextInSlideshowMode</name>
<message>
<location filename="../BT_Training.cpp" line="427"/>
<source>Good job! Now drag quickly to the right OR push the right arrow key.</source>
<translation>Good job! Now quickly flick the photo to the right OR push the right arrow key.</translation>
</message>
</context>
<context>
<name>SwipeNextAgainInSlideshowMode</name>
<message>
<location filename="../BT_Training.cpp" line="450"/>
<source>Sweet! Now try quickly dragging to the left OR push the left arrow key.</source>
<translation>Sweet! Now try quickly flicking to the left OR push the left arrow key.</translation>
</message>
</context>
<context>
<name>ExitSlideshowMode</name>
<message>
<location filename="../BT_Training.cpp" line="472"/>
<source>Great! Now single click on the picture to zoom back out OR drag down.</source>
<translation>Great! Now tap on the picture to zoom back out OR drag down.</translation>
</message>
</context>
<context>
<name>StartPart2</name>
<message>
<location filename="../BT_Training.cpp" line="497"/>
<source>Part 2/5: Items in BumpTop
You'll see a small BumpTop logo. Click it, and holding
your mouse, move it around.</source>
<translation>Part 2/5: Items in BumpTop
You'll see a small BumpTop logo. Touch the logo, and
using your finger, move it around.</translation>
</message>
</context>
<context>
<name>BounceItemAgainstWalls</name>
<message>
<location filename="../BT_Training.cpp" line="578"/>
<source>In BumpTop, items bump against one another
and the walls, just like in the real world.
Try throwing the item quickly against
any of the walls.</source>
<translation>Try throwing the item against
any of the walls with some force.</translation>
</message>
<!-- FIX: CHANGE ABOVE MESSAGE TO BE OF THE SOURCE, NO TRANSLATION
<message>
<location filename="../BT_Training.cpp" line="578"/>
<source>Try throwing the item against
any of the walls with some force.</source>
<translation></translation>
</message>
-->
</context>
<context>
<name>GrowItem</name>
<message>
<location filename="../BT_Training.cpp" line="610"/>
<source>Now we'll describe how to use the menus in BumpTop.
Right-click the item, and select "Grow."</source>
<translation>Now we'll describe how to use the menus in BumpTop.
Tap and hold the item until the blue menu appears.
Then slide your finger to the "Grow" option.</translation>
</message>
</context>
<context>
<name>DeleteItem</name>
<message>
<location filename="../BT_Training.cpp" line="633"/>
<source>You can also access the standard Windows right-click menu.
To delete the item right-click on it, then select "More...", and then "Delete."</source>
<translation>You can also access the standard Windows right-click menu.
To delete the item tap and hold it, then slide to "More... ", and then tap "Delete."</translation>
</message>
</context>
<context>
<name>CreatePile</name>
<message>
<location filename="../BT_Training.cpp" line="681"/>
<source>Part 3/5: Piles
Let's create a pile!
Draw a circle around the items and without letting go
of the mouse button, drag across the "Pile" icon that
appears in the center
OR Draw a circle around the items, then right-click on
them and select "Create Pile"</source>
<translation>Part 3/5: Piles
Let's create a pile!
Draw a circle around the items and, while keeping your finger
on the screen, drag across the "Pile" icon that
appears in the center
OR Draw a circle around the items, then right-click on
them and select "Create Pile"</translation>
</message>
</context>
<context>
<name>GridView</name>
<message>
<location filename="../BT_Training.cpp" line="787"/>
<source>You can also view the piles in different ways.
As an example, try double clicking the pile.</source>
<translation>You can also view the piles in different ways.
As an example, try double tapping the pile.</translation>
</message>
</context>
<context>
<name>CloseGridView</name>
<message>
<location filename="../BT_Training.cpp" line="804"/>
<source>To close the pile, click on the red "X" in the upper left corner.</source>
<translation>To close the pile, tap on the red "X" in the upper left corner.</translation>
</message>
</context>
<context>
<name>ZoomToWalls</name>
<message>
<location filename="../BT_Training.cpp" line="839"/>
<source>You can also focus in on the walls for a closer look.
Try double-clicking one of the walls.</source>
<translation>You can also focus in on the walls for a closer look.
Try double-tapping one of the walls.</translation>
</message>
</context>
<context>
<name>ZoomToFloor</name>
<message>
<location filename="../BT_Training.cpp" line="857"/>
<source>Double-click the floor to return to the default view</source>
<translation>Double-tap the floor to return to the default view</translation>
</message>
</context>
<context>
<name>OrganizeByType</name>
<message>
<location filename="../BT_Training.cpp" line="894"/>
<source>If you'd like to give some automatic ordering to your files,
you can ask BumpTop to organize by type.
Right-click on the desktop, and select "Pile by Type..."</source>
<translation>If you'd like to give some automatic ordering to your files,
you can ask BumpTop to organize by type.
Tap and hold on the desktop until the menu appears, and select "Pile by Type..."</translation>
</message>
</context>
<context>
<name>AutomatedTradeshowDemo::PrepareScene</name>
<message>
<location filename="../BT_AutomatedTradeshowDemo.cpp" line="34"/>
<source>BumpTop In Action!
Click Here to Try</source>
<translation>BumpTop In Action!
Tap Here to Try</translation>
</message>
</context>
<context>
<name>FacebookActorImpl</name>
<message>
<location filename="../BT_CustomActor.cpp" line="303"/>
<source>Drop images to here to upload them to Facebook
and double-click to go to your profile!</source>
<translation>Drop images to here to upload them to Facebook
and double-click to go to your profile!</translation>
</message>
</context>
<context>
<name>TwitterActorImpl</name>
<message>
<location filename="../BT_CustomActor.cpp" line="549"/>
<source>Drop images here to update your Twitter
and double-click to send a tweet!</source>
<translation>Drop images here to update your Twitter
and double-tap to send a tweet!</translation>
</message>
</context>
<context>
<name>HISLogoActorImpl</name>
<message>
<location filename="../BT_CustomActor.cpp" line="1421"/>
<source>Double click this icon to visit the HIS Digital webpage</source>
<translation>Double-tap this icon to visit the HIS Digital webpage</translation>
</message>
</context>
</TS> | the_stack |
import { capitalize } from "lodash"
import * as Oni from "oni-api"
import * as Log from "oni-core-logging"
import { IDisposable } from "oni-types"
import * as React from "react"
import { store, SupportedProviders, VersionControlPane, VersionControlProvider } from "./"
import getBufferLayerInstance from "./../../Editor/NeovimEditor/BufferLayerManager"
import { Notifications } from "./../../Services/Notifications"
import { Branch } from "./../../UI/components/VersionControl/Branch"
import { SidebarManager } from "./../Sidebar"
import VersionControlBlameLayer from "./VersionControlBlameLayer"
interface ISendNotificationsArgs {
detail: string
level: "info" | "warn"
title: string
expiration?: number
}
export type ISendVCSNotification = (args: ISendNotificationsArgs) => void
export class VersionControlManager {
private _vcs: SupportedProviders
private _vcsProvider: VersionControlProvider
private _menuInstance: Oni.Menu.MenuInstance
private _vcsStatusItem: Oni.StatusBarItem
private _subscriptions: IDisposable[] = []
private _providers = new Map<string, VersionControlProvider>()
private _bufferLayerManager = getBufferLayerInstance()
constructor(
private _oni: Oni.Plugin.Api,
private _sidebar: SidebarManager,
private _notifications: Notifications,
) {}
public get providers() {
return this._providers
}
public get activeProvider(): VersionControlProvider {
return this._vcsProvider
}
public async registerProvider(provider: VersionControlProvider): Promise<void> {
if (provider) {
this._providers.set(provider.name, provider)
const canHandleWorkspace = await provider.canHandleWorkspace()
if (canHandleWorkspace) {
await this._activateVCSProvider(provider)
}
this._oni.workspace.onDirectoryChanged.subscribe(async dir => {
const providerToUse = await this.getCompatibleProvider(dir)
await this.handleProviderStatus(providerToUse)
})
}
}
// Use arrow function to maintain this binding of sendNotification
public sendNotification: ISendVCSNotification = ({ expiration = 3_000, ...args }) => {
const notification = this._notifications.createItem()
notification.setContents(args.title, args.detail)
notification.setExpiration(expiration)
notification.setLevel(args.level) // TODO: Integrate setLevel into API
notification.show()
}
public deactivateProvider(): void {
this._vcsProvider.deactivate()
this._subscriptions.map(s => s.dispose())
if (this._vcsStatusItem) {
this._vcsStatusItem.hide()
}
this._vcsProvider = null
this._vcs = null
}
public async handleProviderStatus(newProvider: VersionControlProvider): Promise<void> {
const isSameProvider = this._vcsProvider && newProvider && this._vcs === newProvider.name
const noCompatibleProvider = this._vcsProvider && !newProvider
const newReplacementProvider = Boolean(this._vcsProvider && newProvider)
const compatibleProvider = Boolean(!this._vcsProvider && newProvider)
switch (true) {
case isSameProvider:
break
case noCompatibleProvider:
this.deactivateProvider()
break
case newReplacementProvider:
this.deactivateProvider()
await this._activateVCSProvider(newProvider)
break
case compatibleProvider:
await this._activateVCSProvider(newProvider)
break
default:
break
}
}
private async getCompatibleProvider(dir: string): Promise<VersionControlProvider | null> {
const allCompatibleProviders: VersionControlProvider[] = []
for (const vcs of this._providers.values()) {
const isCompatible = await vcs.canHandleWorkspace(dir)
if (isCompatible) {
allCompatibleProviders.push(vcs)
}
}
// TODO: when we have multiple providers we will need logic to determine which to
// use if more than one is compatible
const [providerToUse] = allCompatibleProviders
return providerToUse
}
private _activateVCSProvider = async (provider: VersionControlProvider) => {
this._vcs = provider.name
this._vcsProvider = provider
await this._initialize()
provider.activate()
}
private async _initialize() {
try {
await this._updateBranchIndicator()
this._setupSubscriptions()
const hasVcsSidebar = this._oni.sidebar.entries.some(({ id }) => id.includes("vcs"))
const enabled = this._oni.configuration.getValue("experimental.vcs.sidebar")
if (!hasVcsSidebar && enabled) {
const vcsPane = new VersionControlPane(
this._oni,
this._vcsProvider,
this.sendNotification,
this._sidebar, // TODO: Refactor API
store,
)
this._sidebar.add("code-fork", vcsPane) // TODO: Refactor API
}
// TODO: this should only be active if this is a file under version control
this._bufferLayerManager.addBufferLayer(
buffer =>
this._oni.configuration.getValue("experimental.vcs.blame.enabled") &&
!!buffer.filePath,
buf =>
new VersionControlBlameLayer(
buf,
this._vcsProvider,
this._oni.configuration,
this._oni.commands,
),
)
this._registerCommands()
} catch (e) {
Log.warn(`Failed to initialise provider, because, ${e.message}`)
}
}
private _setupSubscriptions() {
this._subscriptions = [
this._oni.editors.activeEditor.onBufferEnter.subscribe(async () => {
await this._updateBranchIndicator()
}),
this._vcsProvider.onBranchChanged.subscribe(async newBranch => {
await this._updateBranchIndicator(newBranch)
await this._oni.editors.activeEditor.neovim.command("e!")
}),
this._oni.editors.activeEditor.onBufferSaved.subscribe(async () => {
await this._updateBranchIndicator()
}),
(this._oni.workspace as any).onFocusGained.subscribe(async () => {
await this._updateBranchIndicator()
}),
]
}
private _registerCommands = () => {
const toggleVCS = () => {
this._sidebar.toggleVisibilityById("oni.sidebar.vcs") // TODO: Refactor API
}
this._oni.commands.registerCommand({
command: "vcs.sidebar.toggle",
name: "Version Control: Toggle Visibility",
detail: "Toggles the vcs pane in the sidebar",
execute: toggleVCS,
enabled: () => this._oni.configuration.getValue("experimental.vcs.sidebar"),
})
this._oni.commands.registerCommand({
command: `vcs.fetch`,
name: "Fetch the selected branch",
detail: "",
execute: this._fetchBranch,
})
this._oni.commands.registerCommand({
command: `vcs.branches`,
name: `Local ${capitalize(this._vcs)} Branches`,
detail: "Open a menu with a list of all local branches",
execute: this._createBranchList,
})
}
private _updateBranchIndicator = async (branchName?: string) => {
if (!this._vcsProvider) {
return
} else if (!this._vcsStatusItem) {
const vcsId = `oni.status.${this._vcs}`
this._vcsStatusItem = this._oni.statusBar.createItem(1, vcsId)
}
try {
// FIXME: there is race condition on deactivation of the provider
const branch = await this._vcsProvider.getBranch()
const diff = await this._vcsProvider.getDiff()
if (!branch || !diff) {
return Log.warn(`The ${!branch ? "branch name" : "diff"} could not be found`)
} else if (!branch && !diff) {
return this._vcsStatusItem.hide()
}
this._vcsStatusItem.setContents(<Branch branch={branch} diff={diff} />)
this._vcsStatusItem.show()
} catch (e) {
this._notifyOfError(e)
return this._vcsStatusItem.hide()
}
}
private _createBranchList = async () => {
if (!this._vcsProvider) {
return
}
const [currentBranch, branches] = await Promise.all([
this._vcsProvider.getBranch(),
this._vcsProvider.getLocalBranches(),
])
this._menuInstance = this._oni.menu.create()
if (!branches) {
return
}
const branchItems = branches.all.map(branch => ({
label: branch,
icon: "code-fork",
pinned: currentBranch === branch,
}))
this._menuInstance.show()
this._menuInstance.setItems(branchItems)
this._menuInstance.onItemSelected.subscribe(async menuItem => {
if (menuItem && menuItem.label) {
try {
await this._vcsProvider.changeBranch(menuItem.label)
} catch (e) {
this._notifyOfError(e)
}
}
})
}
private _notifyOfError(error: Error) {
const name = this._vcsProvider ? capitalize(this._vcs) : "VCS"
const errorMessage = error && error.message ? error.message : null
this.sendNotification({
title: `${capitalize(name)} Plugin Error:`,
detail: `${name} plugin encountered an error ${errorMessage}`,
level: "warn",
})
}
private _fetchBranch = async () => {
if (this._menuInstance.isOpen() && this._menuInstance.selectedItem) {
try {
await this._vcsProvider.fetchBranchFromRemote({
currentDir: this._oni.workspace.activeWorkspace,
branch: this._menuInstance.selectedItem.label,
})
} catch (e) {
this._notifyOfError(e)
}
}
}
}
// Shelter the instance from the global scope -> globals are evil.
function init() {
let Provider: VersionControlManager
const Activate = (
oni: Oni.Plugin.Api,
sidebar: SidebarManager,
notifications: Notifications,
): void => {
Provider = new VersionControlManager(oni, sidebar, notifications)
}
const GetInstance = () => {
return Provider
}
return {
activate: Activate,
getInstance: GetInstance,
}
}
export const { activate, getInstance } = init() | the_stack |
import type { ICategory, IndicesArray, UIntTypedArray } from '../model';
import { IForEachAble, ISequence, isIndicesAble } from './interable';
import { createWorkerCodeBlob, IPoorManWorkerScope, toFunctionBody } from './worker';
import type {
IAdvancedBoxPlotData,
IStatistics,
INumberBin,
IDateBin,
IDateStatistics,
ICategoricalStatistics,
ICategoricalBin,
IDateHistGranularity,
IStringStatistics,
} from './mathInterfaces';
/**
* computes the optimal number of bins for a given array length
* @internal
* @param {number} length
* @returns {number}
*/
export function getNumberOfBins(length: number) {
if (length === 0) {
return 1;
}
// as by default used in d3 the Sturges' formula
return Math.ceil(Math.log(length) / Math.LN2) + 1;
}
/**
* @internal
*/
export function min(values: number[]): number;
export function min<T>(values: T[], acc: (v: T) => number): number;
export function min<T>(values: T[], acc?: (v: T) => number) {
let min = Number.POSITIVE_INFINITY;
for (const d of values) {
const v = acc ? acc(d) : (d as any as number);
if (v < min) {
min = v;
}
}
return min;
}
/**
* @internal
*/
export function max(values: number[]): number;
export function max<T>(values: T[], acc: (v: T) => number): number;
export function max<T>(values: T[], acc?: (v: T) => number) {
let max = Number.NEGATIVE_INFINITY;
for (const d of values) {
const v = acc ? acc(d) : (d as any as number);
if (v > max) {
max = v;
}
}
return max;
}
/**
* @internal
*/
export function extent(values: number[]): [number, number];
export function extent<T>(values: T[], acc: (v: T) => number): [number, number];
export function extent<T>(values: T[], acc?: (v: T) => number) {
let max = Number.NEGATIVE_INFINITY;
let min = Number.POSITIVE_INFINITY;
for (const d of values) {
const v = acc ? acc(d) : (d as any as number);
if (v < min) {
min = v;
}
if (v > max) {
max = v;
}
}
return [min, max];
}
/**
* @internal
*/
export function range(length: number) {
const r: number[] = new Array(length);
for (let i = 0; i < length; ++i) {
r[i] = i;
}
return r;
}
/**
* an empty range
* @internal
*/
export function empty(length: number) {
const r: null[] = new Array(length);
r.fill(null);
return r;
}
/**
* computes the X quantile assumes the values are sorted
* @internal
*/
export function quantile(values: ArrayLike<number>, quantile: number, length = values.length) {
if (length === 0) {
return NaN;
}
const target = (length - 1) * quantile;
const index = Math.floor(target);
if (index === target) {
return values[index];
}
const v = values[index];
const vAfter = values[index + 1];
return v + (vAfter - v) * (target - index); // shift by change
}
/**
* @internal
*/
export function median(values: number[]): number;
export function median<T>(values: T[], acc: (v: T) => number): number;
export function median<T>(values: T[], acc?: (v: T) => number) {
const arr = acc ? values.map(acc) : (values as any as number[]).slice();
arr.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
return quantile(arr, 0.5);
}
function pushAll<T>(push: (v: T) => void) {
return (vs: IForEachAble<T>) => {
if (!isIndicesAble(vs)) {
vs.forEach(push);
return;
}
for (let j = 0; j < vs.length; ++j) {
push(vs[j]);
}
};
}
/**
* common interface for a builder pattern
* @internal
*/
export interface IBuilder<T, R> {
/**
* push an entry
*/
push(v: T): void;
/**
* push multiple values at once
*/
pushAll(vs: IForEachAble<T>): void;
/**
* build the result
*/
build(): R;
}
/**
* @internal
*/
export function boxplotBuilder(
fixedLength?: number
): IBuilder<number, IAdvancedBoxPlotData> & { buildArr: (s: Float32Array) => IAdvancedBoxPlotData } {
let min = Number.POSITIVE_INFINITY;
let max = Number.NEGATIVE_INFINITY;
let sum = 0;
let length = 0;
let missing = 0;
// if fixed size use the typed array else a regular array
const values: number[] = [];
const vs: Float32Array | null = fixedLength != null ? new Float32Array(fixedLength) : null;
const push = (v: number) => {
length += 1;
if (v == null || Number.isNaN(v)) {
missing += 1;
return;
}
if (v < min) {
min = v;
}
if (v > max) {
max = v;
}
sum += v;
};
const pushAndSave = (v: number) => {
push(v);
if (vs) {
vs[length] = v;
} else {
values.push(v);
}
};
const invalid = {
min: NaN,
max: NaN,
mean: NaN,
missing,
count: length,
whiskerHigh: NaN,
whiskerLow: NaN,
outlier: [],
median: NaN,
q1: NaN,
q3: NaN,
};
const buildImpl = (s: ArrayLike<number>) => {
const valid = length - missing;
const median = quantile(s, 0.5, valid)!;
const q1 = quantile(s, 0.25, valid)!;
const q3 = quantile(s, 0.75, valid)!;
const iqr = q3 - q1;
const left = q1 - 1.5 * iqr;
const right = q3 + 1.5 * iqr;
let outlier: number[] = [];
// look for the closest value which is bigger than the computed left
let whiskerLow = left;
for (let i = 0; i < valid; ++i) {
const v = s[i];
if (left < v) {
whiskerLow = v;
break;
}
// outlier
outlier.push(v);
}
// look for the closest value which is smaller than the computed right
let whiskerHigh = right;
const reversedOutliers: number[] = [];
for (let i = valid - 1; i >= 0; --i) {
const v = s[i];
if (v < right) {
whiskerHigh = v;
break;
}
// outlier
reversedOutliers.push(v);
}
outlier = outlier.concat(reversedOutliers.reverse());
return {
min,
max,
count: length,
missing,
mean: sum / valid,
whiskerHigh,
whiskerLow,
outlier,
median,
q1,
q3,
};
};
const build = () => {
const valid = length - missing;
if (valid === 0) {
return invalid;
}
const s = vs ? vs.sort() : Float32Array.from(values).sort();
return buildImpl(s);
};
const buildArr = (vs: Float32Array) => {
const s = vs.slice().sort();
for (let j = 0; j < vs.length; ++j) {
push(vs[j]);
}
// missing are the last
return buildImpl(s);
};
return {
push: pushAndSave,
build,
buildArr,
pushAll: pushAll(pushAndSave),
};
}
/**
* @internal
*/
export function numberStatsBuilder(domain: [number, number], numberOfBins: number): IBuilder<number, IStatistics> {
const hist: INumberBin[] = [];
let x0 = domain[0];
const range = domain[1] - domain[0];
const binWidth = range / numberOfBins;
for (let i = 0; i < numberOfBins; ++i, x0 += binWidth) {
hist.push({
x0,
x1: x0 + binWidth,
count: 0,
});
}
const bin1 = domain[0] + binWidth;
const binN = domain[1] - binWidth;
const toBin = (v: number) => {
if (v < bin1) {
return 0;
}
if (v >= binN) {
return numberOfBins - 1;
}
if (numberOfBins === 3) {
return 1;
}
let low = 1;
let high = numberOfBins - 1;
// binary search
while (low < high) {
const center = Math.floor((high + low) / 2);
if (v < hist[center].x1) {
high = center;
} else {
low = center + 1;
}
}
return low;
};
// filter out NaN
let min = Number.POSITIVE_INFINITY;
let max = Number.NEGATIVE_INFINITY;
let sum = 0;
let length = 0;
let missing = 0;
const push = (v: number) => {
length += 1;
if (v == null || Number.isNaN(v)) {
missing += 1;
return;
}
if (v < min) {
min = v;
}
if (v > max) {
max = v;
}
sum += v;
hist[toBin(v)].count++;
};
const build = () => {
const valid = length - missing;
if (valid === 0) {
return {
count: missing,
missing,
min: NaN,
max: NaN,
mean: NaN,
hist,
maxBin: 0,
};
}
return {
count: length,
min,
max,
mean: sum / valid,
missing,
hist,
maxBin: hist.reduce((a, b) => Math.max(a, b.count), 0),
};
};
return { push, build, pushAll: pushAll(push) };
}
/**
* guesses the histogram granularity to use based on min and max date
*/
function computeGranularity(
min: Date | null,
max: Date | null
): { histGranularity: IDateHistGranularity; hist: IDateBin[] } {
if (min == null || max == null) {
return { histGranularity: 'year', hist: [] };
}
const hist: IDateBin[] = [];
if (max.getFullYear() - min.getFullYear() >= 2) {
// more than two years difference
const minYear = min.getFullYear();
const maxYear = max.getFullYear();
for (let i = minYear; i <= maxYear; ++i) {
hist.push({
x0: new Date(i, 0, 1),
x1: new Date(i + 1, 0, 1),
count: 0,
});
}
return { hist, histGranularity: 'year' };
}
if (max.getTime() - min.getTime() <= 1000 * 60 * 60 * 24 * 31) {
// less than a month use day
let x0 = new Date(min.getFullYear(), min.getMonth(), min.getDate());
while (x0 <= max) {
const x1 = new Date(x0);
x1.setDate(x1.getDate() + 1);
hist.push({
x0,
x1,
count: 0,
});
x0 = x1;
}
return { hist, histGranularity: 'day' };
}
// by month
let x0 = new Date(min.getFullYear(), min.getMonth(), 1);
while (x0 <= max) {
const x1 = new Date(x0);
x1.setMonth(x1.getMonth() + 1);
hist.push({
x0,
x1,
count: 0,
});
x0 = x1;
}
return { hist, histGranularity: 'month' };
}
function pushDateHist(hist: IDateBin[], v: Date, count = 1) {
if (v < hist[0].x1) {
hist[0].count += count;
return;
}
const l = hist.length - 1;
if (v > hist[l].x0) {
hist[l].count += count;
return;
}
if (l === 2) {
hist[1].count += count;
return;
}
let low = 1;
let high = l;
// binary search
while (low < high) {
const center = Math.floor((high + low) / 2);
if (v < hist[center].x1) {
high = center;
} else {
low = center + 1;
}
}
hist[low].count += count;
}
/**
* @internal
*/
export function dateStatsBuilder(template?: IDateStatistics): IBuilder<Date | null, IDateStatistics> {
let min: Date | null = null;
let max: Date | null = null;
let count = 0;
let missing = 0;
// yyyymmdd, count
const byDay = new Map<number, { x: Date; count: number }>();
const templateHist = template ? template.hist.map((d) => ({ x0: d.x0, x1: d.x1, count: 0 })) : null;
const push = (v: Date | null) => {
count += 1;
if (!v || v == null) {
missing += 1;
return;
}
if (min == null || v < min) {
min = v;
}
if (max == null || v > max) {
max = v;
}
if (templateHist) {
pushDateHist(templateHist, v, 1);
return;
}
const key = v.getFullYear() * 10000 + v.getMonth() * 100 + v.getDate();
if (byDay.has(key)) {
byDay.get(key)!.count++;
} else {
byDay.set(key, { count: 1, x: v });
}
};
const build = () => {
if (templateHist) {
return {
min,
max,
missing,
count,
maxBin: templateHist.reduce((acc, h) => Math.max(acc, h.count), 0),
hist: templateHist,
histGranularity: template!.histGranularity,
};
}
// copy template else derive
const { histGranularity, hist } = computeGranularity(min, max);
byDay.forEach((v) => pushDateHist(hist, v.x, v.count));
return {
min,
max,
missing,
count,
maxBin: hist.reduce((acc, h) => Math.max(acc, h.count), 0),
hist,
histGranularity,
};
};
return { push, build, pushAll: pushAll(push) };
}
/**
* computes a categorical histogram
* @param arr the data array
* @param categories the list of known categories
* @returns {{hist: {cat: string, y: number}[]}}
* @internal
*/
export function categoricalStatsBuilder(
categories: { name: string }[]
): IBuilder<{ name: string } | null, ICategoricalStatistics> {
const m = new Map<string, ICategoricalBin>();
categories.forEach((cat) => m.set(cat.name, { cat: cat.name, count: 0 }));
let missing = 0;
let count = 0;
const push = (v: ICategory | null) => {
count += 1;
if (v == null) {
missing += 1;
} else {
const entry = m.get(v.name);
if (entry) {
entry.count++;
} else {
m.set(v.name, { cat: v.name, count: 1 });
}
}
};
const build = () => {
const entries: ICategoricalBin[] = categories.map((d) => m.get(d.name)!);
const maxBin = entries.reduce((a, b) => Math.max(a, b.count), Number.NEGATIVE_INFINITY);
return {
maxBin,
hist: entries,
count,
missing,
};
};
return { push, build, pushAll: pushAll(push) };
}
/**
* computes a string statistics
* @internal
*/
export function stringStatsBuilder(topN: number | readonly string[]): IBuilder<string | null, IStringStatistics> {
let missing = 0;
let count = 0;
const m = new Map<string, { value: string; count: number }>();
if (Array.isArray(topN)) {
for (const t of topN) {
m.set(t, { value: t, count: 0 });
}
}
const push = (v: string | null) => {
count += 1;
if (v == null) {
missing += 1;
} else {
const entry = m.get(v);
if (entry) {
entry.count++;
} else {
m.set(v, { value: v, count: 1 });
}
}
};
const build = (): IStringStatistics => {
const byFrequency = Array.isArray(topN)
? topN.map((d) => m.get(d)!)
: Array.from(m.values()).sort((a, b) => {
if (a.count === b.count) {
return a.value.localeCompare(b.value);
}
return b.count - a.count;
});
return {
count,
missing,
topN: byFrequency.slice(0, Math.min(byFrequency.length, Array.isArray(topN) ? topN.length : (topN as number))),
unique: m.size,
};
};
return { push, build, pushAll: pushAll(push) };
}
/**
* round to the given commas similar to d3.round
* @param {number} v
* @param {number} precision
* @returns {number}
* @internal
*/
export function round(v: number, precision = 0) {
if (precision === 0) {
return Math.round(v);
}
const scale = Math.pow(10, precision);
return Math.round(v * scale) / scale;
}
/**
* compares two number whether they are similar up to delta
* @param {number} a first number
* @param {number} b second number
* @param {number} delta
* @returns {boolean} a and b are similar
* @internal
*/
export function similar(a: number, b: number, delta = 0.5) {
if (a === b) {
return true;
}
return Math.abs(a - b) < delta;
}
/**
* @internal
*/
export function isPromiseLike<T>(value: any): value is PromiseLike<T> {
return value instanceof Promise || typeof value.then === 'function';
}
/**
* @internal
*/
export function createIndexArray(length: number, dataSize = length) {
if (dataSize <= 255) {
return new Uint8Array(length);
}
if (dataSize <= 65535) {
return new Uint16Array(length);
}
return new Uint32Array(length);
}
/**
* @internal
*/
export function toIndexArray(arr: ISequence<number> | IndicesArray, maxDataIndex?: number): UIntTypedArray {
if (arr instanceof Uint8Array || arr instanceof Uint16Array || arr instanceof Uint32Array) {
return arr.slice();
}
const l = maxDataIndex != null ? maxDataIndex : arr.length;
if (l <= 255) {
return Uint8Array.from(arr);
}
if (l <= 65535) {
return Uint16Array.from(arr);
}
return Uint32Array.from(arr);
}
function createLike(template: IndicesArray, total: number, maxDataIndex?: number) {
if (template instanceof Uint8Array) {
return new Uint8Array(total);
}
if (template instanceof Uint16Array) {
return new Uint16Array(total);
}
if (template instanceof Uint32Array) {
return new Uint32Array(total);
}
return createIndexArray(total, maxDataIndex);
}
/**
* @internal
*/
export function joinIndexArrays(groups: IndicesArray[], maxDataIndex?: number) {
switch (groups.length) {
case 0:
return [];
case 1:
return groups[0];
default:
const total = groups.reduce((a, b) => a + b.length, 0);
const r = createLike(groups[0], total, maxDataIndex);
let shift = 0;
for (const g of groups) {
r.set(g, shift);
shift += g.length;
}
return r;
}
}
function asc(a: any, b: any) {
return a < b ? -1 : a > b ? 1 : 0;
}
function desc(a: any, b: any) {
return a < b ? 1 : a > b ? -1 : 0;
}
export declare type ILookUpArray =
| Uint8Array
| Uint16Array
| Uint32Array
| Int8Array
| Int16Array
| Int32Array
| string[]
| Float32Array
| Float64Array;
/**
* sort the given index array based on the lookup array
* @internal
*/
export function sortComplex(indices: UIntTypedArray | number[], comparators: { asc: boolean; lookup: ILookUpArray }[]) {
if (indices.length < 2) {
return indices;
}
switch (comparators.length) {
case 0:
// sort by indices
return indices.sort();
case 1:
const c = comparators[0]!.asc ? asc : desc;
const cLookup = comparators[0]!.lookup;
return indices.sort((a, b) => {
const r = c(cLookup[a]!, cLookup[b]!);
return r !== 0 ? r : a - b;
});
case 2:
const c1 = comparators[0]!.asc ? asc : desc;
const c1Lookup = comparators[0]!.lookup;
const c2 = comparators[1]!.asc ? asc : desc;
const c2Lookup = comparators[1]!.lookup;
return indices.sort((a, b) => {
let r = c1(c1Lookup[a], c1Lookup[b]);
r = r !== 0 ? r : c2(c2Lookup[a], c2Lookup[b]);
return r !== 0 ? r : a - b;
});
default:
const l = comparators.length;
const fs = comparators.map((d) => (d.asc ? asc : desc));
return indices.sort((a, b) => {
for (let i = 0; i < l; ++i) {
const l = comparators[i].lookup;
const r = fs[i](l[a], l[b]);
if (r !== 0) {
return r;
}
}
return a - b;
});
}
}
// note the whole worker thing is in this one file to be able to copy the code
/**
* base worker message
* @internal
*/
export interface IWorkerMessage {
type: string;
uid: number;
}
/**
* @internal
*/
export interface IStatsWorkerMessage extends IWorkerMessage {
/**
* reference key for the indices array
*/
refIndices: string | null;
indices?: UIntTypedArray;
/**
* reference key for the data indices
*/
refData: string;
data?: UIntTypedArray | Float32Array | Int32Array | Float64Array | readonly string[];
}
/**
* @internal
*/
export interface ISortMessageRequest {
type: 'sort';
uid: number;
ref: string;
indices: UIntTypedArray;
sortOrders?: { asc: boolean; lookup: ILookUpArray }[];
}
/**
* @internal
*/
export interface ISortMessageResponse {
type: 'sort';
ref: string;
order: IndicesArray;
}
/**
* @internal
*/
export interface IDeleteRefMessageRequest {
type: 'deleteRef';
ref: string;
startsWith?: boolean;
}
/**
* @internal
*/
export interface ISetRefMessageRequest {
type: 'setRef';
uid: number;
ref: string;
data: UIntTypedArray | Float32Array | Int32Array | Float64Array | readonly string[] | null;
}
/**
* @internal
*/
export interface IDateStatsMessageRequest {
type: 'dateStats';
uid: number;
refIndices: string | null;
indices?: UIntTypedArray;
refData: string;
data?: UIntTypedArray;
template?: IDateStatistics;
}
/**
* @internal
*/
export interface IDateStatsMessageResponse {
type: 'dateStats';
uid: number;
stats: IDateStatistics;
}
/**
* @internal
*/
export interface INumberStatsMessageRequest {
type: 'numberStats';
uid: number;
refIndices: string | null;
indices?: UIntTypedArray;
refData: string;
data?: Float32Array;
domain: [number, number];
numberOfBins: number;
}
/**
* @internal
*/
export interface INumberStatsMessageResponse {
type: 'numberStats';
uid: number;
stats: IStatistics;
}
/**
* @internal
*/
export interface IBoxPlotStatsMessageRequest {
type: 'boxplotStats';
uid: number;
refIndices: string | null;
indices?: UIntTypedArray;
refData: string;
data?: Float32Array;
}
/**
* @internal
*/
export interface IBoxPlotStatsMessageResponse {
type: 'boxplotStats';
uid: number;
stats: IAdvancedBoxPlotData;
}
/**
* @internal
*/
export interface ICategoricalStatsMessageRequest {
type: 'categoricalStats';
uid: number;
refIndices: string | null;
indices?: UIntTypedArray;
refData: string;
data?: UIntTypedArray;
categories: string[];
}
/**
* @internal
*/
export interface ICategoricalStatsMessageResponse {
type: 'categoricalStats';
uid: number;
stats: ICategoricalStatistics;
}
/**
* @internal
*/
export interface IStringStatsMessageRequest {
type: 'stringStats';
uid: number;
refIndices: string | null;
indices?: UIntTypedArray;
refData: string;
data?: readonly string[];
topN: number | readonly string[];
}
/**
* @internal
*/
export interface IStringStatsMessageResponse {
type: 'stringStats';
uid: number;
stats: IStringStatistics;
}
/**
* helper to build a value cache for dates, use dateValueCache2Value to convert back
* @internal
*/
export function dateValueCacheBuilder(length: number) {
const vs = new Float64Array(length);
let i = 0;
return {
push: (d: Date | null) => (vs[i++] = d == null ? NaN : d.getTime()),
cache: vs,
};
}
/**
* @internal
*/
export function dateValueCache2Value(v: number) {
return Number.isNaN(v) ? null : new Date(v);
}
/**
* @internal
*/
export function categoricalValueCacheBuilder(length: number, categories: { name: string }[]) {
const vs = createIndexArray(length, categories.length + 1);
const name2index = new Map<string, number>();
for (let i = 0; i < categories.length; ++i) {
name2index.set(categories[i].name, i + 1); // shift by one for missing = 0
}
let i = 0;
return {
push: (d: { name: string } | null) => (vs[i++] = d == null ? 0 : name2index.get(d.name) || 0),
cache: vs,
};
}
/**
* @internal
*/
export function categoricalValueCache2Value<T extends { name: string }>(v: number, categories: T[]) {
return v === 0 ? null : categories[v - 1];
}
function sortWorkerMain() {
// eslint-disable-next-line no-restricted-globals
const workerSelf = self as any as IPoorManWorkerScope;
// stored refs to avoid duplicate copy
const refs = new Map<string, UIntTypedArray | Float32Array | Int32Array | Float64Array | readonly string[]>();
const sort = (r: ISortMessageRequest) => {
if (r.sortOrders) {
sortComplex(r.indices, r.sortOrders);
}
const order = r.indices;
workerSelf.postMessage(
{
type: r.type,
uid: r.uid,
ref: r.ref,
order,
} as ISortMessageResponse,
[r.indices.buffer]
);
};
const setRef = (r: ISetRefMessageRequest) => {
if (r.data) {
refs.set(r.ref, r.data);
} else {
refs.delete(r.ref);
}
};
const deleteRef = (r: IDeleteRefMessageRequest) => {
if (!r.startsWith) {
refs.delete(r.ref);
return;
}
for (const key of Array.from(refs.keys())) {
if (key.startsWith(r.ref)) {
refs.delete(key);
}
}
};
const resolveRefs = <T extends UIntTypedArray | Float32Array | Int32Array | readonly string[]>(
r: IStatsWorkerMessage
) => {
// resolve refs or save the new data
const data: T = r.data ? (r.data as any as T) : (refs.get(r.refData)! as any as T);
const indices = r.indices ? r.indices : r.refIndices ? (refs.get(r.refIndices)! as UIntTypedArray) : undefined;
if (r.refData) {
refs.set(r.refData, data);
}
if (r.refIndices) {
refs.set(r.refIndices, indices!);
}
return { data, indices };
};
const dateStats = (r: IDateStatsMessageRequest) => {
const { data, indices } = resolveRefs<Int32Array>(r);
const b = dateStatsBuilder(r.template);
if (indices) {
for (let ii = 0; ii < indices.length; ++ii) {
const v = data[indices[ii]];
b.push(dateValueCache2Value(v));
}
} else {
for (let i = 0; i < data.length; ++i) {
b.push(dateValueCache2Value(data[i]));
}
}
workerSelf.postMessage({
type: r.type,
uid: r.uid,
stats: b.build(),
} as IDateStatsMessageResponse);
};
const categoricalStats = (r: ICategoricalStatsMessageRequest) => {
const { data, indices } = resolveRefs<UIntTypedArray>(r);
const cats = r.categories.map((name) => ({ name }));
const b = categoricalStatsBuilder(cats);
if (indices) {
for (let ii = 0; ii < indices.length; ++ii) {
b.push(categoricalValueCache2Value(data[indices[ii]], cats));
}
} else {
for (let i = 0; i < data.length; ++i) {
b.push(categoricalValueCache2Value(data[i], cats));
}
}
workerSelf.postMessage({
type: r.type,
uid: r.uid,
stats: b.build(),
} as ICategoricalStatsMessageResponse);
};
const stringStats = (r: IStringStatsMessageRequest) => {
const { data, indices } = resolveRefs<readonly string[]>(r);
const b = stringStatsBuilder(r.topN ?? 10);
if (indices) {
for (let ii = 0; ii < indices.length; ++ii) {
b.push(data[indices[ii]]);
}
} else {
for (let i = 0; i < data.length; ++i) {
b.push(data[i]);
}
}
workerSelf.postMessage({
type: r.type,
uid: r.uid,
stats: b.build(),
} as IStringStatsMessageResponse);
};
const numberStats = (r: INumberStatsMessageRequest) => {
const { data, indices } = resolveRefs<Float32Array>(r);
const b = numberStatsBuilder(r.domain ?? [0, 1], r.numberOfBins);
if (indices) {
for (let ii = 0; ii < indices.length; ++ii) {
b.push(data[indices[ii]]);
}
} else {
for (let i = 0; i < data.length; ++i) {
b.push(data[i]);
}
}
workerSelf.postMessage({
type: r.type,
uid: r.uid,
stats: b.build(),
} as INumberStatsMessageResponse);
};
const boxplotStats = (r: IBoxPlotStatsMessageRequest) => {
const { data, indices } = resolveRefs<Float32Array>(r);
const b = boxplotBuilder(indices ? indices.length : undefined);
let stats: IAdvancedBoxPlotData;
if (!indices) {
stats = b.buildArr(data);
} else {
for (let ii = 0; ii < indices.length; ++ii) {
b.push(data[indices[ii]]);
}
stats = b.build();
}
workerSelf.postMessage({
type: r.type,
uid: r.uid,
stats,
} as IBoxPlotStatsMessageResponse);
};
// message type to handler function
const msgHandlers: { [key: string]: (r: any) => void } = {
sort,
setRef,
deleteRef,
dateStats,
categoricalStats,
numberStats,
boxplotStats,
stringStats,
};
workerSelf.addEventListener('message', (evt) => {
const r = evt.data;
if (typeof r.uid !== 'number' || typeof r.type !== 'string') {
return;
}
const h = msgHandlers[r.type];
if (h) {
h(r);
}
});
}
/**
* copy source code of a worker and create a blob out of it
* to avoid webpack imports all the code functions need to be in this file
* @internal
*/
export function createWorkerBlob() {
return createWorkerCodeBlob([
pushAll.toString(),
quantile.toString(),
numberStatsBuilder.toString(),
boxplotBuilder.toString(),
computeGranularity.toString(),
pushDateHist.toString(),
dateStatsBuilder.toString(),
categoricalStatsBuilder.toString(),
stringStatsBuilder.toString(),
createIndexArray.toString(),
asc.toString(),
desc.toString(),
sortComplex.toString(),
dateValueCache2Value.toString(),
categoricalValueCache2Value.toString(),
toFunctionBody(sortWorkerMain),
]);
} | the_stack |
import * as numbers from "./magic_numbers";
import {PageIndicator} from "./support_menus/PageIndicator";
import * as utils from "./utils";
/**
* The type that holds some basic info about
* any kind of text that is set in a window.
*/
export type TextObj = {
text: Phaser.BitmapText;
shadow: Phaser.BitmapText;
right_align: boolean;
initial_x: number;
text_bg?: Phaser.Graphics;
};
/**
* The type that holds info about an icon
* that is on a window like the icon sprite by
* itself, broken and equipped indication graphics
* etc.
*/
export type ItemObj = {
icon: Phaser.Sprite;
background?: Phaser.Sprite;
equipped?: Phaser.Sprite;
broken?: Phaser.Sprite;
quantity?: Phaser.BitmapText;
};
/**
* A basic window template used in most menus.
* Creates the background and borders.
* Supports the addition of sprites, texts, and custom groups.
* Supports pagination indication, text manipulation and also
* icons positioning.
*/
export class Window {
private static readonly DEFAULT_WINDOW_COLOR = 0x006080;
private static readonly BG_SHIFT = 2;
private static readonly MIND_READ_WINDOW_COLOR = 0xffffff;
public static readonly MIND_READ_FONT_COLOR = 0x0000f8;
private static readonly MIND_READ_AMPLITUDE = 4;
private static readonly MIND_READ_PERIOD = 20;
private static readonly MIND_READ_CORNER_RADIUS = 12;
private static readonly MIND_READ_WAVE_SPEED = 0.005;
private static readonly TRANSITION_TIME = Phaser.Timer.QUARTER >> 2;
private static readonly ITEM_OBJ = {
EQUIPPED_X: 7,
EQUIPPED_Y: 8,
QUANTITY_END_X: 15,
QUANTITY_Y: 8,
};
private game: Phaser.Game;
private _group: Phaser.Group;
private _x: number;
private _y: number;
private _width: number;
private _height: number;
private _color: number;
private _font_color: number;
private _mind_read_window: boolean;
private border_graphics: Phaser.Graphics;
private bg_graphics: Phaser.Graphics;
private separators_graphics: Phaser.Graphics;
private _open: boolean;
private extra_sprites: (Phaser.Sprite | Phaser.Graphics | Phaser.BitmapText | Phaser.Group)[];
private internal_groups: {[key: string]: Phaser.Group};
private close_callback: () => void;
private _page_indicator: PageIndicator;
private _mind_read_time: number;
private _mind_read_borders: {
left: Phaser.BitmapData;
right: Phaser.BitmapData;
};
constructor(
game: Phaser.Game,
x: number,
y: number,
width: number,
height: number,
color?: number,
font_color?: number,
mind_read_window: boolean = false
) {
this.game = game;
this._group = game.add.group();
this._x = x;
this._y = y;
this._width = width;
this._height = height;
this._mind_read_window = mind_read_window;
this._color = color ?? (this._mind_read_window ? Window.MIND_READ_WINDOW_COLOR : Window.DEFAULT_WINDOW_COLOR);
this._font_color =
font_color ?? (this._mind_read_window ? Window.MIND_READ_FONT_COLOR : numbers.DEFAULT_FONT_COLOR);
this.extra_sprites = [];
this.internal_groups = {};
this.bg_graphics = this.game.add.graphics(0, 0);
this.draw_background();
this.group.add(this.bg_graphics);
if (this._mind_read_window) {
this.init_mind_read_borders();
this._mind_read_time = 0;
} else {
this.separators_graphics = this.game.add.graphics(0, 0);
this.border_graphics = this.game.add.graphics(0, 0);
this.draw_borders();
this.group.add(this.border_graphics);
this.group.add(this.separators_graphics);
}
this.group.visible = false;
this.group.width = 0;
this.group.height = 0;
this._open = false;
this._page_indicator = new PageIndicator(this.game, this);
}
get color() {
return this._color;
}
get font_color() {
return this._font_color;
}
get x() {
return this._x;
}
get y() {
return this._y;
}
get width() {
return this._width;
}
get height() {
return this._height;
}
get group() {
return this._group;
}
get page_indicator() {
return this._page_indicator;
}
get open() {
return this._open;
}
get real_x() {
return this.group.x;
}
get real_y() {
return this.group.y;
}
/**
* Creates in this window an item object. An item object is a internal window group
* that contains the item icon, the item quantity, the graphics for a broken item,
* the equip graphics indication and the item background graphics (like in shops).
* @param key_name the item key name.
* @param pos the item object position.
* @param params some optional parameters.
* @returns returns the item object.
*/
make_item_obj(
key_name: string,
pos?: {x: number; y: number},
params?: {
/** Whether this item obj. has a background graphics (like in shops). */
bg?: boolean;
/** Whether this item obj. should show the equipped indication graphics. */
equipped?: boolean;
/** Whether this item obj. should show the broken item graphics. */
broken?: boolean;
/** Shows the quatity indicator graphics if the given quantity is bigger than 1. */
quantity?: number;
/** The window internal group key. If using params arg, this key must be passed. */
internal_group: string;
/** Whether the icon positioning should be relative to item obj. center. */
center?: boolean;
}
) {
const obj: ItemObj = {icon: null, background: null, equipped: null, broken: null, quantity: null};
const base_x = pos ? pos.x : 0;
const base_y = pos ? pos.y : 0;
if (params) {
if (params.bg) {
obj.background = this.create_at_group(base_x, base_y, "menu", {
frame: "item_border",
internal_group_key: params.internal_group,
});
}
obj.icon = this.create_at_group(base_x, base_y, "items_icons", {
frame: key_name,
internal_group_key: params.internal_group,
});
if (params.center) {
obj.icon.anchor.setTo(0.5, 0.5);
}
if (params.broken) {
obj.broken = this.create_at_group(base_x, base_y, "menu", {
frame: "broken",
internal_group_key: params.internal_group,
});
if (params.center) {
obj.broken.anchor.setTo(0.5, 0.5);
}
}
const shift = params.center ? -(numbers.ICON_WIDTH >> 1) : 0;
if (params.equipped) {
obj.equipped = this.create_at_group(
base_x + Window.ITEM_OBJ.EQUIPPED_X + shift,
base_y + Window.ITEM_OBJ.EQUIPPED_Y + shift,
"menu",
{
frame: "equipped",
internal_group_key: params.internal_group,
}
);
}
if (params.quantity && params.quantity > 1) {
obj.quantity = this.game.add.bitmapText(
base_x + Window.ITEM_OBJ.QUANTITY_END_X + shift,
base_y + Window.ITEM_OBJ.QUANTITY_Y + shift,
"gs-item-bmp-font",
params.quantity.toString()
);
obj.quantity.x -= obj.quantity.width;
if (params.internal_group) {
this.add_to_internal_group(params.internal_group, obj.quantity);
} else {
this.group.add(obj.quantity);
}
}
} else {
obj.icon = this.create_at_group(base_x, base_y, "items_icons", {frame: key_name});
}
return obj;
}
/**
* Moves an item object in the window.
* @param item_obj The item object.
* @param new_pos The coordinates of the new position.
*/
move_item_obj(item_obj: ItemObj, new_pos: {x: number; y: number}) {
for (let obj in item_obj) {
if (item_obj[obj]) {
item_obj[obj].x = new_pos.x;
item_obj[obj].y = new_pos.y;
if (obj === "equipped") {
item_obj[obj].x += Window.ITEM_OBJ.EQUIPPED_X;
item_obj[obj].y += Window.ITEM_OBJ.EQUIPPED_Y;
} else if (obj === "quantity") {
item_obj[obj].x += Window.ITEM_OBJ.QUANTITY_END_X - item_obj[obj].width;
item_obj[obj].y += Window.ITEM_OBJ.QUANTITY_Y;
}
}
}
}
/**
* Brings the border graphics to top position in window group.
*/
bring_border_to_top() {
this.group.bringToTop(this.border_graphics);
}
/**
* Removes existing separator graphics.
*/
clear_separators() {
this.separators_graphics.clear();
}
/**
* Draws separator graphics in the window. These are created by changing the brightness of the background.
* @param x_0 Initial x line separator position.
* @param y_0 Initial y line separator position.
* @param x_1 Final x line separator position.
* @param y_1 Final y line separator position.
* @param vertical if true, the separator is a vertical line, otherwise horizontal.
*/
draw_separator(x_0: number, y_0: number, x_1: number, y_1: number, vertical = true) {
const lighter = utils.change_brightness(this.color, 1.3);
const darker = utils.change_brightness(this.color, 0.8);
const medium = utils.change_brightness(this.color, 0.9);
const colors = [medium, darker, lighter];
for (let i = 0; i < colors.length; ++i) {
const color = colors[i];
const shift = i - 1;
this.separators_graphics.lineStyle(1, color);
this.separators_graphics.moveTo(x_0 + shift * +vertical, y_0 + shift * +!vertical);
this.separators_graphics.lineTo(x_1 + shift * +vertical, y_1 + shift * +!vertical);
}
}
/**
* Creates the window background.
* Fills the window's space with the window color.
*/
private draw_background() {
this.bg_graphics.beginFill(this.color, 1);
if (this._mind_read_window) {
this.bg_graphics.drawRoundedRect(
Window.BG_SHIFT,
Window.BG_SHIFT,
this.width,
this.height,
Window.MIND_READ_CORNER_RADIUS
);
} else {
this.bg_graphics.drawRect(Window.BG_SHIFT, Window.BG_SHIFT, this.width, this.height);
}
this.bg_graphics.endFill();
}
/**
* Initializes the waving borders of the mind read window.
*/
init_mind_read_borders() {
this._mind_read_borders = {
right: null,
left: null,
};
const left_img = this.game.add.image(0, 0);
this.group.addChild(left_img);
left_img.x = -(Window.MIND_READ_AMPLITUDE << 1) + Window.BG_SHIFT;
left_img.y = Window.BG_SHIFT;
const width = Window.MIND_READ_AMPLITUDE << 2;
this._mind_read_borders.left = this.game.add.bitmapData(width, this.height);
this._mind_read_borders.left.smoothed = false;
this._mind_read_borders.left.add(left_img);
const right_img = this.game.add.image(0, 0);
this.group.addChild(right_img);
right_img.x = this.width - (Window.MIND_READ_AMPLITUDE << 1) + Window.BG_SHIFT;
right_img.y = Window.BG_SHIFT;
this._mind_read_borders.right = this.game.add.bitmapData(width, this.height);
this._mind_read_borders.right.smoothed = false;
this._mind_read_borders.right.add(right_img);
}
/**
* Updates the waving borders of the mind read window.
*/
update_mind_read_borders() {
const color = utils.hex2rgb(this.color);
this._mind_read_borders.left.clear();
this._mind_read_borders.right.clear();
this._mind_read_time += this.game.time.elapsedMS * Window.MIND_READ_WAVE_SPEED;
const k = (2 * Math.PI) / Window.MIND_READ_PERIOD;
const height = this._mind_read_borders.left.height;
const half_radius = Window.MIND_READ_CORNER_RADIUS >> 1;
const quad_amplitude = Window.MIND_READ_AMPLITUDE << 2;
const corner_ratio = half_radius / height;
for (let x = 0; x < this._mind_read_borders.left.width; ++x) {
for (let y = 0; y < height; ++y) {
const y_ratio = y / height;
let shift = 0;
if (y_ratio <= corner_ratio) {
const border_ratio = Phaser.Easing.Cubic.Out(y / half_radius);
shift = quad_amplitude * (1 - border_ratio);
} else if (y_ratio >= 1 - corner_ratio) {
const border_ratio = Phaser.Easing.Cubic.Out((height - y) / half_radius);
shift = quad_amplitude * (1 - border_ratio);
}
const wave_x =
Window.MIND_READ_AMPLITUDE * Math.sin(-k * y - this._mind_read_time) + Window.MIND_READ_AMPLITUDE;
const l_wave_x = wave_x + shift;
const r_wave_x = wave_x - shift + (Window.MIND_READ_AMPLITUDE << 1);
if (l_wave_x >= x) {
this._mind_read_borders.left.setPixel32(x, y, 0, 0, 0, 0, false);
} else {
this._mind_read_borders.left.setPixel32(x, y, color.r, color.g, color.b, 255, false);
}
if (r_wave_x >= x) {
this._mind_read_borders.right.setPixel32(x, y, color.r, color.g, color.b, 255, false);
} else {
this._mind_read_borders.right.setPixel32(x, y, 0, 0, 0, 0, false);
}
}
}
this._mind_read_borders.left.context.putImageData(this._mind_read_borders.left.imageData, 0, 0);
this._mind_read_borders.right.context.putImageData(this._mind_read_borders.right.imageData, 0, 0);
}
/**
* Draws the window borders.
* Lines are drawn to create the borders, including corners.
* Colors used:
* 0xFFFFFF = White,
* 0xA5A5A5 = Gray (Lighter),
* 0x525252 = Gray (Darker),
* 0x111111 = Black.
*/
private draw_borders() {
//Left
this.border_graphics.lineStyle(1, 0x525252);
this.border_graphics.moveTo(0, 1);
this.border_graphics.lineTo(0, this.height + 1);
this.border_graphics.lineStyle(1, 0xffffff);
this.border_graphics.moveTo(1, 1);
this.border_graphics.lineTo(1, this.height + 1);
this.border_graphics.lineStyle(1, 0xa5a5a5);
this.border_graphics.moveTo(2, 1);
this.border_graphics.lineTo(2, this.height);
this.border_graphics.lineStyle(1, 0x111111);
this.border_graphics.moveTo(3, 3);
this.border_graphics.lineTo(3, this.height - 1);
//Right
this.border_graphics.lineStyle(1, 0x525252);
this.border_graphics.moveTo(this.width, 2);
this.border_graphics.lineTo(this.width, this.height);
this.border_graphics.lineStyle(1, 0xa5a5a5);
this.border_graphics.moveTo(this.width + 2, 1);
this.border_graphics.lineTo(this.width + 2, this.height + 1);
this.border_graphics.lineStyle(1, 0xffffff);
this.border_graphics.moveTo(this.width + 1, 1);
this.border_graphics.lineTo(this.width + 1, this.height);
this.border_graphics.lineStyle(1, 0x111111);
this.border_graphics.moveTo(this.width + 3, 1);
this.border_graphics.lineTo(this.width + 3, this.height + 1);
//Up
this.border_graphics.lineStyle(1, 0x525252);
this.border_graphics.moveTo(2, 0);
this.border_graphics.lineTo(this.width + 2, 0);
this.border_graphics.lineStyle(1, 0xffffff);
this.border_graphics.moveTo(2, 1);
this.border_graphics.lineTo(this.width + 2, 1);
this.border_graphics.lineStyle(1, 0xa5a5a5);
this.border_graphics.moveTo(3, 2);
this.border_graphics.lineTo(this.width + 1, 2);
this.border_graphics.lineStyle(1, 0x111111);
this.border_graphics.moveTo(3, 3);
this.border_graphics.lineTo(this.width, 3);
//Down
this.border_graphics.lineStyle(1, 0x525252);
this.border_graphics.moveTo(3, this.height);
this.border_graphics.lineTo(this.width, this.height);
this.border_graphics.lineStyle(1, 0xffffff);
this.border_graphics.moveTo(2, this.height + 1);
this.border_graphics.lineTo(this.width + 2, this.height + 1);
this.border_graphics.lineStyle(1, 0xa5a5a5);
this.border_graphics.moveTo(2, this.height + 2);
this.border_graphics.lineTo(this.width + 2, this.height + 2);
this.border_graphics.lineStyle(1, 0x111111);
this.border_graphics.moveTo(2, this.height + 3);
this.border_graphics.lineTo(this.width + 2, this.height + 3);
//Corners
this.border_graphics.lineStyle(1, 0x525252);
this.border_graphics.moveTo(1, 1);
this.border_graphics.lineTo(2, 2);
this.border_graphics.lineStyle(1, 0x525252);
this.border_graphics.moveTo(1, this.height + 2);
this.border_graphics.lineTo(2, this.height + 3);
this.border_graphics.lineStyle(1, 0x525252);
this.border_graphics.moveTo(this.width + 2, this.height + 2);
this.border_graphics.lineTo(this.width + 3, this.height + 3);
this.border_graphics.lineStyle(1, 0x525252);
this.border_graphics.moveTo(this.width + 2, 1);
this.border_graphics.lineTo(this.width + 3, 2);
this.border_graphics.lineStyle(1, 0x111111);
this.border_graphics.moveTo(4, 4);
this.border_graphics.lineTo(5, 5);
this.border_graphics.lineStyle(1, 0x525252);
this.border_graphics.moveTo(3, 3);
this.border_graphics.lineTo(4, 4);
this.border_graphics.lineStyle(1, 0x525252);
this.border_graphics.moveTo(this.width - 1, this.height - 1);
this.border_graphics.lineTo(this.width, this.height);
this.border_graphics.lineStyle(1, 0x111111);
this.border_graphics.moveTo(this.width - 1, 4);
this.border_graphics.lineTo(this.width, 5);
this.border_graphics.lineStyle(1, 0x111111);
this.border_graphics.moveTo(4, this.height - 1);
this.border_graphics.lineTo(5, this.height);
}
/**
* Changes the window's size and redraws it.
* @param new_size The new width and height parameters.
*/
update_size(new_size: {width?: number; height?: number}) {
if (new_size.width !== undefined) {
this._width = new_size.width;
}
if (new_size.height !== undefined) {
this._height = new_size.height;
}
this.bg_graphics.clear();
this.draw_background();
if (this._mind_read_window) {
} else {
this.border_graphics.clear();
this.draw_borders();
}
}
/**
* Changes the window's position.
* @param new_position The position's parameters.
* @param relative_to_camera_pos If true, moves the window by the x and y offset values.
*/
update_position(new_position: {x?: number; y?: number}, relative_to_camera_pos = true) {
if (new_position.x !== undefined) {
this._x = new_position.x;
}
if (new_position.y !== undefined) {
this._y = new_position.y;
}
this.group.x = (relative_to_camera_pos ? this.game.camera.x : 0) + this.x;
this.group.y = (relative_to_camera_pos ? this.game.camera.y : 0) + this.y;
}
/**
* Creates an internal group. A internal group is a Phaser.Group that can be
* retrieved by a key and is used to attach other sprites to this window.
* @param key The group's key.
* @param position The position object of the internal group.
* @returns Returns the internal group.
*/
define_internal_group(key: string, position: {x?: number; y?: number} = {}) {
const internal_group = this.game.add.group();
this.destroy_internal_group(key);
this.internal_groups[key] = internal_group;
if (position.x !== undefined) {
internal_group.x = position.x;
}
if (position.y !== undefined) {
internal_group.y = position.y;
}
this.group.add(internal_group);
return internal_group;
}
/**
* Returns an internal group.
* @param key The internal group key.
* @returns Returns an internal group.
*/
get_internal_group(key: string) {
return this.internal_groups[key];
}
/**
* Adds a sprite to an internal group.
* @param key The internal group key.
* @param sprite The sprite to be added.
* @returns True if the sprite was successfully added, false otherwise.
*/
add_to_internal_group(key: string, sprite: Phaser.Sprite | Phaser.Graphics | Phaser.BitmapText | Phaser.Group) {
if (key in this.internal_groups) {
this.internal_groups[key].add(sprite);
return true;
}
return false;
}
/**
* Destroys an internal group and its elements.
* @param key The internal group key.
*/
destroy_internal_group(key: string) {
if (key in this.internal_groups && this.internal_groups[key]) {
this.internal_groups[key].destroy(true);
delete this.internal_groups[key];
}
}
/**
* Destroy all internal groups of this window.
*/
destroy_all_internal_groups() {
const internal_group_keys = Object.keys(this.internal_groups);
for (let key of internal_group_keys) {
this.internal_groups[key].destroy(true);
delete this.internal_groups[key];
}
}
/**
* Displays this window.
* @param show_callback on window show callback.
* @param animate If true, plays an opening animation.
* @param close_callback on window close callback.
*/
show(show_callback?: () => void, animate = true, close_callback?: () => void) {
this.group.visible = true;
this.group.x = this.game.camera.x + this.x;
this.group.y = this.game.camera.y + this.y;
this.close_callback = close_callback;
if (animate) {
this.game.add
.tween(this.group.scale)
.to({x: 1, y: 1}, Window.TRANSITION_TIME, Phaser.Easing.Linear.None, true)
.onComplete.addOnce(() => {
this._open = true;
if (show_callback !== undefined) show_callback();
});
} else {
this._open = true;
this.group.scale.setTo(1, 1);
if (show_callback !== undefined) show_callback();
}
}
/**
* Updates the window position if necessary.
* @param force If true, forces an update.
*/
update() {
this.group.x = this.game.camera.x + this.x;
this.group.y = this.game.camera.y + this.y;
}
/**
* Adds a sprite to the main group of this window.
* @param sprite The sprite to be added.
*/
add_sprite_to_window_group(sprite: Phaser.Sprite | Phaser.Graphics | Phaser.BitmapText | Phaser.Group) {
this.group.add(sprite);
this.extra_sprites.push(sprite);
}
/**
* Creates a new sprite in the main group of this window.
* @param x the x position of the sprite.
* @param y the y position of the sprite.
* @param key the sprite key name.
* @param options some optional options.
* @returns Returns the added sprite.
*/
create_at_group(
x: number,
y: number,
key: string,
options?: {
/** The color of the sprite (tint property). */
color?: number;
/** The sprite frame name. */
frame?: string;
/** The internal group key in the case the sprite should be added in an internal group. */
internal_group_key?: string;
}
): Phaser.Sprite {
let group = this.group;
if (options?.internal_group_key !== undefined) {
const internal_group = this.get_internal_group(options.internal_group_key);
if (internal_group) {
group = internal_group;
}
}
const sprite = group.create(x, y, key, options?.frame);
if (options?.color !== undefined) {
sprite.tint = options.color;
}
this.extra_sprites.push(sprite);
return sprite;
}
/**
* Sends this window to the front of the screen.
*/
send_to_front() {
(this.group.parent as Phaser.Group).bringToTop(this.group);
}
/**
* Removes a sprite from the main group of this window.
* @param sprite The sprite to be removed.
* @param destroy If true, the sprite is destroyed.
*/
remove_from_this_window(
sprite?: Phaser.Sprite | Phaser.Graphics | Phaser.BitmapText | Phaser.Group,
destroy = true
) {
if (sprite !== undefined) {
this.group.remove(sprite, destroy);
} else {
for (let i = 0; i < this.extra_sprites.length; ++i) {
this.group.remove(this.extra_sprites[i], destroy);
}
}
}
/**
* Sets a text in a dialog manner in this window.
* @param lines The text lines (array of string).
* @param options some optional parameters.
* @returns Returns a promise that is resolved on animation finish.
*/
set_dialog_text(
lines: string[],
options?: {
/** The x internal padding text position. */
padding_x?: number;
/** The y internal padding text position. */
padding_y?: number;
/** A custom value for the space between text lines. */
space_between_lines?: number;
/** Whether the text is in italic. */
italic?: boolean;
/** Whether the text is displayed in a animated manner. */
animate?: boolean;
/** The font color. Can be an array of colors the indicates for each letter. */
colors?: number | number[][];
/** A callback the is called whenever a word is displayed in the window when animate is true. */
word_callback?: (word?: string, current_text?: string) => void;
}
) {
const top_shift = options?.italic ? -2 : 0;
const x_pos = options?.padding_x ?? numbers.WINDOW_PADDING_H + 4;
let y_pos = options?.padding_y ?? numbers.WINDOW_PADDING_TOP + top_shift;
const font_name = options?.italic ? utils.ITALIC_FONT_NAME : utils.FONT_NAME;
const lines_promises = [];
let anim_promise_resolve;
const anim_promise = options?.animate ? new Promise<void>(resolve => (anim_promise_resolve = resolve)) : null;
for (let i = 0; i < lines.length; ++i) {
const line = lines[i];
const text_sprite = this.game.add.bitmapText(
x_pos,
y_pos,
font_name,
options?.animate ? "" : line,
numbers.FONT_SIZE
);
let text_sprite_shadow: Phaser.BitmapText = null;
if (!this._mind_read_window) {
text_sprite_shadow = this.game.add.bitmapText(
x_pos + 1,
y_pos + 1,
font_name,
options?.animate ? "" : line,
numbers.FONT_SIZE
);
}
y_pos += numbers.FONT_SIZE + (options?.space_between_lines ?? numbers.SPACE_BETWEEN_LINES);
text_sprite.tint =
options?.colors !== undefined
? Array.isArray(options.colors)
? options.colors[i]
: options.colors
: this.font_color;
if (text_sprite_shadow) {
text_sprite_shadow.tint = 0x0;
}
if (options?.animate) {
const words = line.split(" ");
let words_index = 0;
let line_promise_resolve;
const repeater = () => {
this.game.time.events.repeat(30, words.length, () => {
text_sprite.text += words[words_index] + " ";
if (text_sprite_shadow) {
text_sprite_shadow.text += words[words_index] + " ";
}
++words_index;
if (options?.word_callback) {
options.word_callback(words[words_index], text_sprite.text);
}
if (words_index === words.length) {
line_promise_resolve();
}
});
};
if (!lines_promises.length) {
repeater();
} else {
lines_promises.pop().then(repeater);
}
lines_promises.push(new Promise(resolve => (line_promise_resolve = resolve)));
}
if (text_sprite_shadow) {
this.group.add(text_sprite_shadow);
}
this.group.add(text_sprite);
}
Promise.all(lines_promises).then(anim_promise_resolve);
return anim_promise;
}
/**
* Resets a text object to default position.
* @param text_obj The text object.
* @param italic Whether the text object is in italic.
*/
reset_text_position(text_obj: TextObj, italic: boolean = false) {
const x_pos = italic ? numbers.WINDOW_PADDING_H + 2 : numbers.WINDOW_PADDING_H + 4;
const y_pos = italic ? numbers.WINDOW_PADDING_TOP - 2 : numbers.WINDOW_PADDING_TOP;
text_obj.text.x = x_pos;
text_obj.text.y = y_pos;
if (text_obj.shadow) {
text_obj.shadow.x = x_pos + 1;
text_obj.shadow.y = y_pos + 1;
}
}
/**
* Creates a sprite to represent a text at a given location.
* @param text The text to display.
* @param x_pos The desired x postion. If not passed, default value will be assumed.
* @param y_pos The desired y postion. If not passed, default value will be assumed.
* @param options Some optional parameters.
* @returns Returns the resulting text object.
*/
set_text_in_position(
text: string,
x_pos?: number,
y_pos?: number,
options?: {
/** If true, the text will be right-aligned. */
right_align?: boolean;
/** If true, the text will be centered. */
is_center_pos?: boolean;
/** The text's desired color */
color?: number;
/** If true, gives the text a background shape. */
with_bg?: boolean;
/** If this exists, the text will belong to that group. */
internal_group_key?: string;
/** If true, the text will be italic. */
italic?: boolean;
}
): TextObj {
x_pos = x_pos ?? (options?.italic ? numbers.WINDOW_PADDING_H + 2 : numbers.WINDOW_PADDING_H + 4);
y_pos = y_pos ?? (options?.italic ? numbers.WINDOW_PADDING_TOP - 2 : numbers.WINDOW_PADDING_TOP);
const font_name = options?.italic ? utils.ITALIC_FONT_NAME : utils.FONT_NAME;
const text_sprite = this.game.add.bitmapText(x_pos, y_pos, font_name, text, numbers.FONT_SIZE);
let text_sprite_shadow: Phaser.BitmapText = null;
text_sprite_shadow = this.game.add.bitmapText(x_pos + 1, y_pos + 1, font_name, text, numbers.FONT_SIZE);
if (options?.is_center_pos) {
text_sprite.centerX = x_pos;
text_sprite.centerY = y_pos;
if (text_sprite_shadow) {
text_sprite_shadow.centerX = x_pos + 1;
text_sprite_shadow.centerY = y_pos + 1;
}
}
if (options?.right_align) {
text_sprite.x -= text_sprite.width;
if (text_sprite_shadow) {
text_sprite_shadow.x -= text_sprite_shadow.width;
}
}
let text_bg;
if (options?.with_bg) {
text_bg = this.game.add.graphics(text_sprite.x - 1, text_sprite.y);
text_bg.beginFill(this.color, 1);
text_bg.drawRect(0, 0, text_sprite.width + 3, numbers.FONT_SIZE);
text_bg.endFill();
if (
options?.internal_group_key === undefined ||
!this.add_to_internal_group(options?.internal_group_key, text_bg)
) {
this.group.add(text_bg);
}
}
text_sprite.tint = options?.color ?? this.font_color;
if (text_sprite_shadow) {
text_sprite_shadow.tint = 0x0;
}
let added_to_internal = false;
if (options?.internal_group_key !== undefined) {
added_to_internal =
(!text_sprite_shadow || this.add_to_internal_group(options?.internal_group_key, text_sprite_shadow)) &&
this.add_to_internal_group(options?.internal_group_key, text_sprite);
}
if (!added_to_internal) {
if (text_sprite_shadow) {
this.group.add(text_sprite_shadow);
}
this.group.add(text_sprite);
}
return {
text: text_sprite,
shadow: text_sprite_shadow,
right_align: options?.right_align,
initial_x: x_pos,
text_bg: text_bg,
};
}
/**
* Sets in this window lines of text.
* @param lines An array of strings containing the texts.
* @param options Some optional parameters.
* @returns Returns an array of TextObjs that were inserted.
*/
set_lines_of_text(
lines: string[],
options?: {
/** The x internal padding text position. */
padding_x?: number;
/** The y internal padding text position. */
padding_y?: number;
/** A custom value for the space between text lines. */
space_between_lines?: number;
} & Parameters<Window["set_text_in_position"]>[3]
) {
const top_shift = options?.italic ? -2 : 0;
const x_pos = options?.padding_x ?? numbers.WINDOW_PADDING_H + 4;
let y_pos = options?.padding_y ?? numbers.WINDOW_PADDING_TOP + top_shift;
const lines_objs: TextObj[] = [];
for (let i = 0; i < lines.length; ++i) {
const line = lines[i];
const text_obj = this.set_text_in_position(line, x_pos, y_pos, options);
lines_objs.push(text_obj);
y_pos += numbers.FONT_SIZE + (options?.space_between_lines ?? numbers.SPACE_BETWEEN_LINES);
}
return lines_objs;
}
/**
* Tweens the text horizontally back and forth. Use this when you expect
* the text to be bigger than the window.
* @param text_obj The text object to be tweened.
* @param x the x postition destination.
* @param duration The tween duration.
* @returns Return the tween object.
*/
tween_text_horizontally(text_obj: TextObj, x: number, duration: number = 3000) {
const foo = {x: text_obj.text.x};
const tween = this.game.add.tween(foo).to(
{
x: [text_obj.text.x, x, x],
},
duration,
Phaser.Easing.Linear.None,
true,
0,
-1,
true
);
tween.onUpdateCallback(() => {
text_obj.text.x = foo.x;
if (text_obj.shadow) {
text_obj.shadow.x = foo.x + 1;
}
});
return tween;
}
/**
* Changes the text of a text object.
* @param new_text The new text to show.
* @param text_obj The text object to be updated.
* @param new_x
* @param new_y
*/
update_text(new_text: string, text_obj: TextObj) {
text_obj.text.setText(new_text);
if (text_obj.shadow) {
text_obj.shadow.setText(new_text);
}
if (text_obj.right_align) {
text_obj.text.x = text_obj.initial_x - text_obj.text.width;
if (text_obj.shadow) {
text_obj.shadow.x = text_obj.initial_x - text_obj.shadow.width + 1;
}
if (text_obj.text_bg) {
text_obj.text_bg.x = text_obj.text.x - 1;
}
}
}
/**
* Changes the position of the given text object.
* @param new_position The desired position object.
* @param text_obj The text object to move repositioned.
*/
update_text_position(new_position: {x?: number; y?: number}, text_obj: TextObj) {
if (new_position.x !== undefined) {
text_obj.text.x = new_position.x;
if (text_obj.shadow) {
text_obj.shadow.x = new_position.x + 1;
}
text_obj.initial_x = new_position.x;
if (text_obj.text_bg) {
text_obj.text_bg.x = text_obj.text.x - 1;
}
}
if (new_position.y !== undefined) {
text_obj.text.y = new_position.y;
if (text_obj.shadow) {
text_obj.shadow.y = new_position.y + 1;
}
if (text_obj.text_bg) {
text_obj.text_bg.y = text_obj.text.y;
}
}
if (text_obj.right_align) {
text_obj.text.x = text_obj.initial_x - text_obj.text.width;
if (text_obj.shadow) {
text_obj.shadow.x = text_obj.initial_x - text_obj.shadow.width + 1;
}
if (text_obj.text_bg) {
text_obj.text_bg.x = text_obj.text.x - 1;
}
}
}
/**
* Changes the color of the given text object.
* @param color The new color to set.
* @param text_obj The text obj.
*/
update_text_color(color: number, text_obj: TextObj) {
text_obj.text.tint = color;
}
/**
* Destroys a given text object.
* @param text_obj The text obj. to be destroyed.
*/
destroy_text_obj(text_obj: TextObj) {
text_obj.text.destroy();
if (text_obj.shadow) {
text_obj.shadow.destroy();
}
if (text_obj.text_bg) {
text_obj.text_bg.destroy();
}
}
/**
* Closes this window.
* @param callback Callback function.
* @param animate Plays a fading animation if true.
*/
close(callback?: () => void, animate = true) {
if (animate) {
this.game.add
.tween(this.group.scale)
.to({x: 0, y: 0}, Window.TRANSITION_TIME, Phaser.Easing.Linear.None, true)
.onComplete.addOnce(() => {
this.group.visible = false;
this._open = false;
if (this.page_indicator.is_set) {
this.page_indicator.terminante();
}
if (callback !== undefined) {
callback();
}
if (this.close_callback !== undefined) {
this.close_callback();
}
});
} else {
this.group.visible = false;
this._open = false;
if (this.page_indicator.is_set) {
this.page_indicator.terminante();
}
this.group.scale.setTo(0, 0);
if (callback !== undefined) {
callback();
}
if (this.close_callback !== undefined) {
this.close_callback();
}
}
}
/**
* Destroys this window.
* @param animate Plays a fading animation if true.
* @param destroy_callback Callback function.
*/
destroy(animate: boolean, destroy_callback?: () => void) {
let on_destroy = () => {
if (this.page_indicator.is_set) {
this.page_indicator.terminante(true);
}
this.group.destroy(true);
this.internal_groups = {};
if (destroy_callback !== undefined) {
destroy_callback();
}
};
if (animate) {
this.game.add
.tween(this.group.scale)
.to({y: 0, x: 0}, Window.TRANSITION_TIME, Phaser.Easing.Linear.None, true)
.onComplete.addOnce(on_destroy);
} else {
on_destroy();
}
}
} | the_stack |
import { deepEqual } from 'fast-equals';
import memoize from '../src';
import { isSameValueZero } from '../src/utils';
describe('memoize', () => {
it('will return the memoized function', () => {
let callCount = 0;
const fn = (one: any, two: any) => {
callCount++;
return {
one,
two,
};
};
const memoized = memoize(fn);
expect(memoized.cache.snapshot).toEqual({
keys: [],
size: 0,
values: [],
});
expect(memoized.cache.snapshot).toEqual({
keys: [],
size: 0,
values: [],
});
expect(memoized.isMemoized).toEqual(true);
expect(memoized.options).toEqual({
isEqual: isSameValueZero,
isMatchingKey: undefined,
isPromise: false,
maxSize: 1,
transformKey: undefined,
});
new Array(1000).fill('z').forEach(() => {
const result = memoized('one', 'two');
expect(result).toEqual({
one: 'one',
two: 'two',
});
});
expect(callCount).toEqual(1);
expect(memoized.cache.snapshot).toEqual({
keys: [['one', 'two']],
size: 1,
values: [
{
one: 'one',
two: 'two',
},
],
});
});
it('will return the memoized function that can have multiple cached key => value pairs', () => {
let callCount = 0;
const fn = (one: any, two: any) => {
callCount++;
return {
one,
two,
};
};
const maxSize = 3;
const memoized = memoize(fn, { maxSize });
expect(memoized.cache.snapshot).toEqual({
keys: [],
size: 0,
values: [],
});
expect(memoized.cache.snapshot).toEqual({
keys: [],
size: 0,
values: [],
});
expect(memoized.isMemoized).toEqual(true);
expect(memoized.options.maxSize).toEqual(maxSize);
expect(memoized('one', 'two')).toEqual({
one: 'one',
two: 'two',
});
expect(memoized('two', 'three')).toEqual({
one: 'two',
two: 'three',
});
expect(memoized('three', 'four')).toEqual({
one: 'three',
two: 'four',
});
expect(memoized('four', 'five')).toEqual({
one: 'four',
two: 'five',
});
expect(memoized('two', 'three')).toEqual({
one: 'two',
two: 'three',
});
expect(memoized('three', 'four')).toEqual({
one: 'three',
two: 'four',
});
expect(callCount).toEqual(4);
expect(memoized.cache.snapshot).toEqual({
keys: [
['three', 'four'],
['two', 'three'],
['four', 'five'],
],
size: 3,
values: [
{
one: 'three',
two: 'four',
},
{
one: 'two',
two: 'three',
},
{
one: 'four',
two: 'five',
},
],
});
});
it('will return the memoized function that will use the custom isEqual method', () => {
let callCount = 0;
const fn = (one: any, two: any) => {
callCount++;
return {
one,
two,
};
};
const memoized = memoize(fn, { isEqual: deepEqual });
expect(memoized.options.isEqual).toBe(deepEqual);
expect(
memoized(
{ deep: { value: 'value' } },
{ other: { deep: { value: 'value' } } },
),
).toEqual({
one: { deep: { value: 'value' } },
two: { other: { deep: { value: 'value' } } },
});
expect(
memoized(
{ deep: { value: 'value' } },
{ other: { deep: { value: 'value' } } },
),
).toEqual({
one: { deep: { value: 'value' } },
two: { other: { deep: { value: 'value' } } },
});
expect(callCount).toEqual(1);
expect(memoized.cache.snapshot).toEqual({
keys: [
[{ deep: { value: 'value' } }, { other: { deep: { value: 'value' } } }],
],
size: 1,
values: [
{
one: { deep: { value: 'value' } },
two: { other: { deep: { value: 'value' } } },
},
],
});
});
it('will return the memoized function that will use the transformKey method', () => {
let callCount = 0;
const fn = (one: any, two: any) => {
callCount++;
return {
one,
two,
};
};
const transformKey = function (args: any[]) {
return [JSON.stringify(args)];
};
const memoized = memoize(fn, { transformKey });
expect(memoized.options.transformKey).toBe(transformKey);
const fnArg1 = () => {};
const fnArg2 = () => {};
const fnArg3 = () => {};
expect(memoized({ one: 'one' }, fnArg1)).toEqual({
one: { one: 'one' },
two: fnArg1,
});
expect(memoized({ one: 'one' }, fnArg2)).toEqual({
one: { one: 'one' },
two: fnArg1,
});
expect(memoized({ one: 'one' }, fnArg3)).toEqual({
one: { one: 'one' },
two: fnArg1,
});
expect(callCount).toEqual(1);
expect(memoized.cache.snapshot).toEqual({
keys: [['[{"one":"one"},null]']],
size: 1,
values: [
{
one: { one: 'one' },
two: fnArg1,
},
],
});
});
it('will return the memoized function that will use the transformKey method with a custom isEqual', () => {
let callCount = 0;
const fn = (one: any, two: any) => {
callCount++;
return {
one,
two,
};
};
const isEqual = function (key1: any, key2: any) {
return key1.args === key2.args;
};
const transformKey = function (args: any[]) {
return [
{
args: JSON.stringify(args),
},
];
};
const memoized = memoize(fn, {
isEqual,
transformKey,
});
expect(memoized.options.isEqual).toBe(isEqual);
expect(memoized.options.transformKey).toBe(transformKey);
const fnArg1 = () => {};
const fnArg2 = () => {};
const fnArg3 = () => {};
expect(memoized({ one: 'one' }, fnArg1)).toEqual({
one: { one: 'one' },
two: fnArg1,
});
expect(memoized({ one: 'one' }, fnArg2)).toEqual({
one: { one: 'one' },
two: fnArg1,
});
expect(memoized({ one: 'one' }, fnArg3)).toEqual({
one: { one: 'one' },
two: fnArg1,
});
expect(callCount).toEqual(1);
expect(memoized.cache.snapshot).toEqual({
keys: [
[
{
args: '[{"one":"one"},null]',
},
],
],
size: 1,
values: [
{
one: { one: 'one' },
two: fnArg1,
},
],
});
});
it('will return a memoized method that will auto-remove the key from cache if isPromise is true and the promise is rejected', async () => {
const timeout = 200;
const error = new Error('boom');
const fn = async (ignored: string) => {
await new Promise((resolve: Function) => {
setTimeout(resolve, timeout);
});
throw error;
};
const isPromise = true;
const memoized = memoize(fn, { isPromise });
expect(memoized.options.isPromise).toEqual(isPromise);
const spy = jest.fn();
memoized('foo').catch(spy);
expect(memoized.cache.snapshot.keys.length).toEqual(1);
expect(memoized.cache.snapshot.values.length).toEqual(1);
await new Promise((resolve: Function) => {
setTimeout(resolve, timeout + 50);
});
expect(memoized.cache.snapshot).toEqual({
keys: [],
size: 0,
values: [],
});
expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledWith(error);
});
it('will fire the onCacheChange method passed with the cache when it is added to', () => {
const fn = (one: string, two: string) => ({ one, two });
const onCacheChange = jest.fn();
const memoized = memoize(fn, { onCacheChange });
expect(memoized.options.onCacheChange).toBe(onCacheChange);
memoized('foo', 'bar');
expect(onCacheChange).toHaveBeenCalledTimes(1);
expect(onCacheChange).toHaveBeenCalledWith(
memoized.cache,
{
onCacheChange,
isEqual: isSameValueZero,
isMatchingKey: undefined,
isPromise: false,
maxSize: 1,
transformKey: undefined,
},
memoized,
);
});
it('will fire the onCacheChange method passed with the cache when it is updated', () => {
const fn = (one: string, two: string) => ({ one, two });
const onCacheChange = jest.fn();
const maxSize = 2;
const memoized = memoize(fn, {
maxSize,
onCacheChange,
});
expect(memoized.options.onCacheChange).toBe(onCacheChange);
memoized('foo', 'bar');
expect(onCacheChange).toHaveBeenCalledTimes(1);
expect(onCacheChange).toHaveBeenCalledWith(
memoized.cache,
memoized.options,
memoized,
);
onCacheChange.mockReset();
memoized('bar', 'foo');
expect(onCacheChange).toHaveBeenCalledTimes(1);
expect(onCacheChange).toHaveBeenCalledWith(
memoized.cache,
memoized.options,
memoized,
);
onCacheChange.mockReset();
memoized('bar', 'foo');
expect(onCacheChange).toHaveBeenCalledTimes(0);
onCacheChange.mockReset();
memoized('foo', 'bar');
expect(onCacheChange).toHaveBeenCalledTimes(1);
expect(onCacheChange).toHaveBeenCalledWith(
memoized.cache,
memoized.options,
memoized,
);
onCacheChange.mockReset();
memoized('foo', 'bar');
expect(onCacheChange).toHaveBeenCalledTimes(0);
});
it('will not fire the onCacheHit method passed with the cache when it is added to', () => {
const fn = (one: string, two: string) => ({ one, two });
const onCacheHit = jest.fn();
const memoized = memoize(fn, { onCacheHit });
expect(memoized.options.onCacheHit).toBe(onCacheHit);
memoized('foo', 'bar');
expect(onCacheHit).toHaveBeenCalledTimes(0);
});
it('will fire the onCacheHit method passed with the cache when it is updated', () => {
const fn = (one: any, two: any) => ({
one,
two,
});
const onCacheHit = jest.fn();
const maxSize = 2;
const memoized = memoize(fn, {
maxSize,
onCacheHit,
});
expect(memoized.options.onCacheHit).toBe(onCacheHit);
memoized('foo', 'bar');
expect(onCacheHit).toHaveBeenCalledTimes(0);
memoized('bar', 'foo');
expect(onCacheHit).toHaveBeenCalledTimes(0);
memoized('bar', 'foo');
expect(onCacheHit).toHaveBeenCalledTimes(1);
expect(onCacheHit).toHaveBeenCalledWith(
memoized.cache,
memoized.options,
memoized,
);
onCacheHit.mockReset();
memoized('foo', 'bar');
expect(onCacheHit).toHaveBeenCalledTimes(1);
expect(onCacheHit).toHaveBeenCalledWith(
memoized.cache,
memoized.options,
memoized,
);
onCacheHit.mockReset();
memoized('foo', 'bar');
expect(onCacheHit).toHaveBeenCalledTimes(1);
expect(onCacheHit).toHaveBeenCalledWith(
memoized.cache,
memoized.options,
memoized,
);
});
it('will fire the onCacheAdd method passed with the cache when it is added but not when hit', () => {
const fn = (one: any, two: any) => ({
one,
two,
});
const onCacheAdd = jest.fn();
const memoized = memoize(fn, { onCacheAdd });
expect(memoized.options.onCacheAdd).toBe(onCacheAdd);
memoized('foo', 'bar');
expect(onCacheAdd).toHaveBeenCalledTimes(1);
memoized('foo', 'bar');
expect(onCacheAdd).toHaveBeenCalledTimes(1);
});
it('will fire the onCacheAdd method passed with the cache when it is added but never again', () => {
const fn = (one: any, two: any) => ({
one,
two,
});
const onCacheAdd = jest.fn();
const maxSize = 2;
const memoized = memoize(fn, {
maxSize,
onCacheAdd,
});
expect(memoized.options.onCacheAdd).toBe(onCacheAdd);
memoized('foo', 'bar');
expect(onCacheAdd).toHaveBeenCalledTimes(1);
expect(onCacheAdd).toHaveBeenCalledWith(
memoized.cache,
memoized.options,
memoized,
);
onCacheAdd.mockReset();
memoized('bar', 'foo');
expect(onCacheAdd).toHaveBeenCalledTimes(1);
expect(onCacheAdd).toHaveBeenCalledWith(
memoized.cache,
memoized.options,
memoized,
);
onCacheAdd.mockReset();
memoized('bar', 'foo');
expect(onCacheAdd).toHaveBeenCalledTimes(0);
onCacheAdd.mockReset();
memoized('foo', 'bar');
expect(onCacheAdd).toHaveBeenCalledTimes(0);
memoized('foo', 'bar');
expect(onCacheAdd).toHaveBeenCalledTimes(0);
});
type Dictionary<Type> = {
[key: string]: Type;
};
test('if recursive calls to self will be respected at runtime', () => {
const calc = memoize(
(
object: { [key: string]: any },
metadata: { c: number },
): Dictionary<any> =>
Object.keys(object).reduce((totals: { [key: string]: number }, key) => {
if (Array.isArray(object[key])) {
totals[key] = object[
key
].map((subObject: { [key: string]: number }) =>
calc(subObject, metadata),
);
} else {
totals[key] = object[key].a + object[key].b + metadata.c;
}
return totals;
}, {}),
{
maxSize: 10,
},
);
const data = {
fifth: {
a: 4,
b: 5,
},
first: [
{
second: {
a: 1,
b: 2,
},
},
{
third: [
{
fourth: {
a: 2,
b: 3,
},
},
],
},
],
};
const metadata = {
c: 6,
};
const result1 = calc(data, metadata);
const result2 = calc(data, metadata);
expect(result1).toEqual(result2);
});
it('will re-memoize the function with merged options if already memoized', () => {
const fn = () => {};
const maxSize = 5;
const isEqual = () => true;
const memoized = memoize(fn, { maxSize });
const reMemoized = memoize(memoized, { isEqual });
expect(reMemoized).not.toBe(memoized);
expect(reMemoized.options.maxSize).toBe(maxSize);
expect(reMemoized.options.isEqual).toBe(isEqual);
});
it('will throw an error if not a function', () => {
const fn = 123;
// @ts-ignore
expect(() => memoize(fn)).toThrow();
});
describe('documentation examples', () => {
it('matches simple usage', () => {
const assembleToObject = (one: string, two: string) => ({ one, two });
const memoized = memoize(assembleToObject);
const result1 = memoized('one', 'two');
const result2 = memoized('one', 'two');
expect(result1).toEqual({ one: 'one', two: 'two' });
expect(result2).toBe(result1);
});
it('matches for option `isEqual`', () => {
type ContrivedObject = {
deep: string;
};
const deepObject = (object: {
foo: ContrivedObject;
bar: ContrivedObject;
baz?: any;
}) => ({
foo: object.foo,
bar: object.bar,
});
const memoizedDeepObject = memoize(deepObject, { isEqual: deepEqual });
const result1 = memoizedDeepObject({
foo: {
deep: 'foo',
},
bar: {
deep: 'bar',
},
baz: {
deep: 'baz',
},
});
const result2 = memoizedDeepObject({
foo: {
deep: 'foo',
},
bar: {
deep: 'bar',
},
baz: {
deep: 'baz',
},
});
expect(result1).toEqual({
foo: { deep: 'foo' },
bar: { deep: 'bar' },
});
expect(result2).toBe(result1);
});
it('matches for option `isMatchingKey`', () => {
type ContrivedObject = { foo: string; bar: number; baz: string };
const deepObject = (object: ContrivedObject) => ({
foo: object.foo,
bar: object.bar,
});
const memoizedShape = memoize(deepObject, {
// receives the full key in cache and the full key of the most recent call
isMatchingKey(key1, key2) {
const object1 = key1[0];
const object2 = key2[0];
return (
object1.hasOwnProperty('foo') &&
object2.hasOwnProperty('foo') &&
object1.bar === object2.bar
);
},
});
const result1 = memoizedShape({ foo: 'foo', bar: 123, baz: 'baz' });
const result2 = memoizedShape({ foo: 'foo', bar: 123, baz: 'baz' });
expect(result1).toEqual({ foo: 'foo', bar: 123 });
expect(result2).toBe(result1);
});
it('matches for option `isPromise`', (done) => {
const fn = async (one: string, two: string) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error(JSON.stringify({ one, two })));
}, 500);
});
};
const memoized = memoize(fn, { isPromise: true });
const call = memoized('one', 'two');
expect(memoized.cache.snapshot.keys).toEqual([['one', 'two']]);
expect(memoized.cache.snapshot.values).toEqual([expect.any(Promise)]);
call.catch((error) => {
expect(memoized.cache.snapshot.keys).toEqual([]);
expect(memoized.cache.snapshot.values).toEqual([]);
expect(error).toEqual(new Error('{"one":"one","two":"two"}'));
done();
});
});
it('matches for option `maxSize`', () => {
const manyPossibleArgs = jest.fn((one: string, two: string) => [
one,
two,
]);
const memoized = memoize(manyPossibleArgs, { maxSize: 3 });
memoized('one', 'two');
memoized('two', 'three');
memoized('three', 'four');
expect(manyPossibleArgs).toHaveBeenCalledTimes(3);
expect(memoized.cache.snapshot.keys).toEqual([
['three', 'four'],
['two', 'three'],
['one', 'two'],
]);
expect(memoized.cache.snapshot.values).toEqual([
['three', 'four'],
['two', 'three'],
['one', 'two'],
]);
manyPossibleArgs.mockClear();
memoized('one', 'two');
memoized('two', 'three');
memoized('three', 'four');
expect(manyPossibleArgs).not.toHaveBeenCalled();
memoized('four', 'five');
expect(manyPossibleArgs).toHaveBeenCalled();
});
it('matches for option `onCacheAdd`', () => {
const fn = (one: string, two: string) => [one, two];
const options = {
maxSize: 2,
onCacheAdd: jest.fn(),
};
const memoized = memoize(fn, options);
memoized('foo', 'bar'); // cache has been added to
memoized('foo', 'bar');
memoized('foo', 'bar');
expect(options.onCacheAdd).toHaveBeenCalledTimes(1);
memoized('bar', 'foo'); // cache has been added to
memoized('bar', 'foo');
memoized('bar', 'foo');
expect(options.onCacheAdd).toHaveBeenCalledTimes(2);
memoized('foo', 'bar');
memoized('foo', 'bar');
memoized('foo', 'bar');
expect(options.onCacheAdd).toHaveBeenCalledTimes(2);
});
it('matches for option `onCacheChange`', () => {
const fn = (one: string, two: string) => [one, two];
const options = {
maxSize: 2,
onCacheChange: jest.fn(),
};
const memoized = memoize(fn, options);
memoized('foo', 'bar');
memoized('foo', 'bar');
memoized('foo', 'bar');
expect(options.onCacheChange).toHaveBeenCalledTimes(1);
memoized('bar', 'foo');
memoized('bar', 'foo');
memoized('bar', 'foo');
expect(options.onCacheChange).toHaveBeenCalledTimes(2);
memoized('foo', 'bar');
memoized('foo', 'bar');
memoized('foo', 'bar');
expect(options.onCacheChange).toHaveBeenCalledTimes(3);
});
it('matches for option `onCacheHit`', () => {
const fn = (one: string, two: string) => [one, two];
const options = {
maxSize: 2,
onCacheHit: jest.fn(),
};
const memoized = memoize(fn, options);
memoized('foo', 'bar');
memoized('foo', 'bar');
memoized('foo', 'bar');
expect(options.onCacheHit).toHaveBeenCalledTimes(2);
memoized('bar', 'foo');
memoized('bar', 'foo');
memoized('bar', 'foo');
expect(options.onCacheHit).toHaveBeenCalledTimes(4);
memoized('foo', 'bar');
memoized('foo', 'bar');
memoized('foo', 'bar');
expect(options.onCacheHit).toHaveBeenCalledTimes(7);
});
it('matches for option `transformKey`', () => {
const ignoreFunctionArg = jest.fn((one: string, two: () => void) => [
one,
two,
]);
const memoized = memoize(ignoreFunctionArg, {
isMatchingKey: (key1, key2) => key1[0] === key2[0],
// Cache based on the serialized first parameter
transformKey: (args) => [JSON.stringify(args[0])],
});
memoized('one', () => {});
memoized('one', () => {});
expect(ignoreFunctionArg).toHaveBeenCalledTimes(1);
});
});
}); | the_stack |
import * as deepFreeze from 'deep-freeze';
import {
AddFieldUpdateAction,
DiscardObjectUpdatesAction,
FieldChangeType,
InitializeFieldsAction,
ReinstateObjectUpdatesAction,
RemoveAllObjectUpdatesAction,
RemoveFieldUpdateAction,
RemoveObjectUpdatesAction,
SelectVirtualMetadataAction,
SetEditableFieldUpdateAction,
SetValidFieldUpdateAction
} from './object-updates.actions';
import { OBJECT_UPDATES_TRASH_PATH, objectUpdatesReducer } from './object-updates.reducer';
import { Relationship } from '../../shared/item-relationships/relationship.model';
class NullAction extends RemoveFieldUpdateAction {
type = null;
payload = null;
constructor() {
super(null, null);
}
}
const identifiable1 = {
uuid: '8222b07e-330d-417b-8d7f-3b82aeaf2320',
key: 'dc.contributor.author',
language: null,
value: 'Smith, John'
};
const identifiable1update = {
uuid: '8222b07e-330d-417b-8d7f-3b82aeaf2320',
key: 'dc.contributor.author',
language: null,
value: 'Smith, James'
};
const identifiable2 = {
uuid: '26cbb5ce-5786-4e57-a394-b9fcf8eaf241',
key: 'dc.title',
language: null,
value: 'New title'
};
const identifiable3 = {
uuid: 'c5d2c2f7-d757-48bf-84cc-8c9229c8407e',
key: 'dc.description.abstract',
language: null,
value: 'Unchanged value'
};
const relationship: Relationship = Object.assign(new Relationship(), { uuid: 'test relationship uuid' });
const modDate = new Date(2010, 2, 11);
const uuid = identifiable1.uuid;
const url = 'test-object.url/edit';
describe('objectUpdatesReducer', () => {
const testState = {
[url]: {
fieldStates: {
[identifiable1.uuid]: {
editable: true,
isNew: false,
isValid: true
},
[identifiable2.uuid]: {
editable: false,
isNew: true,
isValid: true
},
[identifiable3.uuid]: {
editable: false,
isNew: false,
isValid: false
},
},
fieldUpdates: {
[identifiable2.uuid]: {
field: {
uuid: identifiable2.uuid,
key: 'dc.titl',
language: null,
value: 'New title'
},
changeType: FieldChangeType.ADD
}
},
lastModified: modDate,
virtualMetadataSources: {
[relationship.uuid]: { [identifiable1.uuid]: true }
},
}
};
const discardedTestState = {
[url]: {
fieldStates: {
[identifiable1.uuid]: {
editable: true,
isNew: false,
isValid: true
},
[identifiable2.uuid]: {
editable: false,
isNew: true,
isValid: true
},
[identifiable3.uuid]: {
editable: false,
isNew: false,
isValid: true
},
},
lastModified: modDate,
virtualMetadataSources: {
[relationship.uuid]: { [identifiable1.uuid]: true }
},
},
[url + OBJECT_UPDATES_TRASH_PATH]: {
fieldStates: {
[identifiable1.uuid]: {
editable: true,
isNew: false,
isValid: true
},
[identifiable2.uuid]: {
editable: false,
isNew: true,
isValid: true
},
[identifiable3.uuid]: {
editable: false,
isNew: false,
isValid: false
},
},
fieldUpdates: {
[identifiable2.uuid]: {
field: {
uuid: identifiable2.uuid,
key: 'dc.titl',
language: null,
value: 'New title'
},
changeType: FieldChangeType.ADD
}
},
lastModified: modDate,
virtualMetadataSources: {
[relationship.uuid]: { [identifiable1.uuid]: true }
},
}
};
deepFreeze(testState);
it('should return the current state when no valid actions have been made', () => {
const action = new NullAction();
const newState = objectUpdatesReducer(testState, action);
expect(newState).toEqual(testState);
});
it('should start with an empty object', () => {
const action = new NullAction();
const initialState = objectUpdatesReducer(undefined, action);
expect(initialState).toEqual({});
});
it('should perform the INITIALIZE_FIELDS action without affecting the previous state', () => {
const action = new InitializeFieldsAction(url, [identifiable1, identifiable2], modDate);
// testState has already been frozen above
objectUpdatesReducer(testState, action);
});
it('should perform the SET_EDITABLE_FIELD action without affecting the previous state', () => {
const action = new SetEditableFieldUpdateAction(url, uuid, false);
// testState has already been frozen above
objectUpdatesReducer(testState, action);
});
it('should perform the ADD_FIELD action without affecting the previous state', () => {
const action = new AddFieldUpdateAction(url, identifiable1update, FieldChangeType.UPDATE);
// testState has already been frozen above
objectUpdatesReducer(testState, action);
});
it('should perform the DISCARD action without affecting the previous state', () => {
const action = new DiscardObjectUpdatesAction(url, null);
// testState has already been frozen above
objectUpdatesReducer(testState, action);
});
it('should perform the REINSTATE action without affecting the previous state', () => {
const action = new ReinstateObjectUpdatesAction(url);
// testState has already been frozen above
objectUpdatesReducer(testState, action);
});
it('should perform the REMOVE action without affecting the previous state', () => {
const action = new RemoveFieldUpdateAction(url, uuid);
// testState has already been frozen above
objectUpdatesReducer(testState, action);
});
it('should perform the REMOVE_FIELD action without affecting the previous state', () => {
const action = new RemoveFieldUpdateAction(url, uuid);
// testState has already been frozen above
objectUpdatesReducer(testState, action);
});
it('should perform the SELECT_VIRTUAL_METADATA action without affecting the previous state', () => {
const action = new SelectVirtualMetadataAction(url, relationship.uuid, identifiable1.uuid, true);
// testState has already been frozen above
objectUpdatesReducer(testState, action);
});
it('should initialize all fields when the INITIALIZE action is dispatched, based on the payload', () => {
const action = new InitializeFieldsAction(url, [identifiable1, identifiable3], modDate);
const expectedState = {
[url]: {
fieldStates: {
[identifiable1.uuid]: {
editable: false,
isNew: false,
isValid: true
},
[identifiable3.uuid]: {
editable: false,
isNew: false,
isValid: true
},
},
fieldUpdates: {},
virtualMetadataSources: {},
lastModified: modDate,
patchOperationService: undefined
}
};
const newState = objectUpdatesReducer(testState, action);
expect(newState).toEqual(expectedState);
});
it('should set the given field\'s fieldStates when the SET_EDITABLE_FIELD action is dispatched, based on the payload', () => {
const action = new SetEditableFieldUpdateAction(url, identifiable3.uuid, true);
const newState = objectUpdatesReducer(testState, action);
expect(newState[url].fieldStates[identifiable3.uuid].editable).toBeTruthy();
});
it('should set the given field\'s fieldStates when the SET_VALID_FIELD action is dispatched, based on the payload', () => {
const action = new SetValidFieldUpdateAction(url, identifiable3.uuid, false);
const newState = objectUpdatesReducer(testState, action);
expect(newState[url].fieldStates[identifiable3.uuid].isValid).toBeFalsy();
});
it('should add a given field\'s update to the state when the ADD_FIELD action is dispatched, based on the payload', () => {
const action = new AddFieldUpdateAction(url, identifiable1update, FieldChangeType.UPDATE);
const newState = objectUpdatesReducer(testState, action);
expect(newState[url].fieldUpdates[identifiable1.uuid].field).toEqual(identifiable1update);
expect(newState[url].fieldUpdates[identifiable1.uuid].changeType).toEqual(FieldChangeType.UPDATE);
});
it('should discard a given url\'s updates from the state when the DISCARD action is dispatched, based on the payload', () => {
const action = new DiscardObjectUpdatesAction(url, null);
const newState = objectUpdatesReducer(testState, action);
expect(newState[url].fieldUpdates).toEqual({});
expect(newState[url + OBJECT_UPDATES_TRASH_PATH]).toEqual(testState[url]);
});
it('should reinstate a given url\'s updates from the state when the REINSTATE action is dispatched, based on the payload', () => {
const action = new ReinstateObjectUpdatesAction(url);
const newState = objectUpdatesReducer(discardedTestState, action);
expect(newState).toEqual(testState);
});
it('should remove a given url\'s updates from the state when the REMOVE action is dispatched, based on the payload', () => {
const action = new RemoveObjectUpdatesAction(url);
const newState = objectUpdatesReducer(discardedTestState, action);
expect(newState[url].fieldUpdates).toBeUndefined();
expect(newState[url + OBJECT_UPDATES_TRASH_PATH]).toBeUndefined();
});
it('should remove all updates from the state when the REMOVE_ALL action is dispatched', () => {
const action = new RemoveAllObjectUpdatesAction();
const newState = objectUpdatesReducer(discardedTestState, action as any);
expect(newState[url].fieldUpdates).toBeUndefined();
expect(newState[url + OBJECT_UPDATES_TRASH_PATH]).toBeUndefined();
});
it('should remove a given field\'s update from the state when the REMOVE_FIELD action is dispatched, based on the payload', () => {
const action = new RemoveFieldUpdateAction(url, uuid);
const newState = objectUpdatesReducer(testState, action);
expect(newState[url].fieldUpdates[uuid]).toBeUndefined();
});
}); | the_stack |
import * as bridge from '../lib/bridge/bridge';
import * as consent from './consent';
import * as globals from './globals';
import * as _ from 'lodash';
import * as logging from '../lib/logging/logging';
import Persistent from '../interfaces/persistent';
import * as remote_instance from './remote-instance';
import * as social from '../interfaces/social';
import * as ui from './ui_connector';
import * as uproxy_core_api from '../interfaces/uproxy_core_api';
import storage = globals.storage;
var log :logging.Log = new logging.Log('remote-user');
/**
* remote_user.User
*
* Builts upon a freedom.Social.UserProfile.
* Maintains a mapping between a User's clientIds and instanceIds, while
* handling messages from its parent network to keep connection status,
* instance messages, and consent up-to-date.
*
* NOTE: Deals with communications purely in terms of instanceIds.
*/
export class User implements social.BaseUser, Persistent {
// Name of the user as provided by the social network.
public name :string;
public clientIdToStatusMap :{ [clientId :string] :social.ClientStatus };
public profile :social.UserProfile;
public consent :consent.State;
// Each instance is a user and social network pair.
private instances_ :{ [instanceId :string] :remote_instance.RemoteInstance };
private clientToInstanceMap_ :{ [clientId :string] :string };
private instanceToClientMap_ :{ [instanceId :string] :string };
private fulfillStorageLoad_ : () => void;
public onceLoaded : Promise<void> = new Promise<void>((F, R) => {
this.fulfillStorageLoad_ = F;
}).then(() => {
this.notifyUI();
});
private fulfillNameReceived_ :(name:string) => void;
public onceNameReceived : Promise<string> = new Promise<string>((F, R) => {
this.fulfillNameReceived_ = F;
});
/**
* Users are constructed purely on the basis of receiving a userId.
* They may or may not have a :UserProfile (because the Network may have
* received a ClientState or Message for the user, prior to receiving the
* UserProfile from the social provider.)
*
* In any case, a User without a name is known to be 'pending', and should
* not appear in the UI until actually receiving and being updated with a
* full UserProfile.
*/
constructor(public network :social.Network,
public userId :string) {
this.name = 'pending';
this.profile = {
userId: this.userId,
name: '',
timestamp: Date.now()
}
this.clientIdToStatusMap = {};
this.instances_ = {};
this.clientToInstanceMap_ = {};
this.instanceToClientMap_ = {};
this.consent =
new consent.State(userId === this.network.myInstance.userId);
// Because it requires user action to add a cloud friend, and because
// these cloud instances are only sharers, by default all users are
// requesting access from cloud instances.
if (this.network.name === 'Cloud') {
this.consent.localRequestsAccessFromRemote = true;
}
storage.load<social.UserState>(this.getStorePath()).then((state) => {
this.restoreState(state);
}).catch((e) => {
// User not found in storage - we should fulfill the create promise
// anyway as this is not an error.
this.fulfillStorageLoad_();
});
}
/**
* Update the information about this user.
* The userId must match.
*/
public update = (profile :social.UserProfile) : void => {
if (profile.userId != this.userId) {
throw Error('Updating User ' + this.userId +
' with unexpected userID: ' + profile.userId);
}
this.name = profile.name;
this.fulfillNameReceived_(this.name);
this.profile = profile;
if (!this.profile.status && this.network.name === 'Cloud') {
this.profile.status = social.UserStatus.CLOUD_INSTANCE_SHARED_WITH_LOCAL;
} else if (typeof this.profile.status === 'undefined') {
this.profile.status = social.UserStatus.FRIEND;
}
this.saveToStorage();
this.notifyUI();
}
/**
* Handle 'onClientState' events from the social provider, which indicate
* changes in status such as becoming online, offline.
* - Only adds uProxy clients to the clients table.
* - Sends local instance information as an 'Instance Handshake' to the
* remote client if it is known to be uProxy client.
*/
public handleClient = (client :social.ClientState) : void => {
if (client.userId != this.userId) {
log.error('received client with unexpected userId', {
clientUserId: this.userId,
userId: client.userId
});
return;
}
log.debug('received client', client);
if (client.clientId in this.clientIdToStatusMap &&
this.clientIdToStatusMap[client.clientId] == client.status) {
// Client is already in mapping and its status has not changed, skip.
// This is done to skip onClientState events we get for each message
// when only the timestamp has been updated.
log.debug('Client already in memory and is unchanged', client.clientId);
return;
}
switch (client.status) {
// Send an instance message to newly ONLINE remote uProxy clients.
case social.ClientStatus.ONLINE:
if (!(client.clientId in this.clientIdToStatusMap) ||
(this.clientIdToStatusMap[client.clientId] !=
social.ClientStatus.ONLINE)) {
// Client is new, or has changed status from !ONLINE to ONLINE.
this.sendInstanceHandshake(client.clientId);
}
this.clientIdToStatusMap[client.clientId] = client.status;
break;
case social.ClientStatus.OFFLINE:
case social.ClientStatus.ONLINE_WITH_OTHER_APP:
// Just delete OFFLINE clients, because they will never be ONLINE
// again as the same clientID (removes clientId from
// clientIdToStatusMap and related data structures).
this.removeClient_(client.clientId);
break;
default:
log.warn('Received client %1 with invalid status %2',
client.clientId, client.status);
break;
}
this.notifyUI();
}
/**
* Handle 'onMessage' events from the social provider, which can be any type
* of message from another contact, then delegate the message to the correct
* handler.
* Emits an error for a message from a client which doesn't exist.
*/
public handleMessage = (clientId :string,
msg :social.VersionedPeerMessage) : void => {
if (!(clientId in this.clientIdToStatusMap)) {
log.error('%1 received message for non-existing client %2',
this.userId, clientId);
return;
}
switch (msg.type) {
case social.PeerMessageType.INSTANCE:
this.syncInstance_(clientId, <social.InstanceHandshake>msg.data,
msg.version).then((instance: remote_instance.RemoteInstance) => {
// Check if we have an unusedPermissionToken for this instance.
if (instance.unusedPermissionToken) {
this.sendPermissionToken(clientId,
instance.unusedPermissionToken);
instance.unusedPermissionToken = null;
instance.saveToStorage();
}
}).catch((e) => {
log.error('syncInstance_ failed for ', msg.data);
});
return;
case social.PeerMessageType.SIGNAL_FROM_CLIENT_PEER:
case social.PeerMessageType.SIGNAL_FROM_SERVER_PEER:
const recipientInstance = this.getInstance(this.clientToInstance(clientId));
if (!recipientInstance) {
// TODO: this may occur due to a race condition where uProxy has
// received an onUserProfile and onClientState event, but not yet
// recieved and instance message, and the peer tries to start
// proxying. We should fix this somehow.
// issues: https://github.com/uProxy/uproxy/pull/732
log.error('failed to get instance', clientId);
return;
}
recipientInstance.handleSignal(msg);
return;
case social.PeerMessageType.INSTANCE_REQUEST:
log.debug('received instance request', clientId);
this.sendInstanceHandshake(clientId);
return;
case social.PeerMessageType.PERMISSION_TOKEN:
var token = (<social.PermissionTokenMessage>msg.data).token;
var tokenInfo =
this.network.myInstance.exchangeInviteToken(token, this.userId);
if (!tokenInfo) {
return;
}
if (tokenInfo.isOffering) {
this.consent.localGrantsAccessToRemote = true;
}
if (tokenInfo.isRequesting) {
this.consent.localRequestsAccessFromRemote = true;
}
// Send them a new instance handshake with updated consent.
this.sendInstanceHandshake(clientId);
this.saveToStorage(); // Save new consent to storage.
this.notifyUI(); // Notify UI that consent has changed
return;
case social.PeerMessageType.KEY_VERIFY_MESSAGE:
log.debug('got instance key-verify mssage', msg);
// Find the RemoteInstance representing the peer, and relay
// the message there.
let peerInstance = this.getInstance(this.clientToInstance(clientId));
if (!peerInstance) {
// issues: https://github.com/uProxy/uproxy/pull/732
log.error('failed to get instance', clientId);
return;
}
peerInstance.handleKeyVerifyMessage(msg.data);
return;
default:
log.error('received invalid message', {
userId: this.userId,
msg: msg
});
}
}
public getInstance = (instanceId:string)
: remote_instance.RemoteInstance => {
return this.instances_[instanceId];
}
/**
* Helper that returns the local user's instance ID.
* TODO: This API is confusing because it doesn't return the instance
* for this (remote) user object, but instead returns information about the
* user running uProxy. We should clean this up somehow.
*/
public getLocalInstanceId = () : string => {
return this.network.getLocalInstanceId();
}
/**
* Synchronize with new remote instance data, update the instance-client
* mapping, save to storage, and update the UI.
* Assumes the clientId associated with this instance is valid and belongs
* to this user.
* In no case will this function fail to generate or update an entry of
* this user's instance table.
*/
public syncInstance_ = (
clientId :string,
instanceHandshake :social.InstanceHandshake,
messageVersion :number) : Promise<remote_instance.RemoteInstance> => {
// TODO: use handlerQueues to process instances messages in order, to
// address potential race conditions described in
// https://github.com/uProxy/uproxy/issues/734
if (social.ClientStatus.ONLINE !== this.clientIdToStatusMap[clientId]) {
log.error('Received an instance handshake from a non-uProxy client',
clientId);
return Promise.reject(new Error(
'Received an instance handshake from a non-uProxy client'));
}
log.info('received instance', instanceHandshake);
if (!instanceHandshake.consent) {
// This indicates that a user was running an old version of uProxy
// (prior to moving consent to user).
log.warn('No consent received with instance', instanceHandshake);
return Promise.reject('No consent received with instance');
}
var instanceId = instanceHandshake.instanceId;
var oldClientId = this.instanceToClientMap_[instanceId];
if (oldClientId) {
// Remove old mapping if it exists.
this.clientToInstanceMap_[oldClientId] = null;
}
this.clientToInstanceMap_[clientId] = instanceId;
this.instanceToClientMap_[instanceId] = clientId;
// Create or update the Instance object.
var instance = this.instances_[instanceId];
if (!instance) {
// Create a new instance.
instance = new remote_instance.RemoteInstance(this, instanceId);
this.instances_[instanceId] = instance;
}
return instance.update(instanceHandshake,
messageVersion).then(() => {
this.saveToStorage();
this.notifyUI();
return instance;
});
}
/**
* Maintain a mapping between clientIds and instanceIds.
*/
public clientToInstance = (clientId :string) : string => {
return this.clientToInstanceMap_[clientId];
}
public instanceToClient = (instanceId :string) : string => {
return this.instanceToClientMap_[instanceId];
}
/**
* Remove a client from this User. Also removes the client <--> instance
* mapping if it exists.
*/
private removeClient_ = (clientId:string) : void => {
delete this.clientIdToStatusMap[clientId];
var instanceId = this.clientToInstanceMap_[clientId];
if (instanceId) {
delete this.instanceToClientMap_[instanceId];
}
delete this.clientToInstanceMap_[clientId];
}
private ignoreUser_ = () => {
return Object.keys(this.instances_).length === 0 &&
(!this.network.areAllContactsUproxy() ||
this.userId === this.network.myInstance.userId)
}
public currentStateForUI = () : social.UserData => {
if ('pending' == this.name) {
log.warn('Not showing UI without profile');
return null;
}
// TODO: there is a bug where sometimes this.profile.name is not set,
// even though we have this.name set. This should be tracked down, but for now
// we can just copy this.name to this.profile.name.
if (!this.profile.name) {
this.profile.name = this.name;
}
var isOnline = false;
var offeringInstanceStatesForUi :social.InstanceData[] = [];
var allInstanceIds :string[] = [];
var instancesSharingWithLocal :string[] = [];
for (var instanceId in this.instances_) {
allInstanceIds.push(instanceId);
var instance = this.instances_[instanceId];
if (instance.wireConsentFromRemote.isOffering) {
offeringInstanceStatesForUi.push(instance.currentStateForUi());
}
if (!isOnline && this.isInstanceOnline(instanceId)) {
isOnline = true;
}
if (instance.isSharing()) {
instancesSharingWithLocal.push(instanceId);
}
}
if (this.ignoreUser_()) {
// Don't send users with no instances to the UI if either the network
// gives us non-uProxy contacts, or it is the user we are logged in
// with.
return null;
}
// TODO: There is a bug in here somewhere. The UI message doesn't make it,
// sometimes.
return {
network: this.network.name,
user: {
userId: this.profile.userId,
name: this.profile.name,
imageData: this.profile.imageData,
url: this.profile.url,
status: this.profile.status
},
consent: this.consent,
offeringInstances: offeringInstanceStatesForUi,
instancesSharingWithLocal: instancesSharingWithLocal,
allInstanceIds: allInstanceIds,
isOnline: isOnline
};
}
/**
* Send the latest full state about everything in this user to the UI.
* Only sends to UI if the user is ready to be visible. (has UserProfile)
*/
public notifyUI = () : void => {
this.onceLoaded.then(() => {
var state = this.currentStateForUI();
if (state) { // state may be null if we don't yet have a user name.
ui.connector.syncUser(state);
}
});
}
public monitor = () : void => {
for (var clientId in this.clientIdToStatusMap) {
var isMissingInstance =
(this.clientIdToStatusMap[clientId] == social.ClientStatus.ONLINE) &&
!(clientId in this.clientToInstanceMap_);
if (isMissingInstance) {
log.warn('monitor could not find instance for clientId', clientId);
this.requestInstance_(clientId);
}
}
}
private requestInstance_ = (clientId:string) : void => {
log.debug('requesting instance', clientId);
var instanceRequest :social.PeerMessage = {
type: social.PeerMessageType.INSTANCE_REQUEST,
data: {}
};
this.network.send(this, clientId, instanceRequest);
}
public isInstanceOnline = (instanceId :string) : boolean => {
var clientId = this.instanceToClientMap_[instanceId];
if (!clientId) {
return false;
}
var status = this.clientIdToStatusMap[clientId];
if (status == social.ClientStatus.ONLINE) {
return true;
}
return false;
}
public getStorePath() {
return this.network.getStorePath() + this.userId;
}
public saveToStorage = () : void => {
this.onceLoaded.then(() => {
if (!this.ignoreUser_()) {
var state = this.currentState();
storage.save(this.getStorePath(), state).catch(() => {
log.error('Could not save user to storage');
});
}
});
}
public restoreState = (state :social.UserState) : void => {
if (this.name === 'pending') {
this.name = state.name;
}
if (this.name !== 'pending') {
this.fulfillNameReceived_(this.name);
}
if (typeof this.profile.imageData === 'undefined') {
this.profile.imageData = state.imageData;
}
if (typeof this.profile.url === 'undefined') {
this.profile.url = state.url;
}
if (typeof state.status === 'undefined' &&
this.network.name === 'Cloud') {
this.profile.status = social.UserStatus.CLOUD_INSTANCE_SHARED_WITH_LOCAL;
} else if (typeof state.status === 'undefined') {
this.profile.status = social.UserStatus.FRIEND;
} else {
this.profile.status = state.status;
}
// Restore all instances.
var onceLoadedPromises :Promise<void>[] = [];
for (var i in state.instanceIds) {
var instanceId = state.instanceIds[i];
if (!(instanceId in this.instances_)) {
this.instances_[instanceId] = new remote_instance.RemoteInstance(this, instanceId);
onceLoadedPromises.push(this.instances_[instanceId].onceLoaded);
}
}
Promise.all(onceLoadedPromises).then(this.fulfillStorageLoad_);
if (state.consent) {
this.consent = state.consent;
} else {
log.error(
'Error loading consent from storage for user ' + this.userId,
state);
}
}
public currentState = () :social.UserState => {
return _.cloneDeep({
name : this.name,
imageData: this.profile.imageData,
url: this.profile.url,
instanceIds: Object.keys(this.instances_),
consent: this.consent,
status: this.profile.status
});
}
public handleLogout = () : void => {
for (var instanceId in this.instances_) {
this.instances_[instanceId].handleLogout();
}
}
public sendPermissionToken = (clientId :string, token :string) => {
var message = {
type: social.PeerMessageType.PERMISSION_TOKEN,
data: {token: token}
}
this.network.send(this, clientId, message);
}
public sendInstanceHandshake = (clientId :string) : Promise<void> => {
var myInstance = this.network.myInstance;
if (!myInstance) {
// TODO: consider waiting until myInstance is constructing
// instead of dropping this message.
// Currently we will keep receiving INSTANCE_REQUEST until instance
// handshake is sent to the peer.
log.error('Attempting to send instance handshake before ready');
return;
} else if (this.network.name === 'Cloud') {
// Don't send instance handshake to cloud servers.
return;
}
// Ensure that the user is loaded so that we have correct consent bits.
return this.onceLoaded.then(() => {
var instanceMessage = {
type: social.PeerMessageType.INSTANCE,
data: {
instanceId: myInstance.instanceId,
description: globals.settings.description,
consent: {
isRequesting: this.consent.localRequestsAccessFromRemote,
isOffering: this.consent.localGrantsAccessToRemote
},
// This is not yet used for encrypted networks like Quiver.
// TODO: once we have key verification, remove publicKey
// from Quiver instance messages if it's not used, e.g. if we
// use Quiver's userId (fingerprint) for verification instead.
publicKey: globals.publicKey
}
};
return this.network.send(this, clientId, instanceMessage);
});
}
public resendInstanceHandshakes = () : void => {
for (var instanceId in this.instanceToClientMap_) {
var clientId = this.instanceToClientMap_[instanceId];
this.sendInstanceHandshake(clientId);
}
}
/**
* Modify the consent for this instance, *locally*. (User clicked on one of
* the consent buttons in the UI.) Sends updated consent bits to the
* remote instance afterwards. Returns a Promise which fulfills once
* the consent has been modified.
*/
public modifyConsent = (action :uproxy_core_api.ConsentUserAction) : Promise<void> => {
var consentModified = this.onceLoaded.then(() => {
if (!consent.handleUserAction(this.consent, action)) {
return Promise.reject(new Error(
'Invalid user action on consent ' +
JSON.stringify({
consent: this.consent,
action: action
})));
}
});
// After consent has been modified, cancel connection if needed,
// send new instance handshakes, save to storage, and update the UI.
// We don't need callers to block on any of this, so we can just
// return consentModified.
consentModified.then(() => {
// If remote is currently an active client, but user revokes access, also
// stop the proxy session.
if (uproxy_core_api.ConsentUserAction.CANCEL_OFFER === action) {
for (const instanceId in this.instances_) {
var instanceData = this.instances_[instanceId].currentStateForUi();
if (instanceData.localSharingWithRemote == social.SharingState.SHARING_ACCESS) {
this.instances_[instanceId].stopShare();
}
}
}
// Send new consent bits to all remote clients, and save to storage.
for (const instanceId in this.instances_) {
if (this.isInstanceOnline(instanceId)) {
this.sendInstanceHandshake(this.instanceToClient(instanceId));
}
}
this.saveToStorage();
// Send an update to the UI.
this.notifyUI();
});
return consentModified;
}
public updateRemoteRequestsAccessFromLocal = () => {
// Set this.consent.remoteRequestsAccessFromLocal based on if any
// instances are currently requesting access
for (var instanceId in this.instances_) {
if (this.instances_[instanceId].wireConsentFromRemote.isRequesting) {
this.consent.remoteRequestsAccessFromLocal = true;
return;
}
}
this.consent.remoteRequestsAccessFromLocal = false;
}
public handleInvitePermissions = (tokenObj ?:social.InviteTokenData) => {
var permission = tokenObj.permission;
if (!permission.isRequesting && !permission.isOffering) {
return; // Nothing to do.
}
// Ensure that user name is set (in case this is a newly constructed
// user object).
if (!this.name || this.name === 'pending') {
this.name = tokenObj.userName;
}
// Get or create an instance
var instanceId = tokenObj.instanceId;
var instance = this.getInstance(instanceId);
if (!instance) {
// Create a simulated instance handshake using permission information
var handshake :social.InstanceHandshake = {
instanceId: instanceId,
consent: {
isOffering: permission.isOffering,
isRequesting: permission.isRequesting
}
};
instance = new remote_instance.RemoteInstance(this, instanceId);
this.instances_[instanceId] = instance;
// Assume lowest possible version until we get a real instance message.
instance.update(handshake, 1);
}
if (this.isInstanceOnline(instanceId)) {
var clientId = this.instanceToClient(instanceId);
this.sendPermissionToken(clientId, permission.token);
} else {
// save permission token so that we send it back next time we get
// an instance message from them.
instance.unusedPermissionToken = permission.token;
}
// Save user and instance to storage, notify UI
this.saveToStorage();
instance.saveToStorage();
this.notifyUI();
}
} // class User | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.