text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import {Z80Ports} from './z80ports'; import {Z80RegistersClass} from '../z80registers'; import {MemBuffer, Serializeable} from '../../misc/membuffer' import {Settings} from '../../settings'; import * as Z80 from '../../3rdparty/z80.js/Z80.js'; import {SimulatedMemory} from './simmemory'; export class Z80Cpu implements Serializeable { // Pointer to the Z80.js (Z80.ts) simulator protected z80: any; // Time until next interrupt. protected remainingInterruptTstates: number; // Time for interrupt in T-States protected INTERRUPT_TIME_AS_T_STATES: number; // For calculation of the CPU load. // Summarizes all instruction besides HALT. protected cpuLoadTstates: number; // Summarizes all instruction including HALT. public cpuWithHaltTstates: number; // cpuLoadTstates divided by cpuTotalTstates. public cpuLoad: number; // The number of interrupts to calculate the average from. protected cpuLoadRange: number; // Counts the current number of interrupts. protected cpuLoadRangeCounter: number; // Used to calculate the number of t-states for a step-over or similar. // Is reset by the remote. public cpuTstatesCounter: number; // Set to true if a ZX Spectrum like interrupt should be generated. protected vsyncInterrupt: boolean; // At the moment just a constant. CPU frequency. public cpuFreq: number; // Memory public memory: SimulatedMemory; // Ports public ports: Z80Ports; // Used to indicate an error in peripherals, i.e. an error in the custom javascript code. // Will make the program break. // undefined = no error public error: string|undefined; // A function that is called when a vertical interrupt is generated. protected vertInterruptFunc: () => void; /** * Constructor. * @param memory The Z80 memory. * @param ports The Z80 ports. * @param vertInterruptFunc An optional function that is called on a vertical interrupt. * Can be used by teh caller to sync the display. */ constructor(memory: SimulatedMemory, ports: Z80Ports, vertInterruptFunc = () => {}) { this.vertInterruptFunc = vertInterruptFunc; this.error=undefined; this.memory=memory; this.ports=ports; this.cpuFreq = Settings.launch.zsim.cpuFrequency; // e.g. 3500000.0 for 3.5MHz. this.INTERRUPT_TIME_AS_T_STATES=0.02*this.cpuFreq; // 20ms * 3.5 MHz this.remainingInterruptTstates=this.INTERRUPT_TIME_AS_T_STATES; /* IM 0: Executes an instruction that is placed on the data bus by a peripheral. IM 1: Jumps to address &0038 IM 2: Uses an interrupt vector table, indexed by value on data bus. */ this.cpuTstatesCounter=0 this.cpuLoadTstates=0; this.cpuWithHaltTstates=0; this.cpuLoad=1.0; // Start with full load this.cpuLoadRangeCounter=0; this.cpuLoadRange=Settings.launch.zsim.cpuLoadInterruptRange; this.vsyncInterrupt=Settings.launch.zsim.vsyncInterrupt; // Initialize Z80, call constructor const z80n_enabled=Settings.launch.zsim.Z80N; this.z80=new (Z80.Z80 as any)({ mem_read: (address) => {return memory.read8(address);}, mem_write: (address, val) => {memory.write8(address, val); }, io_read: (address) => { try { return ports.read(address); } catch(e) { this.error="io_read: "+e.message; return 0; }; }, io_write: (address, val) => { try { ports.write(address, val); } catch (e) { this.error="io_write: "+e.message; }; }, z80n_enabled: z80n_enabled }); } /** * Executes one instruction. * @returns The number of t-states used for execution. * Sets also the 'update' variable: * true if a (vertical) interrupt happened or would have happened. * Also if interrupts are disabled at the Z80. * And also if 'vsyncInterrupt' is false. * The return value is used for regularly updating the ZSimulationView. * And this is required even if interrupts are off. Or even if * there is only Z80 simulation without ZX Spectrum. */ public execute(): number { const z80=this.z80; // Handle instruction const tStates = z80.run_instruction(); let accumulatedTstates = tStates; // Statistics if (z80.halted) { // HALT instruction if (z80.interruptsEnabled && this.vsyncInterrupt) { // HALT instructions are treated specially: // If a HALT is found the t-states to the next interrupt are calculated. // The t-states are added and the interrupt is executed immediately. // So only one HALT is ever executed, skipping execution of the others // saves processing time. accumulatedTstates = this.remainingInterruptTstates; this.remainingInterruptTstates = 0; } else { // Simply count the HALT instruction, no optimization this.cpuLoadTstates += tStates; } } else { // No HALT: Count everything besides the HALT instruction and add to cpu-load. this.cpuLoadTstates+=tStates; } // Add t-states this.cpuTstatesCounter += accumulatedTstates; this.cpuWithHaltTstates += accumulatedTstates; // Interrupt this.remainingInterruptTstates-=tStates; if (this.remainingInterruptTstates<=0) { // Interrupt this.remainingInterruptTstates = this.INTERRUPT_TIME_AS_T_STATES; // Really generate interrupt? if (this.vsyncInterrupt) { // Inform e.g. ZSimulationView about interrupt, for synching of the display this.vertInterruptFunc(); // And generate this.generateInterrupt(false, 0); } } return accumulatedTstates; } /** * Properties to set flags. */ set pc(value) { this.z80.pc=value; } get pc() {return this.z80.pc;} set sp(value) {this.z80.sp=value;} get sp() {return this.z80.sp;} set af(value) { const r=this.z80.getState(); r.a=value>>>8; r.flags=this.revConvertFlags(value&0xFF); this.z80.setState(r); } set bc(value) { const r=this.z80.getState(); r.b=value>>>8; r.c=value&0xFF; this.z80.setState(r); } set de(value) { const r=this.z80.getState(); r.d=value>>>8; r.e=value&0xFF; this.z80.setState(r); } set hl(value) { const r=this.z80.getState(); r.h=value>>>8; r.l=value&0xFF; this.z80.setState(r); } set ix(value) { const r=this.z80.getState(); r.ix=value; this.z80.setState(r); } set iy(value) { const r=this.z80.getState(); r.iy=value; this.z80.setState(r); } set af2(value) { const r=this.z80.getState(); r.a_prime=value>>>8; r.flags_prime=this.revConvertFlags(value&0xFF); this.z80.setState(r); } set bc2(value) { const r=this.z80.getState(); r.b_prime=value>>>8; r.c_prime=value&0xFF; this.z80.setState(r); } set de2(value) { const r=this.z80.getState(); r.d_prime=value>>>8; r.e_prime=value&0xFF; this.z80.setState(r); } set hl2(value) { const r=this.z80.getState(); r.h_prime=value>>>8; r.l_prime=value&0xFF; this.z80.setState(r); } set im(value) { const r=this.z80.getState(); r.imode=value; this.z80.setState(r); } set iff1(value) { const r=this.z80.getState(); r.iff1=value; this.z80.setState(r); } set iff2(value) { const r=this.z80.getState(); r.iff2=value; this.z80.setState(r); } set r(value) { const r=this.z80.getState(); r.r=value; this.z80.setState(r); } set i(value) { const r=this.z80.getState(); r.i=value; this.z80.setState(r); } set a(value) { const r=this.z80.getState(); r.a=value; this.z80.setState(r); } set f(value) { const r=this.z80.getState(); r.f=this.revConvertFlags(value); this.z80.setState(r); } set b(value) { const r=this.z80.getState(); r.b=value; this.z80.setState(r); } set c(value) { const r=this.z80.getState(); r.c=value; this.z80.setState(r); } set d(value) { const r=this.z80.getState(); r.d=value; this.z80.setState(r); } set e(value) { const r=this.z80.getState(); r.e=value; this.z80.setState(r); } set h(value) { const r=this.z80.getState(); r.h=value; this.z80.setState(r); } set l(value) { const r=this.z80.getState(); r.l=value; this.z80.setState(r); } set ixl(value) { const r=this.z80.getState(); r.ix=(r.ix&0xFF00)+value; this.z80.setState(r); } set ixh(value) { const r=this.z80.getState(); r.ix=(r.ix&0xFF)+256*value; this.z80.setState(r); } set iyl(value) { const r=this.z80.getState(); r.iy=(r.iy&0xFF00)+value; this.z80.setState(r); } set iyh(value) { const r=this.z80.getState(); r.iy=(r.iy&0xFF)+256*value; this.z80.setState(r); } /** * Simulates pulsing the processor's INT (or NMI) pin. * Is called for the ULA vertical sync and also from custom code. * @param non_maskable - true if this is a non-maskable interrupt. * @param data - the value to be placed on the data bus, if needed. */ public generateInterrupt(non_maskable: boolean, data: number) { this.z80.interrupt(non_maskable, data); // Measure CPU load this.cpuLoadRangeCounter++; if (this.cpuLoadRangeCounter>=this.cpuLoadRange) { if (this.cpuWithHaltTstates>0) { this.cpuLoad=this.cpuLoadTstates/this.cpuWithHaltTstates; this.cpuLoadTstates=0; this.cpuWithHaltTstates=0; this.cpuLoadRangeCounter=0; } } } /** * Converts the Z80 flags object into a number. */ protected convertFlags(flags: { S: number, Z: number, Y: number, H: number, X: number, P: number, N: number, C: number }): number { const f=128*flags.S+64*flags.Z+32*flags.Y+16*flags.H+8*flags.X+4*flags.P+2*flags.N+flags.C; return f; } /** * Returns all registers. */ protected getAllRegisters(): { pc: number, sp: number, af: number, bc: number, de: number, hl: number, ix: number, iy: number, af2: number, bc2: number, de2: number, hl2: number, i: number, r: number, im: number, iff1: number, iff2: number, } { const r=this.z80.getState(); const flags=this.convertFlags(r.flags); const flags2=this.convertFlags(r.flags_prime); const regs={ pc: r.pc, sp: r.sp, af: r.a*256+flags, bc: r.b*256+r.c, de: r.d*256+r.e, hl: r.h*256+r.l, ix: r.ix, iy: r.iy, af2: r.a_prime*256+flags2, bc2: r.b_prime*256+r.c_prime, de2: r.d_prime*256+r.e_prime, hl2: r.h_prime*256+r.l_prime, i: r.i, r: r.r, im: r.imode, iff1: r.iff1, iff2: r.iff2 }; return regs; } /** * Returns the register data in the Z80Registers format. */ public getRegisterData(): Uint16Array { const r=this.getAllRegisters(); // Convert regs const slots=this.memory.getSlots()||[]; const regData=Z80RegistersClass.getRegisterData( r.pc, r.sp, r.af, r.bc, r.de, r.hl, r.ix, r.iy, r.af2, r.bc2, r.de2, r.hl2, r.i, r.r, r.im, slots ); return regData; } /** * Returns the register, opcode and sp contents data, */ public getHistoryData(): Uint16Array { // Get registers const regData=this.getRegisterData(); // Add opcode and sp contents const startHist=regData.length; const histData=new Uint16Array(startHist+3); // Copy registers histData.set(regData); // Store opcode (4 bytes) const z80=this.z80; const pc=z80.pc; const opcodes=this.memory.getMemory32(pc); histData[startHist]=opcodes&0xFFFF; histData[startHist+1]=opcodes>>>16; // Store sp contents (2 bytes) const sp=z80.sp; const spContents=this.memory.getMemory16(sp); histData[startHist+2]=spContents; // return return histData; } /** * Returns the size the serialized object would consume. */ public getSerializedSize(): number { // Create a MemBuffer to calculate the size. const memBuffer=new MemBuffer(); // Serialize object to obtain size this.serialize(memBuffer); // Get size const size=memBuffer.getSize(); return size; } /** * Converts the Z80 flags object into a number. */ protected revConvertFlags(flags: number): { S: number, Z: number, Y: number, H: number, X: number, P: number, N: number, C: number } { const f={ S: (flags>>>7)&0x01, Z: (flags>>>6)&0x01, Y: (flags>>>5)&0x01, H: (flags>>>4)&0x01, X: (flags>>>3)&0x01, P: (flags>>>2)&0x01, N: (flags>>>1)&0x01, C: flags&0x01, }; return f; } /** * Serializes the object. */ public serialize(memBuffer: MemBuffer) { // Save all registers etc. const r=this.getAllRegisters(); // Store memBuffer.write16(r.pc); memBuffer.write16(r.sp); memBuffer.write16(r.af); memBuffer.write16(r.bc); memBuffer.write16(r.de); memBuffer.write16(r.hl); memBuffer.write16(r.ix); memBuffer.write16(r.iy); memBuffer.write16(r.af2); memBuffer.write16(r.bc2); memBuffer.write16(r.de2); memBuffer.write16(r.hl2); // Also the 1 byte data is stored in 2 bytes for simplicity: memBuffer.write8(r.i); memBuffer.write8(r.r); memBuffer.write8(r.im); memBuffer.write8(r.iff1); memBuffer.write8(r.iff2); // Additional const s=this.z80.getState(); memBuffer.write8(Number(s.halted)); memBuffer.write8(Number(s.do_delayed_di)); memBuffer.write8(Number(s.do_delayed_ei)); //memBuffer.write8(s.cycle_counter); // Additional state memBuffer.writeNumber(this.remainingInterruptTstates); memBuffer.writeNumber(this.cpuTstatesCounter); } /** * Deserializes the object. */ public deserialize(memBuffer: MemBuffer) { // Store let r=new Object() as any; r.pc=memBuffer.read16(); r.sp=memBuffer.read16(); const af=memBuffer.read16(); r.a=af>>>8; r.flags=this.revConvertFlags(af&0xFF); const bc=memBuffer.read16(); r.b=bc>>>8; r.c=bc&0xFF; const de=memBuffer.read16(); r.d=de>>>8; r.e=de&0xFF; const hl=memBuffer.read16(); r.h=hl>>>8; r.l=hl&0xFF; r.ix=memBuffer.read16(); r.iy=memBuffer.read16(); const af2=memBuffer.read16(); r.a_prime=af2>>>8; r.flags_prime=this.revConvertFlags(af2&0xFF); const bc2=memBuffer.read16(); r.b_prime=bc2>>>8; r.c_prime=bc2&0xFF; const de2=memBuffer.read16(); r.d_prime=de2>>>8; r.e_prime=de2&0xFF; const hl2=memBuffer.read16(); r.h_prime=hl2>>>8; r.l_prime=hl2&0xFF; // Also the 1 byte data is stored in 2 bytes for simplicity: r.i=memBuffer.read8(); r.r=memBuffer.read8(); r.imode=memBuffer.read8(); r.iff1=memBuffer.read8(); r.iff2=memBuffer.read8(); // Additional r.halted=(memBuffer.read8()!=0); r.do_delayed_di=(memBuffer.read8()!=0); r.do_delayed_ei=(memBuffer.read8()!=0); r.cycle_counter=0; // Restore all registers etc. const z80=this.z80; z80.setState(r); // Additional state this.remainingInterruptTstates = memBuffer.readNumber(); this.cpuTstatesCounter = memBuffer.readNumber(); // Reset statistics this.cpuLoadTstates=0; this.cpuWithHaltTstates=0; this.cpuLoad = 1.0; // Start with full load } }
the_stack
import Application from "./application"; import StreamClient from "./streamclient"; // const xCloudClient from '../xsdk/client.js' export default class StreamingView { _application:Application _streamClient:StreamClient _streamActive = false _lastMouseMovement = 0 _mouseInterval:any _keepAliveInterval:any _networkIndicatorLastToggle = 0 _showDebug = false // _quality = { // video: 'bad', // audio: 'unknown', // metadata: 'unknown', // gamepad: 'unknown', // } _qualityVideo = 'perfect' _qualityAudio = 'perfect' _qualityMetadata = 'perfect' _qualityGamepad = 'perfect' constructor(application:Application){ this._application = application console.log('StreamingView.js: Created view') document.onmousemove = () => { this._lastMouseMovement = Date.now() } document.onkeypress = (e:any) => { e = e || window.event; switch(e.keyCode){ case 126: this._showDebug = (this._showDebug === false) ? true : false this.updateDebugLayer() break; } }; document.onkeydown = (e:any) => { e = e || window.event; console.log('pressed key:', e.keyCode) if(this._application._StreamingView._streamClient !== undefined){ switch(e.keyCode){ case 38: this._application._StreamingView._streamClient._xCloudPlayer.getChannelProcessor('input').pressButton(0, { DPadUp: 1 }) break; case 40: this._application._StreamingView._streamClient._xCloudPlayer.getChannelProcessor('input').pressButton(0, { DPadDown: 1 }) break; case 37: this._application._StreamingView._streamClient._xCloudPlayer.getChannelProcessor('input').pressButton(0, { DPadLeft: 1 }) break; case 39: this._application._StreamingView._streamClient._xCloudPlayer.getChannelProcessor('input').pressButton(0, { DPadRight: 1 }) break; case 13: case 65: this._application._StreamingView._streamClient._xCloudPlayer.getChannelProcessor('input').pressButton(0, { A: 1 }) break; case 8: case 66: this._application._StreamingView._streamClient._xCloudPlayer.getChannelProcessor('input').pressButton(0, { B: 1 }) break; case 88: this._application._StreamingView._streamClient._xCloudPlayer.getChannelProcessor('input').pressButton(0, { X: 1 }) break; case 89: this._application._StreamingView._streamClient._xCloudPlayer.getChannelProcessor('input').pressButton(0, { Y: 1 }) break; case 78: this._application._StreamingView._streamClient._xCloudPlayer.getChannelProcessor('input').pressButton(0, { Nexus: 1 }) break; case 219: this._application._StreamingView._streamClient._xCloudPlayer.getChannelProcessor('input').pressButton(0, { LeftShoulder: 1 }) break; case 221: this._application._StreamingView._streamClient._xCloudPlayer.getChannelProcessor('input').pressButton(0, { RightShoulder: 1 }) break; case 86: this._application._StreamingView._streamClient._xCloudPlayer.getChannelProcessor('input').pressButton(0, { View: 1 }) break; case 77: this._application._StreamingView._streamClient._xCloudPlayer.getChannelProcessor('input').pressButton(0, { Menu: 1 }) break; case 48: this._application._StreamingView._streamClient._xCloudPlayer.getChannelProcessor('audio')._softReset() break; } } }; // Display loading screen... const actionBar = (<HTMLInputElement>document.getElementById('loadingScreen')) actionBar.style.display = 'block' // Handle network indicator const checkNetworkIndicator = () => { let overallQuality = 'perfect' if((this._qualityVideo === 'good' || this._qualityAudio === 'good' || this._qualityMetadata === 'good' || this._qualityGamepad === 'good') && overallQuality === 'perfect'){ overallQuality = 'good' } if((this._qualityVideo === 'low' || this._qualityAudio === 'low' || this._qualityMetadata === 'low' || this._qualityGamepad === 'low') && (overallQuality === 'good' || overallQuality === 'perfect')){ overallQuality = 'low' } if((this._qualityVideo === 'bad' || this._qualityAudio === 'bad' || this._qualityMetadata === 'bad' || this._qualityGamepad === 'bad') && (overallQuality === 'bad' || overallQuality === 'good' || overallQuality === 'perfect')){ overallQuality = 'bad' } const niVideo = (<HTMLInputElement>document.getElementById('niVideo')) const niAudio = (<HTMLInputElement>document.getElementById('niAudio')) const niMetadata = (<HTMLInputElement>document.getElementById('niMetadata')) const niGamepad = (<HTMLInputElement>document.getElementById('niGamepad')) niVideo.innerHTML = (this._qualityVideo === 'perfect' || this._qualityVideo === 'good') ? '&#x2713;' : this._qualityVideo niAudio.innerHTML = (this._qualityAudio === 'perfect' || this._qualityAudio === 'good') ? '&#x2713;' : this._qualityAudio niMetadata.innerHTML = (this._qualityMetadata === 'perfect' || this._qualityMetadata === 'good') ? '&#x2713;' : this._qualityMetadata niGamepad.innerHTML = (this._qualityGamepad === 'perfect' || this._qualityGamepad === 'good') ? '&#x2713;' : this._qualityGamepad console.log('stream quality is:', overallQuality) const actionBar = (<HTMLInputElement>document.getElementById('networkIndicator')) if(overallQuality === 'low' || overallQuality === 'bad'){ // actionBar.style.display = 'block' if(actionBar.classList.contains('hidden')) actionBar.classList.remove('hidden') this._networkIndicatorLastToggle = Math.floor(Date.now() / 1000) } else { if((Math.floor(Date.now() / 1000) - this._networkIndicatorLastToggle) > 3){ // actionBar.style.display = 'none' if(! actionBar.classList.contains('hidden')) actionBar.classList.add('hidden') this._networkIndicatorLastToggle = Math.floor(Date.now() / 1000) } } if(this._streamActive === false){ setTimeout(checkNetworkIndicator, 500) } } setTimeout(checkNetworkIndicator, 500) } startStream(type:string, serverId:string):void { console.log('StreamingView.js: Start stream for:', serverId) this._streamClient = new StreamClient() const streamStatus = (<HTMLInputElement>document.getElementById('streamStatus')) streamStatus.innerHTML = 'Connecting to: '+ serverId const loadingStatus = (<HTMLInputElement>document.getElementById('loadingStatus')) loadingStatus.innerHTML = 'Connecting to console: '+ serverId +'<br /><span id="streamStatusDetailed">Provisioning...</span>' this._streamClient.start(this._application, type, serverId).then(() => { console.log('StreamingView.js: Stream started for:', serverId) // this._streamClient._xCloudPlayer.addEventListener('connect', (event:any) => { // const streamStatus = (<HTMLInputElement>document.getElementById('streamStatus')) // streamStatus.innerHTML = 'Connecting to '+ event.serverId // console.log('STREAM CONNECT') // }) // this._streamClient._xCloudPlayer.addEventListener('openstream', (event:any) => { // const streamStatus = (<HTMLInputElement>document.getElementById('streamStatus')) // streamStatus.innerHTML = 'Connected to '+ event.serverId // console.log('STREAM CONNECTED') // }) document.getElementById('request_videoframe').onclick = (event:any) => { console.log('streamingView.js: Requesting videokeyframe') this._streamClient._xCloudPlayer.getChannelProcessor('video').resetBuffer() console.log('streamingView.js: Requested videokeyframe') } this._streamClient._xCloudPlayer.getEventBus().on('fps_video', (event:any) => { document.getElementById('videoFpsCounter').innerHTML = event.fps }) this._streamClient._xCloudPlayer.getEventBus().on('fps_audio', (event:any) => { document.getElementById('audioFpsCounter').innerHTML = event.fps }) this._streamClient._xCloudPlayer.getEventBus().on('fps_metadata', (event:any) => { document.getElementById('metadataFpsCounter').innerHTML = event.fps }) this._streamClient._xCloudPlayer.getEventBus().on('fps_input', (event:any) => { document.getElementById('inputFpsCounter').innerHTML = event.fps }) this._streamClient._xCloudPlayer.getEventBus().on('bitrate_video', (event:any) => { // document.getElementById('videoBitrate').innerHTML = JSON.stringify(event) document.getElementById('videoBitrate').innerHTML = (event.data/8)+' KBps / '+(event.packets/8)+' KBps' }) this._streamClient._xCloudPlayer.getEventBus().on('bitrate_audio', (event:any) => { document.getElementById('audioBitrate').innerHTML = (event.data/8)+' KBps / '+(event.packets/8)+' KBps' // document.getElementById('audioBitrate').innerHTML = (event.audioBitrate/8)+' KBps' }) this._streamClient._xCloudPlayer.getEventBus().on('latency_audio', (event:any) => { // console.log('FPS Event:', event) document.getElementById('audioLatencyCounter').innerHTML = 'min: '+event.min+'ms / avg: '+event.avg+'ms / max: '+event.max+'ms' }) this._streamClient._xCloudPlayer.getEventBus().on('latency_video', (event:any) => { // console.log('FPS Event:', event) document.getElementById('videoLatencyCounter').innerHTML = 'min: '+event.min+'ms / avg: '+event.avg+'ms / max: '+event.max+'ms' }) // // OLD FUNCTIONS BELOW // this.streamIsReady() // const streamStatus = (<HTMLInputElement>document.getElementById('streamStatus')) streamStatus.innerHTML = 'Connected to: '+ serverId const streamStatusDetailed = (<HTMLInputElement>document.getElementById('streamStatusDetailed')) streamStatusDetailed.innerHTML = 'Waiting for video stream...' setTimeout(() => { const loadingPage = (<HTMLInputElement>document.getElementById('loadingScreen')) loadingPage.style.display = 'none' const videoHolder = (<HTMLInputElement>document.getElementById('videoHolder')) videoHolder.style.display = 'block' const videoRender = (<HTMLInputElement>document.querySelector("#videoHolder video")) videoRender.width = videoHolder.clientWidth videoRender.height = videoHolder.clientHeight }, 1000) // Show link in menubar const activeStreamingView = (<HTMLInputElement>document.getElementById('actionBarStreamingViewActive')) const actionBarStreamingDisconnect = (<HTMLInputElement>document.getElementById('actionBarStreamingDisconnect')) const actionBarStreamingDisconnectElem = (<HTMLInputElement>document.getElementById('actionBarStreamingDisconnect')) activeStreamingView.style.display = (this._streamActive === true) ? 'block': 'none' actionBarStreamingDisconnectElem.style.display = (this._streamActive === true) ? 'block': 'none' actionBarStreamingDisconnect.addEventListener('click', () => { // alert('Disconnect stream') this._streamClient.disconnect() // clearInterval(this._keepAliveInterval) }) // this._streamClient._xCloudPlayer.getChannelProcessor('input').addEventListener('latency', (event:any) => { // // console.log('FPS Event:', event) // document.getElementById('inputLatencyCounter').innerHTML = 'min: '+event.minLatency+'ms / avg: '+event.avgLatency+'ms / max: '+event.maxLatency+'ms' // if(event.maxLatency > 150 && event.maxLatency <= 300){ // this._qualityMetadata = 'good' // } else if(event.maxLatency > 300 && event.maxLatency <= 450){ // this._qualityMetadata = 'low' // } else if(event.maxLatency > 450){ // this._qualityMetadata = 'bad' // } else { // this._qualityMetadata = 'perfect' // } // }) // this._streamClient._xCloudPlayer.getChannelProcessor('input').addEventListener('gamepadlatency', (event:any) => { // // console.log('FPS Event:', event) // document.getElementById('gamepadLatencyCounter').innerHTML = 'min: '+event.minLatency+'ms / avg: '+event.avgLatency+'ms / max: '+event.maxLatency+'ms' // if(event.maxLatency > 10 && event.maxLatency <= 25){ // this._qualityGamepad = 'good' // } else if(event.maxLatency > 25 && event.maxLatency < 100){ // this._qualityGamepad = 'low' // } else if(event.maxLatency > 100){ // this._qualityGamepad = 'bad' // } else { // this._qualityGamepad = 'perfect' // } // }) // Debug: Performance // this._streamClient._xCloudPlayer.getChannelProcessor('video').addEventListener('queue', (event:any) => { // document.getElementById('videoPerformance').innerHTML = JSON.stringify(event) // }) // this._streamClient._xCloudPlayer.getChannelProcessor('video').addEventListener('latency', (event:any) => { // document.getElementById('videoLatency').innerHTML = JSON.stringify(event) // }) // this._streamClient._xCloudPlayer.getChannelProcessor('audio').addEventListener('queue', (event:any) => { // document.getElementById('audioPerformance').innerHTML = JSON.stringify(event) // }) // this._streamClient._xCloudPlayer.getChannelProcessor('audio').addEventListener('latency', (event:any) => { // document.getElementById('audioLatency').innerHTML = JSON.stringify(event) // }) // this._streamClient._xCloudPlayer.getChannelProcessor('input').addEventListener('queue', (event:any) => { // document.getElementById('inputPerformance').innerHTML = JSON.stringify(event) // }) // this._streamClient._xCloudPlayer.getChannelProcessor('input').addEventListener('latency', (event:any) => { // document.getElementById('inputLatency').innerHTML = JSON.stringify(event) // }) // Bitrate control // document.getElementById('control_bitrate_512').onclick = (event:any) => { // this._streamClient._xCloudPlayer.getChannelProcessor('control').setBitrate(512) // console.log('streamingView.js: Set bitrate to 512') // } // document.getElementById('control_bitrate_2500').onclick = (event:any) => { // this._streamClient._xCloudPlayer.getChannelProcessor('control').setBitrate(2500) // console.log('streamingView.js: Set bitrate to 2500') // } // document.getElementById('control_bitrate_5000').onclick = (event:any) => { // this._streamClient._xCloudPlayer.getChannelProcessor('control').setBitrate(5000) // console.log('streamingView.js: Set bitrate to 5000') // } // document.getElementById('control_bitrate_8500').onclick = (event:any) => { // this._streamClient._xCloudPlayer.getChannelProcessor('control').setBitrate(8500) // console.log('streamingView.js: Set bitrate to 8500') // } // document.getElementById('control_bitrate_12000').onclick = (event:any) => { // this._streamClient._xCloudPlayer.getChannelProcessor('control').setBitrate(12000) // console.log('streamingView.js: Set bitrate to 12000') // } // Dialogs // this._streamClient._xCloudPlayer.getChannelProcessor('message').addEventListener('dialog', (event:any) => { // console.log('Got dialog event:', event) // document.getElementById('modalDialog').style.display = 'block' // document.getElementById('dialogTitle').innerHTML = event.TitleText // document.getElementById('dialogText').innerHTML = event.ContentText // if(event.CommandLabel1 !== '') // document.getElementById('dialogButton1').innerHTML = event.CommandLabel1 // else // document.getElementById('dialogButton1').style.display = 'none' // if(event.CommandLabel2 !== '') // document.getElementById('dialogButton2').innerHTML = event.CommandLabel2 // else // document.getElementById('dialogButton2').style.display = 'none' // if(event.CommandLabel3 !== '') // document.getElementById('dialogButton3').innerHTML = event.CommandLabel3 // else // document.getElementById('dialogButton3').style.display = 'none' // // if(event.CancelIndex != event.DefaultIndex){ // const primaryIndex = (event.DefaultIndex+1) // console.log('prim index', primaryIndex) // document.getElementById('dialogButton'+primaryIndex).classList.add("btn-primary") // // } // // var cancelIndex = (event.CancelIndex+1) // // document.getElementById('dialogButton'+cancelIndex).classList.add("btn-cancel") // document.getElementById('dialogButton1').onclick = (clickEvent) =>{ // this._streamClient._xCloudPlayer.getChannelProcessor('message').sendTransaction(event.id, { Result: 0 }) // resetDialog() // } // document.getElementById('dialogButton2').onclick = (clickEvent) => { // this._streamClient._xCloudPlayer.getChannelProcessor('message').sendTransaction(event.id, { Result: 1 }) // resetDialog() // } // document.getElementById('dialogButton3').onclick = (clickEvent) => { // this._streamClient._xCloudPlayer.getChannelProcessor('message').sendTransaction(event.id, { Result: 2 }) // resetDialog() // } // }) // const resetDialog = function(){ // document.getElementById('modalDialog').style.display = 'none' // document.getElementById('dialogTitle').innerHTML = 'No active dialog' // document.getElementById('dialogText').innerHTML = 'There is no active dialog. This is an error. Please try gain.' // document.getElementById('dialogButton1').innerHTML = 'Button1' // document.getElementById('dialogButton2').innerHTML = 'Button2' // document.getElementById('dialogButton3').innerHTML = 'Button3' // document.getElementById('dialogButton1').style.display = 'inline-block' // document.getElementById('dialogButton2').style.display = 'inline-block' // document.getElementById('dialogButton3').style.display = 'inline-block' // document.getElementById('dialogButton1').classList.remove("btn-primary") // document.getElementById('dialogButton2').classList.remove("btn-primary") // document.getElementById('dialogButton3').classList.remove("btn-primary") // document.getElementById('dialogButton1').classList.remove("btn-cancel") // document.getElementById('dialogButton2').classList.remove("btn-cancel") // document.getElementById('dialogButton3').classList.remove("btn-cancel") // document.getElementById('dialogButton1').onclick = function(){} // document.getElementById('dialogButton2').onclick = function(){} // document.getElementById('dialogButton3').onclick = function(){} // } }).catch((error) => { console.log('StreamingView.js: Start stream error:', error) // alert('Start stream error: '+ JSON.stringify(error)) const streamStatusDetailed = (<HTMLInputElement>document.getElementById('streamStatusDetailed')) streamStatusDetailed.innerHTML = 'Error provisioning xbox: '+JSON.stringify(error) }) } streamIsReady():void { this._streamActive = true // this._keepAliveInterval = setInterval(() => { // this._streamClient.sendKeepalive() // }, 60000) this._mouseInterval = setInterval(() => { const lastMovement = (Date.now()-this._lastMouseMovement)/1000 // console.log('last Movement:', lastMovement) if(lastMovement > 3){ const actionBar = (<HTMLInputElement>document.getElementById('actionBar')) // actionBar.style.display = 'none' if(! actionBar.classList.contains('hidden')) actionBar.classList.add('hidden') } else { const actionBar = (<HTMLInputElement>document.getElementById('actionBar')) // actionBar.style.display = 'block' if(actionBar.classList.contains('hidden')) actionBar.classList.remove('hidden') } }, 250) } updateDebugLayer(){ const debugRightTop = (<HTMLInputElement>document.getElementById('debugRightTop')) const debugRightBottom = (<HTMLInputElement>document.getElementById('debugRightBottom')) const debugLeftBottom = (<HTMLInputElement>document.getElementById('debugLeftBottom')) debugRightTop.style.display = (this._showDebug === true) ? 'block' : 'none' debugRightBottom.style.display = (this._showDebug === true) ? 'block' : 'none' debugLeftBottom.style.display = (this._showDebug === true) ? 'block' : 'none' } load(){ return new Promise((resolve, reject) => { console.log('StreamingView.js: Loaded view') if(this._mouseInterval != undefined){ this._mouseInterval = setInterval(() => { const lastMovement = (Date.now()-this._lastMouseMovement)/1000 // console.log('last Movement:', lastMovement) if(lastMovement > 5){ const actionBar = (<HTMLInputElement>document.getElementById('actionBar')) if(actionBar.classList.contains('hidden')) actionBar.classList.add('hidden') } else { const actionBar = (<HTMLInputElement>document.getElementById('actionBar')) if(actionBar.classList.contains('hidden')) actionBar.classList.remove('hidden') } }, 1000) } resolve(true) }) } unload(){ return new Promise((resolve, reject) => { console.log('StreamingView.js: Unloaded view') clearInterval(this._mouseInterval) const actionBar = (<HTMLInputElement>document.getElementById('actionBar')) // actionBar.style.display = 'block' if(actionBar.classList.contains('hidden')) actionBar.classList.remove('hidden') resolve(true) }) } }
the_stack
type Long = protobuf.Long; // DO NOT EDIT! This is a generated file. Edit the JSDoc in src/*.js instead and run 'npm run types'. /** Namespace pb_test. */ declare namespace pb_test { /** Properties of a ResData. */ interface IResData { /** ResData result */ result: number; /** ResData param */ param?: (string[]|null); } /** Represents a ResData. */ class ResData implements IResData { /** * Constructs a new ResData. * @param [properties] Properties to set */ constructor(properties?: pb_test.IResData); /** ResData result. */ public result: number; /** ResData param. */ public param: string[]; /** * Creates a new ResData instance using the specified properties. * @param [properties] Properties to set * @returns ResData instance */ public static create(properties?: pb_test.IResData): pb_test.ResData; /** * Encodes the specified ResData message. Does not implicitly {@link pb_test.ResData.verify|verify} messages. * @param message ResData message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.IResData, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a ResData message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ResData * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.ResData; /** * Verifies a ResData message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Pt_GetAsset. */ interface IPt_GetAsset { /** Pt_GetAsset asset_type */ asset_type: number; /** Pt_GetAsset asset_num */ asset_num: (number|Long); } /** Represents a Pt_GetAsset. */ class Pt_GetAsset implements IPt_GetAsset { /** * Constructs a new Pt_GetAsset. * @param [properties] Properties to set */ constructor(properties?: pb_test.IPt_GetAsset); /** Pt_GetAsset asset_type. */ public asset_type: number; /** Pt_GetAsset asset_num. */ public asset_num: (number|Long); /** * Creates a new Pt_GetAsset instance using the specified properties. * @param [properties] Properties to set * @returns Pt_GetAsset instance */ public static create(properties?: pb_test.IPt_GetAsset): pb_test.Pt_GetAsset; /** * Encodes the specified Pt_GetAsset message. Does not implicitly {@link pb_test.Pt_GetAsset.verify|verify} messages. * @param message Pt_GetAsset message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.IPt_GetAsset, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Pt_GetAsset message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Pt_GetAsset * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Pt_GetAsset; /** * Verifies a Pt_GetAsset message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Pt_BaseGoods. */ interface IPt_BaseGoods { /** Pt_BaseGoods base_id */ base_id: number; /** Pt_BaseGoods num */ num: number; } /** Represents a Pt_BaseGoods. */ class Pt_BaseGoods implements IPt_BaseGoods { /** * Constructs a new Pt_BaseGoods. * @param [properties] Properties to set */ constructor(properties?: pb_test.IPt_BaseGoods); /** Pt_BaseGoods base_id. */ public base_id: number; /** Pt_BaseGoods num. */ public num: number; /** * Creates a new Pt_BaseGoods instance using the specified properties. * @param [properties] Properties to set * @returns Pt_BaseGoods instance */ public static create(properties?: pb_test.IPt_BaseGoods): pb_test.Pt_BaseGoods; /** * Encodes the specified Pt_BaseGoods message. Does not implicitly {@link pb_test.Pt_BaseGoods.verify|verify} messages. * @param message Pt_BaseGoods message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.IPt_BaseGoods, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Pt_BaseGoods message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Pt_BaseGoods * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Pt_BaseGoods; /** * Verifies a Pt_BaseGoods message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Pt_BaseGene. */ interface IPt_BaseGene { /** Pt_BaseGene base_id */ base_id: number; /** Pt_BaseGene strg_rank */ strg_rank: number; /** Pt_BaseGene star_rank */ star_rank: number; /** Pt_BaseGene limit_id */ limit_id: number; } /** Represents a Pt_BaseGene. */ class Pt_BaseGene implements IPt_BaseGene { /** * Constructs a new Pt_BaseGene. * @param [properties] Properties to set */ constructor(properties?: pb_test.IPt_BaseGene); /** Pt_BaseGene base_id. */ public base_id: number; /** Pt_BaseGene strg_rank. */ public strg_rank: number; /** Pt_BaseGene star_rank. */ public star_rank: number; /** Pt_BaseGene limit_id. */ public limit_id: number; /** * Creates a new Pt_BaseGene instance using the specified properties. * @param [properties] Properties to set * @returns Pt_BaseGene instance */ public static create(properties?: pb_test.IPt_BaseGene): pb_test.Pt_BaseGene; /** * Encodes the specified Pt_BaseGene message. Does not implicitly {@link pb_test.Pt_BaseGene.verify|verify} messages. * @param message Pt_BaseGene message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.IPt_BaseGene, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Pt_BaseGene message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Pt_BaseGene * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Pt_BaseGene; /** * Verifies a Pt_BaseGene message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a DrawAward. */ interface IDrawAward { /** DrawAward award_goods */ award_goods?: (pb_test.IPt_BaseGoods[]|null); /** DrawAward award_asset */ award_asset?: (pb_test.IPt_GetAsset[]|null); /** DrawAward award_genome */ award_genome?: (pb_test.IPt_BaseGene[]|null); } /** Represents a DrawAward. */ class DrawAward implements IDrawAward { /** * Constructs a new DrawAward. * @param [properties] Properties to set */ constructor(properties?: pb_test.IDrawAward); /** DrawAward award_goods. */ public award_goods: pb_test.IPt_BaseGoods[]; /** DrawAward award_asset. */ public award_asset: pb_test.IPt_GetAsset[]; /** DrawAward award_genome. */ public award_genome: pb_test.IPt_BaseGene[]; /** * Creates a new DrawAward instance using the specified properties. * @param [properties] Properties to set * @returns DrawAward instance */ public static create(properties?: pb_test.IDrawAward): pb_test.DrawAward; /** * Encodes the specified DrawAward message. Does not implicitly {@link pb_test.DrawAward.verify|verify} messages. * @param message DrawAward message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.IDrawAward, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a DrawAward message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DrawAward * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.DrawAward; /** * Verifies a DrawAward message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a HeroExpMsg. */ interface IHeroExpMsg { /** HeroExpMsg hero_id */ hero_id: number; /** HeroExpMsg grade */ grade: number; /** HeroExpMsg exp */ exp: number; } /** Represents a HeroExpMsg. */ class HeroExpMsg implements IHeroExpMsg { /** * Constructs a new HeroExpMsg. * @param [properties] Properties to set */ constructor(properties?: pb_test.IHeroExpMsg); /** HeroExpMsg hero_id. */ public hero_id: number; /** HeroExpMsg grade. */ public grade: number; /** HeroExpMsg exp. */ public exp: number; /** * Creates a new HeroExpMsg instance using the specified properties. * @param [properties] Properties to set * @returns HeroExpMsg instance */ public static create(properties?: pb_test.IHeroExpMsg): pb_test.HeroExpMsg; /** * Encodes the specified HeroExpMsg message. Does not implicitly {@link pb_test.HeroExpMsg.verify|verify} messages. * @param message HeroExpMsg message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.IHeroExpMsg, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a HeroExpMsg message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns HeroExpMsg * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.HeroExpMsg; /** * Verifies a HeroExpMsg message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a BattleAward. */ interface IBattleAward { /** BattleAward draw_award */ draw_award?: (pb_test.IDrawAward[]|null); /** BattleAward hero_exp_msg */ hero_exp_msg?: (pb_test.IHeroExpMsg[]|null); } /** Represents a BattleAward. */ class BattleAward implements IBattleAward { /** * Constructs a new BattleAward. * @param [properties] Properties to set */ constructor(properties?: pb_test.IBattleAward); /** BattleAward draw_award. */ public draw_award: pb_test.IDrawAward[]; /** BattleAward hero_exp_msg. */ public hero_exp_msg: pb_test.IHeroExpMsg[]; /** * Creates a new BattleAward instance using the specified properties. * @param [properties] Properties to set * @returns BattleAward instance */ public static create(properties?: pb_test.IBattleAward): pb_test.BattleAward; /** * Encodes the specified BattleAward message. Does not implicitly {@link pb_test.BattleAward.verify|verify} messages. * @param message BattleAward message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.IBattleAward, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a BattleAward message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns BattleAward * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.BattleAward; /** * Verifies a BattleAward message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Pt_AttList. */ interface IPt_AttList { /** Pt_AttList att_id */ att_id: number; /** Pt_AttList att_value */ att_value: number; } /** Represents a Pt_AttList. */ class Pt_AttList implements IPt_AttList { /** * Constructs a new Pt_AttList. * @param [properties] Properties to set */ constructor(properties?: pb_test.IPt_AttList); /** Pt_AttList att_id. */ public att_id: number; /** Pt_AttList att_value. */ public att_value: number; /** * Creates a new Pt_AttList instance using the specified properties. * @param [properties] Properties to set * @returns Pt_AttList instance */ public static create(properties?: pb_test.IPt_AttList): pb_test.Pt_AttList; /** * Encodes the specified Pt_AttList message. Does not implicitly {@link pb_test.Pt_AttList.verify|verify} messages. * @param message Pt_AttList message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.IPt_AttList, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Pt_AttList message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Pt_AttList * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Pt_AttList; /** * Verifies a Pt_AttList message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Pt_HeroAttList. */ interface IPt_HeroAttList { /** Pt_HeroAttList hid */ hid: (number|Long); /** Pt_HeroAttList hero_id */ hero_id: number; /** Pt_HeroAttList index_id */ index_id: number; /** Pt_HeroAttList att_list */ att_list?: (pb_test.IPt_AttList[]|null); } /** Represents a Pt_HeroAttList. */ class Pt_HeroAttList implements IPt_HeroAttList { /** * Constructs a new Pt_HeroAttList. * @param [properties] Properties to set */ constructor(properties?: pb_test.IPt_HeroAttList); /** Pt_HeroAttList hid. */ public hid: (number|Long); /** Pt_HeroAttList hero_id. */ public hero_id: number; /** Pt_HeroAttList index_id. */ public index_id: number; /** Pt_HeroAttList att_list. */ public att_list: pb_test.IPt_AttList[]; /** * Creates a new Pt_HeroAttList instance using the specified properties. * @param [properties] Properties to set * @returns Pt_HeroAttList instance */ public static create(properties?: pb_test.IPt_HeroAttList): pb_test.Pt_HeroAttList; /** * Encodes the specified Pt_HeroAttList message. Does not implicitly {@link pb_test.Pt_HeroAttList.verify|verify} messages. * @param message Pt_HeroAttList message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.IPt_HeroAttList, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Pt_HeroAttList message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Pt_HeroAttList * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Pt_HeroAttList; /** * Verifies a Pt_HeroAttList message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Pt_SkillItem. */ interface IPt_SkillItem { /** Pt_SkillItem cfg_skill_id */ cfg_skill_id: number; /** Pt_SkillItem lvl */ lvl: number; /** Pt_SkillItem extra_hurt */ extra_hurt: number; } /** Represents a Pt_SkillItem. */ class Pt_SkillItem implements IPt_SkillItem { /** * Constructs a new Pt_SkillItem. * @param [properties] Properties to set */ constructor(properties?: pb_test.IPt_SkillItem); /** Pt_SkillItem cfg_skill_id. */ public cfg_skill_id: number; /** Pt_SkillItem lvl. */ public lvl: number; /** Pt_SkillItem extra_hurt. */ public extra_hurt: number; /** * Creates a new Pt_SkillItem instance using the specified properties. * @param [properties] Properties to set * @returns Pt_SkillItem instance */ public static create(properties?: pb_test.IPt_SkillItem): pb_test.Pt_SkillItem; /** * Encodes the specified Pt_SkillItem message. Does not implicitly {@link pb_test.Pt_SkillItem.verify|verify} messages. * @param message Pt_SkillItem message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.IPt_SkillItem, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Pt_SkillItem message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Pt_SkillItem * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Pt_SkillItem; /** * Verifies a Pt_SkillItem message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Pt_WarHeroAtt. */ interface IPt_WarHeroAtt { /** Pt_WarHeroAtt HeroAtt */ HeroAtt: pb_test.IPt_HeroAttList; /** Pt_WarHeroAtt skill_items */ skill_items?: (pb_test.IPt_SkillItem[]|null); /** Pt_WarHeroAtt p_skill_items */ p_skill_items?: (pb_test.IPt_SkillItem[]|null); } /** Represents a Pt_WarHeroAtt. */ class Pt_WarHeroAtt implements IPt_WarHeroAtt { /** * Constructs a new Pt_WarHeroAtt. * @param [properties] Properties to set */ constructor(properties?: pb_test.IPt_WarHeroAtt); /** Pt_WarHeroAtt HeroAtt. */ public HeroAtt: pb_test.IPt_HeroAttList; /** Pt_WarHeroAtt skill_items. */ public skill_items: pb_test.IPt_SkillItem[]; /** Pt_WarHeroAtt p_skill_items. */ public p_skill_items: pb_test.IPt_SkillItem[]; /** * Creates a new Pt_WarHeroAtt instance using the specified properties. * @param [properties] Properties to set * @returns Pt_WarHeroAtt instance */ public static create(properties?: pb_test.IPt_WarHeroAtt): pb_test.Pt_WarHeroAtt; /** * Encodes the specified Pt_WarHeroAtt message. Does not implicitly {@link pb_test.Pt_WarHeroAtt.verify|verify} messages. * @param message Pt_WarHeroAtt message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.IPt_WarHeroAtt, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Pt_WarHeroAtt message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Pt_WarHeroAtt * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Pt_WarHeroAtt; /** * Verifies a Pt_WarHeroAtt message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Cs_10000001. */ interface ICs_10000001 { /** Cs_10000001 mg_name */ mg_name: string; /** Cs_10000001 id */ id: number; /** Cs_10000001 num */ num: number; } /** Represents a Cs_10000001. */ class Cs_10000001 implements ICs_10000001 { /** * Constructs a new Cs_10000001. * @param [properties] Properties to set */ constructor(properties?: pb_test.ICs_10000001); /** Cs_10000001 mg_name. */ public mg_name: string; /** Cs_10000001 id. */ public id: number; /** Cs_10000001 num. */ public num: number; /** * Creates a new Cs_10000001 instance using the specified properties. * @param [properties] Properties to set * @returns Cs_10000001 instance */ public static create(properties?: pb_test.ICs_10000001): pb_test.Cs_10000001; /** * Encodes the specified Cs_10000001 message. Does not implicitly {@link pb_test.Cs_10000001.verify|verify} messages. * @param message Cs_10000001 message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.ICs_10000001, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Cs_10000001 message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Cs_10000001 * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Cs_10000001; /** * Verifies a Cs_10000001 message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Sc_10000001. */ interface ISc_10000001 { /** Sc_10000001 res */ res: pb_test.IResData; } /** Represents a Sc_10000001. */ class Sc_10000001 implements ISc_10000001 { /** * Constructs a new Sc_10000001. * @param [properties] Properties to set */ constructor(properties?: pb_test.ISc_10000001); /** Sc_10000001 res. */ public res: pb_test.IResData; /** * Creates a new Sc_10000001 instance using the specified properties. * @param [properties] Properties to set * @returns Sc_10000001 instance */ public static create(properties?: pb_test.ISc_10000001): pb_test.Sc_10000001; /** * Encodes the specified Sc_10000001 message. Does not implicitly {@link pb_test.Sc_10000001.verify|verify} messages. * @param message Sc_10000001 message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.ISc_10000001, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Sc_10000001 message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Sc_10000001 * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Sc_10000001; /** * Verifies a Sc_10000001 message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Cs_Handshake. */ interface ICs_Handshake { /** Cs_Handshake ver */ ver: string; } /** Represents a Cs_Handshake. */ class Cs_Handshake implements ICs_Handshake { /** * Constructs a new Cs_Handshake. * @param [properties] Properties to set */ constructor(properties?: pb_test.ICs_Handshake); /** Cs_Handshake ver. */ public ver: string; /** * Creates a new Cs_Handshake instance using the specified properties. * @param [properties] Properties to set * @returns Cs_Handshake instance */ public static create(properties?: pb_test.ICs_Handshake): pb_test.Cs_Handshake; /** * Encodes the specified Cs_Handshake message. Does not implicitly {@link pb_test.Cs_Handshake.verify|verify} messages. * @param message Cs_Handshake message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.ICs_Handshake, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Cs_Handshake message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Cs_Handshake * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Cs_Handshake; /** * Verifies a Cs_Handshake message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Sc_Handshake. */ interface ISc_Handshake { /** Sc_Handshake heartbeatInterval */ heartbeatInterval: number; /** Sc_Handshake heartbeatTimeout */ heartbeatTimeout: number; /** * 返回码 * RES_OK 200 * RES_FAIL 500 * RES_OLD_CLIENT 501 */ code: number; } /** Represents a Sc_Handshake. */ class Sc_Handshake implements ISc_Handshake { /** * Constructs a new Sc_Handshake. * @param [properties] Properties to set */ constructor(properties?: pb_test.ISc_Handshake); /** Sc_Handshake heartbeatInterval. */ public heartbeatInterval: number; /** Sc_Handshake heartbeatTimeout. */ public heartbeatTimeout: number; /** * 返回码 * RES_OK 200 * RES_FAIL 500 * RES_OLD_CLIENT 501 */ public code: number; /** * Creates a new Sc_Handshake instance using the specified properties. * @param [properties] Properties to set * @returns Sc_Handshake instance */ public static create(properties?: pb_test.ISc_Handshake): pb_test.Sc_Handshake; /** * Encodes the specified Sc_Handshake message. Does not implicitly {@link pb_test.Sc_Handshake.verify|verify} messages. * @param message Sc_Handshake message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.ISc_Handshake, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Sc_Handshake message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Sc_Handshake * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Sc_Handshake; /** * Verifies a Sc_Handshake message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Heartbeat. */ interface IHeartbeat { } /** Represents a Heartbeat. */ class Heartbeat implements IHeartbeat { /** * Constructs a new Heartbeat. * @param [properties] Properties to set */ constructor(properties?: pb_test.IHeartbeat); /** * Creates a new Heartbeat instance using the specified properties. * @param [properties] Properties to set * @returns Heartbeat instance */ public static create(properties?: pb_test.IHeartbeat): pb_test.Heartbeat; /** * Encodes the specified Heartbeat message. Does not implicitly {@link pb_test.Heartbeat.verify|verify} messages. * @param message Heartbeat message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.IHeartbeat, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Heartbeat message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Heartbeat * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Heartbeat; /** * Verifies a Heartbeat message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Kick. */ interface IKick { /** Kick code */ code: number; } /** Represents a Kick. */ class Kick implements IKick { /** * Constructs a new Kick. * @param [properties] Properties to set */ constructor(properties?: pb_test.IKick); /** Kick code. */ public code: number; /** * Creates a new Kick instance using the specified properties. * @param [properties] Properties to set * @returns Kick instance */ public static create(properties?: pb_test.IKick): pb_test.Kick; /** * Encodes the specified Kick message. Does not implicitly {@link pb_test.Kick.verify|verify} messages. * @param message Kick message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.IKick, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Kick message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Kick * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Kick; /** * Verifies a Kick message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Pt_HeroMsg. */ interface IPt_HeroMsg { /** Pt_HeroMsg id */ id: (number|Long); /** Pt_HeroMsg hero_id */ hero_id: number; /** Pt_HeroMsg index_id */ index_id: number; /** Pt_HeroMsg grade */ grade: number; /** Pt_HeroMsg hero_name */ hero_name: string; } /** Represents a Pt_HeroMsg. */ class Pt_HeroMsg implements IPt_HeroMsg { /** * Constructs a new Pt_HeroMsg. * @param [properties] Properties to set */ constructor(properties?: pb_test.IPt_HeroMsg); /** Pt_HeroMsg id. */ public id: (number|Long); /** Pt_HeroMsg hero_id. */ public hero_id: number; /** Pt_HeroMsg index_id. */ public index_id: number; /** Pt_HeroMsg grade. */ public grade: number; /** Pt_HeroMsg hero_name. */ public hero_name: string; /** * Creates a new Pt_HeroMsg instance using the specified properties. * @param [properties] Properties to set * @returns Pt_HeroMsg instance */ public static create(properties?: pb_test.IPt_HeroMsg): pb_test.Pt_HeroMsg; /** * Encodes the specified Pt_HeroMsg message. Does not implicitly {@link pb_test.Pt_HeroMsg.verify|verify} messages. * @param message Pt_HeroMsg message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.IPt_HeroMsg, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Pt_HeroMsg message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Pt_HeroMsg * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Pt_HeroMsg; /** * Verifies a Pt_HeroMsg message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Pt_RoleInfo. */ interface IPt_RoleInfo { /** Pt_RoleInfo role_id */ role_id: (number|Long); /** Pt_RoleInfo headicon_id */ headicon_id: number; /** Pt_RoleInfo nickname */ nickname: string; /** Pt_RoleInfo exp_pool */ exp_pool: (number|Long); /** Pt_RoleInfo vip_grade */ vip_grade: number; /** Pt_RoleInfo vip_exp */ vip_exp: number; /** Pt_RoleInfo gold_coin */ gold_coin: number; /** Pt_RoleInfo diamond */ diamond: number; /** Pt_RoleInfo fighting */ fighting: number; /** Pt_RoleInfo hero_list */ hero_list?: (pb_test.IPt_HeroMsg[]|null); } /** Represents a Pt_RoleInfo. */ class Pt_RoleInfo implements IPt_RoleInfo { /** * Constructs a new Pt_RoleInfo. * @param [properties] Properties to set */ constructor(properties?: pb_test.IPt_RoleInfo); /** Pt_RoleInfo role_id. */ public role_id: (number|Long); /** Pt_RoleInfo headicon_id. */ public headicon_id: number; /** Pt_RoleInfo nickname. */ public nickname: string; /** Pt_RoleInfo exp_pool. */ public exp_pool: (number|Long); /** Pt_RoleInfo vip_grade. */ public vip_grade: number; /** Pt_RoleInfo vip_exp. */ public vip_exp: number; /** Pt_RoleInfo gold_coin. */ public gold_coin: number; /** Pt_RoleInfo diamond. */ public diamond: number; /** Pt_RoleInfo fighting. */ public fighting: number; /** Pt_RoleInfo hero_list. */ public hero_list: pb_test.IPt_HeroMsg[]; /** * Creates a new Pt_RoleInfo instance using the specified properties. * @param [properties] Properties to set * @returns Pt_RoleInfo instance */ public static create(properties?: pb_test.IPt_RoleInfo): pb_test.Pt_RoleInfo; /** * Encodes the specified Pt_RoleInfo message. Does not implicitly {@link pb_test.Pt_RoleInfo.verify|verify} messages. * @param message Pt_RoleInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.IPt_RoleInfo, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Pt_RoleInfo message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Pt_RoleInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Pt_RoleInfo; /** * Verifies a Pt_RoleInfo message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Pt_Currency. */ interface IPt_Currency { /** Pt_Currency vip_grade */ vip_grade: number; /** Pt_Currency vip_exp */ vip_exp: number; /** Pt_Currency gold_coin */ gold_coin: number; /** Pt_Currency diamond */ diamond: number; /** Pt_Currency fighting */ fighting: number; } /** Represents a Pt_Currency. */ class Pt_Currency implements IPt_Currency { /** * Constructs a new Pt_Currency. * @param [properties] Properties to set */ constructor(properties?: pb_test.IPt_Currency); /** Pt_Currency vip_grade. */ public vip_grade: number; /** Pt_Currency vip_exp. */ public vip_exp: number; /** Pt_Currency gold_coin. */ public gold_coin: number; /** Pt_Currency diamond. */ public diamond: number; /** Pt_Currency fighting. */ public fighting: number; /** * Creates a new Pt_Currency instance using the specified properties. * @param [properties] Properties to set * @returns Pt_Currency instance */ public static create(properties?: pb_test.IPt_Currency): pb_test.Pt_Currency; /** * Encodes the specified Pt_Currency message. Does not implicitly {@link pb_test.Pt_Currency.verify|verify} messages. * @param message Pt_Currency message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.IPt_Currency, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Pt_Currency message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Pt_Currency * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Pt_Currency; /** * Verifies a Pt_Currency message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Cs_10010001. */ interface ICs_10010001 { /** Cs_10010001 account_id */ account_id: number; /** Cs_10010001 token */ token: string; } /** Represents a Cs_10010001. */ class Cs_10010001 implements ICs_10010001 { /** * Constructs a new Cs_10010001. * @param [properties] Properties to set */ constructor(properties?: pb_test.ICs_10010001); /** Cs_10010001 account_id. */ public account_id: number; /** Cs_10010001 token. */ public token: string; /** * Creates a new Cs_10010001 instance using the specified properties. * @param [properties] Properties to set * @returns Cs_10010001 instance */ public static create(properties?: pb_test.ICs_10010001): pb_test.Cs_10010001; /** * Encodes the specified Cs_10010001 message. Does not implicitly {@link pb_test.Cs_10010001.verify|verify} messages. * @param message Cs_10010001 message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.ICs_10010001, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Cs_10010001 message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Cs_10010001 * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Cs_10010001; /** * Verifies a Cs_10010001 message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Sc_10010001. */ interface ISc_10010001 { /** Sc_10010001 res */ res: pb_test.IResData; /** Sc_10010001 role_info */ role_info?: (pb_test.IPt_RoleInfo|null); } /** Represents a Sc_10010001. */ class Sc_10010001 implements ISc_10010001 { /** * Constructs a new Sc_10010001. * @param [properties] Properties to set */ constructor(properties?: pb_test.ISc_10010001); /** Sc_10010001 res. */ public res: pb_test.IResData; /** Sc_10010001 role_info. */ public role_info?: (pb_test.IPt_RoleInfo|null); /** * Creates a new Sc_10010001 instance using the specified properties. * @param [properties] Properties to set * @returns Sc_10010001 instance */ public static create(properties?: pb_test.ISc_10010001): pb_test.Sc_10010001; /** * Encodes the specified Sc_10010001 message. Does not implicitly {@link pb_test.Sc_10010001.verify|verify} messages. * @param message Sc_10010001 message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.ISc_10010001, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Sc_10010001 message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Sc_10010001 * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Sc_10010001; /** * Verifies a Sc_10010001 message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Cs_10010002. */ interface ICs_10010002 { /** Cs_10010002 account_id */ account_id: number; /** Cs_10010002 token */ token: string; /** Cs_10010002 nickname */ nickname: string; /** Cs_10010002 hero_id */ hero_id: number; } /** Represents a Cs_10010002. */ class Cs_10010002 implements ICs_10010002 { /** * Constructs a new Cs_10010002. * @param [properties] Properties to set */ constructor(properties?: pb_test.ICs_10010002); /** Cs_10010002 account_id. */ public account_id: number; /** Cs_10010002 token. */ public token: string; /** Cs_10010002 nickname. */ public nickname: string; /** Cs_10010002 hero_id. */ public hero_id: number; /** * Creates a new Cs_10010002 instance using the specified properties. * @param [properties] Properties to set * @returns Cs_10010002 instance */ public static create(properties?: pb_test.ICs_10010002): pb_test.Cs_10010002; /** * Encodes the specified Cs_10010002 message. Does not implicitly {@link pb_test.Cs_10010002.verify|verify} messages. * @param message Cs_10010002 message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.ICs_10010002, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Cs_10010002 message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Cs_10010002 * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Cs_10010002; /** * Verifies a Cs_10010002 message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Sc_10010002. */ interface ISc_10010002 { /** Sc_10010002 res */ res: pb_test.IResData; } /** Represents a Sc_10010002. */ class Sc_10010002 implements ISc_10010002 { /** * Constructs a new Sc_10010002. * @param [properties] Properties to set */ constructor(properties?: pb_test.ISc_10010002); /** Sc_10010002 res. */ public res: pb_test.IResData; /** * Creates a new Sc_10010002 instance using the specified properties. * @param [properties] Properties to set * @returns Sc_10010002 instance */ public static create(properties?: pb_test.ISc_10010002): pb_test.Sc_10010002; /** * Encodes the specified Sc_10010002 message. Does not implicitly {@link pb_test.Sc_10010002.verify|verify} messages. * @param message Sc_10010002 message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.ISc_10010002, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Sc_10010002 message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Sc_10010002 * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Sc_10010002; /** * Verifies a Sc_10010002 message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Cs_10010003. */ interface ICs_10010003 { /** Cs_10010003 rand */ rand?: (number|null); } /** Represents a Cs_10010003. */ class Cs_10010003 implements ICs_10010003 { /** * Constructs a new Cs_10010003. * @param [properties] Properties to set */ constructor(properties?: pb_test.ICs_10010003); /** Cs_10010003 rand. */ public rand: number; /** * Creates a new Cs_10010003 instance using the specified properties. * @param [properties] Properties to set * @returns Cs_10010003 instance */ public static create(properties?: pb_test.ICs_10010003): pb_test.Cs_10010003; /** * Encodes the specified Cs_10010003 message. Does not implicitly {@link pb_test.Cs_10010003.verify|verify} messages. * @param message Cs_10010003 message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.ICs_10010003, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Cs_10010003 message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Cs_10010003 * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Cs_10010003; /** * Verifies a Cs_10010003 message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Sc_10010003. */ interface ISc_10010003 { /** Sc_10010003 interval */ interval: number; } /** Represents a Sc_10010003. */ class Sc_10010003 implements ISc_10010003 { /** * Constructs a new Sc_10010003. * @param [properties] Properties to set */ constructor(properties?: pb_test.ISc_10010003); /** Sc_10010003 interval. */ public interval: number; /** * Creates a new Sc_10010003 instance using the specified properties. * @param [properties] Properties to set * @returns Sc_10010003 instance */ public static create(properties?: pb_test.ISc_10010003): pb_test.Sc_10010003; /** * Encodes the specified Sc_10010003 message. Does not implicitly {@link pb_test.Sc_10010003.verify|verify} messages. * @param message Sc_10010003 message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.ISc_10010003, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Sc_10010003 message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Sc_10010003 * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Sc_10010003; /** * Verifies a Sc_10010003 message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Sc_10010004. */ interface ISc_10010004 { /** Sc_10010004 res */ res: pb_test.IResData; } /** Represents a Sc_10010004. */ class Sc_10010004 implements ISc_10010004 { /** * Constructs a new Sc_10010004. * @param [properties] Properties to set */ constructor(properties?: pb_test.ISc_10010004); /** Sc_10010004 res. */ public res: pb_test.IResData; /** * Creates a new Sc_10010004 instance using the specified properties. * @param [properties] Properties to set * @returns Sc_10010004 instance */ public static create(properties?: pb_test.ISc_10010004): pb_test.Sc_10010004; /** * Encodes the specified Sc_10010004 message. Does not implicitly {@link pb_test.Sc_10010004.verify|verify} messages. * @param message Sc_10010004 message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.ISc_10010004, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Sc_10010004 message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Sc_10010004 * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Sc_10010004; /** * Verifies a Sc_10010004 message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } /** Properties of a Sc_10010005. */ interface ISc_10010005 { /** Sc_10010005 currency */ currency: pb_test.IPt_Currency; } /** Represents a Sc_10010005. */ class Sc_10010005 implements ISc_10010005 { /** * Constructs a new Sc_10010005. * @param [properties] Properties to set */ constructor(properties?: pb_test.ISc_10010005); /** Sc_10010005 currency. */ public currency: pb_test.IPt_Currency; /** * Creates a new Sc_10010005 instance using the specified properties. * @param [properties] Properties to set * @returns Sc_10010005 instance */ public static create(properties?: pb_test.ISc_10010005): pb_test.Sc_10010005; /** * Encodes the specified Sc_10010005 message. Does not implicitly {@link pb_test.Sc_10010005.verify|verify} messages. * @param message Sc_10010005 message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: pb_test.ISc_10010005, writer?: protobuf.Writer): protobuf.Writer; /** * Decodes a Sc_10010005 message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Sc_10010005 * @throws {Error} If the payload is not a reader or valid buffer * @throws {protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Sc_10010005; /** * Verifies a Sc_10010005 message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); } }
the_stack
import type { IAsync, IFold, Instruction, IRaceWith } from "@effect/core/io/Effect/definition/primitives" import { instruction } from "@effect/core/io/Effect/definition/primitives" import { CancelerState } from "@effect/core/io/Fiber/_internal/cancelerState" import type { Callback } from "@effect/core/io/Fiber/_internal/fiberState" import { FiberState } from "@effect/core/io/Fiber/_internal/fiberState" import { _A, _E, FiberSym } from "@effect/core/io/Fiber/definition" import { FiberStatus } from "@effect/core/io/Fiber/status" import { concreteFiberRefs } from "@effect/core/io/FiberRefs/operations/_internal/FiberRefsInternal" import { joinFiberRefs } from "@effect/core/io/FiberRefs/operations/_internal/join" import { defaultScheduler } from "@effect/core/support/Scheduler" import * as StackTraceBuilder from "@effect/core/support/StackTraceBuilder" import { constVoid } from "@tsplus/stdlib/data/Function" const fiberFailureCauses = LazyValue.make(() => Metric.frequency("effect_fiber_failure_causes")) const fiberForkLocations = LazyValue.make(() => Metric.frequency("effect_fiber_fork_locations")) const fibersStarted = LazyValue.make(() => Metric.counter("effect_fiber_started")) const fiberSuccesses = LazyValue.make(() => Metric.counter("effect_fiber_successes")) const fiberFailures = LazyValue.make(() => Metric.counter("effect_fiber_failures")) const fiberLifetimes = LazyValue.make(() => { const fiberLifetimeBoundaries = Metric.Histogram.Boundaries.exponential(1, 2, 100) return Metric.histogram("effect_fiber_lifetimes", fiberLifetimeBoundaries) }) export class InterruptExit { readonly _tag = "InterruptExit" constructor( readonly apply: (a: any) => Effect<any, any, any>, readonly trace?: string ) {} } export class Finalizer { readonly _tag = "Finalizer" constructor( readonly finalizer: Effect<unknown, never, any>, readonly handleInterrupts: () => void, readonly trace?: string ) {} apply<X>(a: X): Effect<any, any, any> { this.handleInterrupts() return this.finalizer.map(() => a, instruction(this.finalizer).trace) } } export class ApplyFrame { readonly _tag = "ApplyFrame" constructor( readonly apply: <X>(a: Cause<X>) => Effect<any, any, any>, readonly trace?: string ) {} } export type Frame = | InterruptExit | Finalizer | IFold<any, any, any, any, any, any, any, any, any> | ApplyFrame export type FiberRefLocals = ImmutableMap<FiberRef<unknown, unknown>, List.NonEmpty<Tuple<[FiberId.Runtime, unknown]>>> export const catastrophicFailure = new AtomicBoolean(false) export const currentFiber = new AtomicReference<FiberContext<any, any> | null>(null) export class FiberContext<E, A> implements Fiber.Runtime<E, A> { readonly _tag = "RuntimeFiber" readonly [FiberSym]: FiberSym = FiberSym readonly [_E]!: () => E readonly [_A]!: () => A readonly state = new AtomicReference(FiberState.initial<E, A>()) asyncEpoch = 0 stack: Stack<Frame> | undefined = undefined nextEffect: Effect<any, any, any> | undefined = undefined runtimeConfig: RuntimeConfig interruptStatus?: Stack<boolean> | undefined fiberRefLocals: FiberRefLocals constructor( readonly _id: FiberId.Runtime, readonly childFibers: Set<FiberContext<any, any>>, fiberRefLocals: FiberRefLocals, runtimeConfig: RuntimeConfig, interruptStatus?: Stack<boolean> ) { this.fiberRefLocals = fiberRefLocals this.runtimeConfig = runtimeConfig this.interruptStatus = interruptStatus if (this.trackMetrics) { fibersStarted.value.unsafeUpdate(1, HashSet.empty()) fiberForkLocations.value.unsafeUpdate(this._location.stringify(), HashSet.empty()) } } // --------------------------------------------------------------------------- // Base Fiber // --------------------------------------------------------------------------- get fiberId(): FiberId { return this._id } get _await(): Effect<unknown, never, Exit<E, A>> { return Effect.asyncInterruptBlockingOn<unknown, never, Exit<E, A>>((k) => { const cb: Callback<never, Exit<E, A>> = (x) => k(Effect.done(x)) const result = this.unsafeAddObserverMaybe(cb) return result == null ? Either.left(Effect.succeed(this.unsafeRemoveObserver(cb))) : Either.right(Effect.succeedNow(result)) }, this.fiberId) } get _children(): Effect<unknown, never, Chunk<Fiber.Runtime<any, any>>> { return this._evalOnEffect( Effect.succeed(() => { const chunkBuilder = Chunk.builder<Fiber.Runtime<any, any>>() for (const child of this.childFibers) { chunkBuilder.append(child) } return chunkBuilder.build() }), Effect.succeed(Chunk.empty()) ) } get _inheritRefs(): Effect<unknown, never, void> { return Effect.suspendSucceed(() => { if (this.fiberRefLocals.size === 0) { return Effect.unit } const childFiberRefs = FiberRefs(this.fiberRefLocals) return Effect.updateFiberRefs((_, parentFiberRefs) => joinFiberRefs(parentFiberRefs, childFiberRefs)) }) } get _poll(): Effect<unknown, never, Option<Exit<E, A>>> { return Effect.succeed(this.unsafePoll()) } _interruptAs(fiberId: FiberId): Effect<unknown, never, Exit<E, A>> { return this.unsafeInterruptAs(fiberId) } // --------------------------------------------------------------------------- // Runtime Fiber // --------------------------------------------------------------------------- _location: TraceElement = this._id.location get _scope(): FiberScope { return FiberScope.unsafeMake(this) } get _status(): Effect<unknown, never, FiberStatus> { return Effect.succeed(this.state.get.status) } get _trace(): Effect<unknown, never, Trace> { return Effect.succeed(this.unsafeCaptureTrace([])) } _evalOn( effect: Effect<unknown, never, any>, orElse: Effect<unknown, never, any> ): Effect<unknown, never, any> { return Effect.suspendSucceed( this.unsafeEvalOn(effect) ? Effect.unit : orElse.asUnit() ) } _evalOnEffect<R, E2, A2>( effect: Effect<R, E2, A2>, orElse: Effect<R, E2, A2> ): Effect<R, E2, A2> { return Effect.environment<R>().flatMap((environment) => Deferred.make<E2, A2>().flatMap((deferred) => this._evalOn( effect.provideEnvironment(environment).intoDeferred(deferred), orElse.provideEnvironment(environment).intoDeferred(deferred) ).zipRight(deferred.await()) ) ) } // --------------------------------------------------------------------------- // Descriptor // --------------------------------------------------------------------------- unsafeGetDescriptor(): Fiber.Descriptor { return { id: this.fiberId, status: this.state.get.status, interrupters: this.state.get.interruptors, interruptStatus: InterruptStatus.fromBoolean(this.unsafeIsInterruptible) } } // --------------------------------------------------------------------------- // Metrics // --------------------------------------------------------------------------- get trackMetrics(): boolean { return this.runtimeConfig.value.flags.isEnabled( RuntimeConfigFlag.TrackRuntimeMetrics ) } observeFailure(failure: string): void { if (this.trackMetrics) { fiberFailureCauses.value.unsafeUpdate(failure, HashSet.empty()) } } // --------------------------------------------------------------------------- // Logging // --------------------------------------------------------------------------- unsafeLog(message: () => string, trace?: string): void { const logLevel = this.unsafeGetRef(FiberRef.currentLogLevel.value) const spans = this.unsafeGetRef(FiberRef.currentLogSpan.value) const annotations = this.unsafeGetRef(FiberRef.currentLogAnnotations.value) const contextMap = this.unsafeGetRefs(this.fiberRefLocals) this.runtimeConfig.value.loggers.forEach((logger) => { logger.apply( TraceElement.parse(trace), this.fiberId, logLevel, message, () => Cause.empty, contextMap, spans, annotations ) }) } unsafeLogWith( message: Lazy<string>, cause: Lazy<Cause<unknown>>, overrideLogLevel: Option<LogLevel>, overrideRef1: FiberRef<unknown, unknown> | null = null, overrideValue1: unknown = null, trace?: string ): void { const logLevel = overrideLogLevel.getOrElse( this.unsafeGetRef(FiberRef.currentLogLevel.value) ) const spans = this.unsafeGetRef(FiberRef.currentLogSpan.value) const annotations = this.unsafeGetRef(FiberRef.currentLogAnnotations.value) let contextMap = this.unsafeGetRefs(this.fiberRefLocals) if (overrideRef1 != null) { if (overrideValue1 == null) { contextMap = contextMap.remove(overrideRef1) } else { contextMap = contextMap.set(overrideRef1, overrideValue1) } } this.runtimeConfig.value.loggers.forEach((logger) => { logger.apply( TraceElement.parse(trace), this.fiberId, logLevel, message, cause, contextMap, spans, annotations ) }) } // --------------------------------------------------------------------------- // Frame // --------------------------------------------------------------------------- get isStackEmpty(): boolean { return this.stack == null } pushContinuation(k: Frame): void { this.stack = new Stack(k, this.stack) } popContinuation(): Frame | undefined { if (this.stack) { const current = this.stack.value this.stack = this.stack.previous return current } return undefined } unsafeNextEffect(previousSuccess: any): Instruction | undefined { if (!this.isStackEmpty) { const frame = this.popContinuation()! return instruction( frame._tag === "Fold" ? frame.success(previousSuccess) : frame.apply(previousSuccess) ) } return this.unsafeTryDone(Exit.succeed(previousSuccess)) } /** * Unwinds the stack, leaving the first error handler on the top of the stack * (assuming one is found), and returning whether or not some folds had to be * discarded (indicating a change in the error type). */ unsafeUnwindStack(): boolean { let unwinding = true let discardedFolds = false // Unwind the stack, looking for an error handler while (unwinding && !this.isStackEmpty) { const frame = this.popContinuation()! switch (frame._tag) { case "InterruptExit": { this.popInterruptStatus() break } case "Finalizer": { // We found a finalizer, we have to immediately disable interruption // so the runloop will continue and not abort due to interruption this.unsafeDisableInterrupting() this.pushContinuation( new ApplyFrame((cause) => frame.finalizer.foldCauseEffect( (finalizerCause) => { this.popInterruptStatus() this.unsafeAddSuppressed(finalizerCause) return Effect.failCauseNow(cause) }, () => { this.popInterruptStatus() return Effect.failCauseNow(cause) } ) ) ) unwinding = false break } case "Fold": { if (this.unsafeShouldInterrupt) { discardedFolds = true } else { // Push error handler back onto the stack and halt iteration this.pushContinuation(new ApplyFrame(frame.failure, frame.trace)) unwinding = false } break } } } return discardedFolds } // --------------------------------------------------------------------------- // Interruption // --------------------------------------------------------------------------- interruptExit: InterruptExit = new InterruptExit((v: any) => { if (this.unsafeIsInterruptible) { this.popInterruptStatus() return instruction(Effect.succeedNow(v)) } else { return instruction( Effect.succeed(() => { this.popInterruptStatus() return v }) ) } }) pushInterruptStatus(flag: boolean): void { this.interruptStatus = new Stack(flag, this.interruptStatus) } popInterruptStatus(): boolean | undefined { if (this.interruptStatus) { const current = this.interruptStatus.value this.interruptStatus = this.interruptStatus.previous return current } return undefined } private unsafeInterruptAs(fiberId: FiberId): Effect<unknown, never, Exit<E, A>> { const interruptedCause = Cause.interrupt(fiberId) return Effect.suspendSucceed(() => { const oldState = this.state.get if ( oldState._tag === "Executing" && oldState.status._tag === "Suspended" && oldState.status.interruptible && oldState.asyncCanceler._tag === "Registered" ) { const newState = FiberState.Executing( FiberStatus.Running(true), oldState.observers, oldState.suppressed, oldState.interruptors.add(fiberId), CancelerState.Empty, oldState.mailbox ) this.state.set(newState) const interrupt = Effect.failCause(interruptedCause) const asyncCanceler = oldState.asyncCanceler.asyncCanceler const effect = asyncCanceler === Effect.unit ? interrupt : asyncCanceler.zipRight(interrupt) this.unsafeRunLater(instruction(effect)) } else if (oldState._tag === "Executing") { const newCause = oldState.suppressed + interruptedCause const newState = FiberState.Executing( oldState.status, oldState.observers, newCause, oldState.interruptors.add(fiberId), oldState.asyncCanceler, oldState.mailbox ) this.state.set(newState) } return this._await }) } private unsafeSetInterrupting(value: boolean): void { const oldState = this.state.get if (oldState._tag === "Executing") { this.state.set( FiberState.Executing( oldState.status.withInterrupting(value), oldState.observers, oldState.suppressed, oldState.interruptors, oldState.asyncCanceler, oldState.mailbox ) ) } } /** * Disables interruption for the fiber. */ private unsafeDisableInterrupting(): void { this.interruptStatus = new Stack(false, this.interruptStatus) } private unsafeRestoreInterrupt(): void { this.stack = new Stack(this.interruptExit, this.stack) } get unsafeIsInterrupted(): boolean { return this.state.get.interruptors.size > 0 } get unsafeIsInterruptible(): boolean { return this.interruptStatus ? this.interruptStatus.value : true } get unsafeIsInterrupting(): boolean { return this.state.get.isInterrupting() } get unsafeShouldInterrupt(): boolean { return ( this.unsafeIsInterrupted && this.unsafeIsInterruptible && !this.unsafeIsInterrupting ) } // --------------------------------------------------------------------------- // FiberRefs // --------------------------------------------------------------------------- unsafeGetRef<A, P>(fiberRef: FiberRef<A, P>): A { return this.fiberRefLocals.get(fiberRef) .map((stack) => stack.head.get(1) as A) .getOrElse(fiberRef.initial()) } unsafeGetRefs(fiberRefLocals: FiberRefLocals): ImmutableMap<FiberRef<unknown, unknown>, unknown> { const refs: Array<Tuple<[FiberRef<unknown, unknown>, unknown]>> = [] for (const { tuple: [fiberRef, stack] } of fiberRefLocals) { refs.push(Tuple(fiberRef, stack.head.get(1))) } return ImmutableMap.from(...refs) } unsafeSetRef<A, P>(fiberRef: FiberRef<A, P>, value: A): void { const oldStack = this.fiberRefLocals.get(fiberRef).getOrElse(List.empty<Tuple<[FiberId.Runtime, unknown]>>()) const newStack = ( oldStack.isNil() ? List.cons(Tuple(this._id, value), List.nil()) : List.cons(Tuple(this._id, value), oldStack.tail) ) as List.NonEmpty<Tuple<[FiberId.Runtime, unknown]>> this.fiberRefLocals = this.fiberRefLocals.set(fiberRef, newStack) } unsafeDeleteRef<A, P>(fiberRef: FiberRef<A, P>): void { this.fiberRefLocals = this.fiberRefLocals.remove(fiberRef) } // --------------------------------------------------------------------------- // Observers // --------------------------------------------------------------------------- unsafeAddObserverMaybe(k: Callback<never, Exit<E, A>>): Exit<E, A> | undefined { const oldState = this.state.get switch (oldState._tag) { case "Executing": { this.state.set( FiberState.Executing( oldState.status, oldState.observers.prepend(k), oldState.suppressed, oldState.interruptors, oldState.asyncCanceler, oldState.mailbox ) ) return undefined } case "Done": { return oldState.value } } } unsafeRemoveObserver(k: Callback<never, Exit<E, A>>): void { const oldState = this.state.get if (oldState._tag === "Executing") { const observers = oldState.observers.filter((o) => o !== k) this.state.set( FiberState.Executing( oldState.status, observers, oldState.suppressed, oldState.interruptors, oldState.asyncCanceler, oldState.mailbox ) ) } } unsafeNotifyObservers( v: Exit<E, A>, observers: List<Callback<never, Exit<E, A>>> ): void { if (observers.length() > 0) { const result = Exit.succeed(v) observers.forEach((k) => k(result)) } } unsafeReportUnhandled(exit: Exit<E, A>, trace?: string): void { if (exit._tag === "Failure") { try { this.unsafeLogWith( () => `Fiber ${this.fiberId.threadName()} did not handle an error`, () => exit.cause, Option.some(LogLevel.Debug), null, null, trace ) } catch (error) { if (this.runtimeConfig.value.fatal(error)) { this.runtimeConfig.value.reportFatal(error) } else { console.log(`An exception was thrown by a logger:\n${error}`) } } } } private unsafeAddSuppressed(cause: Cause<never>): void { if (!cause.isEmpty()) { const oldState = this.state.get if (oldState._tag === "Executing") { const newState = FiberState.Executing( oldState.status, oldState.observers, oldState.suppressed + cause, oldState.interruptors, oldState.asyncCanceler, oldState.mailbox ) this.state.set(newState) } } } private unsafeClearSuppressed(): Cause<never> { const oldState = this.state.get switch (oldState._tag) { case "Executing": { const newState = FiberState.Executing( oldState.status, oldState.observers, Cause.empty, oldState.interruptors, oldState.asyncCanceler, oldState.mailbox ) this.state.set(newState) const interruptorsCause = oldState.interruptorsCause() return oldState.suppressed.contains(interruptorsCause) ? oldState.suppressed : oldState.suppressed + interruptorsCause } case "Done": { return oldState.interruptorsCause() } } } unsafeAddChild(child: FiberContext<any, any>): boolean { return this.unsafeEvalOn(Effect.succeed(this.childFibers.add(child))) } unsafePoll(): Option<Exit<E, A>> { const state = this.state.get return state._tag === "Done" ? Option.some(state.value) : Option.none } // --------------------------------------------------------------------------- // Tracing // --------------------------------------------------------------------------- unsafeCaptureTrace(prefix: Array<TraceElement>): Trace { const builder = StackTraceBuilder.unsafeMake() prefix.forEach((_) => builder.append(_)) if (this.stack != null) { const stack = this.stack const frames: Array<Frame> = [stack.value] let previous = stack.previous while (previous != null) { frames.unshift(previous.value) previous = previous.previous } frames.forEach((frame) => builder.append(TraceElement.parse(frame.trace))) } return new Trace(this.fiberId, builder.build()) } // --------------------------------------------------------------------------- // Async // --------------------------------------------------------------------------- unsafeEnterAsync(epoch: number, blockingOn: FiberId, trace: TraceElement): void { const oldState = this.state.get if ( oldState._tag === "Executing" && oldState.status._tag === "Running" && oldState.asyncCanceler._tag === "Empty" ) { const newStatus = FiberStatus.Suspended( oldState.status.interrupting, this.unsafeIsInterruptible && !this.unsafeIsInterrupting, epoch, blockingOn, trace ) const newState = FiberState.Executing( newStatus, oldState.observers, oldState.suppressed, oldState.interruptors, CancelerState.Pending, oldState.mailbox ) this.state.set(newState) } else { throw new IllegalStateException( `Fiber ${this.fiberId.threadName()} is not running` ) } } unsafeExitAsync(epoch: number): boolean { const oldState = this.state.get if ( oldState._tag === "Executing" && oldState.status._tag === "Suspended" && oldState.status.asyncs === epoch ) { const newState = FiberState.Executing( FiberStatus.Running(oldState.status.interrupting), oldState.observers, oldState.suppressed, oldState.interruptors, CancelerState.Empty, oldState.mailbox ) this.state.set(newState) return true } return false } unsafeCreateAsyncResume(epoch: number): (_: Effect<any, any, any>) => void { return (effect) => { if (this.unsafeExitAsync(epoch)) { this.unsafeRunLater(instruction(effect)) } } } unsafeSetAsyncCanceler( epoch: number, asyncCanceler0: Effect<any, any, any> | undefined ): void { const oldState = this.state.get const asyncCanceler = asyncCanceler0 == null ? Effect.unit : asyncCanceler0 if ( oldState._tag === "Executing" && oldState.status._tag === "Suspended" && oldState.asyncCanceler._tag === "Pending" && epoch === oldState.status.asyncs ) { this.state.set( FiberState.Executing( oldState.status, oldState.observers, oldState.suppressed, oldState.interruptors, CancelerState.Registered(asyncCanceler), oldState.mailbox ) ) } else if ( oldState._tag === "Executing" && oldState.status._tag === "Suspended" && oldState.asyncCanceler._tag === "Registered" && epoch === oldState.status.asyncs ) { throw new Error("Bug, inconsistent state in unsafeSetAsyncCanceler") } } // --------------------------------------------------------------------------- // Finalizer // --------------------------------------------------------------------------- unsafeAddFinalizer(finalizer: Effect<unknown, never, any>): void { this.pushContinuation( new Finalizer(finalizer, () => { this.unsafeDisableInterrupting() this.unsafeRestoreInterrupt() }) ) } // --------------------------------------------------------------------------- // Execution // --------------------------------------------------------------------------- unsafeEvalOn(effect: Effect<unknown, never, any>): boolean { const oldState = this.state.get switch (oldState._tag) { case "Executing": { const newMailbox = oldState.mailbox == null ? effect : oldState.mailbox.zipRight(effect) this.state.set( FiberState.Executing( oldState.status, oldState.observers, oldState.suppressed, oldState.interruptors, oldState.asyncCanceler, newMailbox ) ) return true } case "Done": { return false } } } unsafeTryDone(exit: Exit<E, A>): Instruction | undefined { const oldState = this.state.get switch (oldState._tag) { case "Executing": { if (oldState.mailbox != null) { // Not done because the mailbox isn't empty const newState = FiberState.Executing( oldState.status, oldState.observers, oldState.suppressed, oldState.interruptors, oldState.asyncCanceler, undefined ) this.state.set(newState) this.unsafeSetInterrupting(true) return instruction(oldState.mailbox.zipRight(Effect.done(exit))) } else if (this.childFibers.size === 0) { // The mailbox is empty and the _children are shut down const interruptorsCause = oldState.interruptorsCause() const newExit = interruptorsCause === Cause.empty ? exit : exit.mapErrorCause((cause) => cause.contains(interruptorsCause) ? cause : cause + interruptorsCause) // We are truly "unsafeTryDone" because the scope has been closed this.state.set(FiberState.Done(newExit)) this.unsafeReportUnhandled(newExit) this.unsafeNotifyObservers(newExit, oldState.observers) const startTimeSeconds = this._id.startTimeSeconds const endTimeSeconds = new Date().getTime() / 1000 const lifetime = endTimeSeconds - startTimeSeconds if (this.trackMetrics) { fiberLifetimes.value.unsafeUpdate(lifetime, HashSet.empty()) } newExit.fold( (cause) => { if (this.trackMetrics) { fiberFailures.value.unsafeUpdate(1, HashSet.empty()) } return cause.fold<E, void>( () => fiberFailureCauses.value.unsafeUpdate("<empty>", HashSet.empty()), (failure, _) => { this.observeFailure( typeof failure === "object" ? (failure as any).constructor.name : "<anonymous>" ) }, (defect, _) => { this.observeFailure( typeof defect === "object" ? (defect as any).constructor.name : "<anonymous>" ) }, () => { this.observeFailure("InterruptedException") }, constVoid, constVoid, constVoid ) }, () => { if (this.trackMetrics) { fiberSuccesses.value.unsafeUpdate(1, HashSet.empty()) } } ) return undefined } else { // Not done because there are _children left to close this.unsafeSetInterrupting(true) let interruptChildren = Effect.unit for (const child of this.childFibers) { interruptChildren = interruptChildren.zipRight(child._interruptAs(this._id)) } this.childFibers.clear() return instruction(interruptChildren.zipRight(Effect.done(exit))) } } case "Done": { // Already unsafeTryDone return undefined } } } unsafeDrainMailbox(): Effect<unknown, never, any> | undefined { const oldState = this.state.get switch (oldState._tag) { case "Executing": { const newState = FiberState.Executing( oldState.status, oldState.observers, oldState.suppressed, oldState.interruptors, oldState.asyncCanceler, undefined ) this.state.set(newState) return oldState.mailbox } case "Done": { return undefined } } } unsafeOnDone(k: Callback<never, Exit<E, A>>): void { const result = this.unsafeAddObserverMaybe(k) if (result != null) { k(Exit.succeed(result)) } } /** * Forks an `IO` with the specified failure handler. */ unsafeFork( effect: Instruction, trace: TraceElement, forkScope: Option<FiberScope> = Option.none ): FiberContext<any, any> { const childId = FiberId.unsafeMake(trace) const childFiberRefLocalEntries: Array< Tuple<[ FiberRef<unknown, unknown>, List.NonEmpty<Tuple<[FiberId.Runtime, unknown]>> ]> > = [] for (const { tuple: [fiberRef, stack] } of this.fiberRefLocals) { const value = fiberRef.patch(fiberRef.fork())(stack.head.get(1)) childFiberRefLocalEntries.push(Tuple(fiberRef, stack.prepend(Tuple(childId, value)))) } const childFiberRefLocals: FiberRefLocals = ImmutableMap.from(...childFiberRefLocalEntries) const parentScope = forkScope.orElse(this.unsafeGetRef(FiberRef.forkScopeOverride.value)).getOrElse(this._scope) const grandChildren = new Set<FiberContext<unknown, unknown>>() const childContext = new FiberContext( childId, grandChildren, childFiberRefLocals, this.runtimeConfig, new Stack(this.interruptStatus ? this.interruptStatus.value : true) ) if (this.runtimeConfig.value.supervisor !== Supervisor.none) { this.runtimeConfig.value.supervisor.unsafeOnStart( this.unsafeGetRef(FiberRef.currentEnvironment.value), effect, Option.some(this), childContext ) childContext.unsafeOnDone((exit) => this.runtimeConfig.value.supervisor.unsafeOnEnd(exit.flatten(), childContext)) } const childEffect = !parentScope.unsafeAdd(this.runtimeConfig, childContext) ? Effect.interruptAs(parentScope.fiberId) : effect childContext.nextEffect = childEffect defaultScheduler(() => childContext.runUntil(this.runtimeConfig.value.maxOp)) return childContext } complete<R, R1, R2, E2, A2, R3, E3, A3>( winner: Fiber<any, any>, loser: Fiber<any, any>, cont: (winner: Fiber<any, any>, loser: Fiber<any, any>) => Effect<any, any, any>, ab: AtomicReference<boolean>, cb: (_: Effect<R & R1 & R2 & R3, E2 | E3, A2 | A3>) => void ): void { if (ab.compareAndSet(true, false)) { cb(cont(winner, loser)) } } unsafeRace<R, E, A, R1, E1, A1, R2, E2, A2, R3, E3, A3>( race: IRaceWith<R, E, A, R1, E1, A1, R2, E2, A2, R3, E3, A3>, trace: TraceElement ): Effect<R & R1 & R2 & R3, E2 | E3, A2 | A3> { const raceIndicator = new AtomicBoolean(true) const left = this.unsafeFork(instruction(race.left()), trace) const right = this.unsafeFork(instruction(race.right()), trace) return Effect.asyncBlockingOn((cb) => { const leftRegister = left.unsafeAddObserverMaybe(() => this.complete(left, right, race.leftWins, raceIndicator, cb) ) if (leftRegister != null) { this.complete(left, right, race.leftWins, raceIndicator, cb) } else { const rightRegister = right.unsafeAddObserverMaybe(() => this.complete(right, left, race.rightWins, raceIndicator, cb) ) if (rightRegister != null) { this.complete(right, left, race.rightWins, raceIndicator, cb) } } }, FiberId.combineAll(HashSet.from([left.fiberId, right.fiberId]))) } unsafeRunLater(instr: Instruction): void { this.nextEffect = instr defaultScheduler(() => this.runUntil(this.runtimeConfig.value.maxOp)) } /** * The main evaluator loop for the fiber. For purely synchronous effects, this * will run either to completion, or for the specified maximum operation * count. For effects with asynchronous callbacks, the loop will proceed no * further than the first asynchronous boundary. */ runUntil(maxOpCount: number): void { try { const flags = this.runtimeConfig.value.flags const logRuntime = flags.isEnabled(RuntimeConfigFlag.LogRuntime) let current: Instruction | undefined = this.nextEffect as Instruction | undefined this.nextEffect = undefined const superviseOps = flags.isEnabled(RuntimeConfigFlag.SuperviseOperations) && this.runtimeConfig.value.supervisor !== Supervisor.none if (flags.isEnabled(RuntimeConfigFlag.EnableCurrentFiber)) { currentFiber.set(this) } if (this.runtimeConfig.value.supervisor !== Supervisor.none) { this.runtimeConfig.value.supervisor.unsafeOnResume(this) } while (current != null) { try { let opCount = 0 do { // Check to see if the fiber should continue executing or not: if (!this.unsafeShouldInterrupt) { // Fiber does not need to be interrupted, but might need to yield: const message = this.unsafeDrainMailbox() if (message != null) { const oldEffect: Effect<any, any, any> = current // TODO: trace current = instruction(message.flatMap(() => oldEffect)) } else if (opCount === maxOpCount) { this.unsafeRunLater(instruction(current)) current = undefined } else { if (logRuntime) { this.unsafeLog(() => current!.unsafeLog(), current.trace) } if (superviseOps) { this.runtimeConfig.value.supervisor.unsafeOnEffect(this, current) } // Fiber is neither being interrupted nor needs to yield. Execute // the next instruction in the program: switch (current._tag) { case "FlatMap": { this.pushContinuation(new ApplyFrame(current.k, current.trace)) current = instruction(current.effect) break } case "SucceedNow": { current = this.unsafeNextEffect(current.value) break } case "Succeed": { current = this.unsafeNextEffect(current.effect()) break } case "SucceedWith": { current = this.unsafeNextEffect( current.effect(this.runtimeConfig, this._id) ) break } case "Fail": { const cause = current.cause() const tracedCause = cause.isTraced() ? cause : cause.traced( this.unsafeCaptureTrace([TraceElement.parse(current.trace)]) ) const discardedFolds = this.unsafeUnwindStack() const strippedCause = discardedFolds ? // We threw away some error handlers while unwinding the // stack because we got interrupted during this instruction. // So it's not safe to return typed failures from cause0, // because they might not be typed correctly. Instead, we // strip the typed failures, and return the remainders and // the interruption. tracedCause.stripFailures() : tracedCause const suppressed = this.unsafeClearSuppressed() const fullCause = strippedCause.contains(suppressed) ? strippedCause : strippedCause + suppressed if (this.isStackEmpty) { // Error not caught, stack is empty this.unsafeSetInterrupting(true) current = this.unsafeTryDone(Exit.failCause(fullCause)) } else { this.unsafeSetInterrupting(false) // Error caught, next continuation on the stack will deal // with it, so we just have to compute it here: current = this.unsafeNextEffect(fullCause) } break } case "Fold": { const effect = current current = instruction(effect.effect) this.pushContinuation(effect) break } case "Suspend": { current = instruction(current.make()) break } case "SuspendWith": { current = instruction(current.make(this.runtimeConfig, this._id)) break } case "InterruptStatus": { const boolFlag = current.flag().toBoolean const interruptStatus = this.interruptStatus ? this.interruptStatus.value : true if (interruptStatus !== boolFlag) { this.interruptStatus = new Stack(boolFlag, this.interruptStatus) this.unsafeRestoreInterrupt() } current = instruction(current.effect) break } case "CheckInterrupt": { current = instruction( current.k(InterruptStatus.fromBoolean(this.unsafeIsInterruptible)) ) break } case "Async": { const effect: IAsync<any, any, any> = current const epoch = this.asyncEpoch this.asyncEpoch = epoch + 1 // Enter suspended state this.unsafeEnterAsync( epoch, effect.blockingOn(), TraceElement.parse(effect.trace) ) const k = effect.register const either = k(this.unsafeCreateAsyncResume(epoch)) switch (either._tag) { case "Left": { const canceler = either.left this.unsafeSetAsyncCanceler(epoch, canceler) if (this.unsafeShouldInterrupt) { if (this.unsafeExitAsync(epoch)) { this.unsafeSetInterrupting(true) current = instruction( canceler.zipRight( Effect.failCause(this.unsafeClearSuppressed()) ) ) } else { current = undefined } } else { current = undefined } break } case "Right": { if (!this.unsafeExitAsync(epoch)) { current = undefined } else { current = instruction(either.right) } break } } break } case "Fork": { const effect = current current = this.unsafeNextEffect( this.unsafeFork( instruction(effect.effect), TraceElement.parse(effect.trace), effect.scope() ) ) break } case "Descriptor": { current = instruction(current.f(this.unsafeGetDescriptor())) break } case "Yield": { this.unsafeRunLater(instruction(Effect.unit)) current = undefined break } case "Trace": { current = this.unsafeNextEffect( this.unsafeCaptureTrace([TraceElement.parse(current.trace)]) ) break } case "FiberRefModify": { const { tuple: [result, newValue] } = current.f(this.unsafeGetRef(current.fiberRef)) this.unsafeSetRef(current.fiberRef, newValue) current = this.unsafeNextEffect(result) break } case "FiberRefModifyAll": { const { tuple: [result, newValue] } = current.f(this._id, FiberRefs(this.fiberRefLocals)) concreteFiberRefs(newValue) this.fiberRefLocals = newValue.fiberRefLocals current = this.unsafeNextEffect(result) break } case "FiberRefLocally": { const effect = current const fiberRef = effect.fiberRef const oldValue = this.unsafeGetRef(fiberRef) this.unsafeSetRef(fiberRef, effect.localValue) current = instruction( effect.effect.ensuring( Effect.succeed(this.unsafeSetRef(fiberRef, oldValue)) ) ) break } case "FiberRefDelete": { this.unsafeDeleteRef(current.fiberRef) current = this.unsafeNextEffect(undefined) break } case "FiberRefWith": { current = instruction( current.f(this.unsafeGetRef(current.fiberRef)) ) break } case "RaceWith": { current = instruction( this.unsafeRace(current, TraceElement.parse(current.trace)) ) break } case "Supervise": { const effect = current const oldSupervisor = this.runtimeConfig.value.supervisor const newSupervisor = effect.supervisor() + oldSupervisor this.runtimeConfig = RuntimeConfig({ ...this.runtimeConfig.value, supervisor: newSupervisor }) this.unsafeAddFinalizer( Effect.succeed(() => { this.runtimeConfig = RuntimeConfig({ ...this.runtimeConfig.value, supervisor: oldSupervisor }) }) ) current = instruction(effect.effect) break } case "GetForkScope": { const effect = current current = instruction( effect.f( this.unsafeGetRef(FiberRef.forkScopeOverride.value).getOrElse( this._scope ) ) ) break } case "OverrideForkScope": { const oldForkScopeOverride = this.unsafeGetRef( FiberRef.forkScopeOverride.value ) this.unsafeSetRef( FiberRef.forkScopeOverride.value, current.forkScope() ) this.unsafeAddFinalizer( Effect.succeed( this.unsafeSetRef( FiberRef.forkScopeOverride.value, oldForkScopeOverride ) ) ) current = instruction(current.effect) break } case "Ensuring": { this.unsafeAddFinalizer(current.finalizer) current = instruction(current.effect) break } case "Logged": { const effect = current this.unsafeLogWith( effect.message, effect.cause, effect.overrideLogLevel, effect.overrideRef1, effect.overrideValue1, effect.trace ) current = this.unsafeNextEffect(undefined) break } case "SetRuntimeConfig": { this.runtimeConfig = current.runtimeConfig current = instruction(Effect.unit) break } } } } else { // Fiber was interrupted const trace = current.trace current = instruction( Effect.failCause(this.unsafeClearSuppressed(), trace) ) // Prevent interruption of interruption this.unsafeSetInterrupting(true) } opCount = opCount + 1 } while (current != null) } catch (e) { if (e instanceof InterruptedException) { const trace = current?.trace current = instruction(Effect.interruptAs(FiberId.none, trace)) // Prevent interruption of interruption: this.unsafeSetInterrupting(true) } else if (e instanceof Effect.Error) { switch (e.exit._tag) { case "Success": { current = this.unsafeNextEffect(e.exit.value) break } case "Failure": { const trace = current ? current.trace : undefined current = instruction(Effect.failCause(e.exit.cause, trace)) break } } } else if (this.runtimeConfig.value.fatal(e)) { catastrophicFailure.set(true) // Catastrophic error handler. Any error thrown inside the interpreter // is either a bug in the interpreter or a bug in the user's code. Let // the fiber die but attempt finalization & report errors. this.runtimeConfig.value.reportFatal(e) current = undefined } else { this.unsafeSetInterrupting(true) current = instruction(Effect.die(e)) } } } } finally { if ( this.runtimeConfig.value.flags.isEnabled(RuntimeConfigFlag.EnableCurrentFiber) ) { currentFiber.set(null) } if (this.runtimeConfig.value.supervisor !== Supervisor.none) { this.runtimeConfig.value.supervisor.unsafeOnSuspend(this) } } } run(): void { return this.runUntil(this.runtimeConfig.value.maxOp) } }
the_stack
import { Component } from "../component/Component"; import { Image } from "../component/Image"; import { Rect } from "../component/Rect"; import { Text, TextOptions } from "../component/Text"; import { colorPicker } from "../ColorPicker"; import { canvasHelper } from "../CanvasHelper"; import { Stage } from "../Stage"; import { BaseChart, BaseChartOptions, KeyGenerate } from "./BaseChart"; import { recourse } from "../Recourse"; import { font } from "../Constant"; import { extent, max, range, ScaleLinear, scaleLinear, sum, timeFormat, } from "d3"; export interface BarChartOptions extends BaseChartOptions { domain?: (data: any) => [number, number]; dy?: number; barFontSizeScale?: number; itemCount?: number; barPadding?: number; barGap?: number; clipBar?: boolean; barInfoFormat?: KeyGenerate; showDateLabel?: boolean; dateLabelOptions?: TextOptions; showRankLabel?: boolean; barInfoOptions?: TextOptions; swapDurationMS?: number; } export interface BarOptions { id: string; data: any; value: number; pos: { x: number; y: number }; shape: { width: number; height: number }; color: string; radius: number; alpha: number; image?: string; isUp?: boolean; } export class BarChart extends BaseChart { dateLabelOptions: TextOptions = {}; barFontSizeScale: number = 0.9; showRankLabel: boolean; private readonly rankPadding = 10; rankLabelPlaceholder: number; reduceID = true; dy: number; barInfoOptions: TextOptions = {}; domain: (data: any) => [number, number]; totalHistoryIndex: Map<any, any>; clipBar: boolean = true; get maxRankLabelWidth(): number { return canvasHelper.measure( new Text(this.getRankLabelOptions(this.itemCount)) ).width; } constructor(options: BarChartOptions = {}) { super(options); if (options.itemCount) this.itemCount = options.itemCount; if (options.barPadding !== undefined) this.barPadding = options.barPadding; if (options.barGap !== undefined) this.barGap = options.barGap; if (options.barFontSizeScale !== undefined) this.barFontSizeScale = options.barFontSizeScale; if (options.barInfoFormat !== undefined) this.barInfoFormat = options.barInfoFormat; if (options.showDateLabel !== undefined) this.showDateLabel = options.showDateLabel; if (options.domain) this.domain = options.domain; if (options.barInfoOptions !== undefined) this.barInfoOptions = options.barInfoOptions; if (options.dateLabelOptions !== undefined) this.dateLabelOptions = options.dateLabelOptions; if (options.swapDurationMS !== undefined) this.swapDurationMS = options.swapDurationMS; this.showRankLabel = options.showRankLabel ?? false; if (options.clipBar !== undefined) this.clipBar = options.clipBar; this.dy = options.dy ?? 0; } itemCount = 20; barPadding = 8; barGap = 8; swapDurationMS = 300; rankOffset = 1; lastValue = new Map<string, number>(); labelPlaceholder: number; valuePlaceholder: number; showDateLabel: boolean = true; barInfoFormat = (id: any, meta: Map<string, any>, data: Map<string, any>) => { return this.labelFormat(id, meta, data); }; IDList: string[]; setup(stage: Stage) { super.setup(stage); // 获得曾出现过的Label集合 this.setShowingIDList(); this.rankLabelPlaceholder = this.maxRankLabelWidth; this.labelPlaceholder = this.maxLabelWidth; this.valuePlaceholder = this.maxValueLabelWidth; const historyIndex = this.getTotalHistoryIndex(); const kernel = this.getConvolveKernel(3); for (let [key, _] of historyIndex) { historyIndex.set(key, this.convolve(historyIndex.get(key), kernel)); } this.totalHistoryIndex = historyIndex; } private getConvolveKernel(kw: number) { const normalFunc = function normal(x: number) { return (1 / Math.sqrt(2 * Math.PI)) * Math.exp(-(x ** 2 / 2)); }; let kernel = range( -kw, kw, (((2 * kw) / this.swapDurationMS) * 1000) / this.stage!.options.fps ).map((v) => normalFunc(v)); if (kernel.length % 2 !== 1) { kernel.shift(); } const ks = sum(kernel); kernel = kernel.map((v) => v / ks); return kernel; } private getTotalHistoryIndex() { const secRange = range( 0, this.stage!.options.sec, 1 / this.stage!.options.fps ); const data = secRange.map((t) => this.getCurrentData(t).map((v) => v[this.idField]) ); return this.IDList.reduce((d, id) => { const indexList: number[] = []; for (const dataList of data) { let index = dataList.indexOf(id); if (this.reduceID) { if (index === -1 || index > this.itemCount) index = this.itemCount; } else { if (index === -1) index = this.itemCount; } indexList.push(index); } d.set(id, indexList); return d; }, new Map()); } /** * 卷积的一种实现,特别地,这个函数对左右两边进行 padding 处理。 * * @param array 被卷数组 * @param weights 卷积核 * @returns 卷积后的数组,大小和被卷数组一致 */ private convolve(array: number[], weights: number[]) { if (weights.length % 2 !== 1) throw new Error("weights array must have an odd length"); let al = array.length; let wl = weights.length; let offset = ~~(wl / 2); let output = new Array<number>(al); for (let i = 0; i < al; i++) { let kmin = 0; let kmax = wl - 1; output[i] = 0; for (let k = kmin; k <= kmax; k++) { let idx = i - offset + k; if (idx < 0) idx = 0; if (idx >= array.length) idx = array.length - 1; output[i] += array[idx] * weights[k]; } } return output; } /** * 获得所有能显示在图表上的数据 ID 列表。 * 这个列表可以用于筛去无用数据。 */ private setShowingIDList() { const idSet = new Set<string>(); this.dataGroupByDate.forEach((_, date) => { const dt = this.secToDate.invert(date); let tmp = [...this.dataScales.entries()] .filter((d) => { const data = d[1](dt); return data != undefined && !isNaN(data[this.valueField]); }) .sort((a, b) => { return b[1](dt)[this.valueField] - a[1](dt)[this.valueField]; }); if (this.reduceID) { tmp = tmp.slice(0, this.itemCount); } tmp.forEach((item) => { let id = item[0]; idSet.add(id); }); }); this.IDList = [...idSet.values()]; } get maxValueLabelWidth() { const d = [...this.data.values()]; const maxWidth = max(d, (item) => { const text = new Text( this.getLabelTextOptions( this.valueFormat(item), "#FFF", this.barHeight ) ); const result = canvasHelper.measure(text); return result.width; }) ?? 0; return maxWidth; } get totalRankPlaceHolder() { if (this.showRankLabel) return this.rankPadding + this.rankLabelPlaceholder; else return 0; } get maxLabelWidth() { const maxWidth = max(this.IDList, (id) => { const text = new Text( this.getLabelTextOptions( this.labelFormat(id, this.meta, this.dataGroupByID), "#FFF", this.barHeight ) ); const result = canvasHelper.measure(text); return result.width; }) ?? 0; return maxWidth; } getComponent(sec: number) { let currentData = this.getCurrentData(sec).splice(0, this.itemCount); let scaleX: ScaleLinear<number, number, never> = this.getScaleX( currentData ); const barComponent = new Component({ alpha: this.alphaScale(sec), position: this.position, }); const barGroup = new Component(); barComponent.addChild(barGroup); // 获取非 NaN 的条目数 let barCount = currentData.filter((d) => !Number.isNaN(d[this.idField])) .length; const options = currentData .map((data) => this.getBarOptions(data, scaleX, barCount)) .filter((options) => options.alpha > 0) .sort((a, b) => { if (a.isUp && !b.isUp) { return 1; } else if (!a.isUp && b.isUp) { return -1; } else { return a.value - b.value; } }); barGroup.children = options.map((o) => this.getBarComponent(o)); if (this.showRankLabel) { this.appendRankLabels(barComponent); } if (this.showDateLabel) { let dateLabelText = this.getDateLabelText(sec); let dateLabelOptions = Object.assign( { font, fontSize: 60, fillStyle: "#777", textAlign: "right", fontWeight: "bolder", textBaseline: "bottom", position: { x: this.shape.width - this.margin.right, y: this.shape.height - this.margin.bottom, }, }, this.dateLabelOptions ); dateLabelOptions.text = dateLabelText; const dateLabel = new Text(dateLabelOptions); barComponent.children.push(dateLabel); } return barComponent; } private appendRankLabels(res: Component) { const rankLabelGroup = new Component(); for (let idx = 0; idx < this.itemCount; idx++) { let text = new Text(this.getRankLabelOptions(idx)); rankLabelGroup.addChild(text); } res.addChild(rankLabelGroup); } private getRankLabelOptions(idx: number): TextOptions | undefined { return { text: `${idx + this.rankOffset}`, textBaseline: "middle", textAlign: "right", fontSize: this.barHeight * this.barFontSizeScale, position: { x: this.getBarX() - this.labelPlaceholder - this.rankPadding, y: this.getBarY(idx) + this.barHeight / 2, }, }; } getScaleX(currentData: any[]) { let scaleX: ScaleLinear<number, number, never>; let domain: number[]; if (this.domain != undefined) { domain = this.domain(currentData); } else if (this.visualRange != "history") { const [_, max] = extent(currentData, (d) => d[this.valueField]); domain = [0, max]; } else { domain = [0, max(this.data, (d) => d[this.valueField])]; } scaleX = scaleLinear(domain, [ 0, this.shape.width - this.margin.left - this.barPadding - this.labelPlaceholder - this.totalRankPlaceHolder - this.margin.right - this.valuePlaceholder, ]); return scaleX; } getDateLabelText(sec: number): string { if (this.nonstandardDate) { let index = Math.floor(this.secToDate(sec).getTime()); return this.indexToDate.get(index) ?? ""; } return timeFormat(this.dateFormat)(this.secToDate(sec)); } private get barHeight() { return ( (this.shape.height - this.margin.top - this.margin.bottom - this.barGap * (this.itemCount - 1)) / this.itemCount ); } getTotalHistoryByID(id: any) { return this.totalHistoryIndex.get(id); } private getBarOptions( data: any, scaleX: ScaleLinear<number, number, never>, count: number ): BarOptions { const cFrame = this.stage!.frame; const hisIndex = this.getTotalHistoryByID(data[this.idField]); let idx = this.getBarIdx(hisIndex, cFrame); // 判断这一帧,柱状条是否在上升 let isUp = this.barIsUp(cFrame, hisIndex); let alpha = scaleLinear([-1, 0, count - 2, count - 1], [0, 1, 1, 0]).clamp( true )(idx); if (Number.isNaN(data[this.valueField])) { alpha = 0; } // 保存非 NaN 数据 if (!Number.isNaN(data[this.valueField])) { this.lastValue.set(data[this.idField], data[this.valueField]); } else { // 如果当前数据就是 NaN,则使用上次的数据 data[this.valueField] = this.lastValue.get(data[this.idField]); } data[this.valueField] = this.lastValue.get(data[this.idField]); let color: string; if (typeof this.colorField === "string") { color = data[this.colorField]; } else { color = this.colorField( data[this.idField], this.meta, this.dataGroupByID ); } const image = typeof this.imageField === "string" ? data[this.imageField] : this.imageField(data[this.idField], this.meta, this.dataGroupByID); return { id: data[this.idField], pos: { x: this.getBarX(), y: this.getBarY(idx), }, alpha, data, image, isUp, value: data[this.valueField], shape: { width: scaleX(data[this.valueField]), height: this.barHeight }, color: colorPicker.getColor(color), radius: 4, }; } getBarIdx(hisIndex: number[], cFrame: number) { return hisIndex ? hisIndex[cFrame - 1] : this.itemCount; } /** * 判断当前帧,柱状条是否在上升 * * @param cFrame 当前帧 * @param hisIndex 历史排序数据 * @returns 是否在上升 */ private barIsUp(cFrame: number, hisIndex?: number[]) { if (hisIndex && cFrame > 0 && hisIndex[cFrame] < hisIndex[cFrame - 1]) { return true; } return false; } private getBarX(): number { return ( this.margin.left + this.barPadding + this.labelPlaceholder + this.totalRankPlaceHolder ); } private getBarY(idx: number): number { return this.margin.top + idx * (this.barHeight + this.barGap); } private getBarComponent(options: BarOptions) { const res = new Component({ position: options.pos, alpha: options.alpha, }); const bar = new Rect({ shape: options.shape, fillStyle: options.color, radius: options.radius, clip: this.clipBar, }); const label = new Text( this.getLabelTextOptions( this.labelFormat(options.id, this.meta, this.dataGroupByID), options.color, options.shape.height ) ); const valueLabel = new Text({ textBaseline: "middle", text: `${this.valueFormat(options.data)}`, textAlign: "left", position: { x: options.shape.width + this.barPadding, y: (options.shape.height * this.barFontSizeScale) / 2 + this.dy, }, fontSize: options.shape.height * this.barFontSizeScale, font, fillStyle: options.color, }); const imagePlaceholder = options.image && recourse.images.get(options.image) ? options.shape.height : 0; let defaultBarInfoOptions = { textAlign: "right", textBaseline: "bottom", position: { x: options.shape.width - this.barPadding - imagePlaceholder, y: options.shape.height, }, fontSize: options.shape.height * this.barFontSizeScale, font, fillStyle: "#fff", strokeStyle: options.color, lineWidth: 0, }; let barInfoOptions = Object.assign( defaultBarInfoOptions, this.barInfoOptions ); barInfoOptions.text = this.barInfoFormat( options.id, this.meta, this.dataGroupByID ); const barInfo = new Text(barInfoOptions); if (options.image && recourse.images.get(options.image)) { const img = new Image({ src: options.image, position: { x: options.shape.width - options.shape.height, y: 0, }, shape: { width: options.shape.height, height: options.shape.height, }, }); bar.children.push(img); } // const rank = new Text({ // textAlign: "left", // textBaseline: "bottom", // text: `${index + this.rankOffset}`, // position: { // x: this.barPadding - imagePlaceholder, // y: options.shape.height, // }, // fontSize: options.shape.height * this.barFontSizeScale, // font, // fillStyle: "#fff", // strokeStyle: options.color, // lineWidth: 4, // }); // bar.children.push(rank); bar.children.push(barInfo); res.children.push(bar); res.children.push(valueLabel); res.children.push(label); return res as Component; } private getLabelTextOptions( text: string, color = "#fff", fontSize: number = 16 ): TextOptions { return { text: `${text}`, textAlign: "right", textBaseline: "middle", fontSize: fontSize * this.barFontSizeScale, font, position: { x: 0 - this.barPadding, y: (fontSize * this.barFontSizeScale) / 2 + this.dy, }, fillStyle: color, }; } }
the_stack
import React, {useState, useEffect, useContext, CSSProperties} from "react"; import {faProjectDiagram, faTable} from "@fortawesome/free-solid-svg-icons"; import {FontAwesomeIcon} from "@fortawesome/react-fontawesome"; import {MLButton, MLTooltip, MLAlert, MLRadio} from "@marklogic/design-system"; import "./Modeling.scss"; import ConfirmationModal from "../components/confirmation-modal/confirmation-modal"; import EntityTypeModal from "../components/modeling/entity-type-modal/entity-type-modal"; import EntityTypeTable from "../components/modeling/entity-type-table/entity-type-table"; import styles from "./Modeling.module.scss"; import {deleteEntity, entityReferences, updateHubCentralConfig, primaryEntityTypes, publishDraftModels, updateEntityModels, getHubCentralConfig} from "../api/modeling"; import {UserContext} from "../util/user-context"; import {ModelingContext} from "../util/modeling-context"; import {ModelingMessages, ModelingTooltips} from "../config/tooltips.config"; import {AuthoritiesContext} from "../util/authorities"; import {ConfirmationType} from "../types/common-types"; import {hubCentralConfig} from "../types/modeling-types"; import tiles from "../config/tiles.config"; import {MissingPagePermission} from "../config/messages.config"; import GraphView from "../components/modeling/graph-view/graph-view"; import ModelingLegend from "../components/modeling/modeling-legend/modeling-legend"; import {defaultModelingView} from "../config/modeling.config"; import PublishToDatabaseIcon from "../assets/publish-to-database-icon"; const Modeling: React.FC = () => { const {handleError} = useContext(UserContext); const {modelingOptions, setEntityTypeNamesArray, clearEntityModified, setView, setSelectedEntity} = useContext(ModelingContext); const [entityTypes, setEntityTypes] = useState<any[]>([]); const [showEntityModal, toggleShowEntityModal] = useState(false); const [isEditModal, toggleIsEditModal] = useState(false); const [name, setName] = useState(""); const [description, setDescription] = useState(""); const [namespace, setNamespace] = useState(""); const [prefix, setPrefix] = useState(""); const [color, setColor] = useState(""); const [autoExpand, setAutoExpand] = useState(""); //const [revertAllEntity, toggleRevertAllEntity] = useState(false); const [width, setWidth] = React.useState(window.innerWidth); const [showConfirmModal, toggleConfirmModal] = useState(false); const [showRelationshipModal, toggleRelationshipModal] = useState(true); const [confirmType, setConfirmType] = useState<ConfirmationType>(ConfirmationType.PublishAll); //Role based access const authorityService = useContext(AuthoritiesContext); const canReadEntityModel = authorityService.canReadEntityModel(); const canWriteEntityModel = authorityService.canWriteEntityModel(); const canAccessModel = authorityService.canAccessModel(); //Delete Entity const [confirmBoldTextArray, setConfirmBoldTextArray] = useState<string[]>([]); const [arrayValues, setArrayValues] = useState<string[]>([]); //hubCentral Config const [hubCentralConfig, sethubCentralConfig] = useState({}); useEffect(() => { if (canReadEntityModel && modelingOptions.view === "table") { setEntityTypesFromServer(); } }, [modelingOptions.view]); useEffect(() => { if (canReadEntityModel) { setEntityTypesFromServer(); setHubCentralConfigFromServer(); } }, []); useEffect(() => { window.addEventListener("resize", updateWidthAndHeight); return () => window.removeEventListener("resize", updateWidthAndHeight); }); const updateWidthAndHeight = () => { setWidth(window.innerWidth); }; const setEntityTypesFromServer = async () => { try { const response = await primaryEntityTypes(); if (response) { let model: any = []; let entityTypesArray:any = []; let isDraft = false; await response["data"].forEach(entity => { if (!entity.model.info.draftDeleted) { model.push(entity); entityTypesArray.push({name: entity.entityName, entityTypeId: entity.entityTypeId}); } if (entity.model.info.draft && !isDraft) { isDraft = true; } }); setEntityTypes(model); if (response["data"].length > 0) { setEntityTypeNamesArray(entityTypesArray, isDraft); } } } catch (error) { handleError(error); } }; const setHubCentralConfigFromServer = async () => { try { const response = await getHubCentralConfig(); if (response["status"] === 200) { sethubCentralConfig(response.data); } } catch (error) { handleError(error); } }; const saveAllEntitiesToServer = async (entitiesArray) => { try { let response; if (entitiesArray.length > 0) { response = await updateEntityModels(entitiesArray); } else { response = await updateEntityModels(modelingOptions.modifiedEntitiesArray); } if (response["status"] === 200) { await setEntityTypesFromServer(); } } catch (error) { handleError(error); } finally { toggleRelationshipModal(false); toggleConfirmModal(false); } }; const publishDraftModelToServer = async () => { try { let response = await publishDraftModels(); if (response["status"] === 200) { await setEntityTypesFromServer(); } } catch (error) { handleError(error); } finally { clearEntityModified(); toggleRelationshipModal(false); toggleConfirmModal(false); } }; const publishHubCentralConfig = async (hubCentralConfig: hubCentralConfig) => { try { let response = await updateHubCentralConfig(hubCentralConfig); if (response["status"] === 200) { await setHubCentralConfigFromServer(); } } catch (error) { handleError(error); } finally { toggleRelationshipModal(false); toggleConfirmModal(false); } }; const updateEntityTypesAndHideModal = async (entityName: string, description: string) => { if (!isEditModal) { setAutoExpand(entityName); } toggleShowEntityModal(false); await setEntityTypesFromServer().then((resp => { if (!isEditModal && modelingOptions.view === "graph") { let isDraft = true; setSelectedEntity(entityName, isDraft); } })); }; const editEntityTypeDescription = (entityTypeName: string, entityTypeDescription: string, entityTypeNamespace: string, entityTypePrefix: string, entityTypeColor: string) => { if (canWriteEntityModel) { toggleIsEditModal(true); toggleShowEntityModal(true); setName(entityTypeName); setDescription(entityTypeDescription); setNamespace(entityTypeNamespace); setPrefix(entityTypePrefix); setColor(entityTypeColor); } }; const confirmAction = () => { if (confirmType === ConfirmationType.PublishAll) { publishDraftModelToServer(); } else if (confirmType === ConfirmationType.DeleteEntityRelationshipOutstandingEditWarn || confirmType === ConfirmationType.DeleteEntityNoRelationshipOutstandingEditWarn || confirmType === ConfirmationType.DeleteEntity) { deleteEntityFromServer(); } }; /* Deleting an entity type */ const getEntityReferences = async (entityName: string) => { try { const response = await entityReferences(entityName); if (response["status"] === 200) { let newConfirmType = ConfirmationType.DeleteEntity; if (modelingOptions.isModified) { //newConfirmType = ConfirmationType.DeleteEntityNoRelationshipOutstandingEditWarn; setArrayValues(modelingOptions.modifiedEntitiesArray.map(entity => entity.entityName)); } if (response["data"]["stepNames"].length > 0) { newConfirmType = ConfirmationType.DeleteEntityStepWarn; setArrayValues(response["data"]["stepNames"]); } else if (response["data"]["entityNamesWithForeignKeyReferences"].length > 0) { newConfirmType = ConfirmationType.DeleteEntityWithForeignKeyReferences; setArrayValues(response["data"]["entityNamesWithForeignKeyReferences"]); } else if (response["data"]["entityNames"].length > 0) { if (modelingOptions.isModified) { newConfirmType = ConfirmationType.DeleteEntityRelationshipOutstandingEditWarn; setArrayValues(modelingOptions.modifiedEntitiesArray.map(entity => entity.entityName)); } else { newConfirmType = ConfirmationType.DeleteEntityRelationshipWarn; } } setConfirmBoldTextArray([entityName]); setConfirmType(newConfirmType); toggleConfirmModal(true); } } catch (error) { handleError(error); } }; const deleteEntityFromServer = async () => { let entityName = confirmBoldTextArray.length ? confirmBoldTextArray[0] : ""; try { const response = await deleteEntity(entityName); if (response["status"] === 200) { setEntityTypesFromServer(); } } catch (error) { handleError(error); } finally { toggleConfirmModal(false); if (modelingOptions.selectedEntity && modelingOptions.selectedEntity === entityName) { setSelectedEntity(undefined); } } }; const addButton = <MLButton type="primary" aria-label="add-entity" onClick={() => { toggleIsEditModal(false); toggleShowEntityModal(true); }} disabled={!canWriteEntityModel} className={!canWriteEntityModel && styles.disabledPointerEvents} >Add</MLButton>; const publishIconStyle: CSSProperties = { width: "18px", height: "18px", fill: "currentColor" }; const publishButton = <span className={styles.publishButtonParent}><MLButton className={!modelingOptions.isModified ? styles.disabledPointerEvents : ""} disabled={!modelingOptions.isModified} aria-label="publish-to-database" onClick={() => { setConfirmType(ConfirmationType.PublishAll); toggleConfirmModal(true); }} size="small" > <span className={styles.publishButtonContainer}> <PublishToDatabaseIcon style={publishIconStyle} /> <span className={styles.publishButtonText}>Publish</span> </span> </MLButton> </span>; const handleViewChange = (view) => { if (view === "table") { setView("table"); } else { setView(defaultModelingView); } }; const mlRadioStyle: CSSProperties = { color: "#999" }; const viewSwitch = <div id="switch-view" aria-label="switch-view"> <MLRadio.MLGroup buttonStyle="outline" className={"radioGroupView"} defaultValue={modelingOptions.view} name="radiogroup" onChange={e => handleViewChange(e.target.value)} size="large" style={mlRadioStyle} tabIndex={0} > <MLRadio.MLButton aria-label="switch-view-graph" value={"graph"} checked={modelingOptions.view === "graph"}> <MLTooltip title={"Graph View"}><i>{<FontAwesomeIcon icon={faProjectDiagram}/>}</i></MLTooltip> </MLRadio.MLButton> <MLRadio.MLButton aria-label="switch-view-table" value={"table"} checked={modelingOptions.view === "table"}> <MLTooltip title={"Table View"}><i>{<FontAwesomeIcon icon={faTable}/>}</i></MLTooltip> </MLRadio.MLButton> </MLRadio.MLGroup> </div>; if (canAccessModel) { return ( <div className={styles.modelContainer}> {modelingOptions.view === "table" ? <div className={styles.stickyHeader} style={{width: width - 138, maxWidth: width - 138}}> <div className={styles.intro}> <p>{tiles.model.intro}</p> {viewSwitch} </div> {modelingOptions.isModified ? ( <div className={modelingOptions.isModified ? styles.alertContainer : ""}><MLAlert type="info" aria-label="entity-modified-alert" showIcon message={ModelingMessages.entityEditedAlert}/></div> ) : ""} <div> <div className={styles.header}> <h1>Entity Types</h1> <div className={styles.buttonContainer}> <ModelingLegend/> <div style={{float: "right"}}> {canWriteEntityModel ? <MLTooltip title={ModelingTooltips.addNewEntity}> {addButton} </MLTooltip> : <MLTooltip title={ModelingTooltips.addNewEntity + " " + ModelingTooltips.noWriteAccess} placement="top" overlayStyle={{maxWidth: "175px"}}> <span className={styles.disabledCursor}>{addButton}</span> </MLTooltip> } {canWriteEntityModel ? <MLTooltip title={ModelingTooltips.publish} overlayStyle={{maxWidth: "175px"}}> <span className={modelingOptions.isModified ? styles.CursorButton : styles.disabledCursor}>{publishButton}</span> </MLTooltip> : <MLTooltip title={ModelingTooltips.publish + " " + ModelingTooltips.noWriteAccess} placement="top" overlayStyle={{maxWidth: "225px"}}> <span className={styles.disabledCursor}>{publishButton}</span> </MLTooltip> } </div> </div> </div> </div> </div> : <> <div className={styles.intro}> <p>{tiles.model.intro}</p> {viewSwitch} </div> {modelingOptions.isModified && ( <div className={modelingOptions.isModified ? styles.alertContainer : ""}><MLAlert type="info" aria-label="entity-modified-alert" showIcon message={ModelingMessages.entityEditedAlert}/></div> )} <h1>Entity Types</h1> <div className={styles.borderBelowHeader}></div> <GraphView canReadEntityModel={canReadEntityModel} canWriteEntityModel={canWriteEntityModel} entityTypes={entityTypes} deleteEntityType={getEntityReferences} updateSavedEntity={saveAllEntitiesToServer} updateEntities={setEntityTypesFromServer} relationshipModalVisible={showRelationshipModal} toggleRelationshipModal={toggleRelationshipModal} toggleShowEntityModal={toggleShowEntityModal} toggleIsEditModal={toggleIsEditModal} setEntityTypesFromServer={setEntityTypesFromServer} toggleConfirmModal={toggleConfirmModal} setConfirmType={setConfirmType} hubCentralConfig={hubCentralConfig} updateHubCentralConfig={publishHubCentralConfig} /> </> } {modelingOptions.view === "table" ? <div className={modelingOptions.isModified ? styles.entityTableContainer : styles.entityTableContainerWithoutAlert}> <EntityTypeTable canReadEntityModel={canReadEntityModel} canWriteEntityModel={canWriteEntityModel} allEntityTypesData={entityTypes} editEntityTypeDescription={editEntityTypeDescription} updateEntities={setEntityTypesFromServer} updateSavedEntity={saveAllEntitiesToServer} autoExpand={autoExpand} hubCentralConfig={hubCentralConfig} /> </div> : ""} <ConfirmationModal isVisible={showConfirmModal} type={confirmType} boldTextArray={![ConfirmationType.PublishAll].includes(confirmType) ? confirmBoldTextArray : []} arrayValues={![ConfirmationType.PublishAll].includes(confirmType) ? arrayValues : []} toggleModal={toggleConfirmModal} confirmAction={confirmAction} /> <EntityTypeModal isVisible={showEntityModal} toggleModal={toggleShowEntityModal} updateEntityTypesAndHideModal={updateEntityTypesAndHideModal} isEditModal={isEditModal} name={name} description={description} namespace={namespace} prefix={prefix} color={color} updateHubCentralConfig={publishHubCentralConfig} /> </div> ); } else { return ( <div className={styles.modelContainer}> <p>{MissingPagePermission}</p> </div> ); } }; export default Modeling;
the_stack
import React from "react"; import { Link } from "gatsby"; import { Heading, Inline, Stack, Grid, Button } from "@kiwicom/orbit-components"; import { NewWindow } from "@kiwicom/orbit-components/icons"; import { css } from "styled-components"; import { WindowLocation } from "@reach/router"; // temporarily extract images from @streamlinehq/streamlinehq until they fix the install script import ModulePuzzleIcon from "../images/streamline-light/module-puzzle.svg"; import ColorBrushIcon from "../images/streamline-light/color-brush.svg"; import ExpandDiagonalIcon from "../images/streamline-light/expand-diagonal-1.svg"; import LoveItTextIcon from "../images/streamline-light/love-it-text.svg"; import SpellingCheckIcon from "../images/streamline-light/spelling-check.svg"; import ArrangeLetterIcon from "../images/streamline-light/arrange-letter.svg"; import ComputerBugIcon from "../images/streamline-light/computer-bug.svg"; import LoveBirdIcon from "../images/streamline-light/love-bird.svg"; import StartupLaunchIcon from "../images/streamline-light/startup-launch-1.svg"; import ReadArt from "../images/streamline-light/read-art.svg"; import SearchButton from "../components/Search/SearchButton"; import TypographyIcon from "../components/icons/Typography"; import PuzzleIcon from "../components/icons/Puzzle"; import FigmaIcon from "../components/icons/Figma"; import GitHubIcon from "../components/icons/GitHub"; import Search from "../components/Search"; import ArrowRight from "../components/ArrowRight"; import Layout from "../components/Layout"; import RocketImage from "../components/RocketImage"; import Tile from "../components/Tile"; import BrandedTile from "../components/BrandedTile"; import GitHubLogo from "../images/github-full.svg"; import FigmaLogo from "../images/figma-logo.svg"; import TwitterLogo from "../images/twitter.svg"; import srcTequila from "../images/tequila.png"; import { MAX_CONTENT_WIDTH } from "../consts"; import ScreenReaderText from "../components/ScreenReaderText"; import { useKeyboard } from "../services/KeyboardProvider"; import { BookmarkProvider } from "../services/bookmarks"; interface Props { location: WindowLocation; path: string; } function GatsbyLinkToButton({ href, ...props }: { href: string }) { return <Link to={href} {...props} />; } export default function Home({ location, path }: Props) { const [isSearchOpen, setSearchOpen] = useKeyboard(); return ( <BookmarkProvider location={location} page={path}> <Layout location={location} title="Orbit design system" description="An open source design system for your next travel project." path="/" isHome > <RocketImage /> <div css={css` /* so that the rest of the content has a higher z-order than the image */ position: relative; width: 100%; max-width: ${MAX_CONTENT_WIDTH}; margin: 0 auto; > * + * { margin-top: 5.25rem; } `} > <> <Heading type="display"> <div css={css` max-width: 43rem; font-size: 3rem; line-height: 1.3; `} > Open source design system for your next travel project. </div> </Heading> <div css={css` margin-top: 3rem; button, a { height: 64px; } `} > <Inline spacing="small"> <Button size="large" type="primary" circled iconRight={<ArrowRight />} // @ts-expect-error asComponent has wrong type declaration asComponent={GatsbyLinkToButton} href="/getting-started/" > Get started </Button> <SearchButton onClick={() => setSearchOpen(true)} /> {isSearchOpen && <Search onClose={() => setSearchOpen(false)} />} </Inline> </div> </> <Stack flex direction="column" justify="between" largeMobile={{ direction: "row", align: "stretch" }} > <Tile title="Components" linkContent="See our components" href="/components/" icon={<PuzzleIcon />} > Our components are a collection of interface elements that can be reused across the Orbit design system. </Tile> <Tile title="Patterns" linkContent="See our patterns" href="/design-patterns/" icon={<ModulePuzzleIcon />} > Make the most of our components by using our design patterns to address common design problems. </Tile> </Stack> <div css={css` > * + * { margin-top: 2rem; } `} > <Heading as="h2">Foundation</Heading> <Stack flex direction="column" tablet={{ direction: "row", align: "stretch" }}> <Tile title="Colors" linkContent="See our colors" href="/foundation/color/" icon={<ColorBrushIcon />} > Color is used to signal structure, highlight importance, and display different states. </Tile> <Tile title="Typography" linkContent="See our typography" href="foundation/typography/" icon={<TypographyIcon />} > Typography is critical for communicating the hierarchy of a page. </Tile> <Tile title="Spacing" linkContent="See our spacing" href="foundation/spacing/" icon={<ExpandDiagonalIcon />} > Consistent spacing makes an interface more clear and easy to scan. </Tile> </Stack> <div css={css` display: flex; justify-content: flex-end; `} > <Button href="/foundation/" size="large" circled type="primarySubtle"> See all items </Button> </div> </div> <div css={css` margin-top: 0; > * + * { margin-top: 2rem; } `} > <Heading as="h2">Content</Heading> <Stack flex direction="column" tablet={{ direction: "row", align: "stretch" }}> <Tile title="Voice & tone" linkContent="See our voice" href="/kiwi-use/content/voice-and-tone/" icon={<LoveItTextIcon />} > How we write at Kiwi.com. </Tile> <Tile title="Grammar & mechanics" linkContent="See our standards" href="/kiwi-use/content/grammar-and-mechanics/" icon={<SpellingCheckIcon />} > Basic grammar guidelines for writing with Orbit. </Tile> <Tile title="Glossary" linkContent="See our terms" href="/kiwi-use/content/glossary/" icon={<ArrangeLetterIcon />} > A list of commonly used words and phrases in Kiwi.com products. </Tile> </Stack> <div css={css` display: flex; justify-content: flex-end; `} > <Button href="/kiwi-use/content/" size="large" circled type="primarySubtle"> See all items </Button> </div> </div> <div css={css` margin-top: 0; > * + * { margin-top: 2rem; } `} > <Heading as="h2">Support</Heading> <Grid columns="1fr" gap="1rem" desktop={{ columns: "1fr 1fr" }}> <BrandedTile title="Report a bug" icon={<ComputerBugIcon />} href="https://github.com/kiwicom/orbit/issues/new/choose" linkContent="Report bug on GitHub" logo={<GitHubLogo />} color={{ primary: "#252A31", secondary: "#515C6C", }} > If you find any bugs in our components, report them on Github and we’ll fix them as soon as possible. It’s our highest priority to have Orbit working as expected. </BrandedTile> <BrandedTile title="Get the Figma library" icon={<ReadArt />} href="https://www.figma.com/@orbitbykiwi" linkContent="Go to Figma profile" logo={<FigmaLogo />} color={{ primary: "#D1431A", secondary: "#EC685A", }} > Visit our community profile and download all of our libraries and resources for free. </BrandedTile> <BrandedTile title="Follow us on Twitter" icon={<LoveBirdIcon />} href="https://twitter.com/OrbitKiwi" linkContent="Follow Orbit on Twitter" logo={<TwitterLogo />} color={{ primary: "#0989CF", secondary: "#179CE3", }} > Twitter is one of our main platforms for sharing. Everything important that is happening around Orbit is published on Twitter. </BrandedTile> <BrandedTile title="Connect Orbit to Tequila" icon={<StartupLaunchIcon />} href="https://partners.kiwi.com" linkContent="Explore Tequila possibilities" logo={<img alt="Tequila logo" src={srcTequila} width={144} height={64} />} color="product" > Tequila is an online B2B platform powered by Kiwi.com that allows anyone to access our content, technology, and services. </BrandedTile> </Grid> </div> <div css={css` margin-bottom: 4rem; > * + * { margin-top: 2rem; } `} > <Heading as="h2">Resources</Heading> <Stack flex direction="column" tablet={{ direction: "row", align: "stretch" }}> <Tile title="Figma library" linkContent={ <> <ScreenReaderText> Open Orbit&apost;s public Figma library in a new window </ScreenReaderText> <NewWindow /> </> } href="https://www.figma.com/@orbitbykiwi" icon={<FigmaIcon />} /> <Tile title="Orbit repository" linkContent={ <> <ScreenReaderText>Open GitHub repository in a new window</ScreenReaderText> <NewWindow /> </> } href="https://github.com/kiwicom/orbit" icon={<GitHubIcon />} /> </Stack> </div> </div> </Layout> </BookmarkProvider> ); }
the_stack
import _ from 'underscore' import $ from 'jquery' import Backbone from 'backbone' // #ChromeStorage.Wrapper // A wrapper around the `chrome.storage.*` API that uses // `$.Deferred` objects for greater flexibility. function Wrapper(type) { type = ''+type || 'local'; if (!chrome.storage[type]) { console.warn('Unknown type %s, defaulting to local', type); type = 'local'; } this.type = type; this.storage = chrome.storage[this.type]; } // ## _csResponse // // Private helper function that's used to return a callback to // wrapped `chrome.storage.*` methods. // // It will **resolve** the provided `$.Deferred` object // with the response, or **reject** it if there was an // error. function _csResponse(dfd) { return function() { var err = chrome.runtime.lastError; if (!err) dfd.resolve.apply(dfd, arguments); else { console.warn("chromeStorage error: '%s'", err.message); dfd.reject(dfd, err.message, err); } }; } // ## chrome.storage.* API // Private factory functions for wrapping API methods // ### wrapMethod // // For wrapping **clear** and **getBytesInUse** function wrapMethod(method) { return function(cb) { var dfd = $.Deferred(); if (typeof cb === 'function') dfd.done(cb); this.storage[method](_csResponse(dfd)); return dfd.promise(); }; } // ### wrapAccessor // // For wrapping **get**, **set**, and **remove**. function wrapAccessor(method) { return function(items, cb) { var dfd = $.Deferred(); if (typeof cb === 'function') dfd.done(cb); this.storage[method](items, _csResponse(dfd)); return dfd.promise(); }; } // The `Wrapper` prototype has the same methods as the `chrome.storage.*` API, // accepting the same parameters, except that they return `$.Deferred` promise // and the callback is always optional. If one is provided, it will be added as a // **done** callback. _(Wrapper.prototype).extend({ getBytesInUse: wrapMethod('getBytesInUse'), clear: wrapMethod('clear'), get: wrapAccessor('get'), set: wrapAccessor('set'), remove: wrapAccessor('remove'), // Pick out the relevant properties from the storage API. getQuotaObject: function() { return _(this.storage).pick( 'QUOTA_BYTES', 'QUOTA_BYTES_PER_ITEM', 'MAX_ITEMS', 'MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE', 'MAX_WRITE_OPERATIONS_PER_HOUR'); } }); // #Backbone.ChromeStorage // Public API is essentially the same as Backbone.localStorage. function ChromeStorage(name, type) { _.bindAll.apply(_, [this].concat(_.functions(this))); this.name = name; this.type = type || ChromeStorage.defaultType || 'local'; this.store = new Wrapper(this.type); this.loaded = this.store.get(this.name). pipe(this._parseRecords). done((function(records) { this.records = records; chrome.storage.onChanged.addListener(this.updateRecords.bind(this)); }).bind(this)); } // `Backbone.ChromeStorage.defaultType` can be overridden globally if desired. // // The current options are `'local'` or `'sync'`. ChromeStorage.defaultType = 'local'; // ### wantsJSON // Private helper function for use with a `$.Deferred`'s **pipe**. // // It mimics the effect of returning a JSON representation of the // provided model from a server, in order to satisfy Backbone.sync // methods that expect that. function wantsJSON(model) { return function() { return model.toJSON(); }; } // ### _S4 // Generate a random four-digit hex string for **_guid**. function _S4() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); } // ### _guid // Pseudo-GUID generator function _guid() { return (_S4()+_S4()+"-"+_S4()+"-"+_S4()+"-"+_S4()+"-"+_S4()+_S4()+_S4()); } // ### unstringify // Gracefully upgrade from stringified models. function unstringify(model) { return typeof model === 'string' ? JSON.parse(model) : model; } _(ChromeStorage.prototype).extend({ // ## Methods for updating the record string // // ### updateRecords updateRecords: function(changes, type) { var records_change = changes[this.name]; if (this._recordsChanged(records_change, type)) { this.records = records_change.newValue; } }, // *StorageChange* `records_change` // *string* `type` is one of 'local' or 'sync' _recordsChanged: function(records_change, type) { if (type === this.type && records_change) { return !_.isEqual(records_change.newValue, this.records); } else { return false; } }, // ## CRUD methods // // ### create create: function(model) { if (!model.id) { model.id = _guid(); model.set(model.idAttribute, model.id); } return this.store.set(this._wrap(model), this._created.bind(this, model)).pipe(wantsJSON(model)); }, _created: function(model) { this.records.push(''+model.id); this.save(); }, // ### update update: function(model) { return this.store.set(this._wrap(model), this._updated.bind(this, model)).pipe(wantsJSON(model)); }, _updated: function(model) { var id = ''+model.id; if (!_(this.records).include(id)) { this.records.push(id); this.save(); } }, // ### find find: function(model) { return this.store.get(this._wrap(model)).pipe(this._found.bind(this, model)); }, _found: function(model, result) { return unstringify(result[this._idOf(model)]); }, // ### findAll findAll: function() { var modelsDfd = $.Deferred() /* Bind the callback to use once the models are fetched. */ , resolveModels = modelsDfd.resolve.bind(modelsDfd) ; // Waits until the model IDs have been initially // populated, and then queries the storage for // the actual records. $.when(this.loaded).done((function(records) { var model_ids = this._getRecordIds(); this.store.get(model_ids, resolveModels); }).bind(this)); return modelsDfd.pipe(this._foundAll); }, _foundAll: function(models) { return _(models).map(unstringify); }, // ### destroy destroy: function(model) { return this.store. remove(this._idOf(model), this._destroyed.bind(this, model)). pipe(wantsJSON(model)); }, _destroyed: function(model) { this.records = _.without(this.records, model.id); this.save(); }, // ## Utility methods // // ### quota // This is mostly relevant in `sync` contexts, // given the rate-limited write operations. // // For `local` contexts, it will just return an object with // the `QUOTA_BYTES` property. // // In `sync` contexts, it will return the above as well as: // // * `QUOTA_BYTES_PER_ITEM` // * `MAX_ITEMS` // * `MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE` // * `MAX_WRITE_OPERATIONS_PER_HOUR` // // It also queries the API with `getBytesInUse`, adding that // to the resultant object under the property name `QUOTA_BYTES_IN_USE`. quota: function() { var q = this.store.getQuotaObject(); return this.store.getBytesInUse().pipe(function(bytes) { return _(q).extend({ QUOTA_BYTES_IN_USE: bytes }); }); }, // ### save // Save the current list of model ids into // a stringified array with the collection // name as key. save: function() { var o = {}; o[this.name] = this.records; this.store.set(o); }, // ### _getRecordIds // Get an array of all model IDs to fetch from storage, // prefixed with the collection name _getRecordIds: function() { return this.records.map(this._idOf); }, // ### _idOf // Get the key that the item will be stored as: // the collection name followed by the model's id. // // Accepts a model instance or the id directly. _idOf: function(model) { return this.name+'-'+(_.isString(model) ? model : model.id); }, // ### _wrap // Encapsulate a model into an object that // the storage API wants. // // Accepts a string ID or a model instance. _wrap: function(model) { var o = {}; o[this._idOf(model)] = _.isString(model) ? model : model.toJSON(); return o; }, // ### _parseRecords // Takes the object returned from `chrome.storage` with the // collection name as a property name, and an array of model ids // as the property's value. // // Legacy support for stringified arrays. // It **split**s the string and returns the result. _parseRecords: function(records) { var record_list = records && records[this.name] ? records[this.name] : null; if (_.isArray(record_list)) { return record_list; } else if (typeof record_list === 'string') { console.debug('[Backbone.ChromeStorage (%s / %s)] upgrading from stringified array of ids', this.type, this.name); return record_list.split(','); } else { return []; } } }); //## Backbone.chromeSync // Largely the same implementation as in Backbone.localSync, except that // `$.Deferred` objects are requisite. ChromeStorage.sync = function(method, model, options, error) { var store = model.chromeStorage || model.collection.chromeStorage , resp , isFn = _.isFunction ; switch(method) { case "read": resp = model.id != null ? store.find(model) : store.findAll(); break; case "create": resp = store.create(model); break; case "update": resp = store.update(model); break; case "delete": resp = store.destroy(model); break; default: var err = new Error('Unknown Method: "'+method+'"'); resp = $.Deferred(); resp.reject(resp, err.message, err); } if (isFn(options.success)) resp.done(options.success); if (isFn(options.error)) resp.fail(options.error); if (isFn(error)) resp.fail(options.error); return resp && resp.promise(); }; const getSyncMethod = function(model) { if (model.chromeStorage || (model.collection && model.collection.chromeStorage)) return ChromeStorage.sync; else return Backbone.sync; }; Backbone.sync = function(method, model, options, error?) { return getSyncMethod(model).apply(this, [method, model, options, error]); }; export default ChromeStorage;
the_stack
import tl = require('azure-pipelines-task-lib/task'); import Q = require('q'); import path = require('path'); import minimatch = require('minimatch'); import task = require('./ftpuploadtask'); import FtpOptions = task.FtpOptions; export class FtpHelper { ftpOptions: FtpOptions = null; ftpClient: any = null; progressTracking: ProgressTracking = null; constructor(ftpOptions: FtpOptions, ftpClient: any) { this.ftpOptions = ftpOptions; this.ftpClient = ftpClient; } createRemoteDirectory(remoteDirectory: string): Q.Promise<void> { let defer: Q.Deferred<void> = Q.defer<void>(); tl.debug('creating remote directory: ' + remoteDirectory); this.ftpClient.mkdir(remoteDirectory, true, function (err) { if (err) { defer.reject('Unable to create remote directory: ' + remoteDirectory + ' due to error: ' + err); } else { defer.resolve(null); } }); return defer.promise; } uploadFile(file: string, remoteFile: string): Q.Promise<void> { let defer: Q.Deferred<void> = Q.defer<void>(); tl.debug('uploading file: ' + file + ' remote: ' + remoteFile); this.ftpClient.put(file, remoteFile, function (err) { if (err) { defer.reject('upload failed: ' + remoteFile + ' due to error: ' + err); } else { defer.resolve(null); } }); return defer.promise; } remoteExists(remoteFile: string): Q.Promise<boolean> { let defer: Q.Deferred<boolean> = Q.defer<boolean>(); tl.debug('checking if remote exists: ' + remoteFile); let remoteDirname = path.normalize(path.dirname(remoteFile)); let remoteBasename = path.basename(remoteFile); this.ftpClient.list(remoteDirname, function (err, list) { if (err) { //err.code == 550 is the standard not found error //but just resolve false for all errors defer.resolve(false); } else { for (let remote of list) { if (remote.name == remoteBasename) { defer.resolve(true); return; } } defer.resolve(false); } }); return defer.promise; } rmdir(remotePath: string): Q.Promise<void> { let defer: Q.Deferred<void> = Q.defer<void>(); tl.debug('removing remote directory: ' + remotePath); this.ftpClient.rmdir(remotePath, true, function (err) { if (err) { defer.reject('Unable to remove remote folder: ' + remotePath + ' error: ' + err); } else { defer.resolve(null); } }); return defer.promise; } remoteDelete(remotePath: string): Q.Promise<void> { let defer: Q.Deferred<void> = Q.defer<void>(); tl.debug('removing remote content: ' + remotePath); this.ftpClient.delete(remotePath, function (err) { if (err) { defer.reject('Unable to remove remote content: ' + remotePath + ' error: ' + err); } else { defer.resolve(null); } }); return defer.promise; } async cleanRemote(remotePath: string) { tl.debug('cleaning remote directory: ' + remotePath); if (await this.remoteExists(remotePath)) { await this.rmdir(remotePath); } } async cleanRemoteContents(remotePath: string) { tl.debug('cleaning remote directory contents: ' + remotePath); let that: any = this; let defer: Q.Deferred<void> = Q.defer<void>(); this.ftpClient.list(path.normalize(remotePath), async function (err, list) { try { if (!err) { for (let remote of list) { let item = path.join(remotePath, remote.name); if (remote.type === 'd') { // directories await that.rmdir(item); } else { await that.remoteDelete(item); } } } defer.resolve(null); } catch(err) { defer.reject('Error cleaning remote path: ' + err); } }); return defer.promise; } uploadFiles(files: string[]): Q.Promise<void> { let thisHelper = this; thisHelper.progressTracking = new ProgressTracking(thisHelper.ftpOptions, files.length + 1); // add one extra for the root directory tl.debug('uploading files'); let defer: Q.Deferred<void> = Q.defer<void>(); let outerPromises: Q.Promise<void>[] = []; // these run first, and their then clauses add more promises to innerPromises let innerPromises: Q.Promise<void>[] = []; outerPromises.push(this.createRemoteDirectory(thisHelper.ftpOptions.remotePath).then(() => { thisHelper.progressTracking.directoryProcessed(thisHelper.ftpOptions.remotePath); })); // ensure root remote location exists files.forEach((file) => { tl.debug('file: ' + file); let remoteFile: string = thisHelper.ftpOptions.preservePaths ? path.join(thisHelper.ftpOptions.remotePath, file.substring(thisHelper.ftpOptions.rootFolder.length)) : path.join(thisHelper.ftpOptions.remotePath, path.basename(file)); remoteFile = remoteFile.replace(/\\/gi, "/"); // use forward slashes always tl.debug('remoteFile: ' + remoteFile); let stats = tl.stats(file); if (stats.isDirectory()) { // create directories if necessary outerPromises.push(thisHelper.createRemoteDirectory(remoteFile).then(() => { thisHelper.progressTracking.directoryProcessed(remoteFile); })); } else if (stats.isFile()) { // upload files if (thisHelper.ftpOptions.overwrite) { outerPromises.push(thisHelper.uploadFile(file, remoteFile).then(() => { thisHelper.progressTracking.fileUploaded(file, remoteFile); })); } else { outerPromises.push(thisHelper.remoteExists(remoteFile).then((exists: boolean) => { if (!exists) { innerPromises.push(thisHelper.uploadFile(file, remoteFile).then(() => { thisHelper.progressTracking.fileUploaded(file, remoteFile); })); } else { thisHelper.progressTracking.fileSkipped(file, remoteFile); } })); } } }); Q.all(outerPromises).then(() => { Q.all(innerPromises).then(() => { defer.resolve(null); }).fail((err) => { defer.reject(err); }) }).fail((err) => { defer.reject(err); }); return defer.promise; } } export class ProgressTracking { ftpOptions: FtpOptions = null; fileCount: number = -1; progressFilesUploaded: number = 0; progressFilesSkipped: number = 0; // already exists and overwrite mode off progressDirectoriesProcessed: number = 0; constructor(ftpOptions: FtpOptions, fileCount: number) { this.ftpOptions = ftpOptions; this.fileCount = fileCount; } directoryProcessed(name: string): void { this.progressDirectoriesProcessed++; this.printProgress('remote directory successfully created/verified: ' + name); } fileUploaded(file: string, remoteFile: string): void { this.progressFilesUploaded++; this.printProgress('successfully uploaded: ' + file + ' to: ' + remoteFile); } fileSkipped(file: string, remoteFile: string): void { this.progressFilesSkipped++; this.printProgress('skipping file: ' + file + ' remote: ' + remoteFile + ' because it already exists'); } printProgress(message: string): void { let total: number = this.progressFilesUploaded + this.progressFilesSkipped + this.progressDirectoriesProcessed; let remaining: number = this.fileCount - total; console.log( 'files uploaded: ' + this.progressFilesUploaded + ', files skipped: ' + this.progressFilesSkipped + ', directories processed: ' + this.progressDirectoriesProcessed + ', total: ' + total + ', remaining: ' + remaining + ', ' + message); } getSuccessStatusMessage(): string { return '\nhost: ' + this.ftpOptions.serverEndpointUrl.host + '\npath: ' + this.ftpOptions.remotePath + '\nfiles uploaded: ' + this.progressFilesUploaded + '\nfiles skipped: ' + this.progressFilesSkipped + '\ndirectories processed: ' + this.progressDirectoriesProcessed; } getFailureStatusMessage() { let total: number = this.progressFilesUploaded + this.progressFilesSkipped + this.progressDirectoriesProcessed; let remaining: number = this.fileCount - total; return this.getSuccessStatusMessage() + '\nunprocessed files & directories: ' + remaining; } } export function findFiles(ftpOptions: FtpOptions): string[] { tl.debug('Searching for files to upload'); let rootFolderStats = tl.stats(ftpOptions.rootFolder); if (rootFolderStats.isFile()) { let file = ftpOptions.rootFolder; tl.debug(file + ' is a file. Ignoring all file patterns'); return [file]; } let allFiles = tl.find(ftpOptions.rootFolder); // filePatterns is a multiline input containing glob patterns tl.debug('searching for files using: ' + ftpOptions.filePatterns.length + ' filePatterns: ' + ftpOptions.filePatterns); // minimatch options let matchOptions = { matchBase: true, dot: true }; let win = tl.osType().match(/^Win/); tl.debug('win: ' + win); if (win) { matchOptions["nocase"] = true; } tl.debug('Candidates found for match: ' + allFiles.length); for (let i = 0; i < allFiles.length; i++) { tl.debug('file: ' + allFiles[i]); } // use a set to avoid duplicates let matchingFilesSet: Set<string> = new Set(); for (let i = 0; i < ftpOptions.filePatterns.length; i++) { let normalizedPattern: string = path.join(ftpOptions.rootFolder, path.normalize(ftpOptions.filePatterns[i])); tl.debug('searching for files, pattern: ' + normalizedPattern); let matched = minimatch.match(allFiles, normalizedPattern, matchOptions); tl.debug('Found total matches: ' + matched.length); // ensure each result is only added once for (let j = 0; j < matched.length; j++) { let match = path.normalize(matched[j]); let stats = tl.stats(match); if (!ftpOptions.preservePaths && stats.isDirectory()) { // if not preserving paths, skip all directories } else if (matchingFilesSet.add(match)) { tl.debug('adding ' + (stats.isFile() ? 'file: ' : 'folder: ') + match); if (stats.isFile() && ftpOptions.preservePaths) { // if preservePaths, make sure the parent directory is also included let parent = path.normalize(path.dirname(match)); if (matchingFilesSet.add(parent)) { tl.debug('adding folder: ' + parent); } } } } } return Array.from(matchingFilesSet).sort(); }
the_stack
import { FilledSignaturePayload1155WithTokenId, MintRequest1155, PayloadToSign1155, PayloadToSign1155WithTokenId, PayloadWithUri1155, Signature1155PayloadInputWithTokenId, Signature1155PayloadOutput, SignedPayload1155, } from "../../schema/contracts/common/signature"; import { TransactionResultWithId } from "../types"; import { normalizePriceValue, setErc20Allowance } from "../../common/currency"; import invariant from "tiny-invariant"; import { ContractWrapper } from "./contract-wrapper"; import { ITokenERC1155, TokenERC1155 } from "contracts"; import { IStorage } from "../interfaces"; import { ContractRoles } from "./contract-roles"; import { NFTCollection } from "../../contracts"; import { BigNumber, ethers } from "ethers"; import { uploadOrExtractURIs } from "../../common/nft"; import { TokensMintedWithSignatureEvent } from "contracts/ITokenERC1155"; /** * Enables generating dynamic ERC1155 NFTs with rules and an associated signature, which can then be minted by anyone securely * @public */ export class Erc1155SignatureMinting { private contractWrapper: ContractWrapper<TokenERC1155>; private storage: IStorage; private roles: ContractRoles< TokenERC1155, typeof NFTCollection.contractRoles[number] >; constructor( contractWrapper: ContractWrapper<TokenERC1155>, roles: ContractRoles< TokenERC1155, typeof NFTCollection.contractRoles[number] >, storage: IStorage, ) { this.contractWrapper = contractWrapper; this.storage = storage; this.roles = roles; } /** * Mint a dynamically generated NFT * * @remarks Mint a dynamic NFT with a previously generated signature. * * @example * ```javascript * // see how to craft a payload to sign in the `generate()` documentation * const signedPayload = contract.signature.generate(payload); * * // now anyone can mint the NFT * const tx = contract.signature.mint(signedPayload); * const receipt = tx.receipt; // the mint transaction receipt * const mintedId = tx.id; // the id of the NFT minted * ``` * @param signedPayload - the previously generated payload and signature with {@link Erc721SignatureMinting.generate} */ public async mint( signedPayload: SignedPayload1155, ): Promise<TransactionResultWithId> { const mintRequest = signedPayload.payload; const signature = signedPayload.signature; const message = await this.mapPayloadToContractStruct(mintRequest); const overrides = await this.contractWrapper.getCallOverrides(); await setErc20Allowance( this.contractWrapper, message.pricePerToken.mul(message.quantity), mintRequest.currencyAddress, overrides, ); const receipt = await this.contractWrapper.sendTransaction( "mintWithSignature", [message, signature], overrides, ); const t = this.contractWrapper.parseLogs<TokensMintedWithSignatureEvent>( "TokensMintedWithSignature", receipt.logs, ); if (t.length === 0) { throw new Error("No MintWithSignature event found"); } const id = t[0].args.tokenIdMinted; return { id, receipt, }; } /** * Mint any number of dynamically generated NFT at once * @remarks Mint multiple dynamic NFTs in one transaction. Note that this is only possible for free mints (cannot batch mints with a price attached to it for security reasons) * @param signedPayloads - the array of signed payloads to mint */ public async mintBatch( signedPayloads: SignedPayload1155[], ): Promise<TransactionResultWithId[]> { const contractPayloads = await Promise.all( signedPayloads.map(async (s) => { const message = await this.mapPayloadToContractStruct(s.payload); const signature = s.signature; const price = s.payload.price; if (BigNumber.from(price).gt(0)) { throw new Error( "Can only batch free mints. For mints with a price, use regular mint()", ); } return { message, signature, }; }), ); const encoded = contractPayloads.map((p) => { return this.contractWrapper.readContract.interface.encodeFunctionData( "mintWithSignature", [p.message, p.signature], ); }); const receipt = await this.contractWrapper.multiCall(encoded); const events = this.contractWrapper.parseLogs<TokensMintedWithSignatureEvent>( "TokensMintedWithSignature", receipt.logs, ); if (events.length === 0) { throw new Error("No MintWithSignature event found"); } return events.map((log) => ({ id: log.args.tokenIdMinted, receipt, })); } /** * Verify that a payload is correctly signed * @param signedPayload - the payload to verify */ public async verify(signedPayload: SignedPayload1155): Promise<boolean> { const mintRequest = signedPayload.payload; const signature = signedPayload.signature; const message = await this.mapPayloadToContractStruct(mintRequest); const verification: [boolean, string] = await this.contractWrapper.readContract.verify(message, signature); return verification[0]; } /** * Generate a signature that can be used to mint an NFT dynamically. * * @remarks Takes in an NFT and some information about how it can be minted, uploads the metadata and signs it with your private key. The generated signature can then be used to mint an NFT using the exact payload and signature generated. * * @example * ```javascript * const nftMetadata = { * name: "Cool NFT #1", * description: "This is a cool NFT", * image: fs.readFileSync("path/to/image.png"), // This can be an image url or file * }; * * const startTime = new Date(); * const endTime = new Date(Date.now() + 60 * 60 * 24 * 1000); * const payload = { * metadata: nftMetadata, // The NFT to mint * to: {{wallet_address}}, // Who will receive the NFT (or AddressZero for anyone) * quantity: 2, // the quantity of NFTs to mint * price: 0.5, // the price per NFT * currencyAddress: NATIVE_TOKEN_ADDRESS, // the currency to pay with * mintStartTime: startTime, // can mint anytime from now * mintEndTime: endTime, // to 24h from now * royaltyRecipient: "0x...", // custom royalty recipient for this NFT * royaltyBps: 100, // custom royalty fees for this NFT (in bps) * primarySaleRecipient: "0x...", // custom sale recipient for this NFT * }; * * const signedPayload = contract.signature.generate(payload); * // now anyone can use these to mint the NFT using `contract.signature.mint(signedPayload)` * ``` * @param payloadToSign - the payload to sign * @returns the signed payload and the corresponding signature */ public async generate( payloadToSign: PayloadToSign1155, ): Promise<SignedPayload1155> { const payload = { ...payloadToSign, tokenId: ethers.constants.MaxUint256, }; return this.generateFromTokenId(payload); } /** * Generate a signature that can be used to mint additionaly supply to an existing NFT. * * @remarks Takes in a payload with the token ID of an existing NFT, and signs it with your private key. The generated signature can then be used to mint additional supply to the NFT using the exact payload and signature generated. * * @example * ```javascript * const nftMetadata = { * name: "Cool NFT #1", * description: "This is a cool NFT", * image: fs.readFileSync("path/to/image.png"), // This can be an image url or file * }; * * const startTime = new Date(); * const endTime = new Date(Date.now() + 60 * 60 * 24 * 1000); * const payload = { * tokenId: 0, // Instead of metadata, we specificy the token ID of the NFT to mint supply to * to: {{wallet_address}}, // Who will receive the NFT (or AddressZero for anyone) * quantity: 2, // the quantity of NFTs to mint * price: 0.5, // the price per NFT * currencyAddress: NATIVE_TOKEN_ADDRESS, // the currency to pay with * mintStartTime: startTime, // can mint anytime from now * mintEndTime: endTime, // to 24h from now * royaltyRecipient: "0x...", // custom royalty recipient for this NFT * royaltyBps: 100, // custom royalty fees for this NFT (in bps) * primarySaleRecipient: "0x...", // custom sale recipient for this NFT * }; * * const signedPayload = contract.signature.generate(payload); * // now anyone can use these to mint the NFT using `contract.signature.mint(signedPayload)` * ``` * @param payloadToSign - the payload to sign * @returns the signed payload and the corresponding signature */ public async generateFromTokenId( payloadToSign: PayloadToSign1155WithTokenId, ): Promise<SignedPayload1155> { const payloads = await this.generateBatchFromTokenIds([payloadToSign]); return payloads[0]; } /** * Generate a batch of signatures that can be used to mint many new NFTs dynamically. * * @remarks See {@link Erc1155SignatureMinting.generate} * * @param payloadsToSign - the payloads to sign * @returns an array of payloads and signatures */ public async generateBatch( payloadsToSign: PayloadToSign1155[], ): Promise<SignedPayload1155[]> { const payloads = payloadsToSign.map((payload) => ({ ...payload, tokenId: ethers.constants.MaxUint256, })); return this.generateBatchFromTokenIds(payloads); } /** * Genrate a batch of signatures that can be used to mint new NFTs or additionaly supply to existing NFTs dynamically. * * @remarks See {@link Erc1155SignatureMinting.generateFromTokenId} * * @param payloadsToSign - the payloads to sign with tokenIds specified * @returns an array of payloads and signatures */ public async generateBatchFromTokenIds( payloadsToSign: PayloadToSign1155WithTokenId[], ): Promise<SignedPayload1155[]> { await this.roles.verify( ["minter"], await this.contractWrapper.getSignerAddress(), ); const parsedRequests: FilledSignaturePayload1155WithTokenId[] = payloadsToSign.map((m) => Signature1155PayloadInputWithTokenId.parse(m)); const metadatas = parsedRequests.map((r) => r.metadata); const uris = await uploadOrExtractURIs(metadatas, this.storage); const chainId = await this.contractWrapper.getChainID(); const signer = this.contractWrapper.getSigner(); invariant(signer, "No signer available"); return await Promise.all( parsedRequests.map(async (m, i) => { const uri = uris[i]; const finalPayload = Signature1155PayloadOutput.parse({ ...m, uri, }); const signature = await this.contractWrapper.signTypedData( signer, { name: "TokenERC1155", version: "1", chainId, verifyingContract: this.contractWrapper.readContract.address, }, { MintRequest: MintRequest1155 }, // TYPEHASH await this.mapPayloadToContractStruct(finalPayload), ); return { payload: finalPayload, signature: signature.toString(), }; }), ); } /** ****************************** * PRIVATE FUNCTIONS *******************************/ /** * Maps a payload to the format expected by the contract * * @internal * * @param mintRequest - The payload to map. * @returns - The mapped payload. */ private async mapPayloadToContractStruct( mintRequest: PayloadWithUri1155, ): Promise<ITokenERC1155.MintRequestStructOutput> { const normalizedPricePerToken = await normalizePriceValue( this.contractWrapper.getProvider(), mintRequest.price, mintRequest.currencyAddress, ); return { to: mintRequest.to, tokenId: mintRequest.tokenId, uri: mintRequest.uri, quantity: mintRequest.quantity, pricePerToken: normalizedPricePerToken, currency: mintRequest.currencyAddress, validityStartTimestamp: mintRequest.mintStartTime, validityEndTimestamp: mintRequest.mintEndTime, uid: mintRequest.uid, royaltyRecipient: mintRequest.royaltyRecipient, royaltyBps: mintRequest.royaltyBps, primarySaleRecipient: mintRequest.primarySaleRecipient, } as ITokenERC1155.MintRequestStructOutput; } }
the_stack
import assert from 'assert'; import { CancellationToken } from 'vscode-languageserver'; import { findNodeByOffset } from '../analyzer/parseTreeUtils'; import { Program } from '../analyzer/program'; import { createMapFromItems } from '../common/collectionUtils'; import { ConfigOptions } from '../common/configOptions'; import { TextRange } from '../common/textRange'; import { DocumentSymbolCollector } from '../languageService/documentSymbolCollector'; import { NameNode } from '../parser/parseNodes'; import { Range } from './harness/fourslash/fourSlashTypes'; import { parseAndGetTestState } from './harness/fourslash/testState'; test('folder reference', () => { const code = ` // @filename: common/__init__.py //// from [|io2|] import tools as tools //// from [|io2|].tools import pathUtils as pathUtils // @filename: io2/empty.py //// # empty // @filename: io2/tools/__init__.py //// def combine(a, b): //// pass // @filename: io2/tools/pathUtils.py //// def getFilename(path): //// pass // @filename: test1.py //// from common import * //// //// tools.combine(1, 1) //// pathUtils.getFilename("c") // @filename: test2.py //// from .[|io2|] import tools as t //// //// t.combine(1, 1) // @filename: test3.py //// from .[|io2|].tools import pathUtils as p //// //// p.getFilename("c") // @filename: test4.py //// from common import tools, pathUtils //// //// tools.combine(1, 1) //// pathUtils.getFilename("c") // @filename: test5.py //// from [|io2|] import tools as tools //// from [|io2|].tools import pathUtils as pathUtils //// //// tools.combine(1, 1) //// pathUtils.getFilename("c") `; const state = parseAndGetTestState(code).state; const ranges = state.getRangesByText().get('io2')!; for (const range of ranges) { verifyReferencesAtPosition(state.program, state.configOptions, 'io2', range.fileName, range.pos, ranges); } }); test('__init__ wildcard import', () => { const code = ` // @filename: common/__init__.py //// from io2 import [|tools|] as [|tools|] //// from io2.[|tools|] import pathUtils as pathUtils // @filename: io2/empty.py //// # empty // @filename: io2/tools/__init__.py //// def combine(a, b): //// pass // @filename: io2/tools/pathUtils.py //// def getFilename(path): //// pass // @filename: test1.py //// from common import * //// //// [|tools|].combine(1, 1) //// pathUtils.getFilename("c") // @filename: test2.py //// from .io2 import [|tools|] as t //// //// t.combine(1, 1) // @filename: test3.py //// from .io2.[|tools|] import pathUtils as p //// //// p.getFilename("c") // @filename: test4.py //// from common import [|tools|], pathUtils //// //// [|tools|].combine(1, 1) //// pathUtils.getFilename("c") // @filename: test5.py //// from io2 import [|tools|] as [|tools|] //// from io2.[|tools|] import pathUtils as pathUtils //// //// [|tools|].combine(1, 1) //// pathUtils.getFilename("c") `; const state = parseAndGetTestState(code).state; const ranges = state.getRangesByText().get('tools')!; for (const range of ranges) { verifyReferencesAtPosition(state.program, state.configOptions, 'tools', range.fileName, range.pos, ranges); } }); test('submodule wildcard import', () => { const code = ` // @filename: common/__init__.py //// from io2 import tools as tools //// from io2.tools import [|pathUtils|] as [|pathUtils|] // @filename: io2/empty.py //// # empty // @filename: io2/tools/__init__.py //// def combine(a, b): //// pass // @filename: io2/tools/pathUtils.py //// def getFilename(path): //// pass // @filename: test1.py //// from common import * //// //// tools.combine(1, 1) //// [|pathUtils|].getFilename("c") // @filename: test2.py //// from .io2 import tools as t //// //// t.combine(1, 1) // @filename: test3.py //// from .io2.tools import [|pathUtils|] as p //// //// p.getFilename("c") // @filename: test4.py //// from common import tools, [|pathUtils|] //// //// tools.combine(1, 1) //// [|pathUtils|].getFilename("c") // @filename: test5.py //// from io2 import tools as tools //// from io2.tools import [|pathUtils|] as [|pathUtils|] //// //// tools.combine(1, 1) //// [|pathUtils|].getFilename("c") `; const state = parseAndGetTestState(code).state; const ranges = state.getRangesByText().get('pathUtils')!; for (const range of ranges) { verifyReferencesAtPosition(state.program, state.configOptions, 'pathUtils', range.fileName, range.pos, ranges); } }); test('use localName import alias', () => { const code = ` // @filename: common/__init__.py //// from io2 import tools as [|/*marker1*/tools|] //// from io2.tools import pathUtils as pathUtils // @filename: io2/empty.py //// # empty // @filename: io2/tools/__init__.py //// def combine(a, b): //// pass // @filename: io2/tools/pathUtils.py //// def getFilename(path): //// pass // @filename: test1.py //// from common import * //// //// [|/*marker2*/tools|].combine(1, 1) //// pathUtils.getFilename("c") // @filename: test2.py //// from .io2 import tools as t //// //// t.combine(1, 1) // @filename: test3.py //// from .io2.tools import pathUtils as p //// //// p.getFilename("c") // @filename: test4.py //// from common import [|/*marker3*/tools|], pathUtils //// //// [|/*marker4*/tools|].combine(1, 1) //// pathUtils.getFilename("c") // @filename: test5.py //// from io2 import tools as [|/*marker5*/tools|] //// from io2.tools import pathUtils as pathUtils //// //// [|/*marker6*/tools|].combine(1, 1) //// pathUtils.getFilename("c") `; const state = parseAndGetTestState(code).state; const references = state .getRangesByText() .get('tools')! .map((r) => ({ path: r.fileName, range: state.convertPositionRange(r) })); state.verifyFindAllReferences({ marker1: { references }, marker2: { references }, marker3: { references }, marker4: { references }, marker5: { references }, marker6: { references }, }); }); test('use localName import module', () => { const code = ` // @filename: common/__init__.py //// from io2 import [|/*marker1*/tools|] as [|tools|] //// from io2.[|/*marker2*/tools|] import pathUtils as pathUtils // @filename: io2/empty.py //// # empty // @filename: io2/tools/__init__.py //// def combine(a, b): //// pass // @filename: io2/tools/pathUtils.py //// def getFilename(path): //// pass // @filename: test1.py //// from common import * //// //// [|tools|].combine(1, 1) //// pathUtils.getFilename("c") // @filename: test2.py //// from .io2 import [|/*marker3*/tools|] as t //// //// t.combine(1, 1) // @filename: test3.py //// from .io2.[|/*marker4*/tools|] import pathUtils as p //// //// p.getFilename("c") // @filename: test4.py //// from common import [|tools|], pathUtils //// //// [|tools|].combine(1, 1) //// pathUtils.getFilename("c") // @filename: test5.py //// from io2 import [|/*marker5*/tools|] as [|tools|] //// from io2.[|/*marker6*/tools|] import pathUtils as pathUtils //// //// [|tools|].combine(1, 1) //// pathUtils.getFilename("c") `; const state = parseAndGetTestState(code).state; const references = state .getRangesByText() .get('tools')! .map((r) => ({ path: r.fileName, range: state.convertPositionRange(r) })); state.verifyFindAllReferences({ marker1: { references }, marker2: { references }, marker3: { references }, marker4: { references }, marker5: { references }, marker6: { references }, }); }); test('import dotted name', () => { const code = ` // @filename: nest1/__init__.py //// # empty // @filename: nest1/nest2/__init__.py //// # empty // @filename: nest1/nest2/module.py //// def foo(): //// pass // @filename: test1.py //// import [|nest1|].[|nest2|].[|module|] //// //// [|nest1|].[|nest2|].[|module|] // @filename: nest1/test2.py //// import [|nest1|].[|nest2|].[|module|] //// //// [|nest1|].[|nest2|].[|module|] `; const state = parseAndGetTestState(code).state; function verify(name: string) { const ranges = state.getRangesByText().get(name)!; for (const range of ranges) { verifyReferencesAtPosition(state.program, state.configOptions, name, range.fileName, range.pos, ranges); } } verify('nest1'); verify('nest2'); verify('module'); }); test('import alias', () => { const code = ` // @filename: nest/__init__.py //// # empty // @filename: nest/module2.py //// # empty // @filename: module1.py //// # empty // @filename: test1.py //// import [|/*marker1*/module1|] as [|module1|] // @filename: test2.py //// import nest.[|/*marker2*/module2|] as [|module2|] `; const state = parseAndGetTestState(code).state; const marker1 = state.getMarkerByName('marker1'); const ranges1 = state.getRangesByText().get('module1')!; verifyReferencesAtPosition( state.program, state.configOptions, 'module1', marker1.fileName, marker1.position, ranges1 ); const marker2 = state.getMarkerByName('marker2'); const ranges2 = state.getRangesByText().get('module2')!; verifyReferencesAtPosition( state.program, state.configOptions, 'module2', marker2.fileName, marker2.position, ranges2 ); }); test('string in __all__', () => { const code = ` // @filename: test1.py //// class [|/*marker1*/A|]: //// pass //// //// a: "[|A|]" = "A" //// //// __all__ = [ "[|A|]" ] `; const state = parseAndGetTestState(code).state; const marker1 = state.getMarkerByName('marker1'); const ranges1 = state.getRangesByText().get('A')!; verifyReferencesAtPosition(state.program, state.configOptions, 'A', marker1.fileName, marker1.position, ranges1); }); test('overridden symbols test', () => { const code = ` // @filename: test.py //// class B: //// def [|foo|](self): //// pass //// //// class C(B): //// def [|foo|](self): //// pass //// //// B().[|foo|]() //// C().[|foo|]() `; const state = parseAndGetTestState(code).state; const ranges = state.getRangesByText().get('foo')!; for (const range of ranges) { verifyReferencesAtPosition(state.program, state.configOptions, 'foo', range.fileName, range.pos, ranges); } }); test('overridden symbols multi inheritance test', () => { const code = ` // @filename: test.py //// class A: //// def [|foo|](self): //// pass //// //// class B: //// def [|foo|](self): //// pass //// //// class C(A, B): //// def [|/*marker*/foo|](self): //// pass //// //// A().[|foo|]() //// B().[|foo|]() //// C().[|foo|]() `; const state = parseAndGetTestState(code).state; const marker = state.getMarkerByName('marker'); const ranges = state.getRangesByText().get('foo')!; verifyReferencesAtPosition(state.program, state.configOptions, 'foo', marker.fileName, marker.position, ranges); }); test('overridden symbols multi inheritance with multiple base with same name test', () => { const code = ` // @filename: test.py //// class A: //// def [|/*marker*/foo|](self): //// pass //// //// class B: //// def foo(self): //// pass //// //// class C(A, B): //// def [|foo|](self): //// pass //// //// A().[|foo|]() //// B().foo() //// C().[|foo|]() `; const state = parseAndGetTestState(code).state; const marker = state.getMarkerByName('marker'); const ranges = state.getRangesByText().get('foo')!; verifyReferencesAtPosition(state.program, state.configOptions, 'foo', marker.fileName, marker.position, ranges); }); test('protocol member symbol test', () => { const code = ` // @filename: test.py //// from typing import Protocol //// //// class A: //// def foo(self): //// pass //// //// class P(Protocol): //// def [|foo|](self): ... //// //// def foo(p: P): //// p.[|/*marker*/foo|]() //// //// foo(A().foo()) `; const state = parseAndGetTestState(code).state; const marker = state.getMarkerByName('marker'); const ranges = state.getRangesByText().get('foo')!; verifyReferencesAtPosition(state.program, state.configOptions, 'foo', marker.fileName, marker.position, ranges); }); test('overridden symbols nested inheritance test', () => { const code = ` // @filename: test.py //// class A: //// def [|foo|](self): //// pass //// //// class B(A): //// def [|foo|](self): //// pass //// //// class C(B): //// def [|foo|](self): //// pass //// //// A().[|foo|]() //// B().[|foo|]() //// C().[|foo|]() `; const state = parseAndGetTestState(code).state; const ranges = state.getRangesByText().get('foo')!; for (const range of ranges) { verifyReferencesAtPosition(state.program, state.configOptions, 'foo', range.fileName, range.pos, ranges); } }); test('overridden symbols nested inheritance no direct override test', () => { const code = ` // @filename: test.py //// class A: //// def [|foo|](self): //// pass //// //// class B(A): //// def [|foo|](self): //// pass //// //// class C(B): //// pass //// //// A().[|foo|]() //// B().[|foo|]() //// C().[|foo|]() `; const state = parseAndGetTestState(code).state; const ranges = state.getRangesByText().get('foo')!; for (const range of ranges) { verifyReferencesAtPosition(state.program, state.configOptions, 'foo', range.fileName, range.pos, ranges); } }); test('overridden symbols different type test', () => { const code = ` // @filename: test.py //// class A: //// def [|foo|](self): //// pass //// //// class B: //// foo: int //// //// class C(A, B): //// def [|foo|](self): //// pass //// //// A().[|foo|]() //// B().foo = 1 //// C().[|/*marker*/foo|]() `; const state = parseAndGetTestState(code).state; const marker = state.getMarkerByName('marker'); const ranges = state.getRangesByText().get('foo')!; verifyReferencesAtPosition(state.program, state.configOptions, 'foo', marker.fileName, marker.position, ranges); }); test('overridden and overloaded symbol test', () => { const code = ` // @filename: test.py //// from typing import overload //// //// class A: //// def [|foo|](self): //// pass //// //// class B(A): //// @overload //// def [|foo|](self): //// pass //// @overload //// def [|foo|](self, a): //// pass //// //// A().[|foo|]() //// B().[|foo|](1) `; const state = parseAndGetTestState(code).state; const ranges = state.getRangesByText().get('foo')!; for (const range of ranges) { verifyReferencesAtPosition(state.program, state.configOptions, 'foo', range.fileName, range.pos, ranges); } }); test('library method override test', () => { const code = ` // @filename: test.py //// from lib import BaseType //// //// class A(BaseType): //// def [|foo|](self): //// pass //// //// A().[|foo|]() // @filename: lib/__init__.py // @library: true //// class BaseType: //// def foo(self): //// pass `; const state = parseAndGetTestState(code).state; const ranges = state.getRangesByText().get('foo')!; for (const range of ranges) { verifyReferencesAtPosition(state.program, state.configOptions, 'foo', range.fileName, range.pos, ranges); } }); test('variable overridden test 1', () => { const code = ` // @filename: test.py //// class A: //// [|foo|] = 1 //// //// class B(A): //// foo = 2 //// //// a = A().[|foo|] //// b = B().foo `; const state = parseAndGetTestState(code).state; const ranges = state.getRangesByText().get('foo')!; for (const range of ranges) { verifyReferencesAtPosition(state.program, state.configOptions, 'foo', range.fileName, range.pos, ranges); } }); test('variable overridden test 2', () => { const code = ` // @filename: test.py //// class A: //// foo = 1 //// //// class B(A): //// [|foo|] = 2 //// //// a = A().foo //// b = B().[|foo|] `; const state = parseAndGetTestState(code).state; const ranges = state.getRangesByText().get('foo')!; for (const range of ranges) { verifyReferencesAtPosition(state.program, state.configOptions, 'foo', range.fileName, range.pos, ranges); } }); function verifyReferencesAtPosition( program: Program, configOption: ConfigOptions, symbolName: string, fileName: string, position: number, ranges: Range[] ) { const sourceFile = program.getBoundSourceFile(fileName); assert(sourceFile); const node = findNodeByOffset(sourceFile.getParseResults()!.parseTree, position); const decls = DocumentSymbolCollector.getDeclarationsForNode( node as NameNode, program.evaluator!, /* resolveLocalName */ true, CancellationToken.None, program.test_createSourceMapper(configOption.findExecEnvironment(fileName)) ); const rangesByFile = createMapFromItems(ranges, (r) => r.fileName); for (const rangeFileName of rangesByFile.keys()) { const collector = new DocumentSymbolCollector( symbolName, decls, program.evaluator!, CancellationToken.None, program.getBoundSourceFile(rangeFileName)!.getParseResults()!.parseTree, /* treatModuleInImportAndFromImportSame */ true, /* skipUnreachableCode */ false ); const results = collector.collect(); const rangesOnFile = rangesByFile.get(rangeFileName)!; assert.strictEqual(results.length, rangesOnFile.length, `${rangeFileName}@${symbolName}`); for (const result of results) { assert(rangesOnFile.some((r) => r.pos === result.range.start && r.end === TextRange.getEnd(result.range))); } } }
the_stack
import { decelerateMax, accelerateMax } from './timingFunctions'; import { ultraFast, faster, fast, normal, slow, slower, ultraSlow } from './durations'; export const slideAnimations = { // Slide Down Animations // Slides object down to original position --ultrafast slideDownEnterUltraFast: { keyframe: ({ delta }) => ({ '0%': { transform: `translateY(-${delta})`, opacity: 0, }, '100%': { transform: 'translateY(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: ultraFast, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object down to original position -Faster slideDownEnterFaster: { keyframe: ({ delta }) => ({ '0%': { transform: `translateY(-${delta})`, opacity: 0, }, '100%': { transform: 'translateY(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: faster, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object down to original position -fast slideDownEnterFast: { keyframe: ({ delta }) => ({ '0%': { transform: `translateY(-${delta})`, opacity: 0, }, '100%': { transform: 'translateY(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: fast, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from top to bottom --normal slideDownEnterNormal: { keyframe: ({ delta }) => ({ '0%': { transform: `translateY(-${delta})`, opacity: 0, }, '100%': { transform: 'translateY(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: normal, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from top to bottom --slow slideDownEnterSlow: { keyframe: ({ delta }) => ({ '0%': { transform: `translateY(-${delta})`, opacity: 0, }, '100%': { transform: 'translateY(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: slow, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from top to bottom --slower slideDownEnterSlower: { keyframe: ({ delta }) => ({ '0%': { transform: `translateY(-${delta})`, opacity: 0, }, '100%': { transform: 'translateY(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: slower, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from top to bottom - Slow slideDownEnterUltraSlow: { keyframe: ({ delta }) => ({ '0%': { transform: `translateY(-${delta})`, opacity: 0, }, '100%': { transform: 'translateY(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: ultraSlow, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Up Animations // Slides object in from top to bottom --ultrafast slideUpEnterUltraFast: { keyframe: ({ delta }) => ({ '0%': { transform: `translateY(${delta})`, opacity: 0, }, '100%': { transform: 'translateY(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: ultraFast, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from top to bottom --faster slideUpEnterFaster: { keyframe: ({ delta }) => ({ '0%': { transform: `translateY(${delta})`, opacity: 0, }, '100%': { transform: 'translateY(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: faster, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from top to bottom --fast slideUpEnterFast: { keyframe: ({ delta }) => ({ '0%': { transform: `translateY(${delta})`, opacity: 0, }, '100%': { transform: 'translateY(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: fast, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from down to up-normal slideUpEnterNormal: { keyframe: ({ delta }) => ({ '0%': { transform: `translateY(${delta})`, opacity: 0, }, '100%': { transform: 'translateY(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: normal, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from top to bottom --slow slideUpEnterSlow: { keyframe: ({ delta }) => ({ '0%': { transform: `translateY(${delta})`, opacity: 0, }, '100%': { transform: 'translateY(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: slow, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from bottom to top - slower slideUpEnterSlower: { keyframe: ({ delta }) => ({ '0%': { transform: `translateY(${delta})`, opacity: 0, }, '100%': { transform: 'translateY(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: slower, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from bottom to top - ultraslow slideUpEnterUltraSlow: { keyframe: ({ delta }) => ({ '0%': { transform: `translateY(${delta})`, opacity: 0, }, '100%': { transform: 'translateY(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: ultraSlow, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // ---Horizontal Slide Animations---- // // Slide Left Animations // Slides object in from right to left --ultrafast slideLeftEnterUltraFast: { keyframe: ({ delta }) => ({ '0%': { transform: `translateX(${delta})`, opacity: 0, }, '100%': { transform: 'translateX(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: ultraFast, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from right to left -faster slideLeftEnterFaster: { keyframe: ({ delta }) => ({ '0%': { transform: `translateX(${delta})`, opacity: 0, }, '100%': { transform: 'translateX(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: faster, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from right to left -Fast slideLeftEnterFast: { keyframe: ({ delta }) => ({ '0%': { transform: `translateX(${delta})`, opacity: 0, }, '100%': { transform: 'translateX(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: fast, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from right to left -Normal slideLeftEnterNormal: { keyframe: ({ delta }) => ({ '0%': { transform: `translateX(${delta})`, opacity: 0, }, '100%': { transform: 'translateX(0px)', opacity: 1, }, }), keyframeParams: { delta: '200px' }, duration: normal, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from right to left -Slow slideLeftEnterSlow: { keyframe: ({ delta }) => ({ '0%': { transform: `translateX(${delta})`, opacity: 0, }, '100%': { transform: 'translateX(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: slow, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from right to left - slower slideLeftEnterSlower: { keyframe: ({ delta }) => ({ '0%': { transform: `translateX(${delta})`, opacity: 0, }, '100%': { transform: 'translateX(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: slower, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from right to left - ultraslow slideLeftEnterUltraSlow: { keyframe: ({ delta }) => ({ '0%': { transform: `translateX(${delta})`, opacity: 0, }, '100%': { transform: 'translateX(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: ultraSlow, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Right Animations // Slides object in from left to right -ultrafast slideRightEnterUltraFast: { keyframe: ({ delta }) => ({ '0%': { transform: `translateX(-${delta})`, opacity: 0, }, '100%': { transform: 'translateX(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: ultraFast, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from left to right - Faster slideRightEnterFaster: { keyframe: ({ delta }) => ({ '0%': { transform: `translateX(-${delta})`, opacity: 0, }, '100%': { transform: 'translateX(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: faster, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from left to right -fast slideRightEnterFast: { keyframe: ({ delta }) => ({ '0%': { transform: `translateX(-${delta})`, opacity: 0, }, '100%': { transform: 'translateX(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: fast, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from left to right -normal slideRightEnterNormal: { keyframe: ({ delta }) => ({ '0%': { transform: `translateX(-${delta})`, opacity: 0, }, '100%': { transform: 'translateX(0px)', opacity: 1, }, }), keyframeParams: { delta: '200px' }, duration: normal, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from left to right -slow slideRightEnterSlow: { keyframe: ({ delta }) => ({ '0%': { transform: `translateX(-${delta})`, opacity: 0, }, '100%': { transform: 'translateX(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: slow, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from left to right- slower slideRightEnterSlower: { keyframe: ({ delta }) => ({ '0%': { transform: `translateX(-${delta})`, opacity: 0, }, '100%': { transform: 'translateX(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: slower, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slides object in from left to right- ultraslow slideRightEnterUltraSlow: { keyframe: ({ delta }) => ({ '0%': { transform: `translateX(-${delta})`, opacity: 0, }, '100%': { transform: 'translateX(0px)', opacity: 1, }, }), keyframeParams: { delta: '20px' }, duration: ultraSlow, timingFunction: decelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Exit Animation/// // Slide Down - Exit - UltraFast slideDownExitUltraFast: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateY(0px)', opacity: 1, }, '100%': { transform: `translateY(${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: ultraFast, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Down - Exit - Faster slideDownExitFaster: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateY(0px)', opacity: 1, }, '100%': { transform: `translateY(${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: faster, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Down - Exit - Fast slideDownExitFast: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateY(0px)', opacity: 1, }, '100%': { transform: `translateY(${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: fast, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Down - Exit - Normal slideDownExitNormal: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateY(0px)', opacity: 1, }, '100%': { transform: `translateY(${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: normal, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Down - Exit - Slow slideDownExitSlow: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateY(0px)', opacity: 1, }, '100%': { transform: `translateY(${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: slow, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Down - Exit - Slower slideDownExitSlower: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateY(0px)', opacity: 1, }, '100%': { transform: `translateY(${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: slower, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Down - Exit - Ultraslow slideDownExitUltraSlow: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateY(0px)', opacity: 1, }, '100%': { transform: `translateY(${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: ultraSlow, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Up - Exit- Animations // Slide Up - Exit - UltraFast slideUpExitUltraFast: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateY(0px)', opacity: 1, }, '100%': { transform: `translateY(-${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: ultraFast, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Up - Exit - Faster slideUpExitFaster: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateY(0px)', opacity: 1, }, '100%': { transform: `translateY(-${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: faster, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Up - Exit - Fast slideUpExitFast: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateY(0px)', opacity: 1, }, '100%': { transform: `translateY(-${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: fast, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Up - Exit - Normal slideUpExitNormal: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateY(0px)', opacity: 1, }, '100%': { transform: `translateY(-${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: normal, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Up - Exit - Slow slideUpExitSlow: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateY(0px)', opacity: 1, }, '100%': { transform: `translateY(-${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: slow, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Up - Exit - Slower slideUpExitSlower: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateY(0px)', opacity: 1, }, '100%': { transform: `translateY(-${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: slower, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Up - Exit - Ultra Slow slideUpExitUltraSlow: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateY(0px)', opacity: 1, }, '100%': { transform: `translateY(-${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: ultraSlow, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Right Exit Animations // Slide Right Exit - Ultrafast slideRightExitUltraFast: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateX(0px)', opacity: 1, }, '100%': { transform: `translateX(${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: ultraFast, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Right Exit - Faster slideRightExitFaster: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateX(0px)', opacity: 1, }, '100%': { transform: `translateX(${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: faster, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Right Exit - Fast slideRightExitFast: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateX(0px)', opacity: 1, }, '100%': { transform: `translateX(${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: fast, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Right Exit - Normal slideRightExitNormal: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateX(0px)', opacity: 1, }, '100%': { transform: `translateX(${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: normal, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Right Exit - Slow slideRightExitSlow: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateX(0px)', opacity: 1, }, '100%': { transform: `translateX(${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: slow, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Right Exit - Ultrafast slideRightExitSlower: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateX(0px)', opacity: 1, }, '100%': { transform: `translateX(${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: slower, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Right Exit - Ultraslow slideRightExitUltraSlow: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateX(0px)', opacity: 1, }, '100%': { transform: `translateX(${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: ultraSlow, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Left Exit Aniamtions // Slide Left Exit -ultrafast slideLeftExitUltraFast: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateX(0px)', opacity: 1, }, '100%': { transform: `translateX(-${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: ultraFast, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Left Exit -Faster slideLeftExitFaster: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateX(0px)', opacity: 1, }, '100%': { transform: `translateX(-${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: faster, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Left Exit -Fast slideLeftExitFast: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateX(0px)', opacity: 1, }, '100%': { transform: `translateX(-${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: fast, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Left Exit -Normal slideLeftExitNormal: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateX(0px)', opacity: 1, }, '100%': { transform: `translateX(-${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: normal, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Left Exit -Slow slideLeftExitSlow: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateX(0px)', opacity: 1, }, '100%': { transform: `translateX(-${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: slow, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Left Exit -Slower slideLeftExitSlower: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateX(0px)', opacity: 1, }, '100%': { transform: `translateX(-${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: slower, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, // Slide Left Exit -Ultraslow slideLeftExitUltraSlow: { keyframe: ({ delta }) => ({ '0%': { transform: 'translateX(0px)', opacity: 1, }, '100%': { transform: `translateX(-${delta})`, opacity: 0, }, }), keyframeParams: { delta: '20px' }, duration: ultraSlow, timingFunction: accelerateMax, direction: 'forward', fillMode: 'forwards', }, };
the_stack
import kernel = require("./xray-kernel-turbo"); const turbo = kernel.turbo; const Color = kernel.Color; const Vector = kernel.Vector; const Matrix = kernel.matrix; describe("Turbo Runtime suite", () => { it("Turbo should have defined", () => { expect(turbo).toBeDefined(); }); it("Turbo Runtime should have defined", () => { expect(turbo.Runtime).toBeDefined(); }); }); describe("Kernel suite >> ", () => { it("Kernel should have defined", () => { expect(kernel).toBeDefined(); }); describe("Color definition >> ", () => { it("Color should have defined", () => { expect(Color).toBeDefined(); }); it("Color should have init method", () => { expect(Color.init).toBeDefined(); }); it("Color should have Set method", () => { expect(Color.Set).toBeDefined(); }); it("Color should have HexColor method", () => { expect(Color.HexColor).toBeDefined(); }); it("Color should have kelvin method", () => { expect(Color.Kelvin).toBeDefined(); }); it("Color should have NewColor method", () => { expect(Color.NewColor).toBeDefined(); }); it("Color should have RGBA method", () => { expect(Color.RGBA).toBeDefined(); }); it("Color should have RGBA64 method", () => { expect(Color.RGBA64).toBeDefined(); }); it("Color should have Add method", () => { expect(Color.Add).toBeDefined(); }); it("Color should have Add_mem method", () => { expect(Color.Add_mem).toBeDefined(); }); it("Color should have Sub method", () => { expect(Color.Sub).toBeDefined(); }); it("Color should have Sub_mem method", () => { expect(Color.Sub_mem).toBeDefined(); }); it("Color should have Mul method", () => { expect(Color.Mul).toBeDefined(); }); it("Color should have Mul_mem method", () => { expect(Color.Mul_mem).toBeDefined(); }); it("Color should have MulScalar method", () => { expect(Color.MulScalar).toBeDefined(); }); it("Color should have MulScalar_mem method", () => { expect(Color.MulScalar_mem).toBeDefined(); }); it("Color should have DivScalar method", () => { expect(Color.DivScalar).toBeDefined(); }); it("Color should have DivScalar_mem method", () => { expect(Color.DivScalar_mem).toBeDefined(); }); it("Color should have Min method", () => { expect(Color.Min).toBeDefined(); }); it("Color should have Min_mem method", () => { expect(Color.Min_mem).toBeDefined(); }); it("Color should have Max method", () => { expect(Color.Max).toBeDefined(); }); it("Color should have Max_mem method", () => { expect(Color.Max_mem).toBeDefined(); }); it("Color should have MinComponent method", () => { expect(Color.MinComponent).toBeDefined(); }); it("Color should have MinComponent_mem method", () => { expect(Color.MinComponent_mem).toBeDefined(); }); it("Color should have MaxComponent method", () => { expect(Color.MaxComponent).toBeDefined(); }); it("Color should have MaxComponent_mem method", () => { expect(Color.MaxComponent_mem).toBeDefined(); }); it("Color should have Pow method", () => { expect(Color.Pow).toBeDefined(); }); it("Color should have Pow_mem method", () => { expect(Color.Pow_mem).toBeDefined(); }); it("Color should have Mix method", () => { expect(Color.Mix).toBeDefined(); }); it("Color should have Mix_mem method", () => { expect(Color.Mix_mem).toBeDefined(); }); it("Color should have Clone method", () => { expect(Color.Clone).toBeDefined(); }); it("Color should have Random method", () => { expect(Color.Random).toBeDefined(); }); it("Color should have RandomBrightColor method", () => { expect(Color.RandomBrightColor).toBeDefined(); }); it("Color should have BrightColors property", () => { expect(Color.BrightColors).toBeDefined(); }); }); describe("Color instance >> ", () => { it("Should create without a problem", () => { let color = new Color(0); expect(color).toBeTruthy(); }); it("Should add without a problem", () => { //float64 (input) let red = {R: 1, G: 0, B: 0}; let green = {R: 0, G: 1, B: 0}; let blue = {R: 0, G: 0, B: 1}; //uint8 (output) let white = {R: 255, G: 255, B: 255, A: 255}; let _red:number = Color.NewColor(red); let _green:number = Color.NewColor(green); let _blue:number = Color.NewColor(blue); let result1:number = Color.NewColor(); let tmp1:number = Color.Add_mem(_red, _green); Color.Add_mem(tmp1, _blue, result1); let result2:number = Color.Add_mem(tmp1, _blue); expect(white).toEqual(Color.RGBA(result1)); expect(white).toEqual(Color.RGBA(result2)); }); it("Should subtract without a problem", () => { //float64 (input) let white = {R: 1, G: 1, B: 1}; let green = {R: 0, G: 1, B: 0}; let blue = {R: 0, G: 0, B: 1}; //uint8 (output) let red = {R: 255, G: 0, B: 0, A: 255}; let _white:number = Color.NewColor(white); let _green:number = Color.NewColor(green); let _blue:number = Color.NewColor(blue); let result1:number = Color.NewColor(); let tmp1:number = Color.Sub_mem(_white, _blue); Color.Sub_mem(tmp1, _green, result1); let result2 = Color.Sub_mem(tmp1, _green); expect(red).toEqual(Color.RGBA(result1)); expect(red).toEqual(Color.RGBA(result2)); }); it("Should multiply without a problem", () => { //float64 (input) let red = {R: 1, G: 0, B: 0}; let green = {R: 0, G: 1, B: 0}; let blue = {R: 0, G: 0, B: 1}; //uint8 (output) let black = {R: 0, G: 0, B: 0, A: 255}; let _red:number = Color.NewColor(red); let _green:number = Color.NewColor(green); let _blue:number = Color.NewColor(blue); let result1:number = Color.NewColor(); let tmp1:number = Color.Mul_mem(_red, _green); Color.Mul_mem(tmp1, _blue, result1); let result2:number = Color.Mul_mem(tmp1, _blue); expect(black).toEqual(Color.RGBA(result1)); expect(black).toEqual(Color.RGBA(result2)); }); it("Should multiply scalar without a problem", () => { //float64 (input) let white = {R: 1, G: 1, B: 1}; //uint8 (output) let halfwhite = {R: Math.round(255 * 0.5), G: Math.round(255 * 0.5), B: Math.round(255 * 0.5), A: 255}; let halfwhiteFloat = {R: 0.5, G: 0.5, B: 0.5, A: 1.0}; let _white:number = Color.NewColor(white); let result1:number = Color.NewColor(); Color.MulScalar_mem(_white, 0.5, result1); let result2:number = Color.MulScalar_mem(_white, 0.5); let result3:number = Color.MulScalar_mem(_white, 0.5000000000000001); expect(halfwhite).toEqual(Color.RGBA(result1)); expect(halfwhite).toEqual(Color.RGBA(result2)); expect(halfwhiteFloat).not.toEqual(Color.FloatRGBA(result3)); }); it("Should divide scalar without a problem", () => { //float64 (input) let white = {R: 1, G: 1, B: 1}; //uint8 (output) let halfwhite = {R: Math.round(255 * 0.5), G: Math.round(255 * 0.5), B: Math.round(255 * 0.5), A: 255}; let _white:number = Color.NewColor(white); let result1:number = Color.NewColor(); Color.DivScalar_mem(_white, 2, result1); let result2:number = Color.DivScalar_mem(_white, 2); expect(halfwhite).toEqual(Color.RGBA(result1)); expect(halfwhite).toEqual(Color.RGBA(result2)); }); it("Should calculate minimum value without a problem", () => { //float64 (input) let color1 = {R: 1, G: 0.00055, B: 0.0255}; let color2 = {R: 0.25, G: 0.5, B: 0.05}; let min = {R: 0.25, G: 0.00055, B: 0.0255, A: 1}; let _c1:number = Color.NewColor(color1); let _c2:number = Color.NewColor(color2); let result1:number = Color.NewColor(); Color.Min_mem(_c1, _c2, result1); let result2:number = Color.Min_mem(_c1, _c2); expect(min).toEqual(Color.FloatRGBA(result1)); expect(min).toEqual(Color.FloatRGBA(result2)); }); it("Should calculate maximum value without a problem", () => { //float64 (input) let color1 = {R: 1, G: 0.00055, B: 0.0255}; let color2 = {R: 0.25, G: 0.5, B: 0.05}; let max = {R: 1, G: 0.5, B: 0.05, A: 1}; let _c1:number = Color.NewColor(color1); let _c2:number = Color.NewColor(color2); let result1:number = Color.NewColor(); Color.Max_mem(_c1, _c2, result1); let result2:number = Color.Max_mem(_c1, _c2); expect(max).toEqual(Color.FloatRGBA(result1)); expect(max).toEqual(Color.FloatRGBA(result2)); }); it("Should calculate minimum component without a problem", () => { //float64 (input) let color1 = {R: 1, G: 0.00055, B: 0.0255}; let _c1:number = Color.NewColor(color1); let result:number = Color.MinComponent_mem(_c1); expect(result).toEqual(0.00055); }); it("Should calculate maximum component without a problem", () => { //float64 (input) let color1 = {R: 1, G: 0.00055, B: 0.0255}; let _c1:number = Color.NewColor(color1); let result:number = Color.MaxComponent_mem(_c1); expect(result).toEqual(1); }); it("Should calculate power without a problem", () => { let factor:number = 2; //float64 (input) let color = {R: 1, G: 0.00055, B: 0.0255}; let color_pow = { R: Math.pow(color.R, factor), G: Math.pow(color.G, factor), B: Math.pow(color.B, factor), A: 1.0 }; let _c1:number = Color.NewColor(color); let result:number = Color.Pow_mem(_c1, factor); expect(Color.FloatRGBA(result)).toEqual(color_pow); }); it("Should mix without a problem", () => { let factor:number = 0.5; //float64 (input) let color1 = {R: 1, G: 0, B: 0.0255}; let color2 = {R: 1, G: 1, B: 0.0255}; let color_mix = {R: 1, G: 0.5, B: 0.0255, A: 1}; let _c1:number = Color.NewColor(color1); let _c2:number = Color.NewColor(color2); let result1:number = Color.NewColor(); Color.Mix_mem(_c1, _c2, factor, result1); let result2:number = Color.Mix_mem(_c1, _c2, factor); expect(Color.FloatRGBA(result1)).toEqual(color_mix); expect(Color.FloatRGBA(result2)).toEqual(color_mix); }); it("Should check isEqual without a problem", () => { //float64 (input) let color1 = {R: 0.256, G: 0, B: 1}; let color2 = {R: 0.256, G: 0, B: 1}; let color3 = {R: 0.254, G: 1, B: 0.0255}; let _c1:number = Color.NewColor(color1); let _c2:number = Color.NewColor(color2); let _c3:number = Color.NewColor(color3); let result1:boolean = Color.isEqual(_c1, _c2); let result2:boolean = Color.isEqual(_c2, _c1); let result3:boolean = Color.isEqual(_c1, _c3); let result4:boolean = Color.isEqual(_c2, _c3); expect(result1).toBeTruthy(); expect(result2).toBeTruthy(); expect(result3).not.toBeTruthy(); expect(result4).not.toBeTruthy(); }); it("Should check IsBlack without a problem", () => { //float64 (input) let black = {R: 0, G: 0, B: 0}; let blue = {R: 0, G: 0, B: 1}; let _c1:number = Color.NewColor(black); let _c2:number = Color.NewColor(blue); let result1:boolean = Color.IsBlack(_c1); let result2:boolean = Color.IsBlack(_c2); expect(result1).toBeTruthy(); expect(result2).not.toBeTruthy(); }); it("Should check IsWhite without a problem", () => { //float64 (input) let white = {R: 1, G: 1, B: 1}; let blue = {R: 0, G: 0, B: 1}; let _c1:number = Color.NewColor(white); let _c2:number = Color.NewColor(blue); let result1:boolean = Color.IsWhite(_c1); let result2:boolean = Color.IsWhite(_c2); expect(result1).toBeTruthy(); expect(result2).not.toBeTruthy(); }); it("Should set value without a problem", () => { //float64 (input) let blue = {R: 0, G: 0, B: 1, A: 1}; let _c:number = Color.NewColor(); let result:number = Color.Set(_c, blue.R, blue.G, blue.B); expect(Color.FloatRGBA(result)).toEqual(blue); }); it("Should clone without a problem", () => { //float64 (input) let blue = {R: 0, G: 0, B: 1, A: 1}; let _c:number = Color.NewColor(blue); let result:number = Color.Clone(_c); expect(Color.FloatRGBA(result)).toEqual(blue); }); it("Should create random color without a problem", () => { let color1:number = Color.Random(); let color2:number = Color.Random(); expect(color1).not.toBeNull(); expect(color2).not.toBeNull(); expect(Color.RGBA(color1)).not.toBeNull(); expect(Color.RGBA(color2)).not.toBeNull(); expect(Color.RGBA(color1)).not.toEqual(Color.RGBA(color2)); }); it("Should create random bright color without a problem", () => { let color1:number = Color.RandomBrightColor(); let color2:number = Color.RandomBrightColor(); expect(color1).not.toBeNull(); expect(color2).not.toBeNull(); expect(Color.RGBA(color1)).not.toBeNull(); expect(Color.RGBA(color2)).not.toBeNull(); }); }); describe("Vector definition >> ", () => { it("Vector should have defined", () => { expect(Vector).toBeDefined(); }); it("Vector should have RandomUnitVector method", () => { expect(Vector.RandomUnitVector).toBeDefined(); }); it("Vector should have Length method", () => { expect(Vector.Length).toBeDefined(); }); it("Vector should have LengthN method", () => { expect(Vector.LengthN).toBeDefined(); }); it("Vector should have Dot method", () => { expect(Vector.Dot).toBeDefined(); }); it("Vector should have Dot_mem method", () => { expect(Vector.Dot_mem).toBeDefined(); }); it("Vector should have Cross method", () => { expect(Vector.Cross).toBeDefined(); }); it("Vector should have Cross_mem method", () => { expect(Vector.Cross_mem).toBeDefined(); }); it("Vector should have Normalize method", () => { expect(Vector.Normalize).toBeDefined(); }); it("Vector should have Normalize_mem method", () => { expect(Vector.Normalize_mem).toBeDefined(); }); it("Vector should have Negate method", () => { expect(Vector.Negate).toBeDefined(); }); it("Vector should have Negate_mem method", () => { expect(Vector.Negate_mem).toBeDefined(); }); it("Vector should have Abs method", () => { expect(Vector.Abs).toBeDefined(); }); it("Vector should have Abs_mem method", () => { expect(Vector.Abs_mem).toBeDefined(); }); it("Vector should have Add method", () => { expect(Vector.Add).toBeDefined(); }); it("Vector should have Add_mem method", () => { expect(Vector.Add_mem).toBeDefined(); }); it("Vector should have Sub method", () => { expect(Vector.Sub).toBeDefined(); }); it("Vector should have Sub_mem method", () => { expect(Vector.Sub_mem).toBeDefined(); }); it("Vector should have Mul method", () => { expect(Vector.Mul).toBeDefined(); }); it("Vector should have Mul_mem method", () => { expect(Vector.Mul_mem).toBeDefined(); }); it("Vector should have Div method", () => { expect(Vector.Div).toBeDefined(); }); it("Vector should have Div_mem method", () => { expect(Vector.Div_mem).toBeDefined(); }); it("Vector should have Mod method", () => { expect(Vector.Mod).toBeDefined(); }); it("Vector should have Mod_mem method", () => { expect(Vector.Mod_mem).toBeDefined(); }); it("Vector should have AddScalar method", () => { expect(Vector.AddScalar).toBeDefined(); }); it("Vector should have AddScalar_mem method", () => { expect(Vector.AddScalar_mem).toBeDefined(); }); it("Vector should have SubScalar method", () => { expect(Vector.SubScalar).toBeDefined(); }); it("Vector should have SubScalar_mem method", () => { expect(Vector.SubScalar_mem).toBeDefined(); }); it("Vector should have MulScalar method", () => { expect(Vector.MulScalar).toBeDefined(); }); it("Vector should have MulScalar_mem method", () => { expect(Vector.MulScalar_mem).toBeDefined(); }); it("Vector should have DivScalar method", () => { expect(Vector.DivScalar).toBeDefined(); }); it("Vector should have DivScalar_mem method", () => { expect(Vector.DivScalar_mem).toBeDefined(); }); it("Vector should have Min method", () => { expect(Vector.Min).toBeDefined(); }); it("Vector should have Min_mem method", () => { expect(Vector.Min_mem).toBeDefined(); }); it("Vector should have Max method", () => { expect(Vector.Max).toBeDefined(); }); it("Vector should have Max_mem method", () => { expect(Vector.Max_mem).toBeDefined(); }); it("Vector should have MinAxis method", () => { expect(Vector.MinAxis).toBeDefined(); }); it("Vector should have MinAxis_mem method", () => { expect(Vector.MinAxis_mem).toBeDefined(); }); it("Vector should have MinComponent method", () => { expect(Vector.MinComponent).toBeDefined(); }); it("Vector should have MinComponent_mem method", () => { expect(Vector.MinComponent_mem).toBeDefined(); }); it("Vector should have MaxComponent method", () => { expect(Vector.MaxComponent).toBeDefined(); }); it("Vector should have MaxComponent_mem method", () => { expect(Vector.MaxComponent_mem).toBeDefined(); }); it("Vector should have Reflect method", () => { expect(Vector.Reflect).toBeDefined(); }); it("Vector should have Reflect_mem method", () => { expect(Vector.Reflect_mem).toBeDefined(); }); it("Vector should have Refract method", () => { expect(Vector.Refract).toBeDefined(); }); it("Vector should have Refract_mem method", () => { expect(Vector.Refract_mem).toBeDefined(); }); it("Vector should have Reflectance method", () => { expect(Vector.Reflectance).toBeDefined(); }); it("Vector should have Reflectance_mem method", () => { expect(Vector.Reflectance_mem).toBeDefined(); }); }) describe("Vector instance >> ", () => { it("Should create without a problem", () => { let vector = new Vector(0); expect(vector).toBeTruthy(); }); it("Should add without a problem", () => { //float64 (input) let a1 = {X: 1, Y: 0, Z: 0}; let a2 = {X: 0, Y: 1, Z: 0}; let a3 = {X: 0, Y: 0, Z: 1}; //uint8 (output) let a4 = {X: 1, Y: 1, Z: 1}; let _red:number = Vector.NewVector(a1); let _green:number = Vector.NewVector(a2); let _blue:number = Vector.NewVector(a3); let result1:number = Vector.NewVector(); let tmp1:number = Vector.Add_mem(_red, _green); Vector.Add_mem(tmp1, _blue, result1); let result2:number = Vector.Add_mem(tmp1, _blue); expect(a4).toEqual(Vector.XYZ(result1)); expect(a4).toEqual(Vector.XYZ(result2)); }); it("Should subtract without a problem", () => { //float64 (input) let white = {X: 1, Y: 1, Z: 1}; let a2 = {X: 0, Y: 1, Z: 0}; let a3 = {X: 0, Y: 0, Z: 1}; //uint8 (output) let a1 = {X: 1, Y: 0, Z: 0}; let _white:number = Vector.NewVector(white); let _green:number = Vector.NewVector(a2); let _blue:number = Vector.NewVector(a3); let result1:number = Vector.NewVector(); let tmp1:number = Vector.Sub_mem(_white, _blue); Vector.Sub_mem(tmp1, _green, result1); let result2 = Vector.Sub_mem(tmp1, _green); expect(a1).toEqual(Vector.XYZ(result1)); expect(a1).toEqual(Vector.XYZ(result2)); }); it("Should multiply without a problem", () => { //float64 (input) let a1 = {X: 1, Y: 0, Z: 0}; let a2 = {X: 0, Y: 1, Z: 0}; let a3 = {X: 0, Y: 0, Z: 1}; let black = {X: 0, Y: 0, Z: 0}; let _red:number = Vector.NewVector(a1); let _green:number = Vector.NewVector(a2); let _blue:number = Vector.NewVector(a3); let result1:number = Vector.NewVector(); let tmp1:number = Vector.Mul_mem(_red, _green); Vector.Mul_mem(tmp1, _blue, result1); let result2:number = Vector.Mul_mem(tmp1, _blue); expect(black).toEqual(Vector.XYZ(result1)); expect(black).toEqual(Vector.XYZ(result2)); }); it("Should multiply scalar without a problem", () => { //float64 (input) let white = {X: 1, Y: 1, Z: 1}; let halfwhite = {X: 0.5, Y: 0.5, Z: 0.5}; let _white:number = Vector.NewVector(white); let result1:number = Vector.NewVector(); Vector.MulScalar_mem(_white, 0.5, result1); let result2:number = Vector.MulScalar_mem(_white, 0.5); let result3:number = Vector.MulScalar_mem(_white, 0.5000000000000001); expect(halfwhite).toEqual(Vector.XYZ(result1)); expect(halfwhite).toEqual(Vector.XYZ(result2)); expect(halfwhite).not.toEqual(Vector.XYZ(result3)); }); it("Should divide scalar without a problem", () => { //float64 (input) let white = {X: 1, Y: 1, Z: 1}; //uint8 (output) let halfwhite = {X: 0.5, Y: 0.5, Z: 0.5}; let _white:number = Vector.NewVector(white); let result1:number = Vector.NewVector(); Vector.DivScalar_mem(_white, 2, result1); let result2:number = Vector.DivScalar_mem(_white, 2); expect(halfwhite).toEqual(Vector.XYZ(result1)); expect(halfwhite).toEqual(Vector.XYZ(result2)); }); it("Should calculate minimum value without a problem", () => { //float64 (input) let vector1 = {X: 1, Y: 0.00055, Z: 0.0255}; let vector2 = {X: 0.25, Y: 0.5, Z: 0.05}; let min = {X: 0.25, Y: 0.00055, Z: 0.0255}; let _c1:number = Vector.NewVector(vector1); let _c2:number = Vector.NewVector(vector2); let result1:number = Vector.NewVector(); Vector.Min_mem(_c1, _c2, result1); let result2:number = Vector.Min_mem(_c1, _c2); expect(min).toEqual(Vector.XYZ(result1)); expect(min).toEqual(Vector.XYZ(result2)); }); it("Should calculate maximum value without a problem", () => { //float64 (input) let vector1 = {X: 1, Y: 0.00055, Z: 0.0255}; let vector2 = {X: 0.25, Y: 0.5, Z: 0.05}; let max = {X: 1, Y: 0.5, Z: 0.05}; let _c1:number = Vector.NewVector(vector1); let _c2:number = Vector.NewVector(vector2); let result1:number = Vector.NewVector(); Vector.Max_mem(_c1, _c2, result1); let result2:number = Vector.Max_mem(_c1, _c2); expect(max).toEqual(Vector.XYZ(result1)); expect(max).toEqual(Vector.XYZ(result2)); }); it("Should calculate minimum component without a problem", () => { //float64 (input) let vector1 = {X: 1, Y: 0.00055, Z: 0.0255}; let _c1:number = Vector.NewVector(vector1); let result:number = Vector.MinComponent_mem(_c1); expect(result).toEqual(0.00055); }); it("Should calculate maximum component without a problem", () => { //float64 (input) let vector1 = {X: 1, Y: 0.00055, Z: 0.0255}; let _c1:number = Vector.NewVector(vector1); let result:number = Vector.MaxComponent_mem(_c1); expect(result).toEqual(1); }); it("Should calculate power without a problem", () => { let factor:number = 2; //float64 (input) let vector = {X: 1, Y: 0.00055, Z: 0.0255}; let color_pow = { X: Math.pow(vector.X, factor), Y: Math.pow(vector.Y, factor), Z: Math.pow(vector.Z, factor) }; let _c1:number = Vector.NewVector(vector); let result:number = Vector.Pow_mem(_c1, factor); expect(Vector.XYZ(result)).toEqual(color_pow); }); it("Should check isEqual without a problem", () => { //float64 (input) let vector1 = {X: 0.256, Y: 0, Z: 1}; let vector2 = {X: 0.256, Y: 0, Z: 1}; let color3 = {X: 0.254, Y: 1, Z: 0.0255}; let _c1:number = Vector.NewVector(vector1); let _c2:number = Vector.NewVector(vector2); let _c3:number = Vector.NewVector(color3); let result1:boolean = Vector.isEqual(_c1, _c2); let result2:boolean = Vector.isEqual(_c2, _c1); let result3:boolean = Vector.isEqual(_c1, _c3); let result4:boolean = Vector.isEqual(_c2, _c3); expect(result1).toBeTruthy(); expect(result2).toBeTruthy(); expect(result3).not.toBeTruthy(); expect(result4).not.toBeTruthy(); }); it("Should set value without a problem", () => { //float64 (input) let a3 = {X: 0, Y: 0, Z: 1}; let _c:number = Vector.NewVector(); let result:number = Vector.Set(_c, a3.X, a3.Y, a3.Z); expect(Vector.XYZ(result)).toEqual(a3); }); it("Should clone without a problem", () => { //float64 (input) let a3 = {X: 0, Y: 0, Z: 1}; let _c:number = Vector.NewVector(a3); let result:number = Vector.Clone(_c); expect(Vector.XYZ(result)).toEqual(a3); }); it("Should create random vector without a problem", () => { let vector1:number = Vector.RandomUnitVector(); let vector2:number = Vector.RandomUnitVector(); expect(vector1).not.toBeNull(); expect(vector2).not.toBeNull(); expect(Vector.XYZ(vector1)).not.toBeNull(); expect(Vector.XYZ(vector2)).not.toBeNull(); expect(Vector.XYZ(vector1)).not.toEqual(Vector.XYZ(vector2)); }); }); describe("matrix definition >> ", () => { it("matrix should have defined", () => { expect(Matrix).toBeDefined(); }); it("matrix should have identity method", () => { expect(Matrix.Identity).toBeDefined(); }); it("matrix should have NewMatrix method", () => { expect(Matrix.NewMatrix).toBeDefined(); }); it("matrix should have translateUnitMatrix method", () => { expect(Matrix.TranslateUnitMatrix).toBeDefined(); }); it("matrix should have scaleUnitMatrix method", () => { expect(Matrix.ScaleUnitMatrix).toBeDefined(); }); it("matrix should have rotateUnitMatrix method", () => { expect(Matrix.RotateUnitMatrix).toBeDefined(); }); it("matrix should have frustumUnitMatrix method", () => { expect(Matrix.FrustumUnitMatrix).toBeDefined(); }); it("matrix should have orthographicUnitMatrix method", () => { expect(Matrix.OrthographicUnitMatrix).toBeDefined(); }); it("matrix should have perspectiveUnitMatrix method", () => { expect(Matrix.PerspectiveUnitMatrix).toBeDefined(); }); it("matrix should have LookAtMatrix method", () => { expect(Matrix.LookAtMatrix).toBeDefined(); }); it("matrix should have Translate method", () => { expect(Matrix.Translate).toBeDefined(); }); it("matrix should have Scale method", () => { expect(Matrix.Scale).toBeDefined(); }); it("matrix should have Rotate method", () => { expect(Matrix.Rotate).toBeDefined(); }); it("matrix should have Frustum method", () => { expect(Matrix.Frustum).toBeDefined(); }); it("matrix should have Orthographic method", () => { expect(Matrix.Orthographic).toBeDefined(); }); it("matrix should have Perspective method", () => { expect(Matrix.Perspective).toBeDefined(); }); it("matrix should have Mul method", () => { expect(Matrix.Mul).toBeDefined(); }); it("matrix should have MulPosition method", () => { expect(Matrix.MulPosition).toBeDefined(); }); it("matrix should have MulDirection method", () => { expect(Matrix.MulDirection).toBeDefined(); }); it("matrix should have Mul method", () => { expect(Matrix.Mul).toBeDefined(); }); it("matrix should have MulRay method", () => { expect(Matrix.MulRay).toBeDefined(); }); it("matrix should have MulBox method", () => { expect(Matrix.MulBox).toBeDefined(); }); it("matrix should have transpose method", () => { expect(Matrix.Transpose).toBeDefined(); }); it("matrix should have Determinant method", () => { expect(Matrix.Determinant).toBeDefined(); }); it("matrix should have inverse method", () => { expect(Matrix.Inverse).toBeDefined(); }); }); describe("matrix instance >> ", () => { it("Should create without a problem", () => { let matrix = new Matrix(0); expect(matrix).toBeTruthy(); }); it("Should translateUnitMatrix without a problem", () => { //float64 (input) let a1 = {X: 1, Y: 0, Z: 0}; let vec:number = Vector.NewVector(a1); let expectedMat:number = Matrix.NewMatrix( 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); let transUnitMatrix:number = Matrix.TranslateUnitMatrix(vec); expect(Matrix.IsEqual(transUnitMatrix, expectedMat)).toBeTruthy(); expect(Matrix.IsIdentity(transUnitMatrix)).not.toBeTruthy(); }); it("Should scaleUnitMatrix without a problem", () => { //float64 (input) let a1 = {X: 1, Y: 0, Z: 0}; let vec:number = Vector.NewVector(a1); let expectedMat:number = Matrix.NewMatrix( 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ); let scaleUnitMatrix:number = Matrix.ScaleUnitMatrix(vec); expect(Matrix.IsEqual(scaleUnitMatrix, expectedMat)).toBeTruthy(); expect(Matrix.IsIdentity(scaleUnitMatrix)).not.toBeTruthy(); }); it("Should rotateUnitMatrix without a problem", () => { //float64 (input) let a1 = {X: 1, Y: 0, Z: 0}; let vec:number = Vector.NewVector(a1); let expectedMat:number = Matrix.NewMatrix( 1, 0, 0, 0, 0, -0.4480736161291702, 0.8939966636005579, 0, 0, -0.8939966636005579, -0.4480736161291702, 0, 0, 0, 0, 1 ); let rotateUnitMatrix:number = Matrix.RotateUnitMatrix(vec, 90); // Terminal.write(matrix.DATA(rotateUnitMatrix)); expect(Matrix.IsEqual(rotateUnitMatrix, expectedMat)).toBeTruthy(); expect(Matrix.IsIdentity(rotateUnitMatrix)).not.toBeTruthy(); }); }); });
the_stack
import { assert, expect } from 'chai'; import { ParticipantStack } from '../src'; import { spawnSync } from 'child_process' import { tryTimes } from '../src/index' const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); export const shouldBehaveLikeAWorkgroupOrganization = (getApp: () => ParticipantStack) => () => { describe(`organization details`, () => { let org; before(async () => { org = await getApp().getOrganization(); assert(org, 'org should not be null'); }); describe('contracts', () => { let erc1820Registry; let orgRegistry; let shield; let verifier; let workflowIdentifier; before(async () => { erc1820Registry = await getApp().requireWorkgroupContract('erc1820-registry'); orgRegistry = await getApp().requireWorkgroupContract('organization-registry'); shield = getApp().getWorkgroupContract('shield'); verifier = getApp().getWorkgroupContract('verifier'); workflowIdentifier = getApp().getWorkflowIdentifier(); }); it('should have a local reference to the on-chain ERC1820 registry contract', async () => { assert(erc1820Registry, 'ERC1820 registry contract should not be null'); assert(erc1820Registry.address, 'should have a reference to the on-chain ERC1820 registry contract address'); }); it('should have a local reference to the on-chain organization registry contract', async () => { assert(orgRegistry, 'organization registry contract should not be null'); assert(orgRegistry.address, 'should have a reference to the on-chain organization registry contract address'); }); it('should have a local reference to the on-chain workgroup shield contract', async () => { assert(shield, 'workgroup shield contract should not be null'); assert(shield.address, 'should have a reference to the on-chain workgroup shield contract address'); }); it('should have a local reference to the on-chain workflow circuit verifier contract', async () => { assert(verifier, 'workflow circuit verifier contract should not be null'); assert(verifier.address, 'should have a reference to the on-chain workflow circuit verifier contract address'); }); it('should have a local reference to the workflow circuit identifier', async () => { assert(workflowIdentifier, 'workflow circuit identifier should not be null'); }); }); describe('messaging', () => { let natsService; let natsSubscriptions; before(async () => { natsService = getApp().getMessagingService(); natsSubscriptions = getApp().getProtocolSubscriptions(); }); it('should have an established NATS connection', async () => { assert(natsService, 'should not be null'); assert(natsService.isConnected() === true, 'should have established a connection'); }); it('should have an established a subscription on the baseline.proxy subject', async () => { assert(natsSubscriptions, 'should not be null'); assert(natsSubscriptions.length === 1, 'should have established a subscription'); }); }); describe('registration', () => { let address; before(async () => { const keys = await getApp().fetchKeys(); address = keys && keys.length >= 3 ? keys[2].address : null; assert(address, 'default secp256k1 keypair should not be null'); }); it('should register the organization in the local registry', async () => { assert(org.id, 'org id should not be null'); }); it('should register the organization in the on-chain registry using its default secp256k1 address', async () => { const org = await getApp().requireOrganization(address); assert(org, 'org should be present in on-chain registry'); }); it('should associate the organization with the local workgroup', async () => { const orgs = await getApp().fetchWorkgroupOrganizations(); assert(orgs.length === 1, 'workgroup should have associated org'); }); }); describe('vault', () => { let address; let keys; before(async () => { keys = await getApp().fetchKeys(); address = keys && keys.length >= 3 ? keys[2].address : null; }); it('should create a default vault for the organization', async () => { const vaults = await getApp().fetchVaults(); assert(vaults.length === 1, 'default vault not created'); }); it('should create a set of keypairs for the organization', async () => { assert(keys, 'default keypairs should not be null'); assert(keys.length >= 4, 'minimum default keypairs not created'); // assert(keys.length === 4, 'default keypairs not created'); }); it('should create a babyJubJub keypair for the organization', async () => { assert(keys[1].spec === 'babyJubJub', 'default babyJubJub keypair not created'); }); it('should create a secp256k1 keypair for the organization', async () => { assert(keys[2].spec === 'secp256k1', 'default secp256k1 keypair not created'); }); it('should resolve the created secp256k1 keypair as the organization address', async () => { const addr = await getApp().resolveOrganizationAddress(); assert(keys[2].address === addr, 'default secp256k1 keypair should resolve as the organization address'); }); it('should create a BIP39 HD wallet for the organization', async () => { assert(keys[3].spec === 'BIP39', 'default BIP39 HD wallet not created'); }); }); describe('workflow privacy', () => { let circuit; describe('zkSNARK circuits', () => { describe('synchronization', () => { before(async () => { // We need to Wait for the Sync await tryTimes(async () => { if (getApp().getBaselineCircuit() === undefined) { throw new Error(); }else{ return true; } }, 100, 5000); circuit = getApp().getBaselineCircuit(); assert(circuit, 'setup artifacts should not be null'); }); it('should have a copy of the unique identifier for the circuit', async () => { assert(circuit.id, 'identifier should not be null'); }); it('should have a copy of the proving key id', async () => { assert(circuit.provingKeyId, 'proving key id should not be null'); }); it('should have a copy of the verifying key id', async () => { assert(circuit.verifyingKeyId, 'verifying key id should not be null'); }); it('should have a copy of the raw verifier source code', async () => { assert(circuit.verifierContract, 'verifier contract should not be null'); assert(circuit.verifierContract.source, 'verifier source should not be null'); }); it('should store a reference to the workflow circuit identifier', async () => { assert(getApp().getWorkflowIdentifier() === circuit.id, 'workflow circuit identifier should have a reference'); }); it('should have a copy of the compiled circuit r1cs', async () => { assert(circuit.artifacts, 'circuit artifacts should not be null'); assert(circuit.artifacts.binary, 'circuit r1cs artifact should not be null'); }); it('should have a copy of the keypair for proving and verification', async () => { assert(circuit.artifacts, 'circuit artifacts should not be null'); assert(circuit.artifacts.proving_key, 'proving key artifact should not be null'); assert(circuit.artifacts.verifying_key, 'verifying key artifact should not be null'); }); // it('should have a copy of the ABI of the compiled circuit', async () => { // assert(circuit.abi, 'artifacts should contain the abi'); // }); describe('on-chain artifacts', () => { let shield; let verifier; before(async () => { shield = getApp().getWorkgroupContract('shield'); verifier = getApp().getWorkgroupContract('verifier'); }); it('should reference the deposited workgroup shield contract on-chain', async () => { assert(shield, 'workgroup shield contract should not be null'); assert(shield.address, 'workgroup shield contract should have been deployed'); }); it('should reference the deposited circuit verifier on-chain', async () => { assert(verifier, 'workflow circuit verifier contract should not be null'); assert(verifier.address, 'workflow circuit verifier contract should have been deployed'); }); }); }); }); }); }); }; export const shouldBehaveLikeAWorkgroupCounterpartyOrganization = (getApp: () => ParticipantStack) => () => { describe('counterparties', async () => { let counterparties; let authorizedBearerTokens; let authorizedBearerToken; let messagingEndpoint; before(async () => { counterparties = getApp().getWorkgroupCounterparties(); authorizedBearerTokens = getApp().getNatsBearerTokens(); authorizedBearerToken = await getApp().resolveNatsBearerToken(counterparties[0]); messagingEndpoint = await getApp().resolveMessagingEndpoint(counterparties[0]); await getApp().requireOrganization(await getApp().resolveOrganizationAddress()); }); it('should have a local reference to the workgroup counterparties', async () => { assert(counterparties, 'workgroup counterparties should not be null'); assert(counterparties.length === 1, 'workgroup counterparties should not be empty'); assert(counterparties[0] !== await getApp().resolveOrganizationAddress(), 'workgroup counterparties should not contain local org address'); }); it('should have a local reference to peer-authorized messaging endpoints and associated bearer tokens', async () => { assert(authorizedBearerTokens, 'authorized bearer tokens should not be null'); assert(Object.keys(authorizedBearerTokens).length === 1, 'a local reference should exist for a single authorized bearer token'); }); it('should have a local reference to the peer-authorized messaging endpoint', async () => { assert(messagingEndpoint, 'peer-authorized messaging endpoint should not be null'); }); it('should have a local reference to the peer-authorized bearer token', async () => { assert(authorizedBearerToken, 'peer-authorized bearer token should not be null'); }); }); }; export const shouldCreateBaselineStack = (getApp: () => ParticipantStack) => () => { var org before(async () => { org = await getApp().getOrganization(); await sleep(10000) }); it('should have the baseline stack running ', async () => { var stackStatusCmd = spawnSync(`docker container inspect -f '{{.State.Status}}' ${org.name.replace(/\s+/g, '')}-api`, [], { stdio: 'pipe', shell: true, encoding: 'utf-8'}); var stackStatus = stackStatusCmd.output.toString() var stackStatust = stackStatus.split(",") expect(stackStatust[1].toString().replace(/\,+/g, '')).to.equal(`running\n`); }) } export const shouldBehaveLikeAnInitialWorkgroupOrganization = (getApp: () => ParticipantStack) => () => { describe('baseline config', () => { let cfg; var org before(async () => { cfg = getApp().getBaselineConfig(); org = await getApp().getOrganization(); await sleep(11000) }); it('should have a non-null config', async () => { assert(cfg, 'config should not be null'); }); it('should indicate that this instance is the workgroup initiator', async () => { assert(cfg.initiator === true, 'config should indicate this instance is the workgroup initiator'); }); }); describe('workflow privacy', () => { let circuit; describe('zkSNARK circuits', () => { describe('provisioning', () => { before(async () => { circuit = await getApp().deployBaselineCircuit(); assert(circuit, 'setup artifacts should not be null'); }); it('should output a unique identifier for the circuit', async () => { assert(circuit.id, 'identifier should not be null'); }); it('should output the proving key id', async () => { assert(circuit.provingKeyId, 'proving key id should not be null'); }); it('should output the verifying key id', async () => { assert(circuit.verifyingKeyId, 'verifying key id should not be null'); }); it('should output the raw verifier source code', async () => { assert(circuit.verifierContract, 'verifier contract should not be null'); assert(circuit.verifierContract.source, 'verifier source should not be null'); }); it('should store a reference to the workflow circuit identifier', async () => { assert(getApp().getWorkflowIdentifier() === circuit.id, 'workflow circuit identifier should have a reference'); }); it('should output the compiled circuit r1cs', async () => { assert(circuit.artifacts, 'circuit artifacts should not be null'); assert(circuit.artifacts.binary, 'circuit r1cs artifact should not be null'); }); it('should output the keypair for proving and verification', async () => { assert(circuit.artifacts, 'circuit artifacts should not be null'); assert(circuit.artifacts.proving_key, 'proving key artifact should not be null'); assert(circuit.artifacts.verifying_key, 'verifying key artifact should not be null'); }); // it('should output the ABI of the compiled circuit', async () => { // assert(circuit.abi, 'artifacts should contain the abi'); // }); describe('on-chain artifacts', () => { let shield; let verifier; before(async () => { shield = getApp().getWorkgroupContract('shield'); verifier = getApp().getWorkgroupContract('verifier'); }); it('should deposit the workgroup shield contract on-chain', async () => { assert(shield, 'workgroup shield contract should not be null'); assert(shield.address, 'workgroup shield contract should have been deployed'); }); it('should deposit the circuit verifier on-chain', async () => { assert(verifier, 'workflow circuit verifier contract should not be null'); assert(verifier.address, 'workflow circuit verifier contract should have been deployed'); }); }); }); }); }); }; export const shouldBehaveLikeAnInvitedWorkgroupOrganization = (getApp: () => ParticipantStack) => () => { describe('baseline config', () => { let cfg; before(async () => { cfg = getApp().getBaselineConfig(); }); it('should have a non-null config', async () => { assert(cfg, 'config should not be null'); }); it('should indicate that this instance is not the workgroup initiator', async () => { assert(cfg.initiator === false, 'config should indicate this instance is not the workgroup initiator'); }); }); describe('workgroup', () => { let workgroup; let workgroupToken; before(async () => { workgroup = getApp().getWorkgroup(); workgroupToken = getApp().getWorkgroupToken(); }); it('should persist the workgroup in the local registry', async () => { assert(workgroup, 'workgroup should not be null'); assert(workgroup.id, 'workgroup id should not be null'); }); it('should authorize a bearer token for the workgroup', async () => { assert(workgroupToken, 'workgroup token should not be null'); }); }); };
the_stack
import { Col, Input, PageHeader, Row, Select, Tooltip } from 'antd'; import deepEqual from 'deep-equal'; import parse from 'html-react-parser'; import { cloneDeep } from 'lodash'; import React, { useCallback, useMemo } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import useLocalStorage from '~/hooks/useLocalStorage'; import usePostMessage from '~/hooks/usePostMessage'; import { Dispatch, RootState } from '~/redux/store'; import { AppDataLayoutItemTypes, ArgumentsNumber, ArgumentsString } from '~/types/appData'; import { EventsTypeItem, ExposeFunctions, Modules } from '~/types/modules'; import ArrayArguments from '../ArgumentsSetting/ArrayArguments'; import BooleanArguments from '../ArgumentsSetting/BooleanArguments'; import HtmlSuffix from '../ArgumentsSetting/HtmlSuffix'; import MixedArguments from '../ArgumentsSetting/MixedArguments'; import ObjectArguments from '../ArgumentsSetting/ObjectArguments'; import s from './Presetting.module.less'; interface Props {} interface OnChangeProps { /* 数据索引值 */ index: number; /* 参数索引 */ argIndex: number; /* 参数索引对应的参数值 */ value: any; } /** * 所有预设事件将在挂载时运行, * 其根本还是EventEmitter对事件流控制, * 作为预设模块只操作组件自己的内置方法 * */ const Presetting: React.FC<Props> = () => { // 获取当前激活组件信息 const activationItem = useSelector( (state: RootState) => state.activationItem ); const { events, type, moduleId } = activationItem; // 获取当前appdata数据准备数据更新方法 const appData = useSelector((state: RootState) => state.appData); const [, setLocalStorage] = useLocalStorage('appData', null); const dispatch = useDispatch<Dispatch>(); // 获取runningtime的属性集合 const runningTimes = useSelector((state: RootState) => state.runningTimes); // 数据更新 const updateActDataToAll = useCallback( (actData: AppDataLayoutItemTypes) => { dispatch.activationItem.updateActivationItem(actData); const operateData = [...appData].map((item) => { if (item.moduleId === actData.moduleId) { return actData; } return item; }); dispatch.appData.updateAppData(operateData); setLocalStorage(operateData); }, [appData, dispatch.activationItem, dispatch.appData, setLocalStorage] ); // 获取当前模块 const module: Modules<any> = useMemo( () => (!!type ? require(`~/modules/${type}`).default : {}), [type] ); // 获取当前运行时模块已配置的内置方法 const setFunctions = useMemo(() => events?.mount || [], [events?.mount]); // 获取当前模块类导出的内置方法, const exposeFunctions: ExposeFunctions[] = useMemo( () => module.exposeFunctions || [], [module.exposeFunctions] ); // 执行事件 const sendMessage = usePostMessage(() => {}); const onPlay = useCallback( (data: EventsTypeItem[]) => { const win = ( document.getElementById('wrapiframe') as HTMLIFrameElement ).contentWindow; sendMessage( { tag: 'playEventEmit', value: { event: { name: 'mount', description: '初始化' }, args: data, }, }, win ); }, [sendMessage] ); /** * 处理业务逻辑 * 合并三块数据、组件内部,运行时、以及编辑后的数据 * 组件内部数据是最全面的预设编辑数据,所以以他为预设的配置显示基准 * 而最完整的预设编辑数据的初始值包含内组件部默认数据,运行时mount事件中包含的数据,而运行时数据需要剔除非组件内部属性数据, * 编辑完成后再剔除未配置的数据把配置好的数据返回到运行时数据中 */ // step1、设置预设编辑数据 // 运行时mount数据剔除非当前模块数据 const getData = useCallback(() => { // 深拷一份组件内部可预设数据 和组件运行时数据 const copyExposeFunctions = cloneDeep(exposeFunctions).filter( (item) => item.presettable !== false ); const copySetFunctions = cloneDeep(setFunctions); const result: ExposeFunctions[] = copyExposeFunctions.map((staticItem) => { // copyExposeFunctions是用于即将预设的静态方法 // 断言运行时方法是否有维护当前方法关联的数据,这里使用倒序从后至依次断言,如果有数据,将最后一条数据收集给预设数据 copySetFunctions.reverse().some((setItem) => { const [, funName] = setItem.name.split('/'); if ( funName === staticItem.name && Array.isArray(setItem.arguments) ) { staticItem.arguments = setItem.arguments; return true; } return false; }); return staticItem; }) || []; return result; }, [exposeFunctions, setFunctions]); // step2、获取预设数据 保存预设面板数据,用于页面render const runningData = getData(); // step3、数据变更 const onChange = useCallback( ({ index, argIndex, value }: OnChangeProps) => { let copyRunningData = [...runningData]; // 当前编辑数据赋值 if (copyRunningData[index].arguments) { copyRunningData[index].arguments![argIndex] = value; } // 从编辑器预设面板获取当前已设置的值copyRunningData; // 将预设值回填给运行时运行时mount数据; // step1、判断预设数据值有没有被编辑过,抽取被编辑过的数据 // (判断依据:预设数据和组件静态数据是否保持一至); const readyToSetting: EventsTypeItem[] = []; copyRunningData.forEach((item, index) => { if ( !deepEqual( item.arguments, exposeFunctions[index].arguments ) || !item.arguments?.[index]?.data ) { readyToSetting.push({ name: `${moduleId}/${item.name}`, arguments: item.arguments || [], }); } }); // step2、将抽取的数据更新到运行时mount数据; // 深拷一份当前组件运行时数据 activationItem const copyModuleData = cloneDeep(activationItem); // 没有初始化事件时 if (!copyModuleData.events?.mount) { // 还未定义mount事件 if (!copyModuleData.events) { copyModuleData.events = {}; } // 给运行时追加准备数据 copyModuleData.events.mount = readyToSetting; } else { // 有初始化事件 // 倒序是为了匹配最末一条 const mount = [...copyModuleData.events.mount].reverse(); // 遍历ready数据 readyToSetting.forEach((readyItem) => { // 是否数据覆盖 let isCove: boolean = false; mount.some((mountItem) => { if (mountItem.name === readyItem.name) { mountItem.arguments = readyItem.arguments; // 覆盖旧值 isCove = true; return true; } return false; }); // 如果没有覆盖旧值则追加到mount数据上 if (!isCove) { mount.unshift(readyItem); } }); copyModuleData.events.mount = mount.reverse(); } // 更新且播放所有内部事件 updateActDataToAll(copyModuleData); onPlay(copyModuleData.events.mount); }, [ activationItem, exposeFunctions, moduleId, onPlay, runningData, updateActDataToAll, ] ); if (!moduleId) { return null; } const renderNumberString = ( index: number, argItem: ArgumentsString | ArgumentsNumber, argIndex: number, ) => { // 下拉选择形式 if (argItem?.select) { const { select } = argItem; const keys = Object.keys(select); return <Select onChange={ (e) => onChange({ index, // 数据索引值 argIndex, // 参数索引 value: { // 参数索引对应的参数值 ...argItem, data: e, }, }) } value={argItem.data} className={s.select} placeholder={`请输入值,${argItem.describe || ''}`} > { keys.map((value) => <Select.Option key={value} value={value}>{ select[value] }</Select.Option>) } </Select> } // 输入框形式 return <Input onChange={(e) => onChange({ index, // 数据索引值 argIndex, // 参数索引 value: { // 参数索引对应的参数值 ...argItem, data: e.target.value, }, }) } placeholder={`请输入值,${ argItem.describe || '' }`} value={argItem.data} type="text" suffix={ !!argItem.html ? ( <HtmlSuffix /> ) : null } /> }; return ( <div> {runningData.map((item, index) => !!item.arguments?.length && item.presettable !== false ? ( <div key={index} className={s.item}> <PageHeader title={item.description} /> {item.arguments?.map((argItem, argIndex) => ( <Row className={s.row} key={argIndex} gutter={10}> <Col span={5} className={s.label}> <Tooltip placement="topRight" title={parse(argItem.describe || '')} > {argItem.name} </Tooltip> </Col> <Col span={19}> {argItem.type === 'number' || argItem.type === 'string' ? renderNumberString(index, argItem, argIndex) : null} {argItem.type === 'runningTime' ? ( <Select className={s.select} placeholder="请选择" showSearch value={argItem.data} optionFilterProp="children" filterOption={ (input, option) => { const childrens = (Array.isArray(option?.children)?option?.children.join('') : option?.children).toLowerCase(); if (childrens.indexOf(input) !== -1) { return true; } return false; } // option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 } onChange={(e) => onChange({ index, // 数据索引值 argIndex, // 参数索引 value: { // 参数索引对应的参数值 ...argItem, data: e, }, }) } > {Object.keys(runningTimes)?.map( (item, index) => ( <Select.Option key={index} value={item}> {item} </Select.Option> ) )} </Select> ) : null} {argItem.type === 'array' ? ( <ArrayArguments typeArguments={argItem} flexible htmlInput={!!argItem.html} onChange={(value) => onChange({ index, argIndex, value, }) } /> ) : null} {argItem.type === 'boolean' ? ( <BooleanArguments typeArguments={argItem} flexible={false} onChange={(value) => onChange({ index, argIndex, value, }) } /> ) : null} {argItem.type === 'object' ? ( <ObjectArguments describe={argItem.describe} htmlInput={!!argItem.html} onChange={(value) => onChange({ index, argIndex, value, }) } typeArguments={argItem} flexible={false} /> ) : null} {argItem.type === 'mixed' ? ( <MixedArguments onChange={(value) => onChange({ index, argIndex, value, }) } typeArguments={argItem} flexible={false} /> ) : null} </Col> </Row> ))} </div> ) : null )} </div> ); }; export default Presetting;
the_stack
'use strict'; var assert = require('proclaim'); var Facade = require('segmentio-facade'); var SourceMiddlewareChain = require('../build/middleware') .SourceMiddlewareChain; var IntegrationMiddlewareChain = require('../build/middleware') .IntegrationMiddlewareChain; var middlewareChain = require('../build/middleware').middlewareChain; describe('middlewareChain', function() { var chain; beforeEach(function() { middlewareChain((chain = {})); }); describe('#getMiddlewares', function() { it('should start empty', function() { assert.deepEqual(chain.getMiddlewares(), []); }); it('should get existing middlewares', function() { chain.add(function() { return 'Valid! :)'; }); var middlewares = chain.getMiddlewares(); assert(middlewares.length === 1, 'wrong middleware count'); assert(middlewares[0]() === 'Valid! :)', 'wrong middleware return'); }); }); describe('#add', function() { it('should not allow non-functions to be added', function() { try { chain.add({ 'this is': 'not a function' }); // This assert should not run. assert(false, 'error was not thrown!'); } catch (e) { assert( e.message === 'attempted to add non-function middleware', 'wrong error return' ); } }); it('should not allow the same middleware instance to be added multiple times', function() { var middleware = function() {}; chain.add(middleware); assert(chain.getMiddlewares().length === 1, 'wrong middleware count'); try { chain.add(middleware); // This assert should not run. assert(false, 'error was not thrown!'); } catch (e) { assert( e.message === 'middleware is already registered', 'wrong error return' ); } }); it('should be able to add multiple different middlewares', function() { // Same literal values, but different instances. chain.add(function() {}); chain.add(function() {}); chain.add(function() {}); assert(chain.getMiddlewares().length === 3, 'wrong middleware count'); }); }); }); describe('IntegrationMiddlewareChain', function() { var chain; beforeEach(function() { chain = new IntegrationMiddlewareChain(); }); describe('#applyMiddlewares', function() { it('should require a function callback', function() { try { chain.applyMiddlewares({}); } catch (e) { assert( e.message === 'applyMiddlewares requires a function callback', 'wrong error return' ); } try { chain.applyMiddlewares({}, 'Test', ['this is not a function =(']); } catch (e) { assert( e.message === 'applyMiddlewares requires a function callback', 'wrong error return' ); } }); }); it('should require a payload object', function() { try { chain.applyMiddlewares(7, 'Test', function() { // This assert should not run. assert(false, 'error was not thrown!'); }); } catch (e) { assert( e.message === 'applyMiddlewares requires a payload object', 'wrong error return' ); } chain.applyMiddlewares(null, 'Test', function(payload) { // This assert SHOULD run. assert(payload === null, 'payload should have been null'); }); }); it('should apply no middleware', function() { var payload = new Facade({ testVal: 'success' }); chain.applyMiddlewares(payload, 'Test', function(payload) { assert( payload.obj.testVal === 'success', 'payload value incorrectly set' ); }); }); it('should apply a middleware', function() { chain.add(function(payload, integration, next) { payload.obj.testVal = 'success'; next(payload); }); chain.applyMiddlewares({}, 'Test', function(payload) { assert( payload.obj.testVal === 'success', 'payload value incorrectly set' ); }); }); it('should apply multiple middlewares in order', function() { chain.add(function(payload, integration, next) { payload.obj.test.push(1); next(payload); }); chain.add(function(payload, integration, next) { payload.obj.test.push(2); next(payload); }); chain.add(function(payload, integration, next) { payload.obj.test.push(3); next(payload); }); chain.applyMiddlewares({ test: [] }, 'Test', function(payload) { assert.deepEqual(payload.obj.test, [1, 2, 3]); }); }); it('should stop running middlewares if payload becomes null', function() { chain.add(function(payload, integration, next) { payload.obj.test.push(1); next(payload); }); chain.add(function(payload, integration, next) { next(null); }); chain.add(function() { throw new Error('Middleware chain was not interrupted by null!'); }); chain.applyMiddlewares({ test: [] }, 'Test', function(payload) { assert(payload === null, 'payload was not nullified'); }); }); it('should convert non-facade objects to facades', function() { chain.add(function(payload, integration, next) { next(payload); }); var payload = {}; assert(!(payload instanceof Facade), 'Payload should not be a facade yet.'); chain.applyMiddlewares(payload, 'Test', function(payload) { assert(payload instanceof Facade, 'Payload should be a facade.'); }); }); it('should be able to handle facade objects as input', function() { chain.add(function(payload, integration, next) { next(payload); }); var payload = new Facade({}); assert(payload instanceof Facade, 'Payload should be a facade.'); chain.applyMiddlewares(payload, 'Test', function(payload) { assert(payload instanceof Facade, 'Payload should still be a facade.'); }); }); }); describe('SourceMiddlewareChain', function() { var chain; beforeEach(function() { chain = new SourceMiddlewareChain(); }); describe('#applyMiddlewares', function() { it('should require a function callback', function() { try { chain.applyMiddlewares({}); } catch (e) { assert( e.message === 'applyMiddlewares requires a function callback', 'wrong error return' ); } try { chain.applyMiddlewares({}, 'Test', ['this is not a function =(']); } catch (e) { assert( e.message === 'applyMiddlewares requires a function callback', 'wrong error return' ); } }); }); it('should require a payload object', function() { try { chain.applyMiddlewares(7, 'Test', function() { // This assert should not run. assert(false, 'error was not thrown!'); }); } catch (e) { assert( e.message === 'applyMiddlewares requires a payload object', 'wrong error return' ); } chain.applyMiddlewares(null, 'Test', function(payload) { // This assert SHOULD run. assert(payload === null, 'payload should have been null'); }); }); it('should apply no middleware', function() { var payload = new Facade({ testVal: 'success' }); chain.applyMiddlewares(payload, 'Test', function(payload) { assert( payload.obj.testVal === 'success', 'payload value incorrectly set' ); }); }); it('should apply a middleware', function() { chain.add(function(chain) { chain.payload.obj.testVal = 'success'; chain.next(chain.payload); }); chain.applyMiddlewares({}, 'Test', function(payload) { assert( payload.obj.testVal === 'success', 'payload value incorrectly set' ); }); }); it('should apply multiple middlewares in order', function() { chain.add(function(chain) { chain.payload.obj.test.push(1); chain.next(chain.payload); }); chain.add(function(chain) { chain.payload.obj.test.push(2); chain.next(chain.payload); }); chain.add(function(chain) { chain.payload.obj.test.push(3); chain.next(chain.payload); }); chain.applyMiddlewares({ test: [] }, 'Test', function(payload) { assert.deepEqual(payload.obj.test, [1, 2, 3]); }); }); it('should stop running middlewares if payload becomes null', function() { chain.add(function(chain) { chain.payload.obj.test.push(1); chain.next(chain.payload); }); chain.add(function(chain) { chain.next(null); }); chain.add(function() { throw new Error('Middleware chain was not interrupted by null!'); }); chain.applyMiddlewares({ test: [] }, 'Test', function(payload) { assert(payload === null, 'payload was not nullified'); }); }); it('should convert non-facade objects to facades', function() { chain.add(function(chain) { chain.next(chain.payload); }); var payload = {}; assert(!(payload instanceof Facade), 'Payload should not be a facade yet.'); chain.applyMiddlewares(payload, 'Test', function(payload) { assert(payload instanceof Facade, 'Payload should be a facade.'); }); }); it('should be able to handle facade objects as input', function() { chain.add(function(chain) { chain.next(chain.payload); }); var payload = new Facade({}); assert(payload instanceof Facade, 'Payload should be a facade.'); chain.applyMiddlewares(payload, 'Test', function(payload) { assert(payload instanceof Facade, 'Payload should still be a facade.'); }); }); it('should be able to add and apply middleware interchangably', function() { chain.add(function(chain) { chain.payload.obj.test.push(1); chain.next(chain.payload); }); chain.applyMiddlewares({ test: [] }, 'Test', function(payload) { assert.deepEqual(payload.obj.test, [1]); }); chain.add(function(chain) { chain.payload.obj.test.push(2); chain.next(chain.payload); }); chain.applyMiddlewares({ test: [] }, 'Test', function(payload) { assert.deepEqual(payload.obj.test, [1, 2]); }); chain.add(function(chain) { chain.payload.obj.test.push(3); chain.next(chain.payload); }); chain.applyMiddlewares({ test: [] }, 'Test', function(payload) { assert.deepEqual(payload.obj.test, [1, 2, 3]); }); chain.add(function(chain) { chain.payload.obj.test.push(4); chain.next(chain.payload); }); chain.applyMiddlewares({ test: [] }, 'Test', function(payload) { assert.deepEqual(payload.obj.test, [1, 2, 3, 4]); }); chain.add(function(chain) { chain.payload.obj.test.push(5); chain.next(chain.payload); }); chain.applyMiddlewares({ test: [] }, 'Test', function(payload) { assert.deepEqual(payload.obj.test, [1, 2, 3, 4, 5]); }); chain.add(function(chain) { chain.payload.obj.test.push(6); chain.next(chain.payload); }); chain.applyMiddlewares({ test: [] }, 'Test', function(payload) { assert.deepEqual(payload.obj.test, [1, 2, 3, 4, 5, 6]); }); }); });
the_stack
/// <reference types="node" /> import * as net from "net"; export type FEED_CONTROL_TYPE = 'LF' | 'GLF' | 'FF' | 'CR' | 'HT' | 'VT'; export type BITMAP_FORMAT_TYPE = 'S8' | 'D8' | 'S24' | 'D24'; export type QRCODE_LEVEL = 'L' | 'M' | 'Q' | 'H'; /** * `B` = Bold * `I` = Italic * `U` = Underline */ export type TXT_STYLE = 'NORMAL' | 'B' | 'I' | 'U' | 'U2' | 'BI' | 'BIU' | 'BIU2' | 'BU' | 'BU2' | 'IU' | 'IU2'; export type MIME_TYPE = 'image/png' | 'image/jpg' | 'image/jpeg' | 'image/gif' | 'image/bmp'; export type BARCODE_TYPE = 'UPC_A' | 'UPC_E' | 'EAN13' | 'EAN8' | 'CODE39' | 'ITF' | 'NW7' | 'CODE93' | 'CODE128'; /** * `LT` = Left * `CT` = Center * `RT` = Right */ export type TXT_ALIGN = 'LT' | 'CT' | 'RT'; export namespace command { const LF: '\x0a'; const FS: '\x1c'; const FF: '\x0c'; const GS: '\x1d'; const DLE: '\x10'; const EOT: '\x04'; const NUL: '\x00'; const ESC: '\x1b'; const EOL: '\n'; const FEED_CONTROL_SEQUENCES: { CTL_LF: '\x0a'; // Print and line feed CTL_GLF: '\x4a\x00'; // Print and feed paper (without spaces between lines) CTL_FF: '\x0c'; // Form feed CTL_CR: '\x0d'; // Carriage return CTL_HT: '\x09'; // Horizontal tab CTL_VT: '\x0b'; // Vertical tab }; const CHARACTER_SPACING: { CS_DEFAULT: '\x1b\x20\x00'; CS_SET: '\x1b\x20'; }; const LINE_SPACING: { LS_DEFAULT: '\x1b\x32'; LS_SET: '\x1b\x33'; }; const HARDWARE: { HW_INIT: '\x1b\x40'; // Clear data in buffer and reset modes HW_SELECT: '\x1b\x3d\x01'; // Printer select HW_RESET: '\x1b\x3f\x0a\x00'; // Reset printer hardware }; const CASH_DRAWER: { CD_KICK_2: '\x1b\x70\x00'; // Sends a pulse to pin 2 [] CD_KICK_5: '\x1b\x70\x01'; // Sends a pulse to pin 5 [] }; const MARGINS: { BOTTOM: '\x1b\x4f'; // Fix bottom size LEFT: '\x1b\x6c'; // Fix left size RIGHT: '\x1b\x51'; // Fix right size }; const PAPER: { PAPER_FULL_CUT: '\x1d\x56\x00'; // Full cut paper PAPER_PART_CUT: '\x1d\x56\x01'; // Partial cut paper PAPER_CUT_A: '\x1d\x56\x41'; // Partial cut paper PAPER_CUT_B: '\x1d\x56\x42'; // Partial cut paper }; const TEXT_FORMAT: { TXT_NORMAL: '\x1b\x21\x00'; // Normal text TXT_2HEIGHT: '\x1b\x21\x10'; // Double height text TXT_2WIDTH: '\x1b\x21\x20'; // Double width text TXT_4SQUARE: '\x1b\x21\x30'; // Double width & height text TXT_CUSTOM_SIZE: (width: any, height: any) => any; TXT_HEIGHT: { 1: '\x00'; 2: '\x01'; 3: '\x02'; 4: '\x03'; 5: '\x04'; 6: '\x05'; 7: '\x06'; 8: '\x07'; }; TXT_WIDTH: { 1: '\x00'; 2: '\x10'; 3: '\x20'; 4: '\x30'; 5: '\x40'; 6: '\x50'; 7: '\x60'; 8: '\x70'; }; TXT_UNDERL_OFF: '\x1b\x2d\x00'; // Underline font OFF TXT_UNDERL_ON: '\x1b\x2d\x01'; // Underline font 1-dot ON TXT_UNDERL2_ON: '\x1b\x2d\x02'; // Underline font 2-dot ON TXT_BOLD_OFF: '\x1b\x45\x00'; // Bold font OFF TXT_BOLD_ON: '\x1b\x45\x01'; // Bold font ON TXT_ITALIC_OFF: '\x1b\x35'; // Italic font ON TXT_ITALIC_ON: '\x1b\x34'; // Italic font ON TXT_FONT_A: '\x1b\x4d\x00'; // Font type A TXT_FONT_B: '\x1b\x4d\x01'; // Font type B TXT_FONT_C: '\x1b\x4d\x02'; // Font type C TXT_ALIGN_LT: '\x1b\x61\x00'; // Left justification TXT_ALIGN_CT: '\x1b\x61\x01'; // Centering TXT_ALIGN_RT: '\x1b\x61\x02'; // Right justification }; const MODEL: { QSPRINTER: { BARCODE_MODE: { ON: '\x1d\x45\x43\x01'; // Barcode mode on OFF: '\x1d\x45\x43\x00'; // Barcode mode off }; BARCODE_HEIGHT_DEFAULT: '\x1d\x68\xA2'; // Barcode height default=162 CODE2D_FORMAT: { PIXEL_SIZE: { CMD: '\x1b\x23\x23\x51\x50\x49\x58'; MIN: 1; MAX: 24; DEFAULT: 12; }; VERSION: { CMD: '\x1d\x28\x6b\x03\x00\x31\x43'; MIN: 1; MAX: 16; DEFAULT: 3; }; LEVEL: { CMD: '\x1d\x28\x6b\x03\x00\x31\x45'; OPTIONS: { L: 48; M: 49; Q: 50; H: 51; }; }; LEN_OFFSET: 3; SAVEBUF: { // Format= CMD_P1{LEN_2BYTE}CMD_P2{DATA} // DATA Max Length= 256*256 - 3 (65533) CMD_P1: '\x1d\x28\x6b'; CMD_P2: '\x31\x50\x30'; }; PRINTBUF: { // Format= CMD_P1{LEN_2BYTE}CMD_P2 CMD_P1: '\x1d\x28\x6b'; CMD_P2: '\x31\x51\x30'; }; }; }; }; const BARCODE_FORMAT: { BARCODE_TXT_OFF: '\x1d\x48\x00'; // HRI barcode chars OFF BARCODE_TXT_ABV: '\x1d\x48\x01'; // HRI barcode chars above BARCODE_TXT_BLW: '\x1d\x48\x02'; // HRI barcode chars below BARCODE_TXT_BTH: '\x1d\x48\x03'; // HRI barcode chars both above and below BARCODE_FONT_A: '\x1d\x66\x00'; // Font type A for HRI barcode chars BARCODE_FONT_B: '\x1d\x66\x01'; // Font type B for HRI barcode chars BARCODE_HEIGHT: (height: any) => any; // Barcode Height [1-255] // Barcode Width [2-6] BARCODE_WIDTH: { 1: '\x1d\x77\x02'; 2: '\x1d\x77\x03'; 3: '\x1d\x77\x04'; 4: '\x1d\x77\x05'; 5: '\x1d\x77\x06'; }; BARCODE_HEIGHT_DEFAULT: '\x1d\x68\x64'; // Barcode height default=100 BARCODE_WIDTH_DEFAULT: '\x1d\x77\x01'; // Barcode width default=1 BARCODE_UPC_A: '\x1d\x6b\x00'; // Barcode type UPC-A BARCODE_UPC_E: '\x1d\x6b\x01'; // Barcode type UPC-E BARCODE_EAN13: '\x1d\x6b\x02'; // Barcode type EAN13 BARCODE_EAN8: '\x1d\x6b\x03'; // Barcode type EAN8 BARCODE_CODE39: '\x1d\x6b\x04'; // Barcode type CODE39 BARCODE_ITF: '\x1d\x6b\x05'; // Barcode type ITF BARCODE_NW7: '\x1d\x6b\x06'; // Barcode type NW7 BARCODE_CODE93: '\x1d\x6b\x48'; // Barcode type CODE93 BARCODE_CODE128: '\x1d\x6b\x49'; // Barcode type CODE128 }; const CODE2D_FORMAT: { TYPE_PDF417: any; TYPE_DATAMATRIX: any; TYPE_QR: any; CODE2D: any; QR_LEVEL_L: 'L'; // correct level 7% QR_LEVEL_M: 'M'; // correct level 15% QR_LEVEL_Q: 'Q'; // correct level 25% QR_LEVEL_H: 'H'; // correct level 30% }; const IMAGE_FORMAT: { S_RASTER_N: '\x1d\x76\x30\x00'; // Set raster image normal size S_RASTER_2W: '\x1d\x76\x30\x01'; // Set raster image double width S_RASTER_2H: '\x1d\x76\x30\x02'; // Set raster image double height S_RASTER_Q: '\x1d\x76\x30\x03'; // Set raster image quadruple }; const BITMAP_FORMAT: { BITMAP_S8: '\x1b\x2a\x00'; BITMAP_D8: '\x1b\x2a\x01'; BITMAP_S24: '\x1b\x2a\x20'; BITMAP_D24: '\x1b\x2a\x21'; }; const GSV0_FORMAT: { GSV0_NORMAL: '\x1d\x76\x30\x00'; GSV0_DW: '\x1d\x76\x30\x01'; GSV0_DH: '\x1d\x76\x30\x02'; GSV0_DWDH: '\x1d\x76\x30\x03'; }; const BEEP: '\x1b\x42'; // Printer Buzzer pre hex const COLOR: { 0: '\x1b\x72\x00'; // black 1: '\x1b\x72\x01'; // red }; const SCREEN: { BS: '\x08'; // Moves the cursor one character position to the left HT: '\x09'; // Moves the cursor one character position to the right LF: '\x0a'; // Moves the cursor down one line US_LF: '\x1f\x0a'; // Moves the cursor up one line HOM: '\x0b'; // Moves the cursor to the left-most position on the upper line (home position) CR: '\x0d'; // Moves the cursor to the left-most position on the current line US_CR: '\x1f\x0d'; // Moves the cursor to the right-most position on the current line US_B: '\x1f\x42'; // Moves the cursor to the bottom position US_$: '\x1f\x24'; // Moves the cursor to the nth position on the mth line CLR: '\x0c'; // Clears all displayed characters CAN: '\x18'; // Clears the line containing the cursor US_MD1: '\x1f\x01'; // Selects overwrite mode as the screen display mode US_MD2: '\x1f\x02'; // Selects vertical scroll mode as the screen display mode US_MD3: '\x1f\x03'; // Selects horizontal scroll mode as the display screen mode US_C: '\x1f\x43'; // Turn cursor display mode on/off US_E: '\x1f\x45'; // Sets or cancels the blink interval of the display screen US_T: '\x1f\x54'; // Sets the counter time and displays it in the bottom right of the screen US_U: '\x1f\x55'; // Displays the time counter at the right side of the bottom line US_X: '\x1f\x58'; // Sets the brightness of the fluorescent character display tube US_r: '\x1f\x72'; // Selects or cancels reverse display of the characters received after this command US_v: '\x1f\x76'; // Sets the DTR signal in the host interface to the MARK or SPACE state }; } export interface Adapter { open(...args: any[]): Adapter; write(data: Buffer, callback: (error?: any) => void): Adapter; } export class USB implements Adapter { constructor(vid?: string, pid?: string); static findPrinter(): USB[] | false; static getDevice(vid?: string, pid?: string): Promise<USB>; open(callback?: (error: any, device?: USB) => void): USB; close(callback?: (error?: any) => void): USB; write(data: Buffer, callback: (error?: any) => void): USB; } export class Serial implements Adapter { constructor(port: number, options?: { baudRate: number; autoOpen: boolean }); open(callback?: (error?: any) => void): Serial; close(callback?: (error: any, device: Serial) => void, timeout?: number): Serial; write(data: Buffer, callback: (error?: any) => void): Serial; } export class Network implements Adapter { constructor(address: string, port?: number); open(callback?: (error: any, device: Network) => void): Network; close(callback?: (error: any, device: Network) => void): Network; write(data: Buffer, callback: (error?: any) => void): Network; } export class Console implements Adapter { constructor(handler?: (data: any[][]) => void); open(callback?: (error?: any) => void): Console; write(data: Buffer): Console; } export class Image { constructor(pixels: any); static load(url: string, callback?: (result: Image | Error) => void): void; static load(url: string, type: MIME_TYPE, callback?: (result: Image | Error) => void): void; size(): { width: number; height: number; colors: number }; toBitmap( density?: number ): { data: any; density: number; }; toRaster(): { data: number[]; width: number; height: number; }; } export class Printer { constructor(adapter: Adapter, options?: { encoding?: string }); static create(device: Adapter): Promise<Printer>; /** * Set printer model to recognize model-specific commands. * Supported models: [ null, 'qsprinter' ] * * For generic printers, set model to null */ model(_model: string): Printer; marginBottom(size: number): Printer; marginLeft(size: number): Printer; marginRight(size: number): Printer; /** * Print raw */ print(content: any): Printer; /** * Print raw with EOL */ println(content: any): Printer; newLine(): Printer; /** * Print text with EOL */ text(content: string, encoding?: string): Printer; /** * Draw a horizontal line with EOL * * Example: * `-------` 48x */ drawLine(): Printer; /** * Print list of string with EOL */ table(data: string[], encoding?: string): Printer; tableCustom( data: { text: string, width: number, align: 'LEFT' | 'CENTER' | 'RIGHT' } | { text: string, cols: number, align: 'LEFT' | 'CENTER' | 'RIGHT' }, encoding?: string ): Printer; /** * Print text */ pureText(content: string, encoding?: string): Printer; /** * Set default encoding * @default `GB18030` (Chinese) */ encode(encoding: string): Printer; /** * Print blank lines */ feed(n?: number): Printer; /** * Carrier feed and tabs. */ control(ctrl: FEED_CONTROL_TYPE): Printer; align(align: TXT_ALIGN): Printer; /** * @default 'A' */ font(family: 'A' | 'B'): Printer; style(type: TXT_STYLE): Printer; /** * Set text size * * 1 is for regular size, and 2 is twice the standard size. * * @default `1` */ size(width: 1 | 2, height: 1 | 2): Printer; /** * Set character spacing */ spacing(n?: number): Printer; /** * Set line spacing */ lineSpace(n?: number): Printer; hardware(hw: string): Printer; barcode( code: string, type: BARCODE_TYPE, options?: { width: number; height: number; /** * OFF, ABOVE, BELOW, BOTH * * @default BELOW */ position: 'OFF' | 'ABV' | 'BLW' | 'BTH'; font: 'A' | 'B'; includeParity: boolean }, ): Printer; qrcode( code: string, version: number, level: QRCODE_LEVEL, size: number ): Printer; qrimage(content: string, callback?: (error: Error | null, printer?: Printer) => void): Printer; qrimage(content: string, options?: { type: string; mode: string }, callback?: (error: Error | null, printer?: Printer) => void): Printer; image(image: Image, density: BITMAP_FORMAT_TYPE): Printer; raster(image: Image, mode?: string): Printer; /** * Send pulse to kick the cash drawer * * @default 2 */ cashdraw(pin?: number): Printer; /** * Printer Buzzer (Beep sound) */ beep(numberOfBuzzer: number, time: number): Printer; /** * Send data to hardware and flush buffer */ flush(callback?: (error?: any) => void): Printer; /** * Cut paper. * * *** Cut will flush buffer to printer *** * * @param part If true, PAPER_PART_CUT, else PAPER_FULL_CUT * @param feed */ cut(part?: boolean, feed?: number): Printer; close(callback?: (error?: any) => void, options?: any): Printer; /** * Select between two print color modes, if your printer supports it * @param color - 0 for primary color (black) 1 for secondary color (red) */ color(color: 0 | 1): Printer; } export class Screen { constructor(adapter: Adapter, options?: { encoding?: string }); static create(device: Adapter): Promise<Screen>; clear(callback?: (error?: any) => void): Screen; clearLine(callback?: (error?: any) => void): Screen; moveUp(callback?: (error?: any) => void): Screen; moveLeft(callback?: (error?: any) => void): Screen; moveRight(callback?: (error?: any) => void): Screen; moveDown(callback?: (error?: any) => void): Screen; moveHome(callback?: (error?: any) => void): Screen; moveMaxRight(callback?: (error?: any) => void): Screen; moveMaxLeft(callback?: (error?: any) => void): Screen; moveBottom(callback?: (error?: any) => void): Screen; /** * Moves the cursor. */ move(n: number, m: number): Screen; /** * Selects overwrite mode as the screen display mode. */ overwrite(callback?: (error?: any) => void): Screen; /** * Selects vertical scroll mode as the screen display mode. */ verticalScroll(callback?: (error?: any) => void): Screen; /** * Selects horizontal scroll mode as the display screen mode. */ horizontalScroll(callback?: (error?: any) => void): Screen; /** * Turn cursor display mode on/off. */ cursor(display: boolean): Screen; /** * Sets display screen blank interval. */ blink(step: number): Screen; /** * Sets the counter time and displays it in the bottom right of the screen. */ timer(hour: number, minute: number): Screen; /** * Displays the time counter at the right side of the bottom line. */ displayTimer(): Screen; /** * Sets the brightness of the fluorescent character display tube. */ brightness(level: 1 | 2 | 3 | 4): Screen; /** * Selects or cancels reverse display of the characters received after this command */ reverse(n: boolean): Screen; /** * Set status confirmation for DTR signal */ DTR(n: boolean): Screen; /** * Print raw */ print(content: string): Screen; /** * Print text */ text(content: string, encoding: string): Screen; encode(encoding: string): Screen; /** * Send data to hardware and flush buffer */ flush(callback?: (error?: any) => void): Screen; close(callback?: (error?: any) => void, options?: any): Screen; } export class Server extends net.Server { constructor(device: Adapter); request(client: any): void; } export function Printer2(adapter: Adapter): any;
the_stack
import { injectable } from "inversify"; import { isValidDimension, almostEquals } from "../../utils/geometry"; import { Animation, CompoundAnimation } from '../../base/animations/animation'; import { Command, CommandExecutionContext, CommandResult } from '../../base/commands/command'; import { FadeAnimation, ResolvedElementFade } from '../fade/fade'; import { Action } from '../../base/actions/action'; import { SModelRootSchema, SModelRoot, SChildElement, SModelElement, SParentElement } from "../../base/model/smodel"; import { MoveAnimation, ResolvedElementMove } from "../move/move"; import { Fadeable, isFadeable } from "../fade/model"; import { isLocateable } from "../move/model"; import { isBoundsAware } from "../bounds/model"; import { ViewportRootElement } from "../viewport/viewport-root"; import { isSelectable } from "../select/model"; import { MatchResult, ModelMatcher, Match, forEachMatch } from "./model-matching"; import { ResolvedElementResize, ResizeAnimation } from '../bounds/resize'; /** * Sent from the model source to the client in order to update the model. If no model is present yet, * this behaves the same as a SetModelAction. The transition from the old model to the new one can be animated. */ export class UpdateModelAction implements Action { readonly kind = UpdateModelCommand.KIND; public readonly newRoot?: SModelRootSchema; public readonly matches?: Match[]; constructor(input: SModelRootSchema | Match[], public readonly animate: boolean = true) { if ((input as SModelRootSchema).id !== undefined) this.newRoot = input as SModelRootSchema; else this.matches = input as Match[]; } } export interface UpdateAnimationData { fades: ResolvedElementFade[] moves?: ResolvedElementMove[] resizes?: ResolvedElementResize[] } @injectable() export class UpdateModelCommand extends Command { static readonly KIND = 'updateModel'; oldRoot: SModelRoot; newRoot: SModelRoot; constructor(public action: UpdateModelAction) { super(); } execute(context: CommandExecutionContext): CommandResult { let newRoot: SModelRoot; if (this.action.newRoot !== undefined) { newRoot = context.modelFactory.createRoot(this.action.newRoot); } else { newRoot = context.modelFactory.createRoot(context.root); if (this.action.matches !== undefined) this.applyMatches(newRoot, this.action.matches, context); } this.oldRoot = context.root; this.newRoot = newRoot; return this.performUpdate(this.oldRoot, this.newRoot, context); } protected performUpdate(oldRoot: SModelRoot, newRoot: SModelRoot, context: CommandExecutionContext): CommandResult { if ((this.action.animate === undefined || this.action.animate) && oldRoot.id === newRoot.id) { let matchResult: MatchResult; if (this.action.matches === undefined) { const matcher = new ModelMatcher(); matchResult = matcher.match(oldRoot, newRoot); } else { matchResult = this.convertToMatchResult(this.action.matches, oldRoot, newRoot); } const animationOrRoot = this.computeAnimation(newRoot, matchResult, context); if (animationOrRoot instanceof Animation) return animationOrRoot.start(); else return animationOrRoot; } else { if (oldRoot.type === newRoot.type && isValidDimension(oldRoot.canvasBounds)) newRoot.canvasBounds = oldRoot.canvasBounds; return newRoot; } } protected applyMatches(root: SModelRoot, matches: Match[], context: CommandExecutionContext): void { const index = root.index; for (const match of matches) { if (match.left !== undefined) { const element = index.getById(match.left.id); if (element instanceof SChildElement) element.parent.remove(element); } if (match.right !== undefined) { const element = context.modelFactory.createElement(match.right); let parent: SModelElement | undefined; if (match.rightParentId !== undefined) parent = index.getById(match.rightParentId); if (parent instanceof SParentElement) parent.add(element); else root.add(element); } } } protected convertToMatchResult(matches: Match[], leftRoot: SModelRoot, rightRoot: SModelRoot): MatchResult { const result: MatchResult = {}; for (const match of matches) { const converted: Match = {}; let id: string | undefined = undefined; if (match.left !== undefined) { id = match.left.id; converted.left = leftRoot.index.getById(id); converted.leftParentId = match.leftParentId; } if (match.right !== undefined) { id = match.right.id; converted.right = rightRoot.index.getById(id); converted.rightParentId = match.rightParentId; } if (id !== undefined) result[id] = converted; } return result; } protected computeAnimation(newRoot: SModelRoot, matchResult: MatchResult, context: CommandExecutionContext): SModelRoot | Animation { const animationData: UpdateAnimationData = { fades: [] as ResolvedElementFade[] }; forEachMatch(matchResult, (id, match) => { if (match.left !== undefined && match.right !== undefined) { // The element is still there, but may have been moved this.updateElement(match.left as SModelElement, match.right as SModelElement, animationData); } else if (match.right !== undefined) { // An element has been added const right = match.right as SModelElement; if (isFadeable(right)) { right.opacity = 0; animationData.fades.push({ element: right, type: 'in' }); } } else if (match.left instanceof SChildElement) { // An element has been removed const left = match.left; if (isFadeable(left) && match.leftParentId !== undefined) { if (newRoot.index.getById(left.id) === undefined) { const parent = newRoot.index.getById(match.leftParentId); if (parent instanceof SParentElement) { const leftCopy = context.modelFactory.createElement(left) as SChildElement & Fadeable; parent.add(leftCopy); animationData.fades.push({ element: leftCopy, type: 'out' }); } } } } }); const animations = this.createAnimations(animationData, newRoot, context); if (animations.length >= 2) { return new CompoundAnimation(newRoot, context, animations); } else if (animations.length === 1) { return animations[0]; } else { return newRoot; } } protected updateElement(left: SModelElement, right: SModelElement, animationData: UpdateAnimationData): void { if (isLocateable(left) && isLocateable(right)) { const leftPos = left.position; const rightPos = right.position; if (!almostEquals(leftPos.x, rightPos.x) || !almostEquals(leftPos.y, rightPos.y)) { if (animationData.moves === undefined) animationData.moves = []; animationData.moves.push({ element: right, elementId: right.id, fromPosition: leftPos, toPosition: rightPos }); right.position = leftPos; } } if (isBoundsAware(left) && isBoundsAware(right)) { if (!isValidDimension(right.bounds)) { right.bounds = { x: right.bounds.x, y: right.bounds.y, width: left.bounds.width, height: left.bounds.height }; } else if (!almostEquals(left.bounds.width, right.bounds.width) || !almostEquals(left.bounds.height, right.bounds.height)) { if (animationData.resizes === undefined) animationData.resizes = []; animationData.resizes.push({ element: right, fromDimension: { width: left.bounds.width, height: left.bounds.height, }, toDimension: { width: right.bounds.width, height: right.bounds.height, } }); } } if (isSelectable(left) && isSelectable(right)) { right.selected = left.selected; } if (left instanceof SModelRoot && right instanceof SModelRoot) { right.canvasBounds = left.canvasBounds; } if (left instanceof ViewportRootElement && right instanceof ViewportRootElement) { right.scroll = left.scroll; right.zoom = left.zoom; } } protected createAnimations(data: UpdateAnimationData, root: SModelRoot, context: CommandExecutionContext): Animation[] { const animations: Animation[] = []; if (data.fades.length > 0) { animations.push(new FadeAnimation(root, data.fades, context, true)); } if (data.moves !== undefined && data.moves.length > 0) { const movesMap: Map<string, ResolvedElementMove> = new Map; for (const move of data.moves) { movesMap.set(move.elementId, move); } animations.push(new MoveAnimation(root, movesMap, new Map, context, false)); } if (data.resizes !== undefined && data.resizes.length > 0) { const resizesMap: Map<string, ResolvedElementResize> = new Map; for (const resize of data.resizes) { resizesMap.set(resize.element.id, resize); } animations.push(new ResizeAnimation(root, resizesMap, context, false)); } return animations; } undo(context: CommandExecutionContext): CommandResult { return this.performUpdate(this.newRoot, this.oldRoot, context); } redo(context: CommandExecutionContext): CommandResult { return this.performUpdate(this.oldRoot, this.newRoot, context); } }
the_stack
import {SimpleChanges} from '@angular/core'; import * as _moment from 'moment'; import {DlDateTimePickerModel} from './dl-date-time-picker-model'; import {DlModelProvider} from './dl-model-provider'; /** * Work around for moment namespace conflict when used with webpack and rollup. * See https://github.com/dherges/ng-packagr/issues/163 * * Depending on whether rollup is used, moment needs to be imported differently. * Since Moment.js doesn't have a default export, we normally need to import using * the `* as`syntax. * * rollup creates a synthetic default module and we thus need to import it using * the `default as` syntax. * * @internal **/ const moment = _moment; /** * Default implementation for the `minute` view. */ export class DlMinuteModelProvider implements DlModelProvider { private step = 5; /** * Receives `minuteStep` configuration changes detected by Angular. * * Changes where the value has not changed are ignored. * * Setting `minuteStep` to `null` or `undefined` will result in a * minuteStep of `5`. * * @param changes * the input changes detected by Angular. */ onChanges(changes: SimpleChanges): void { const minuteStepChange = changes['minuteStep']; if (minuteStepChange && (minuteStepChange.previousValue !== minuteStepChange.currentValue) ) { this.step = minuteStepChange.currentValue; if (this.step === null || this.step === undefined) { this.step = 5; } } } /** * Returns the `minute` model for the specified moment in `local` time with the * `active` minute set to the beginning of the hour. * * The `minute` model represents an hour (60 minutes) as three rows with four columns * and each cell representing 5-minute increments. * * The hour always starts at midnight. * * Each cell represents a 5-minute increment starting at midnight. * * The `active` minute will be the 5-minute increments less than or equal to the specified milliseconds. * * @param milliseconds * the moment in time from which the minute model will be created. * @param selectedMilliseconds * the current value of the date/time picker. * @returns * the model representing the specified moment in time. */ getModel(milliseconds: number, selectedMilliseconds: number): DlDateTimePickerModel { const startDate = moment(milliseconds).startOf('hour'); const currentMilliseconds = moment().valueOf(); const minuteSteps = new Array(Math.ceil(60 / this.step)).fill(0).map((zero, index) => zero + index * this.step); const minuteValues = minuteSteps.map((minutesToAdd) => moment(startDate).add(minutesToAdd, 'minutes').valueOf()); const activeValue = moment(minuteValues.filter((value) => value <= milliseconds).pop()).valueOf(); const nowValue = currentMilliseconds >= startDate.valueOf() && currentMilliseconds <= moment(startDate).endOf('hour').valueOf() ? moment(minuteValues.filter((value) => value <= currentMilliseconds).pop()).valueOf() : null; const previousHour = moment(startDate).subtract(1, 'hour'); const nextHour = moment(startDate).add(1, 'hour'); const selectedValue = selectedMilliseconds === null || selectedMilliseconds === undefined ? selectedMilliseconds : moment(minuteValues.filter((value) => value <= selectedMilliseconds).pop()).valueOf(); const rows = new Array(Math.ceil(minuteSteps.length / 4)) .fill(0) .map((zero, index) => zero + index) .map((value) => { return {cells: minuteSteps.slice((value * 4), (value * 4) + 4).map(rowOfMinutes)}; }); return { viewName: 'minute', viewLabel: startDate.format('lll'), activeDate: activeValue, leftButton: { value: previousHour.valueOf(), ariaLabel: `Go to ${previousHour.format('lll')}`, classes: {}, }, upButton: { value: startDate.valueOf(), ariaLabel: `Go to ${startDate.format('ll')}`, classes: {}, }, rightButton: { value: nextHour.valueOf(), ariaLabel: `Go to ${nextHour.format('lll')}`, classes: {}, }, rows }; function rowOfMinutes(stepMinutes): { display: string; ariaLabel: string; value: number; classes: {}; } { const minuteMoment = moment(startDate).add(stepMinutes, 'minutes'); return { display: minuteMoment.format('LT'), ariaLabel: minuteMoment.format('LLL'), value: minuteMoment.valueOf(), classes: { 'dl-abdtp-active': activeValue === minuteMoment.valueOf(), 'dl-abdtp-selected': selectedValue === minuteMoment.valueOf(), 'dl-abdtp-now': nowValue === minuteMoment.valueOf(), } }; } } /** * Move the active `minute` one row `down` from the specified moment in time. * * Moving `down` can result in the `active` minute being part of a different hour than * the specified `fromMilliseconds`, in this case the hour represented by the model * will change to show the correct hour. * * @param fromMilliseconds * the moment in time from which the next `minute` model `down` will be constructed. * @param selectedMilliseconds * the current value of the date/time picker. * @returns * model containing an `active` `minute` one row `down` from the specified moment in time. */ goDown(fromMilliseconds: number, selectedMilliseconds: number): DlDateTimePickerModel { return this.getModel(moment(fromMilliseconds).add(this.step * 4, 'minutes').valueOf(), selectedMilliseconds); } /** * Move the active `minute` one row `down` from the specified moment in time. * * Moving `down` can result in the `active` minute being part of a different hour than * the specified `fromMilliseconds`, in this case the hour represented by the model * will change to show the correct hour. * * @param fromMilliseconds * the moment in time from which the next `minute` model `down` will be constructed. * @param selectedMilliseconds * the current value of the date/time picker. * @returns * model containing an `active` `minute` one row `down` from the specified moment in time. */ goUp(fromMilliseconds: number, selectedMilliseconds: number): DlDateTimePickerModel { return this.getModel(moment(fromMilliseconds).subtract(this.step * 4, 'minutes').valueOf(), selectedMilliseconds); } /** * Move the `active` date one cell to `left` in the current `minute` view. * * Moving `left` can result in the `active` hour being part of a different hour than * the specified `fromMilliseconds`, in this case the hour represented by the model * will change to show the correct hour. * * @param fromMilliseconds * the moment in time from which the `minute` model to the `left` will be constructed. * @param selectedMilliseconds * the current value of the date/time picker. * @returns * model containing an `active` `minute` one cell to the `left` of the specified moment in time. */ goLeft(fromMilliseconds: number, selectedMilliseconds: number): DlDateTimePickerModel { return this.getModel(moment(fromMilliseconds).subtract(this.step, 'minutes').valueOf(), selectedMilliseconds); } /** * Move `active` minute one cell to `right` in the current `minute` view. * * Moving `right` can result in the `active` hour being part of a different hour than * the specified `fromMilliseconds`, in this case the hour represented by the model * will change to show the correct hour. * * @param fromMilliseconds * the moment in time from which the `minute` model to the `right` will be constructed. * @param selectedMilliseconds * the current value of the date/time picker. * @returns * model containing an `active` `minute` one cell to the `right` of the specified moment in time. */ goRight(fromMilliseconds: number, selectedMilliseconds: number): DlDateTimePickerModel { return this.getModel(moment(fromMilliseconds).add(this.step, 'minutes').valueOf(), selectedMilliseconds); } /** * Move the active `minute` one hour `down` from the specified moment in time. * * The `active` minute will be `one (1) hour after` the specified milliseconds. * This moves the `active` date one `page` `down` from the current `minute` view. * * The next cell `page-down` will be in a different hour than the currently * displayed view and the model time range will include the new active cell. * * @param fromMilliseconds * the moment in time from which the next `month` model page `down` will be constructed. * @param selectedMilliseconds * the current value of the date/time picker. * @returns * model containing an `active` `month` one year `down` from the specified moment in time. */ pageDown(fromMilliseconds: number, selectedMilliseconds: number): DlDateTimePickerModel { return this.getModel(moment(fromMilliseconds).add(1, 'hour').valueOf(), selectedMilliseconds); } /** * Move the active `minute` one hour `up` from the specified moment in time. * * The `active` minute will be `one (1) hour before` the specified milliseconds. * This moves the `active` date one `page` `down` from the current `minute` view. * * The next cell `page-up` will be in a different hour than the currently * displayed view and the model time range will include the new active cell. * * @param fromMilliseconds * the moment in time from which the next `month` model page `down` will be constructed. * @param selectedMilliseconds * the current value of the date/time picker. * @returns * model containing an `active` `month` one year `down` from the specified moment in time. */ pageUp(fromMilliseconds: number, selectedMilliseconds: number): DlDateTimePickerModel { return this.getModel(moment(fromMilliseconds).subtract(1, 'hour').valueOf(), selectedMilliseconds); } /** * Move the `active` `minute` to the last cell of the current hour. * * The view or time range will not change unless the `fromMilliseconds` value * is in a different hour than the displayed decade. * * @param fromMilliseconds * the moment in time from which the last cell will be calculated. * @param selectedMilliseconds * the current value of the date/time picker. * @returns * a model with the last cell in the view as the active `minute`. */ goEnd(fromMilliseconds: number, selectedMilliseconds: number): DlDateTimePickerModel { return this.getModel(moment(fromMilliseconds) .endOf('hour') .valueOf(), selectedMilliseconds); } /** * Move the `active` `minute` to the first cell of the current hour. * * The view or time range will not change unless the `fromMilliseconds` value * is in a different hour than the displayed decade. * * @param fromMilliseconds * the moment in time from which the first cell will be calculated. * @param selectedMilliseconds * the current value of the date/time picker. * @returns * a model with the first cell in the view as the active `minute`. */ goHome(fromMilliseconds: number, selectedMilliseconds: number): DlDateTimePickerModel { return this.getModel(moment(fromMilliseconds).startOf('hour').valueOf(), selectedMilliseconds); } }
the_stack
import { prop,propObject,propArray,required,maxLength,range } from "@rxweb/reactive-form-validators" import { gridColumn } from "@rxweb/grid" export class SpecItemHistoryBase { //#region specItemId Prop @prop() specItemId : number; //#endregion specItemId Prop //#region specId Prop @prop() specId : number; //#endregion specId Prop //#region parentSpecItemId Prop @prop() parentSpecItemId : number; //#endregion parentSpecItemId Prop //#region componentId Prop @prop() componentId : number; //#endregion componentId Prop //#region name Prop @maxLength({value:4000}) name : string; //#endregion name Prop //#region identifier Prop @maxLength({value:4000}) identifier : string; //#endregion identifier Prop //#region prePress Prop @maxLength({value:4000}) prePress : string; //#endregion prePress Prop //#region proofs Prop @maxLength({value:4000}) proofs : string; //#endregion proofs Prop //#region proofSets Prop @prop() proofSets : any; //#endregion proofSets Prop //#region pages Prop @prop() pages : any; //#endregion pages Prop //#region quantityId Prop @prop() quantityId : number; //#endregion quantityId Prop //#region quantityFilm Prop @prop() quantityFilm : any; //#endregion quantityFilm Prop //#region quantitySamples Prop @prop() quantitySamples : any; //#endregion quantitySamples Prop //#region sizeWidthFinish Prop @prop() sizeWidthFinish : number; //#endregion sizeWidthFinish Prop //#region sizeLengthFinish Prop @prop() sizeLengthFinish : number; //#endregion sizeLengthFinish Prop //#region sizeWidthFlat Prop @prop() sizeWidthFlat : number; //#endregion sizeWidthFlat Prop //#region sizeLengthFlat Prop @prop() sizeLengthFlat : number; //#endregion sizeLengthFlat Prop //#region ink Prop @maxLength({value:4000}) ink : string; //#endregion ink Prop //#region inkLayoutId Prop @prop() inkLayoutId : number; //#endregion inkLayoutId Prop //#region inkInstructions Prop @maxLength({value:4000}) inkInstructions : string; //#endregion inkInstructions Prop //#region inkProcessin1Pass Prop @prop() inkProcessin1Pass : any; //#endregion inkProcessin1Pass Prop //#region inkOil Prop @prop() inkOil : any; //#endregion inkOil Prop //#region inkRegistration Prop @prop() inkRegistration : any; //#endregion inkRegistration Prop //#region inkMatch Prop @prop() inkMatch : any; //#endregion inkMatch Prop //#region inkLaser Prop @prop() inkLaser : any; //#endregion inkLaser Prop //#region stockManufacture Prop @maxLength({value:4000}) stockManufacture : string; //#endregion stockManufacture Prop //#region stockGrade Prop @maxLength({value:4000}) stockGrade : string; //#endregion stockGrade Prop //#region stockColor Prop @maxLength({value:4000}) stockColor : string; //#endregion stockColor Prop //#region stockBasisWeight Prop @prop() stockBasisWeight : number; //#endregion stockBasisWeight Prop //#region stockBasisWidth Prop @prop() stockBasisWidth : number; //#endregion stockBasisWidth Prop //#region stockBasisLength Prop @prop() stockBasisLength : number; //#endregion stockBasisLength Prop //#region stockInstructions Prop @maxLength({value:4000}) stockInstructions : string; //#endregion stockInstructions Prop //#region stockType Prop @maxLength({value:4000}) stockType : string; //#endregion stockType Prop //#region stockFinish Prop @maxLength({value:4000}) stockFinish : string; //#endregion stockFinish Prop //#region stockWaste Prop @prop() stockWaste : number; //#endregion stockWaste Prop //#region stockSubstitutes Prop @prop() stockSubstitutes : any; //#endregion stockSubstitutes Prop //#region stockRecycledPaper Prop @prop() stockRecycledPaper : any; //#endregion stockRecycledPaper Prop //#region envelopeStyle Prop @maxLength({value:4000}) envelopeStyle : string; //#endregion envelopeStyle Prop //#region envelopeWindows Prop @maxLength({value:4000}) envelopeWindows : string; //#endregion envelopeWindows Prop //#region envelopeMarks Prop @maxLength({value:4000}) envelopeMarks : string; //#endregion envelopeMarks Prop //#region envelopeOther Prop @maxLength({value:4000}) envelopeOther : string; //#endregion envelopeOther Prop //#region labelAdhesiveId Prop @prop() labelAdhesiveId : number; //#endregion labelAdhesiveId Prop //#region labelAdhesiveFormula Prop @maxLength({value:4000}) labelAdhesiveFormula : string; //#endregion labelAdhesiveFormula Prop //#region labelPerSheet Prop @prop() labelPerSheet : any; //#endregion labelPerSheet Prop //#region labelStyleId Prop @prop() labelStyleId : number; //#endregion labelStyleId Prop //#region labelLinerWidth Prop @prop() labelLinerWidth : number; //#endregion labelLinerWidth Prop //#region labelLinerLength Prop @prop() labelLinerLength : number; //#endregion labelLinerLength Prop //#region labelVerticalSpacing Prop @prop() labelVerticalSpacing : number; //#endregion labelVerticalSpacing Prop //#region labelHorizontalSpacing Prop @prop() labelHorizontalSpacing : number; //#endregion labelHorizontalSpacing Prop //#region labelShape Prop @maxLength({value:4000}) labelShape : string; //#endregion labelShape Prop //#region marginalWords Prop @maxLength({value:4000}) marginalWords : string; //#endregion marginalWords Prop //#region marginalWordColor Prop @maxLength({value:4000}) marginalWordColor : string; //#endregion marginalWordColor Prop //#region carbon Prop @maxLength({value:4000}) carbon : string; //#endregion carbon Prop //#region carbonColor Prop @maxLength({value:4000}) carbonColor : string; //#endregion carbonColor Prop //#region rollCoreDiameter Prop @prop() rollCoreDiameter : number; //#endregion rollCoreDiameter Prop //#region rollOutsideDiameter Prop @prop() rollOutsideDiameter : number; //#endregion rollOutsideDiameter Prop //#region rollOrientationId Prop @prop() rollOrientationId : number; //#endregion rollOrientationId Prop //#region rollWarningsStripe Prop @prop() rollWarningsStripe : any; //#endregion rollWarningsStripe Prop //#region variableImage Prop @maxLength({value:4000}) variableImage : string; //#endregion variableImage Prop //#region perforate Prop @maxLength({value:4000}) perforate : string; //#endregion perforate Prop //#region score Prop @maxLength({value:4000}) score : string; //#endregion score Prop //#region fold Prop @maxLength({value:4000}) fold : string; //#endregion fold Prop //#region drill Prop @maxLength({value:4000}) drill : string; //#endregion drill Prop //#region numbering Prop @maxLength({value:4000}) numbering : string; //#endregion numbering Prop //#region dieCut Prop @maxLength({value:4000}) dieCut : string; //#endregion dieCut Prop //#region productApp Prop @maxLength({value:4000}) productApp : string; //#endregion productApp Prop //#region tab Prop @maxLength({value:4000}) tab : string; //#endregion tab Prop //#region corner Prop @maxLength({value:4000}) corner : string; //#endregion corner Prop //#region emboss Prop @maxLength({value:4000}) emboss : string; //#endregion emboss Prop //#region foilStamp Prop @maxLength({value:4000}) foilStamp : string; //#endregion foilStamp Prop //#region coat Prop @maxLength({value:4000}) coat : string; //#endregion coat Prop //#region fasten Prop @maxLength({value:4000}) fasten : string; //#endregion fasten Prop //#region pad Prop @maxLength({value:4000}) pad : string; //#endregion pad Prop //#region bind Prop @maxLength({value:4000}) bind : string; //#endregion bind Prop //#region other Prop @maxLength({value:4000}) other : string; //#endregion other Prop //#region stockCaliper Prop @maxLength({value:4000}) stockCaliper : string; //#endregion stockCaliper Prop //#region staticInkTypeId Prop @prop() staticInkTypeId : number; //#endregion staticInkTypeId Prop //#region variableInkTypeId Prop @prop() variableInkTypeId : number; //#endregion variableInkTypeId Prop //#region componentList Prop @maxLength({value:4000}) componentList : string; //#endregion componentList Prop //#region insertionInstructions Prop @maxLength({value:4000}) insertionInstructions : string; //#endregion insertionInstructions Prop //#region specialInstructions Prop @maxLength({value:4000}) specialInstructions : string; //#endregion specialInstructions Prop //#region affixingInstructions Prop @maxLength({value:4000}) affixingInstructions : string; //#endregion affixingInstructions Prop //#region matchComponents Prop @prop() matchComponents : any; //#endregion matchComponents Prop //#region recordCount Prop @maxLength({value:4000}) recordCount : string; //#endregion recordCount Prop //#region mailTypeId Prop @maxLength({value:40}) mailTypeId : string; //#endregion mailTypeId Prop //#region mailFileName Prop @maxLength({value:4000}) mailFileName : string; //#endregion mailFileName Prop //#region seedListName Prop @maxLength({value:4000}) seedListName : string; //#endregion seedListName Prop //#region stateForeignSuppressions Prop @maxLength({value:4000}) stateForeignSuppressions : string; //#endregion stateForeignSuppressions Prop //#region suppressionFile Prop @maxLength({value:4000}) suppressionFile : string; //#endregion suppressionFile Prop //#region fileTransmissionMethod Prop @maxLength({value:4000}) fileTransmissionMethod : string; //#endregion fileTransmissionMethod Prop //#region totalFilesSubmitted Prop @maxLength({value:4000}) totalFilesSubmitted : string; //#endregion totalFilesSubmitted Prop //#region dataLayout Prop @maxLength({value:4000}) dataLayout : string; //#endregion dataLayout Prop //#region caseConversion Prop @prop() caseConversion : any; //#endregion caseConversion Prop //#region additionMailServices Prop @prop() additionMailServices : any; //#endregion additionMailServices Prop //#region mailForeign Prop @prop() mailForeign : any; //#endregion mailForeign Prop //#region mailInvalid Prop @prop() mailInvalid : any; //#endregion mailInvalid Prop //#region deDupe Prop @prop() deDupe : any; //#endregion deDupe Prop //#region cassDpvNcoa Prop @prop() cassDpvNcoa : any; //#endregion cassDpvNcoa Prop //#region houseHold Prop @prop() houseHold : any; //#endregion houseHold Prop //#region simplexDuplexId Prop @prop() simplexDuplexId : number; //#endregion simplexDuplexId Prop //#region generalInstructions Prop @maxLength({value:4000}) generalInstructions : string; //#endregion generalInstructions Prop //#region prePrintedStockProvided Prop @prop() prePrintedStockProvided : any; //#endregion prePrintedStockProvided Prop //#region prePrintedStockDetails Prop @maxLength({value:4000}) prePrintedStockDetails : string; //#endregion prePrintedStockDetails Prop //#region stockRequirements Prop @maxLength({value:4000}) stockRequirements : string; //#endregion stockRequirements Prop //#region salutation Prop @maxLength({value:4000}) salutation : string; //#endregion salutation Prop //#region address Prop @maxLength({value:4000}) address : string; //#endregion address Prop //#region imbBarCode Prop @prop() imbBarCode : any; //#endregion imbBarCode Prop //#region tipped Prop @prop() tipped : any; //#endregion tipped Prop //#region colorInkForTipping Prop @maxLength({value:4000}) colorInkForTipping : string; //#endregion colorInkForTipping Prop //#region createdBy Prop @prop() createdBy : number; //#endregion createdBy Prop //#region cretaedDateTime Prop @prop() cretaedDateTime : any; //#endregion cretaedDateTime Prop //#region updatedBy Prop @prop() updatedBy : number; //#endregion updatedBy Prop //#region updatedDateTime Prop @prop() updatedDateTime : any; //#endregion updatedDateTime Prop }
the_stack
import test, { Macro } from 'ava'; import { fc, testProp } from 'ava-fast-check'; import { assembleBytecode, assembleBytecodeBCH, assembleBytecodeBTC, AuthenticationInstruction, AuthenticationInstructionPush, authenticationInstructionsAreMalformed, binToHex, disassembleBytecode, disassembleBytecodeBCH, disassembleBytecodeBTC, disassembleParsedAuthenticationInstructions, generateBytecodeMap, hexToBin, OpcodesBCH, OpcodesBTC, parseBytecode, ParsedAuthenticationInstruction, range, serializeAuthenticationInstruction, serializeAuthenticationInstructions, serializeParsedAuthenticationInstructions, } from '../../lib'; test('Each Opcodes enum contains a single instruction for 0-255', (t) => { const expected = range(256); const names = (keys: readonly string[]) => keys.filter((k) => isNaN(parseInt(k, 10))); const numbers = (keys: readonly string[]) => keys.map((k) => parseInt(k, 10)).filter((k) => !isNaN(k)); const bch = Object.keys(OpcodesBCH); t.deepEqual(numbers(bch), expected); t.deepEqual(names(bch).length, expected.length); const btc = Object.keys(OpcodesBTC); t.deepEqual(numbers(btc), expected); t.deepEqual(names(btc).length, expected.length); }); /** * `scriptHex` - the hex-encoded script prepended with `0x` * `asm` – the proper ASM result from disassembling the script * `parse` – an array representing the parsed authentication instructions: * - element 0 – `opcode` * - element 1 – `data`, hex-encoded (if present) * - if the array is longer than this, `malformed` is `true` * - element 2 – `expectedDataBytes`, (if present) * - element 3 – `length`, hex-encoded (if present) * - element 4 – `expectedLengthBytes`, hex-encoded (if present) */ interface CommonScriptParseAndAsmTests { readonly [scriptHex: string]: { readonly asm: string; readonly parse: [number, string?, number?, string?, number?][]; }; } const defToFixtures = (tests: CommonScriptParseAndAsmTests) => Object.entries(tests).map((entry) => { const [fullHex, { asm }] = entry; const [, hex] = fullHex.split('0x'); const script = hexToBin(hex); // eslint-disable-next-line complexity const object = entry[1].parse.map((set) => ({ opcode: set[0], ...(set.length > 2 ? { malformed: true } : undefined), ...(set[1] === undefined ? undefined : { data: hexToBin(set[1]) }), ...(set[2] === undefined ? undefined : { expectedDataBytes: set[2] }), ...(set[3] === undefined ? undefined : { length: hexToBin(set[3]) }), ...(set[4] === undefined ? undefined : { expectedLengthBytes: set[4] }), })); return { asm, hex, object, script }; }); const wellFormedScripts: CommonScriptParseAndAsmTests = { '0x00': { asm: 'OP_0', parse: [[0, '']], }, '0x0001010202020303030376': { asm: 'OP_0 OP_PUSHBYTES_1 0x01 OP_PUSHBYTES_2 0x0202 OP_PUSHBYTES_3 0x030303 OP_DUP', parse: [[0, ''], [1, '01'], [2, '0202'], [3, '030303'], [118]], }, '0x410411db93e1dcdb8a016b49840f8c53bc1eb68a382e97b1482ecad7b148a6909a5cb2e0eaddfb84ccf9744464f82e160bfa9b8b64f9d4c03f999b8643f656b412a3ac': { asm: 'OP_PUSHBYTES_65 0x0411db93e1dcdb8a016b49840f8c53bc1eb68a382e97b1482ecad7b148a6909a5cb2e0eaddfb84ccf9744464f82e160bfa9b8b64f9d4c03f999b8643f656b412a3 OP_CHECKSIG', parse: [ [ 0x41, '0411db93e1dcdb8a016b49840f8c53bc1eb68a382e97b1482ecad7b148a6909a5cb2e0eaddfb84ccf9744464f82e160bfa9b8b64f9d4c03f999b8643f656b412a3', ], [0xac], ], }, '0x4c020304': { asm: 'OP_PUSHDATA_1 2 0x0304', parse: [[0x4c, '0304']], }, '0x76a91411b366edfc0a8b66feebae5c2e25a7b6a5d1cf3188ac': { asm: 'OP_DUP OP_HASH160 OP_PUSHBYTES_20 0x11b366edfc0a8b66feebae5c2e25a7b6a5d1cf31 OP_EQUALVERIFY OP_CHECKSIG', parse: [ [0x76], [0xa9], [0x14, '11b366edfc0a8b66feebae5c2e25a7b6a5d1cf31'], [0x88], [0xac], ], }, }; const malFormedPushes: CommonScriptParseAndAsmTests = { '0x01': { asm: 'OP_PUSHBYTES_1 [missing 1 byte]', parse: [[0x01, '', 1]], }, '0x0201': { asm: 'OP_PUSHBYTES_2 0x01[missing 1 byte]', parse: [[0x02, '01', 2]], }, '0x4b': { asm: 'OP_PUSHBYTES_75 [missing 75 bytes]', parse: [[0x4b, '', 75]], }, '0x4c': { asm: 'OP_PUSHDATA_1 [missing 1 byte]', parse: [[0x4c, undefined, undefined, '', 1]], }, '0x4c02': { asm: 'OP_PUSHDATA_1 2 [missing 2 bytes]', parse: [[0x4c, '', 2]], }, '0x4d': { asm: 'OP_PUSHDATA_2 [missing 2 bytes]', parse: [[0x4d, undefined, undefined, '', 2]], }, '0x4d01': { asm: 'OP_PUSHDATA_2 0x01[missing 1 byte]', parse: [[0x4d, undefined, undefined, '01', 2]], }, '0x4d0101': { asm: 'OP_PUSHDATA_2 257 [missing 257 bytes]', parse: [[0x4d, '', 257]], }, '0x4d010101': { asm: 'OP_PUSHDATA_2 257 0x01[missing 256 bytes]', parse: [[0x4d, '01', 257]], }, '0x4e': { asm: 'OP_PUSHDATA_4 [missing 4 bytes]', parse: [[0x4e, undefined, undefined, '', 4]], }, '0x4e01': { asm: 'OP_PUSHDATA_4 0x01[missing 3 bytes]', parse: [[0x4e, undefined, undefined, '01', 4]], }, '0x4e01000001': { asm: 'OP_PUSHDATA_4 16777217 [missing 16777217 bytes]', parse: [[0x4e, '', 16777217]], }, '0x4e0100000101': { asm: 'OP_PUSHDATA_4 16777217 0x01[missing 16777216 bytes]', parse: [[0x4e, '01', 16777217]], }, }; const parse: Macro<[Uint8Array, readonly ParsedAuthenticationInstruction[]]> = ( t, input, expected ) => { t.deepEqual(parseBytecode(input), expected); }; parse.title = (title) => `parse script: ${title ?? ''}`.trim(); const disassemble: Macro<[ readonly ParsedAuthenticationInstruction[], string ]> = (t, input, expected) => { t.deepEqual( disassembleParsedAuthenticationInstructions(OpcodesBCH, input), expected ); }; disassemble.title = (title) => `disassemble script: ${title ?? ''}`.trim(); const serialize: Macro<[readonly AuthenticationInstruction[], Uint8Array]> = ( t, input, expected ) => { t.deepEqual(serializeAuthenticationInstructions(input), expected); }; serialize.title = (title) => `serialize script: ${title ?? ''}`.trim(); const reSerialize: Macro<[ readonly ParsedAuthenticationInstruction[], Uint8Array ]> = (t, input, expected) => { t.deepEqual(serializeParsedAuthenticationInstructions(input), expected); }; reSerialize.title = (title) => `re-serialize parsed script: ${title ?? ''}`.trim(); defToFixtures(wellFormedScripts).map(({ asm, hex, script, object }) => { test(`0x${hex}`, parse, script, object); test(`0x${hex}`, disassemble, object, asm); test(`0x${hex}`, serialize, object, script); test(`0x${hex}`, reSerialize, object, script); return undefined; }); defToFixtures(malFormedPushes).map(({ asm, hex, script, object }) => { test(`0x${hex}`, parse, script, object); test(`0x${hex}`, disassemble, object, asm); test(`0x${hex}`, reSerialize, object, script); return undefined; }); test('generateBytecodeMap', (t) => { enum TestOpcodes { OP_A = 1, OP_B = 2, OP_C = 3, } t.deepEqual(generateBytecodeMap(TestOpcodes), { OP_A: Uint8Array.of(1), // eslint-disable-line @typescript-eslint/naming-convention OP_B: Uint8Array.of(2), // eslint-disable-line @typescript-eslint/naming-convention OP_C: Uint8Array.of(3), // eslint-disable-line @typescript-eslint/naming-convention }); }); test('serializeAuthenticationInstruction', (t) => { const OP_PUSHDATA_1 = 0x4c; const pushData1Expected = new Uint8Array(102); pushData1Expected.set([OP_PUSHDATA_1, 100]); const pushData1Serialized = serializeAuthenticationInstruction({ data: new Uint8Array(100), opcode: OP_PUSHDATA_1, }); t.deepEqual(pushData1Serialized, pushData1Expected); const OP_PUSHDATA_2 = 0x4d; const pushData2Expected = new Uint8Array(259); pushData2Expected.set([OP_PUSHDATA_2, 0, 1]); const pushData2Serialized = serializeAuthenticationInstruction({ data: new Uint8Array(256), opcode: OP_PUSHDATA_2, }); t.deepEqual(pushData2Serialized, pushData2Expected); const OP_PUSHDATA_4 = 0x4e; const pushData4Expected = new Uint8Array(65541); pushData4Expected.set([OP_PUSHDATA_4, 0, 0, 1, 0]); const pushData4Serialized = serializeAuthenticationInstruction({ data: new Uint8Array(65536), opcode: OP_PUSHDATA_4, }); t.deepEqual(pushData4Serialized, pushData4Expected); }); enum TestOpcodes { OP_PUSH_EMPTY = 0, OP_A = 81, OP_B = 82, OP_C = 83, } test('disassembleBytecode', (t) => { t.deepEqual( disassembleBytecode( TestOpcodes, Uint8Array.from([0, 81, 82, 83, 81, 82, 83]) ), 'OP_PUSH_EMPTY OP_A OP_B OP_C OP_A OP_B OP_C' ); }); test('assembleBytecode', (t) => { t.deepEqual( assembleBytecode( generateBytecodeMap(TestOpcodes), 'OP_PUSH_EMPTY OP_A OP_B OP_C OP_A OP_B OP_C' ), { bytecode: Uint8Array.from([0, 81, 82, 83, 81, 82, 83]), success: true } ); }); const zcfHex = '76a9148b139a5274cc85e2d36d4f97922a15ae5d7f68af8763ac6776a914f127e6b53e2005930718681d245fe5a2b22f2b9f8763785479879169766bbb6cba676a6868'; test('disassembleBytecodeBCH & assembleBytecodeBCH', (t) => { const zcfAsm = 'OP_DUP OP_HASH160 OP_PUSHBYTES_20 0x8b139a5274cc85e2d36d4f97922a15ae5d7f68af OP_EQUAL OP_IF OP_CHECKSIG OP_ELSE OP_DUP OP_HASH160 OP_PUSHBYTES_20 0xf127e6b53e2005930718681d245fe5a2b22f2b9f OP_EQUAL OP_IF OP_OVER OP_4 OP_PICK OP_EQUAL OP_NOT OP_VERIFY OP_DUP OP_TOALTSTACK OP_CHECKDATASIGVERIFY OP_FROMALTSTACK OP_CHECKDATASIG OP_ELSE OP_RETURN OP_ENDIF OP_ENDIF'; t.deepEqual(disassembleBytecodeBCH(hexToBin(zcfHex)), zcfAsm); t.deepEqual(assembleBytecodeBCH(zcfAsm), { bytecode: hexToBin(zcfHex), success: true, }); }); test('disassembleBytecodeBTC & assembleBytecodeBTC', (t) => { const zcfAsm = 'OP_DUP OP_HASH160 OP_PUSHBYTES_20 0x8b139a5274cc85e2d36d4f97922a15ae5d7f68af OP_EQUAL OP_IF OP_CHECKSIG OP_ELSE OP_DUP OP_HASH160 OP_PUSHBYTES_20 0xf127e6b53e2005930718681d245fe5a2b22f2b9f OP_EQUAL OP_IF OP_OVER OP_4 OP_PICK OP_EQUAL OP_NOT OP_VERIFY OP_DUP OP_TOALTSTACK OP_UNKNOWN187 OP_FROMALTSTACK OP_UNKNOWN186 OP_ELSE OP_RETURN OP_ENDIF OP_ENDIF'; t.deepEqual(disassembleBytecodeBTC(hexToBin(zcfHex)), zcfAsm); t.deepEqual(assembleBytecodeBTC(zcfAsm), { bytecode: hexToBin(zcfHex), success: true, }); }); const maxUint8Number = 255; const fcUint8Array = (minLength: number, maxLength: number) => fc .array(fc.integer(0, maxUint8Number), minLength, maxLength) .map((a) => Uint8Array.from(a)); const maxBinLength = 100; testProp( '[fast-check] disassembleBytecodeBCH <-> assembleBytecodeBCH', [fcUint8Array(0, maxBinLength)], (randomBytecode: Uint8Array) => { const parsed = parseBytecode<OpcodesBCH>(randomBytecode); const instructions = (authenticationInstructionsAreMalformed(parsed) ? parsed.slice(0, -1) : parsed) as AuthenticationInstruction<OpcodesBCH>[]; const minimalPush = instructions.map((instruction) => [OpcodesBCH.OP_PUSHDATA_2, OpcodesBCH.OP_PUSHDATA_4].includes( instruction.opcode ) ? { opcode: OpcodesBCH.OP_1 } : instruction.opcode === OpcodesBCH.OP_PUSHDATA_1 && (instruction as AuthenticationInstructionPush).data.length < 76 ? { data: new Uint8Array(76), opcode: OpcodesBCH.OP_PUSHDATA_1, } : instruction ); const serialized = serializeAuthenticationInstructions(minimalPush); const disassembled = disassembleBytecodeBCH(serialized); const reassembled = assembleBytecodeBCH(disassembled); return ( reassembled.success && binToHex(serialized) === binToHex(reassembled.bytecode) ); } ); testProp( '[fast-check] disassembleBytecodeBTC <-> assembleBytecodeBTC', [fcUint8Array(0, maxBinLength)], (randomBytecode: Uint8Array) => { const parsed = parseBytecode<OpcodesBTC>(randomBytecode); const instructions = (authenticationInstructionsAreMalformed(parsed) ? parsed.slice(0, -1) : parsed) as AuthenticationInstruction<OpcodesBTC>[]; const minimalPush = instructions.map((instruction) => [OpcodesBTC.OP_PUSHDATA_2, OpcodesBTC.OP_PUSHDATA_4].includes( instruction.opcode ) ? { opcode: OpcodesBTC.OP_1 } : instruction.opcode === OpcodesBTC.OP_PUSHDATA_1 && (instruction as AuthenticationInstructionPush).data.length < 76 ? { data: new Uint8Array(76), opcode: OpcodesBTC.OP_PUSHDATA_1, } : instruction ); const serialized = serializeAuthenticationInstructions(minimalPush); const disassembled = disassembleBytecodeBTC(serialized); const reassembled = assembleBytecodeBTC(disassembled); return ( reassembled.success && binToHex(serialized) === binToHex(reassembled.bytecode) ); } );
the_stack
import { filterResourcesByGrouping, sortFilteredResources, getGroupsFromResources, expandViewCellsDataWithGroups, updateGroupingWithMainResource, expandGroups, updateTimeTableCellElementsMeta, updateAllDayCellElementsMeta, updateTimeCellsData, } from './computeds'; import { expandGroupedAppointment, groupAppointments } from './helpers'; import { sliceAppointmentsByDays } from '../all-day-panel/helpers'; import { HORIZONTAL_GROUP_ORIENTATION, VERTICAL_GROUP_ORIENTATION } from '../../constants'; jest.mock('./helpers', () => ({ ...jest.requireActual('./helpers'), expandGroupedAppointment: jest.fn(), groupAppointments: jest.fn(), })); jest.mock('../all-day-panel/helpers', () => ({ ...jest.requireActual('../all-day-panel/helpers'), sliceAppointmentsByDays: jest.fn(), })); describe('IntegratedGrouping computeds', () => { describe('#filterResourcesByGrouping', () => { it('should work', () => { const resources = [ { fieldName: 'resource1' }, { fieldName: 'resource2' }, { fieldName: 'resource3' }, ]; const grouping = [ { resourceName: 'resource3' }, { resourceName: 'resource1' }, ]; expect(filterResourcesByGrouping(resources, grouping)) .toEqual([ { fieldName: 'resource1' }, { fieldName: 'resource3' }, ]); }); }); describe('#sortFilteredResources', () => { it('should work', () => { const resources = [ { fieldName: 'resource1' }, { fieldName: 'resource2' }, ]; const grouping = [ { resourceName: 'resource2' }, { resourceName: 'resource1' }, ]; expect(sortFilteredResources(resources, grouping)) .toEqual([ { fieldName: 'resource2' }, { fieldName: 'resource1' }, ]); }); }); describe('#getGroupsFromResources', () => { it('should work', () => { const resources = [{ fieldName: 'resource2', instances: [ { id: 'resource2_1' }, { id: 'resource2_2' }, ], }, { fieldName: 'resource1', instances: [ { id: 'resource1_1' }, { id: 'resource1_2' }, ], }]; const grouping = [ { resourceName: 'resource2' }, { resourceName: 'resource1' }, ]; expect(getGroupsFromResources(resources, grouping)) .toEqual([[ { id: 'resource2_1' }, { id: 'resource2_2' }, ], [ { id: 'resource1_1' }, { id: 'resource1_2' }, { id: 'resource1_1' }, { id: 'resource1_2' }, ]]); }); }); describe('#expandViewCellsDataWithGroups', () => { const viewCellsDataBase = [ [{ startDate: new Date('2018-06-24 08:00'), endDate: new Date('2018-06-24 08:30') }], [{ startDate: new Date('2018-06-24 08:30'), endDate: new Date('2018-06-24 09:00') }], ]; const resourcesBase = [{ fieldName: 'resource1', instances: [{ id: 1 }, { id: 2 }], }]; it('should add cells and groupingInfo to the cells depending on groups', () => { const groups = [[ { fieldName: 'resource1', id: 1 }, { fieldName: 'resource1', id: 2 }, ]]; const result = expandViewCellsDataWithGroups( viewCellsDataBase, groups, resourcesBase, false, HORIZONTAL_GROUP_ORIENTATION, ); expect(result[0][0]) .toEqual({ ...viewCellsDataBase[0][0], groupingInfo: [{ fieldName: 'resource1', id: 1 }], endOfGroup: true, groupOrientation: HORIZONTAL_GROUP_ORIENTATION, }); expect(result[0][1]) .toEqual({ ...viewCellsDataBase[0][0], groupingInfo: [{ fieldName: 'resource1', id: 2 }], endOfGroup: true, groupOrientation: HORIZONTAL_GROUP_ORIENTATION, }); expect(result[1][0]) .toEqual({ ...viewCellsDataBase[1][0], groupingInfo: [{ fieldName: 'resource1', id: 1 }], endOfGroup: true, groupOrientation: HORIZONTAL_GROUP_ORIENTATION, }); expect(result[1][1]) .toEqual({ ...viewCellsDataBase[1][0], groupingInfo: [{ fieldName: 'resource1', id: 2 }], endOfGroup: true, groupOrientation: HORIZONTAL_GROUP_ORIENTATION, }); }); it('should work with multiple groups', () => { const viewCellsData = [ [{ startDate: new Date('2018-06-24 08:00'), endDate: new Date('2018-06-24 08:30') }], ]; const groups = [[ { fieldName: 'resource1', id: 1 }, { fieldName: 'resource1', id: 2 }, ], [ { fieldName: 'resource2', id: 1 }, { fieldName: 'resource2', id: 2 }, { fieldName: 'resource2', id: 1 }, { fieldName: 'resource2', id: 2 }, ]]; const resources = [{ fieldName: 'resource1', instances: [{ id: 1 }, { id: 2 }], }, { fieldName: 'resource2', instances: [{ id: 1 }, { id: 2 }], }]; const result = expandViewCellsDataWithGroups( viewCellsData, groups, resources, false, HORIZONTAL_GROUP_ORIENTATION, ); expect(result[0][0]) .toEqual({ ...viewCellsData[0][0], groupingInfo: [ { fieldName: 'resource2', id: 1 }, { fieldName: 'resource1', id: 1 }, ], endOfGroup: true, groupOrientation: HORIZONTAL_GROUP_ORIENTATION, }); expect(result[0][1]) .toEqual({ ...viewCellsData[0][0], groupingInfo: [ { fieldName: 'resource2', id: 2 }, { fieldName: 'resource1', id: 1 }, ], endOfGroup: true, groupOrientation: HORIZONTAL_GROUP_ORIENTATION, }); expect(result[0][2]) .toEqual({ ...viewCellsData[0][0], groupingInfo: [ { fieldName: 'resource2', id: 1 }, { fieldName: 'resource1', id: 2 }, ], endOfGroup: true, groupOrientation: HORIZONTAL_GROUP_ORIENTATION, }); expect(result[0][3]) .toEqual({ ...viewCellsData[0][0], groupingInfo: [ { fieldName: 'resource2', id: 2 }, { fieldName: 'resource1', id: 2 }, ], endOfGroup: true, groupOrientation: HORIZONTAL_GROUP_ORIENTATION, }); }); it('should not add groupingInfo if groups is an empty array', () => { const groups = []; expect(expandViewCellsDataWithGroups(viewCellsDataBase, groups, resourcesBase)) .toEqual(viewCellsDataBase); }); it('should work when grouping by dates is used', () => { const groups = [[ { fieldName: 'resource1', id: 1 }, { fieldName: 'resource1', id: 2 }, ]]; const viewCellsData = [ [{ startDate: new Date('2018-06-24 08:00'), endDate: new Date('2018-06-24 08:30') }], [{ startDate: new Date('2018-06-25 08:00'), endDate: new Date('2018-06-25 08:30') }], ]; const result = expandViewCellsDataWithGroups( viewCellsData, groups, resourcesBase, true, HORIZONTAL_GROUP_ORIENTATION, ); expect(result[0][0]) .toEqual({ ...viewCellsData[0][0], groupingInfo: [{ fieldName: 'resource1', id: 1 }], endOfGroup: false, groupOrientation: HORIZONTAL_GROUP_ORIENTATION, }); expect(result[0][1]) .toEqual({ ...viewCellsData[0][0], groupingInfo: [{ fieldName: 'resource1', id: 2 }], endOfGroup: true, groupOrientation: HORIZONTAL_GROUP_ORIENTATION, }); expect(result[1][0]) .toEqual({ ...viewCellsData[1][0], groupingInfo: [{ fieldName: 'resource1', id: 1 }], endOfGroup: false, groupOrientation: HORIZONTAL_GROUP_ORIENTATION, }); expect(result[1][1]) .toEqual({ ...viewCellsData[1][0], groupingInfo: [{ fieldName: 'resource1', id: 2 }], endOfGroup: true, groupOrientation: HORIZONTAL_GROUP_ORIENTATION, }); }); it('should work with vertical grouping', () => { const groups = [[ { fieldName: 'resource1', id: 1 }, { fieldName: 'resource1', id: 2 }, ]]; const result = expandViewCellsDataWithGroups( viewCellsDataBase, groups, resourcesBase, false, VERTICAL_GROUP_ORIENTATION, ); expect(result[0][0]) .toEqual({ ...viewCellsDataBase[0][0], groupingInfo: [{ fieldName: 'resource1', id: 1 }], endOfGroup: false, groupOrientation: VERTICAL_GROUP_ORIENTATION, }); expect(result[1][0]) .toEqual({ ...viewCellsDataBase[1][0], groupingInfo: [{ fieldName: 'resource1', id: 1 }], endOfGroup: true, groupOrientation: VERTICAL_GROUP_ORIENTATION, }); expect(result[2][0]) .toEqual({ ...viewCellsDataBase[0][0], groupingInfo: [{ fieldName: 'resource1', id: 2 }], endOfGroup: false, groupOrientation: VERTICAL_GROUP_ORIENTATION, }); expect(result[3][0]) .toEqual({ ...viewCellsDataBase[1][0], groupingInfo: [{ fieldName: 'resource1', id: 2 }], endOfGroup: true, groupOrientation: VERTICAL_GROUP_ORIENTATION, }); }); }); describe('#updateGroupingWithMainResource', () => { it('should return grouping if it is defined', () => { expect(updateGroupingWithMainResource('test')) .toBe('test'); }); it('should return grouping use the main resource for grouping', () => { const resources = [ { fieldName: 'test 1', isMain: false }, { fieldName: 'test 2', isMain: true }, ]; expect(updateGroupingWithMainResource(undefined, resources)) .toEqual([{ resourceName: 'test 2', }]); }); }); describe('#expandGroups', () => { beforeEach(() => { expandGroupedAppointment.mockImplementation(() => ['expandGroupedAppointment']); sliceAppointmentsByDays.mockImplementation(() => [{}]); }); afterEach(() => { jest.resetAllMocks(); }); it('should group and expand appointments', () => { expandGroups([[{}]], 'grouping', 'resources', 'groups', [], false); expect(expandGroupedAppointment) .toHaveBeenCalledWith({}, 'grouping', 'resources'); expect(groupAppointments) .toHaveBeenCalledWith(['expandGroupedAppointment'], 'resources', 'groups'); }); it('should slice appointments if sliceByDay is true', () => { expandGroups([[{}]], 'grouping', 'resources', 'groups', [], true); expect(expandGroupedAppointment) .toHaveBeenCalledWith({}, 'grouping', 'resources'); expect(groupAppointments) .toHaveBeenCalledWith(['expandGroupedAppointment'], 'resources', 'groups'); expect(sliceAppointmentsByDays) .toHaveBeenCalledWith({}, []); }); }); describe('#updateTimeTableCellElementsMeta', () => { it('should not update if getCellRects is undefined', () => { const timeTableCellElementsMeta = {}; expect(updateTimeTableCellElementsMeta( timeTableCellElementsMeta, () => VERTICAL_GROUP_ORIENTATION, 'groups', true, 'viewCellsData', {}, )) .toEqual(timeTableCellElementsMeta); }); it('should leave cell elements as they are if groupOrientation is horizontal or all day panel does not exist', () => { const timeTableCellElementsMeta = { getCellRects: 'test' }; let allDayPanelExists = false; expect(updateTimeTableCellElementsMeta( timeTableCellElementsMeta, () => VERTICAL_GROUP_ORIENTATION, 'groups', allDayPanelExists, 'viewCellsData', {}, )) .toEqual(timeTableCellElementsMeta); allDayPanelExists = true; expect(updateTimeTableCellElementsMeta( timeTableCellElementsMeta, () => HORIZONTAL_GROUP_ORIENTATION, 'groups', allDayPanelExists, 'viewCellsData', {}, )) .toEqual(timeTableCellElementsMeta); }); it('should delete elements belonging to all day cells', () => { const viewCellsData = [ [{ groupingInfo: 'First group' }, { groupingInfo: 'First group' }], [{ groupingInfo: 'First group' }, { groupingInfo: 'First group' }], [{ groupingInfo: 'Second group' }, { groupingInfo: 'Second group' }], [{ groupingInfo: 'Second group' }, { groupingInfo: 'Second group' }], ]; const timeTableCellElementsMeta = { parentRect: 'Parent rect', getCellRects: [ // All-day panel 'First cell', 'Second cell', // TimeTable 'Third cell', 'Fourth cell', 'Fifth cell', 'Sixth cell', // All-day panel 'Seventh cell', 'Eighth cell', // TimeTable 'Ninth cell', 'Tenth cell', 'Eleventh cell', 'Twelfth cell', ], }; const groups = [[{}, {}]]; expect(updateTimeTableCellElementsMeta( timeTableCellElementsMeta, () => VERTICAL_GROUP_ORIENTATION, groups, true, viewCellsData, {}, )) .toEqual({ parentRect: 'Parent rect', getCellRects: [ // TimeTable 'Third cell', 'Fourth cell', 'Fifth cell', 'Sixth cell', // TimeTable 'Ninth cell', 'Tenth cell', 'Eleventh cell', 'Twelfth cell', ], }); }); }); describe('#updateAllDayCellElementsMeta', () => { it('should not update if timeTableCellElementsMeta\'s getCellRects is undefined', () => { const timeTableCellElementsMeta = {}; const allDayElementsMeta = { test: 'test' }; expect(updateAllDayCellElementsMeta( allDayElementsMeta, timeTableCellElementsMeta, () => VERTICAL_GROUP_ORIENTATION, 'groups', true, 'viewCellsData', {}, )) .toEqual(allDayElementsMeta); }); it('should leave cell elements as they are if groupOrientation is horizontal or all day panel does not exist', () => { const timeTableCellElementsMeta = { getCellRects: 'test' }; const allDayElementsMeta = { test: 'test' }; let allDayPanelExists = false; expect(updateAllDayCellElementsMeta( allDayElementsMeta, timeTableCellElementsMeta, () => VERTICAL_GROUP_ORIENTATION, 'groups', allDayPanelExists, 'viewCellsData', {}, )) .toEqual(allDayElementsMeta); allDayPanelExists = true; expect(updateAllDayCellElementsMeta( allDayElementsMeta, timeTableCellElementsMeta, () => HORIZONTAL_GROUP_ORIENTATION, 'groups', allDayPanelExists, 'viewCellsData', {}, )) .toEqual(allDayElementsMeta); }); it('should delete elements belonging to timetable cells', () => { const viewCellsData = [ [{ groupingInfo: 'First group' }, { groupingInfo: 'First group' }], [{ groupingInfo: 'First group' }, { groupingInfo: 'First group' }], [{ groupingInfo: 'Second group' }, { groupingInfo: 'Second group' }], [{ groupingInfo: 'Second group' }, { groupingInfo: 'Second group' }], ]; const timeTableCellElementsMeta = { parentRect: 'Parent rect', getCellRects: [ // All-day panel 'First cell', 'Second cell', // TimeTable 'Third cell', 'Fourth cell', 'Fifth cell', 'Sixth cell', // All-day panel 'Seventh cell', 'Eighth cell', // TimeTable 'Ninth cell', 'Tenth cell', 'Eleventh cell', 'Twelfth cell', ], }; const allDayElementsMeta = {}; const groups = [[{}, {}]]; expect(updateAllDayCellElementsMeta( allDayElementsMeta, timeTableCellElementsMeta, () => VERTICAL_GROUP_ORIENTATION, groups, true, viewCellsData, {}, )) .toEqual({ parentRect: 'Parent rect', getCellRects: [ // All-day panel 'First cell', 'Second cell', // All-day panel 'Seventh cell', 'Eighth cell', ], }); }); }); describe('#updateTimeCellsData', () => { const groups = [[ { fieldName: 'resource1', id: 1 }, { fieldName: 'resource1', id: 2 }, ]]; const resources = [ { fieldName: 'resource1' }, ]; const pacificTimezoneOffset = 480; const winterDate = new Date(2020, 2, 7); const isPacificTimeZone = winterDate.getTimezoneOffset() === pacificTimezoneOffset; it('should return viewCellsData if DST change is not present', () => { const viewCellsData = [[{ startDate: new Date(2020, 11, 7), endDate: new Date(2020, 11, 7, 1), }]]; const timeCells = updateTimeCellsData( viewCellsData, undefined, groups, resources, HORIZONTAL_GROUP_ORIENTATION, ); expect(timeCells) .toBe(viewCellsData); }); if (isPacificTimeZone) { it('should return timeCells if DST change is present and horizontal grouping is used', () => { const viewCellsData = [[{ startDate: new Date(2020, 2, 8), endDate: new Date(2020, 2, 8, 1), }]]; const previousTimeCells = [[{ startDate: new Date(2020, 2, 9), endDate: new Date(2020, 2, 9, 1), }]]; const timeCells = updateTimeCellsData( viewCellsData, previousTimeCells, groups, resources, HORIZONTAL_GROUP_ORIENTATION, ); expect(timeCells) .not.toBe(viewCellsData); expect(timeCells) .toBe(previousTimeCells); }); // tslint:disable-next-line: max-line-length it('should return correct timeCells if DST change is present and vertical grouping is used', () => { const viewCellsData = [[{ startDate: new Date(2020, 2, 8), endDate: new Date(2020, 2, 8, 1), }]]; const previousTimeCells = [[{ startDate: new Date(2020, 2, 9), endDate: new Date(2020, 2, 9, 1), }]]; const timeCells = updateTimeCellsData( viewCellsData, previousTimeCells, groups, resources, VERTICAL_GROUP_ORIENTATION, ); expect(timeCells) .not.toBe(viewCellsData); expect(timeCells) .not.toBe(previousTimeCells); expect(timeCells) .toEqual([[{ startDate: new Date(2020, 2, 9), endDate: new Date(2020, 2, 9, 1), groupingInfo: [{ id: 1, fieldName: 'resource1', }], endOfGroup: true, groupOrientation: VERTICAL_GROUP_ORIENTATION, }], [{ startDate: new Date(2020, 2, 9), endDate: new Date(2020, 2, 9, 1), groupingInfo: [{ id: 2, fieldName: 'resource1', }], endOfGroup: true, groupOrientation: VERTICAL_GROUP_ORIENTATION, }]]); }); } }); });
the_stack
import { GatsbyIterable } from "../iterable" describe(`GatsbyIterable.constructor`, () => { it(`supports arrays`, () => { const arr = [`foo`, `bar`, `baz`] const iterable = new GatsbyIterable(arr) expect(Array.from(iterable)).toEqual([`foo`, `bar`, `baz`]) }) it(`supports array thunks`, () => { const arrThunk = (): Array<string> => [`foo`, `bar`, `baz`] const iterable = new GatsbyIterable(arrThunk) expect(Array.from(iterable)).toEqual([`foo`, `bar`, `baz`]) }) it(`supports other iterables`, () => { const set = new Set([`foo`, `bar`, `baz`]) const iterable = new GatsbyIterable(set) expect(Array.from(iterable)).toEqual([`foo`, `bar`, `baz`]) }) it(`supports iterable thunks`, () => { const mapThunk = (): Map<string, number> => new Map([ [`foo`, 1], [`bar`, 2], [`baz`, 3], ]) const iterable = new GatsbyIterable(mapThunk) expect(Array.from(iterable)).toEqual([ [`foo`, 1], [`bar`, 2], [`baz`, 3], ]) }) it(`supports generators`, () => { function* gen(): Generator<string> { yield `foo` yield `bar` yield `baz` } const iterable = new GatsbyIterable(gen()) expect(Array.from(iterable)).toEqual([`foo`, `bar`, `baz`]) }) it(`supports generator thunks`, () => { function* gen(): Generator<string> { yield `foo` yield `bar` yield `baz` } const iterable = new GatsbyIterable(() => gen()) expect(Array.from(iterable)).toEqual([`foo`, `bar`, `baz`]) }) }) describe(`GatsbyIterable.concat`, () => { it(`returns other GatsbyIterable`, () => { const foo = new GatsbyIterable([`foo`]) const result = foo.concat([`bar`]) expect(result).toBeInstanceOf(GatsbyIterable) }) it(`supports array`, () => { const foo = new GatsbyIterable([`foo`, `bar`]) const result = foo.concat([`baz`]) expect(Array.from(result)).toEqual([`foo`, `bar`, `baz`]) }) it(`supports empty array`, () => { const foo = new GatsbyIterable([`foo`, `bar`]) const result = foo.concat([]) expect(Array.from(result)).toEqual([`foo`, `bar`]) }) it(`supports other iterable`, () => { const foo = new GatsbyIterable([`foo`, `bar`]) const result = foo.concat(new Set([`baz`])) expect(Array.from(result)).toEqual([`foo`, `bar`, `baz`]) }) it(`supports generator`, () => { function* gen(): Generator<string> { yield `bar` yield `baz` } const foo = new GatsbyIterable([`foo`]) const result = foo.concat(gen()) expect(Array.from(result)).toEqual([`foo`, `bar`, `baz`]) }) }) describe(`GatsbyIterable.map`, () => { it(`returns other GatsbyIterable`, () => { const foo = new GatsbyIterable([1]) const result = foo.map(item => item + 1) expect(result).toBeInstanceOf(GatsbyIterable) }) it(`applies mapper function`, () => { const foo = new GatsbyIterable([1, 2, 3]) const mapped = foo.map(item => item + 1) expect(Array.from(mapped)).toEqual([2, 3, 4]) }) it(`supports index argument in mapper function`, () => { const foo = new GatsbyIterable([`foo`, `bar`, `baz`]) const mapped = foo.map((_, index) => index) expect(Array.from(mapped)).toEqual([0, 1, 2]) }) it(`does not support 3rd argument (full iterable) in mapper function`, () => { const foo = new GatsbyIterable([`foo`, `bar`]) const mapper: any = (_, __, nope) => nope const mapped = foo.map(mapper) expect(Array.from(mapped)).toEqual([undefined, undefined]) }) it(`is lazy`, () => { const fn = jest.fn() fn.mockImplementation(item => item + 1) const foo = new GatsbyIterable([1, 2, 3]) const mapped = foo.map(fn) expect(fn.mock.calls.length).toEqual(0) let i = 0 // @ts-ignore for (const _ of mapped) { expect(fn.mock.calls.length).toEqual(++i) } }) }) describe(`GatsbyIterable.filter`, () => { it(`returns other GatsbyIterable`, () => { const foo = new GatsbyIterable([1, 2, 3]) const result = foo.filter(item => item % 2 === 0) expect(result).toBeInstanceOf(GatsbyIterable) }) it(`applies predicate`, () => { const foo = new GatsbyIterable([1, 2, 3]) const odd = foo.filter(item => item % 2 === 1) expect(Array.from(odd)).toEqual([1, 3]) }) it(`is lazy`, () => { const fn = jest.fn() fn.mockImplementation(item => item % 2 === 0) const foo = new GatsbyIterable([1, 2, 3, 4]) const even = foo.filter(fn) expect(fn.mock.calls.length).toEqual(0) let i = 0 // @ts-ignore for (const _ of even) { expect(fn.mock.calls.length).toEqual((i += 2)) } }) }) describe(`GatsbyIterable.slice`, () => { it(`returns other GatsbyIterable`, () => { const foo = new GatsbyIterable([1, 2, 3, 4]) const result = foo.slice(1, 3) expect(result).toBeInstanceOf(GatsbyIterable) }) it(`supports start and end arguments`, () => { const foo = new GatsbyIterable([1, 2, 3, 4]) const slice = foo.slice(1, 3) expect(Array.from(slice)).toEqual([2, 3]) }) it(`works with start argument only`, () => { const foo = new GatsbyIterable([1, 2, 3, 4]) const slice = foo.slice(1, undefined) expect(Array.from(slice)).toEqual([2, 3, 4]) }) it(`throws when start > end`, () => { const foo = new GatsbyIterable([1, 2, 3, 4]) expect(() => foo.slice(3, 1)).toThrow( `Both arguments must not be negative and end must be greater than start` ) }) it(`returns empty iterable when start === end`, () => { const foo = new GatsbyIterable([1, 2, 3, 4]) const slice = foo.slice(1, 1) expect(Array.from(slice)).toEqual([]) }) it(`slices other iterables`, () => { const foo = new GatsbyIterable(new Set([1, 2, 3, 4])) const slice = foo.slice(1, 3) expect(Array.from(slice)).toEqual([2, 3]) }) it(`slices generators`, () => { function* gen(): Generator<number> { yield 1 yield 2 yield 3 yield 4 } const foo = new GatsbyIterable(gen()) const slice = foo.slice(1, 3) expect(Array.from(slice)).toEqual([2, 3]) }) }) describe(`GatsbyIterable.deduplicate`, () => { it(`returns other GatsbyIterable`, () => { const foo = new GatsbyIterable([1, 2, 3, 1]) const result = foo.deduplicate() expect(result).toBeInstanceOf(GatsbyIterable) }) it(`deduplicates numbers`, () => { const foo = new GatsbyIterable([1, 2, 3, 1]) const result = foo.deduplicate() expect(Array.from(result)).toEqual([1, 2, 3]) }) it(`deduplicates strings`, () => { const foo = new GatsbyIterable([`foo`, `bar`, `baz`, `bar`]) const result = foo.deduplicate() expect(Array.from(result)).toEqual([`foo`, `bar`, `baz`]) }) it(`uses strict equality to deduplicate values by default`, () => { const foo = { foo: 1 } const bar = { bar: 1 } const baz = { baz: 1 } const foo2 = { foo: 1 } const iterable = new GatsbyIterable([ foo, bar, bar, foo, baz, bar, foo, foo2, ]) const unique = iterable.deduplicate() expect(Array.from(unique)).toEqual([foo, bar, baz, foo2]) }) it(`supports custom key function`, () => { const foo = { foo: 1 } const bar = { bar: 1 } const baz = { baz: 1 } const foo2 = { foo: 1 } const iterable = new GatsbyIterable([ foo, bar, bar, foo, baz, bar, foo, foo2, ]) const unique = iterable.deduplicate( (value): string => Object.keys(value)[0] ) expect(Array.from(unique)).toEqual([foo, bar, baz]) }) it(`is lazy`, () => { const fn = jest.fn() fn.mockImplementation(item => item) const iterable = new GatsbyIterable([1, 2, 3, 1]) const unique = iterable.deduplicate(fn) expect(fn.mock.calls.length).toEqual(0) let i = 0 // @ts-ignore for (const _ of unique) { expect(fn.mock.calls.length).toEqual(++i) } }) }) describe(`GatsbyIterable.forEach`, () => { it(`is eager`, () => { let isCalled = false const foo = new GatsbyIterable([1, 2, 3]) foo.forEach(() => { isCalled = true }) expect(isCalled).toEqual(true) }) it(`applies callback function`, () => { const foo = new GatsbyIterable([1, 2, 3]) let i = 1 foo.forEach(value => { expect(value).toEqual(i++) }) expect(i).toEqual(4) }) it(`supports index argument in callback function`, () => { const iterable = new GatsbyIterable([`foo`, `bar`, `baz`]) let i = 0 iterable.forEach((_, index) => { expect(i++).toEqual(index) }) expect(i).toEqual(3) }) }) describe(`GatsbyIterable.mergeSorted`, () => { it(`returns other GatsbyIterable`, () => { const foo = new GatsbyIterable([`foo`]) const result = foo.mergeSorted([`bar`]) expect(result).toBeInstanceOf(GatsbyIterable) }) it(`uses standard JS comparison for numbers by default`, () => { const foo = new GatsbyIterable([10, 20, 30, 40]) const bar = foo.mergeSorted([25, 40.1]) expect(Array.from(bar)).toEqual([10, 20, 25, 30, 40, 40.1]) }) it(`uses standard JS comparison for strings by default`, () => { const foo = new GatsbyIterable([`10`, `20`, `30`, `40`]) const bar = foo.mergeSorted([`25`, `4`]) expect(Array.from(bar)).toEqual([`10`, `20`, `25`, `30`, `4`, `40`]) }) it(`supports custom comparator function`, () => { const a = { foo: 10 } const b = { foo: 20 } const c = { foo: 30 } const d = { foo: 40 } const comparatorFn = (a, b): number => { if (a.foo === b.foo) return 0 return a.foo > b.foo ? 1 : -1 } const foo = new GatsbyIterable([a, c]) const result = foo.mergeSorted([b, c, d], comparatorFn) expect(Array.from(result)).toEqual([a, b, c, c, d]) }) it(`assumes sorted iterables (does not enforce or checks it)`, () => { const foo = new GatsbyIterable([30, 10, 20]) const result = foo.mergeSorted([10, 25]) expect(Array.from(result)).toEqual([10, 25, 30, 10, 20]) }) it(`merges in O(N+M)`, () => { const onFooNext = jest.fn() const onBarNext = jest.fn() const foo = new GatsbyIterable(createSeq(0, onFooNext)) const bar = foo.mergeSorted(createSeq(0, onBarNext)) let i = 0 // @ts-ignore for (const _ of bar) { if (i === 100) { break } i++ } expect(onFooNext.mock.calls.length).toEqual(51) expect(onBarNext.mock.calls.length).toEqual(51) }) it(`closes wrapped iterator on early exit`, () => { let closed1 = false let closed2 = false const foo = new GatsbyIterable( createSeq(0, undefined, () => (closed1 = true)) ) const bar = foo.mergeSorted(createSeq(1, undefined, () => (closed2 = true))) expect(closed1).toEqual(false) expect(closed2).toEqual(false) let i = 0 const result = [] // @ts-ignore for (const value of bar) { if (i++ >= 5) { // Early exit from our iterator must close the other iterator as well break } result.push(value) } expect(closed1).toEqual(true) expect(closed2).toEqual(true) expect(i).toEqual(6) expect(result).toEqual([0, 1, 10, 11, 20]) }) it(`closes wrapped iterator on error`, () => { let closed1 = false let closed2 = false const foo = new GatsbyIterable( createSeq(0, undefined, () => (closed1 = true)) ) const bar = foo.mergeSorted(createSeq(1, undefined, () => (closed2 = true))) expect(closed1).toEqual(false) expect(closed2).toEqual(false) let i = 0 const result = [] try { // @ts-ignore for (const value of bar) { if (i++ >= 5) { // Error in our iterator must close the other iterator as well throw new Error(`Throw error`) } result.push(value) } } catch (e) { // no-op } expect(closed1).toEqual(true) expect(closed2).toEqual(true) expect(i).toEqual(6) expect(result).toEqual([0, 1, 10, 11, 20]) }) it(`is lazy`, () => { const fn = jest.fn() fn.mockImplementation((a, b) => { if (a === b) return 0 return a > b ? 1 : -1 }) const foo = new GatsbyIterable([10, 20]) const bar = foo.mergeSorted([15, 30], fn) expect(fn.mock.calls.length).toEqual(0) let i = 0 // @ts-ignore for (const _ of bar) i++ expect(i).toEqual(4) expect(fn.mock.calls.length).toEqual(3) }) }) describe(`GatsbyIterable.intersectSorted`, () => { it(`returns other GatsbyIterable`, () => { const foo = new GatsbyIterable([1, 2, 3, 4, 9]) const bar = foo.intersectSorted([3, 5, 7, 9]) expect(bar).toBeInstanceOf(GatsbyIterable) }) it(`uses standard JS comparison for numbers by default`, () => { const foo = new GatsbyIterable([1, 2, 3, 4, 9]) const bar = foo.intersectSorted([3, 5, 7, 9]) expect(Array.from(bar)).toEqual([3, 9]) }) it(`returns empty result if one iterable is empty`, () => { const foo = new GatsbyIterable([1, 2, 3, 4, 9]) const bar = foo.intersectSorted([]) expect(Array.from(bar)).toEqual([]) }) it(`returns empty result if there is no intersection`, () => { const foo = new GatsbyIterable([1, 3, 5]) const bar = foo.intersectSorted([0, 2, 4]) expect(Array.from(bar)).toEqual([]) }) it(`uses standard JS comparison for strings by default`, () => { const foo = new GatsbyIterable([`10`, `20`, `30`, `40`, `90`]) const bar = foo.intersectSorted([`30`, `5`, `7`, `90`]) expect(Array.from(bar)).toEqual([`30`, `90`]) }) it(`supports custom comparator function`, () => { const a = { foo: 10 } const b = { foo: 20 } const c = { foo: 30 } const d = { foo: 40 } const comparatorFn = (a, b): number => { if (a.foo === b.foo) return 0 return a.foo > b.foo ? 1 : -1 } const foo = new GatsbyIterable([a, b, c]) const result = foo.intersectSorted([b, c, d], comparatorFn) expect(Array.from(result)).toEqual([b, c]) }) it(`assumes sorted iterables (does not enforce or checks it)`, () => { const foo = new GatsbyIterable([30, 10, 20]) const result = foo.intersectSorted([10, 20]) expect(Array.from(result)).toEqual([]) }) it(`intersects in O(N+M)`, () => { const onFooNext = jest.fn() const onBarNext = jest.fn() const foo = new GatsbyIterable(createSeq(0, onFooNext)) const bar = foo.intersectSorted(createSeq(0, onBarNext)) let i = 0 // @ts-ignore for (const _ of bar) { if (i === 50) { break } i++ } expect(onFooNext.mock.calls.length).toEqual(51) expect(onBarNext.mock.calls.length).toEqual(51) }) it(`closes wrapped iterator on early exit`, () => { let closed1 = false let closed2 = false const foo = new GatsbyIterable( createSeq(0, undefined, () => (closed1 = true)) ) const bar = foo.intersectSorted( createSeq(0, undefined, () => (closed2 = true)) ) expect(closed1).toEqual(false) expect(closed2).toEqual(false) let i = 0 const result = [] // @ts-ignore for (const value of bar) { if (i++ >= 5) { // Early exit from our iterator must close the other iterator as well break } result.push(value) } expect(closed1).toEqual(true) expect(closed2).toEqual(true) expect(i).toEqual(6) expect(result).toEqual([0, 10, 20, 30, 40]) }) it(`closes wrapped iterator on error`, () => { let closed1 = false let closed2 = false const foo = new GatsbyIterable( createSeq(0, undefined, () => (closed1 = true)) ) const bar = foo.intersectSorted( createSeq(0, undefined, () => (closed2 = true)) ) expect(closed1).toEqual(false) expect(closed2).toEqual(false) let i = 0 const result = [] try { // @ts-ignore for (const value of bar) { if (i++ >= 5) { // Error in our iterator must close the other iterator as well throw new Error(`Throw error`) } result.push(value) } } catch (e) { // no-op } expect(closed1).toEqual(true) expect(closed2).toEqual(true) expect(i).toEqual(6) expect(result).toEqual([0, 10, 20, 30, 40]) }) it(`is lazy`, () => { const fn = jest.fn() fn.mockImplementation((a, b) => { if (a === b) return 0 return a > b ? 1 : -1 }) const foo = new GatsbyIterable([10, 20, 30, 40]) const bar = foo.intersectSorted([20, 30], fn) expect(fn.mock.calls.length).toEqual(0) let i = 0 // @ts-ignore for (const _ of bar) i++ expect(i).toEqual(2) expect(fn.mock.calls.length).toEqual(5) }) }) describe(`GatsbyIterable.deduplicateSorted`, () => { it(`returns other GatsbyIterable`, () => { const foo = new GatsbyIterable([1, 2, 2, 3]) const result = foo.deduplicateSorted() expect(result).toBeInstanceOf(GatsbyIterable) }) it(`deduplicates numbers`, () => { const foo = new GatsbyIterable([1, 2, 2, 3]) const result = foo.deduplicateSorted() expect(Array.from(result)).toEqual([1, 2, 3]) }) it(`deduplicates strings`, () => { const foo = new GatsbyIterable([`bar`, `baz`, `baz`, `foo`]) const result = foo.deduplicateSorted() expect(Array.from(result)).toEqual([`bar`, `baz`, `foo`]) }) it(`supports custom comparator function`, () => { const bar = { bar: 1 } const baz = { baz: 1 } const baz2 = { baz: 2 } const foo = { foo: 1 } const foo2 = { foo: 2 } const iterable = new GatsbyIterable([bar, baz, baz2, foo, foo2]) const unique = iterable.deduplicateSorted((a, b): number => { const [aKey] = Object.keys(a) const [bKey] = Object.keys(b) if (aKey === bKey) return 0 return aKey > bKey ? 1 : -1 }) expect(Array.from(unique)).toEqual([bar, baz, foo]) }) it(`is lazy`, () => { const fn = jest.fn() fn.mockImplementation((a, b) => { if (a === b) return 0 return a > b ? 1 : -1 }) const iterable = new GatsbyIterable([1, 2, 2, 3]) const unique = iterable.deduplicateSorted(fn) expect(fn.mock.calls.length).toEqual(0) let i = 0 // @ts-ignore for (const value of unique) { if (value === 1) { expect(fn.mock.calls.length).toEqual(0) } if (value === 2) { expect(fn.mock.calls.length).toEqual(1) } if (value === 3) { expect(fn.mock.calls.length).toEqual(3) } i++ } expect(i).toEqual(3) expect(fn.mock.calls.length).toEqual(3) }) }) function createSeq( start: number, onNext?: () => void, onClose?: () => void ): Iterable<number> { return { [Symbol.iterator](): Iterator<number> { let value = start - 10 return { next(): IteratorYieldResult<number> { if (onNext) onNext() value += 10 return { done: false, value } }, return(): IteratorReturnResult<number> { if (onClose) onClose() return { done: true, value } }, } }, } }
the_stack
* @title: User Data * @description: * This samples shows how to load and save user specific data using our Turbulenz services. */ /*{{ javascript("jslib/aabbtree.js") }}*/ /*{{ javascript("jslib/camera.js") }}*/ /*{{ javascript("jslib/geometry.js") }}*/ /*{{ javascript("jslib/material.js") }}*/ /*{{ javascript("jslib/light.js") }}*/ /*{{ javascript("jslib/scenenode.js") }}*/ /*{{ javascript("jslib/scene.js") }}*/ /*{{ javascript("jslib/vmath.js") }}*/ /*{{ javascript("jslib/effectmanager.js") }}*/ /*{{ javascript("jslib/shadermanager.js") }}*/ /*{{ javascript("jslib/texturemanager.js") }}*/ /*{{ javascript("jslib/renderingcommon.js") }}*/ /*{{ javascript("jslib/defaultrendering.js") }}*/ /*{{ javascript("jslib/observer.js") }}*/ /*{{ javascript("jslib/resourceloader.js") }}*/ /*{{ javascript("jslib/utilities.js") }}*/ /*{{ javascript("jslib/requesthandler.js") }}*/ /*{{ javascript("jslib/vertexbuffermanager.js") }}*/ /*{{ javascript("jslib/indexbuffermanager.js") }}*/ /*{{ javascript("jslib/services/turbulenzservices.js") }}*/ /*{{ javascript("jslib/services/turbulenzbridge.js") }}*/ /*{{ javascript("jslib/services/gamesession.js") }}*/ /*{{ javascript("jslib/services/mappingtable.js") }}*/ /*{{ javascript("jslib/services/userdatamanager.js") }}*/ /*{{ javascript("jslib/services/osdlib.js") }}*/ /*{{ javascript("scripts/sceneloader.js") }}*/ /*{{ javascript("scripts/htmlcontrols.js") }}*/ /*global TurbulenzEngine: true */ /*global TurbulenzServices: false */ /*global RequestHandler: false */ /*global OSD: false */ /*global MathDeviceConvert: false */ /*global UserDataManager: false */ /*global TextureManager: false */ /*global ShaderManager: false */ /*global EffectManager: false */ /*global Scene: false */ /*global SceneLoader: false */ /*global Camera: false */ /*global HTMLControls: false */ /*global DefaultRendering: false */ TurbulenzEngine.onload = function onloadFn() { var errorCallback = function errorCallback(msg) { window.alert(msg); }; var osd = OSD.create(); // Print a message to the on-screen-display that the game is loading osd.startLoading(); var inputDevice = TurbulenzEngine.createInputDevice({}); var graphicsDeviceParameters = { }; var graphicsDevice = TurbulenzEngine.createGraphicsDevice(graphicsDeviceParameters); if (!graphicsDevice.shadingLanguageVersion) { errorCallback("No shading language support detected.\nPlease check your graphics drivers are up to date."); graphicsDevice = null; return; } // Clear the background color of the engine window var clearColor = [0.87, 0.87, 0.87, 1.0]; if (graphicsDevice.beginFrame()) { graphicsDevice.clear(clearColor); graphicsDevice.endFrame(); } var mathDeviceParameters = {}; var mathDevice = TurbulenzEngine.createMathDevice(mathDeviceParameters); var requestHandlerParameters = {}; var requestHandler = RequestHandler.create(requestHandlerParameters); var textureManager = TextureManager.create(graphicsDevice, requestHandler, null, errorCallback); var shaderManager = ShaderManager.create(graphicsDevice, requestHandler, null, errorCallback); var effectManager = EffectManager.create(); var scene = Scene.create(mathDevice); var sceneLoader = SceneLoader.create(); var renderer; // Setup world space var worldUp = mathDevice.v3BuildYAxis(); // Setup a camera to view a close-up object var camera = Camera.create(mathDevice); var cameraDistanceFactor = 1.0; camera.nearPlane = 0.05; // The name of the node we want to rotate to demonstrate loading and saving engine objects var nodeName = "LOD3sp"; var objectNode = null; var rotation = 0; var transformToRotateFrom = mathDevice.m43BuildIdentity(); var rotationTransform = mathDevice.m43BuildIdentity(); var duckTransform = mathDevice.m43BuildIdentity(); var duckSpeed = 0.1; var duckDirection = 1; var saveId = 1; var setText = document.getElementById("userDataSet"); var getText = document.getElementById("userDataGet"); var duckText = document.getElementById("userDataDuck"); var getKeysText = document.getElementById("userDataGetKeys"); var setInnerHTML = function setInnerHTMLFn(documentElement, value) { if (documentElement) { documentElement.innerHTML = value; } }; var appendInnerHTML = function appendInnerHTMLFn(documentElement, value) { if (documentElement) { documentElement.innerHTML += value; } }; var buttonLoadDuck = document.getElementById("buttonLoadDuck"); var buttonSaveDuck = document.getElementById("buttonSaveDuck"); var buttonRemoveDuck = document.getElementById("buttonRemoveDuck"); var buttonsAvailable = buttonLoadDuck && buttonSaveDuck && buttonRemoveDuck; var buttonsSetDisabled = function buttonsSetDisabledFn(disabledValue) { if (buttonsAvailable) { buttonLoadDuck.disabled = disabledValue; buttonSaveDuck.disabled = disabledValue; buttonRemoveDuck.disabled = disabledValue; } }; buttonsSetDisabled(true); var gameSession; var userDataManager; var duckSaveOperation = false; var userDataGetKeys = function userDataGetKeysFn() { // Function to call once the Turbulenz Services have successfully completed a set var getKeysSuccess = function setSuccessFn(keys) { setInnerHTML(getKeysText, 'Key list:<br />'); var keysLength = keys.length; for (var i = 0; i < keysLength; i += 1) { var key = keys[i]; appendInnerHTML(getKeysText, key + '<br />'); } }; setInnerHTML(getKeysText, 'Getting keys...<br />'); userDataManager.getKeys(getKeysSuccess); }; var userDataGet = function userDataGetFn() { // Keep track of the number of get operations to reply with success var keysToGet = 2; // Function to call once the Turbulenz Services have successfully completed a get var getSuccess = function getSuccessFn(/* key, value */) { keysToGet -= 1; if (!keysToGet) { appendInnerHTML(getText, 'All keys successfully retrieved<br />'); } }; userDataManager.get("demo", function getDemoValueFn(key, value) { appendInnerHTML(getText, 'Key "' + key + '" has value "' + value + '"<br />'); getSuccess(); }); userDataManager.get("complex-object", function getComplexObjectValueFn(key, value) { var complexObject = JSON.parse(value); appendInnerHTML(getText, 'Key "' + key + '" has value ' + value + '<br />'); appendInnerHTML(getText, 'It can be parsed to get ' + complexObject.can.have[2]["we want"] + '<br />'); getSuccess(); }); }; var userDataSet = function userDataSetFn() { // Keep track of the number of set operations to reply with success var keysToSet = 2; // Function to call once the Turbulenz Services have successfully completed a set var setSuccess = function setSuccessFn(key) { var text = 'Key "' + key + '" has been successfully set'; appendInnerHTML(setText, text + '<br />'); window.console.log(text); keysToSet -= 1; if (!keysToSet) { appendInnerHTML(setText, 'All keys successfully set<br />'); // Now that the keys have been set we can retrieve them with get operations userDataGet(); userDataGetKeys(); } }; // Set the key "demo" equal to the string "hello world" userDataManager.set("demo", "hello world", setSuccess); var complexObject = { "a": "complex object", "can": { "have": ["any", "structure", <string><any>{ "we want": 438 }] } }; // Set the key "complex-object" equal to a stringified object userDataManager.set("complex-object", JSON.stringify(complexObject), setSuccess); }; var userDataError = function userDataErrorFn(errorMsg, status?, errorMethod?) { window.console.log("userDataErrorFn: " + errorMsg); // This is called in the event of an error if (errorMethod === userDataManager.set) { appendInnerHTML(setText, errorMsg + '<br />'); } else if (errorMethod === userDataManager.get) { appendInnerHTML(getText, errorMsg + '<br />'); } else if (errorMethod === userDataManager.getKeys) { appendInnerHTML(getKeysText, errorMsg + '<br />'); } }; var duckError = function duckErrorFn(errorMsg) { appendInnerHTML(duckText, "Failed<br />" + errorMsg); buttonsSetDisabled(false); duckSaveOperation = false; }; var htmlControls = HTMLControls.create(); var loadDuck = function loadDuckFn() { window.console.log("Loading duck ..."); var getSuccess = function setSuccessFn(key, value) { // Check that the value is set if (value) { var duckState = JSON.parse(value); if (duckState) { var duckTransform = duckState.transform; // Convert the duckTransform from a JavaScript array into a MathDevice object // Here we can use a destination MathDeviceConvert.arrayToM43(mathDevice, duckTransform, transformToRotateFrom); duckDirection = duckState.direction; htmlControls.updateCheckbox("checkReverseDuck", (duckDirection === 1)); rotation = 0; } appendInnerHTML(duckText, 'Complete'); } else { appendInnerHTML(duckText, 'No duck save!'); } duckSaveOperation = false; buttonsSetDisabled(false); // Remove the message on the on-screen-display concerning loading osd.stopLoading(); window.console.log("... finished loading duck data"); }; duckSaveOperation = true; setInnerHTML(duckText, 'Loading the duck...<br />'); buttonsSetDisabled(true); // Print message to on-screen-display that the stored state is being loaded osd.startLoading(); userDataManager.get("duck.state" + saveId, getSuccess, duckError); }; var removeDuck = function removeDuckFn() { var removeSuccess = function removeSuccessFn(/* key */) { appendInnerHTML(duckText, 'Complete'); duckSaveOperation = false; buttonsSetDisabled(false); userDataGetKeys(); }; duckSaveOperation = true; setInnerHTML(duckText, 'Removing the duck save...<br />'); buttonsSetDisabled(true); userDataManager.remove("duck.state" + saveId, removeSuccess, duckError); }; var saveDuck = function saveDuckFn() { window.console.log("Saving duck data ..."); // Function to call once the Turbulenz Services have successfully completed a set var setSuccess = function setSuccessFn(/* key */) { appendInnerHTML(duckText, 'Complete'); buttonsSetDisabled(false); duckSaveOperation = false; // Remove the message from the on-screen-display about storing the state osd.stopSaving(); userDataGetKeys(); window.console.log("... finished setting duck data"); }; setInnerHTML(duckText, 'Saving the duck...<br />'); buttonsSetDisabled(true); duckSaveOperation = true; // Print message to on-screen-display that the current state is being stored osd.startSaving(); // Set the key "duck.state" to a native engine math object using the MathDeviceConvert object var duckTransformObject = { "transform": MathDeviceConvert.m43ToArray(objectNode.getLocalTransform()), "direction": duckDirection }; userDataManager.set("duck.state" + saveId, JSON.stringify(duckTransformObject), setSuccess, duckError); }; var userDataDemo = function userDataDemoFn() { // Check that the turbulenz services are available // When running the file from disk this will be false if (TurbulenzServices.available()) { // Create the userData object from a gameSession // This must be done after the createGameSession callback has been called userDataManager = UserDataManager.create(requestHandler, gameSession, userDataError); setInnerHTML(document.getElementById("duckHeading"), "<h3>Duck state<\/h3>"); setInnerHTML(document.getElementById("getKeysHeading"), "<h3>Get Keys status<\/h3>"); setInnerHTML(setText, "<h3>Set status<\/h3>"); setInnerHTML(getText, "<h3>Get status<\/h3>"); buttonsSetDisabled(false); userDataSet(); loadDuck(); } else { var statusText = document.getElementById("userDataStatus"); setInnerHTML(statusText, "<h3>Turbulenz Services Unavailable<\/h3>"); appendInnerHTML(statusText, "You must run this sample from the local server"); } }; // Touch / mouse controls var saved = false; inputDevice.addEventListener('mouseup', function onMouseUpFn() { if (saved) { loadDuck(); } else { saveDuck(); } saved = !saved; }); // HTML controls htmlControls.addButtonControl({ id: "buttonLoadDuck", value: "Get", fn: loadDuck }); htmlControls.addButtonControl({ id: "buttonSaveDuck", value: "Set", fn: saveDuck }); htmlControls.addButtonControl({ id: "buttonRemoveDuck", value: "Remove", fn: removeDuck }); htmlControls.addCheckboxControl({ id: "checkReverseDuck", value: "Clockwise", isSelected: (duckDirection === 1), fn: function reverseFn() { duckDirection = -duckDirection; return (duckDirection === 1); } }); htmlControls.addRadioControl({ id: "radioSave01", groupName: "saveId", radioIndex: 0, value: "pos01", fn: function () { saveId = 1; }, isDefault: true }); htmlControls.addRadioControl({ id: "radioSave02", groupName: "saveId", radioIndex: 1, value: "pos02", fn: function () { saveId = 2; }, isDefault: false }); htmlControls.addRadioControl({ id: "radioSave03", groupName: "saveId", radioIndex: 2, value: "pos03", fn: function () { saveId = 3; }, isDefault: false }); htmlControls.register(); // Initialize the previous frame time var previousFrameTime = TurbulenzEngine.time; var renderFrame = function renderFrameFn() { var currentTime = TurbulenzEngine.time; var deltaTime = (currentTime - previousFrameTime); if (deltaTime > 0.1) { deltaTime = 0.1; } var deviceWidth = graphicsDevice.width; var deviceHeight = graphicsDevice.height; var aspectRatio = (deviceWidth / deviceHeight); if (aspectRatio !== camera.aspectRatio) { camera.aspectRatio = aspectRatio; camera.updateProjectionMatrix(); } camera.updateViewProjectionMatrix(); if (objectNode) { rotation += deltaTime * duckSpeed * duckDirection; if (rotation > 2 * Math.PI) { rotation -= 2 * Math.PI; } else if (rotation < 0) { rotation += 2 * Math.PI; } mathDevice.m43FromAxisRotation(worldUp, rotation, rotationTransform); mathDevice.m43Mul(rotationTransform, transformToRotateFrom, duckTransform); objectNode.setLocalTransform(duckTransform); } scene.update(); renderer.update(graphicsDevice, camera, scene, currentTime); if (graphicsDevice.beginFrame()) { if (renderer.updateBuffers(graphicsDevice, deviceWidth, deviceHeight)) { renderer.draw(graphicsDevice, clearColor); } graphicsDevice.endFrame(); } }; var intervalID; var loadingLoop = function loadingLoopFn() { if (sceneLoader.complete()) { TurbulenzEngine.clearInterval(intervalID); // For the default texture, take the result loaded by the scene objectNode = scene.findNode(nodeName); var sceneExtents = scene.getExtents(); var sceneMinExtent = mathDevice.v3Build(sceneExtents[0], sceneExtents[1], sceneExtents[2]); var sceneMaxExtent = mathDevice.v3Build(sceneExtents[3], sceneExtents[4], sceneExtents[5]); var center = mathDevice.v3ScalarMul(mathDevice.v3Add(sceneMaxExtent, sceneMinExtent), 0.5); var extent = mathDevice.v3Sub(center, sceneMinExtent); camera.lookAt(center, worldUp, mathDevice.v3Build(center[0] + extent[0] * 2 * cameraDistanceFactor, center[1] + extent[1] * cameraDistanceFactor, center[2] + extent[2] * 2 * cameraDistanceFactor)); camera.updateViewMatrix(); renderer.updateShader(shaderManager); // Remove the message on the on-screen-display that the game is loading osd.stopLoading(); userDataDemo(); intervalID = TurbulenzEngine.setInterval(renderFrame, 1000 / 60); } }; intervalID = TurbulenzEngine.setInterval(loadingLoop, 1000 / 10); var loadAssets = function loadAssetsFn() { // Renderer for the scene (requires shader assets). renderer = DefaultRendering.create(graphicsDevice, mathDevice, shaderManager, effectManager); renderer.setGlobalLightPosition(mathDevice.v3Build(0.5, 100.0, 0.5)); renderer.setAmbientColor(mathDevice.v3Build(0.3, 0.3, 0.4)); // Create object using scene loader sceneLoader.load({ scene : scene, assetPath : "models/duck.dae", graphicsDevice : graphicsDevice, mathDevice : mathDevice, textureManager : textureManager, effectManager : effectManager, shaderManager : shaderManager, requestHandler : requestHandler, append : false, dynamic : true }); }; var mappingTableReceived = function mappingTableReceivedFn(mappingTable) { textureManager.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix); shaderManager.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix); sceneLoader.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix); loadAssets(); }; var gameSessionCreated = function gameSessionCreatedFn(gameSession) { TurbulenzServices.createMappingTable(requestHandler, gameSession, mappingTableReceived); }; gameSession = TurbulenzServices.createGameSession(requestHandler, gameSessionCreated); // Create a scene destroy callback to run when the window is closed TurbulenzEngine.onunload = function destroyScene() { TurbulenzEngine.clearInterval(intervalID); intervalID = null; if (gameSession) { gameSession.destroy(); gameSession = null; } clearColor = null; rotation = null; if (scene) { scene.destroy(); scene = null; } sceneLoader = null; requestHandler = null; camera = null; userDataManager = null; if (renderer) { renderer.destroy(); renderer = null; } if (textureManager) { textureManager.destroy(); textureManager = null; } if (shaderManager) { shaderManager.destroy(); shaderManager = null; } effectManager = null; TurbulenzEngine.flush(); graphicsDevice = null; mathDevice = null; }; };
the_stack
import React, {useState, useEffect, useRef} from 'react'; import { Components, registerComponent } from '../../lib/vulcan-lib'; import { useCurrentUser } from '../common/withUser'; import { useUpdateCurrentUser } from '../hooks/useUpdateCurrentUser'; import { userEmailAddressIsVerified, userHasEmailAddress } from '../../lib/collections/users/helpers'; import { useMessages } from '../common/withMessages'; import { getGraphQLErrorID, getGraphQLErrorMessage } from '../../lib/utils/errorUtil'; import { randInt } from '../../lib/random'; import SimpleSchema from 'simpl-schema'; import Button from '@material-ui/core/Button'; import Input from '@material-ui/core/Input'; import MailOutline from '@material-ui/icons/MailOutline' import CheckRounded from '@material-ui/icons/CheckRounded' import withErrorBoundary from '../common/withErrorBoundary' import { AnalyticsContext, useTracking } from "../../lib/analyticsEvents"; import { forumTypeSetting } from '../../lib/instanceSettings'; const isEAForum = forumTypeSetting.get() === 'EAForum' const styles = (theme: ThemeType): JssStyles => ({ root: { marginBottom: theme.spacing.unit*4, position: "relative", backgroundColor: theme.palette.panelBackground.recentDiscussionThread, padding: 16, ...theme.typography.body2, boxShadow: theme.palette.boxShadow.default, marginLeft: "auto", marginRight: "auto", maxWidth: 500, }, adminNotice: { fontStyle: "italic", textAlign: "left", marginTop: 22, fontSize: 12, lineHeight: 1.3, }, loginForm: { margin: "0 auto", maxWidth: 252, }, message: { display: "flex", alignItems: "flex-start", fontSize: 18, lineHeight: 1.75, }, messageDescription: { fontSize: 12, marginTop: 8 }, mailIcon: { color: theme.palette.primary.main, marginTop: 4, marginRight: 12 }, checkIcon: { color: theme.palette.icon.greenCheckmark, marginTop: 4, marginRight: 12 }, emailInput: { marginTop: 18 }, subscribeButton: { margin: "18px auto 0", display: "block", background: theme.palette.primary.main, color: theme.palette.buttons.recentDiscussionSubscribeButtonText, fontSize: 15 }, buttons: { marginTop: 16, textAlign: "right", }, maybeLaterButton: { }, dontAskAgainButton: { }, }); const RecentDiscussionSubscribeReminder = ({classes}: { classes: ClassesType, }) => { const currentUser = useCurrentUser(); const updateCurrentUser = useUpdateCurrentUser(); const [hide, setHide] = useState(false); const [subscribeChecked, setSubscribeChecked] = useState(true); const [verificationEmailSent, setVerificationEmailSent] = useState(false); const [subscriptionConfirmed, setSubscriptionConfirmed] = useState(false); const emailAddressInput = useRef<HTMLInputElement|null>(null); const [loading, setLoading] = useState(false); const { flash } = useMessages(); const {WrappedLoginForm, SignupSubscribeToCurated, Loading, AnalyticsInViewTracker } = Components; const subscriptionDescription = '(2-3 posts per week, selected by the LessWrong moderation team.)'; const { captureEvent } = useTracking({eventProps: {pageElementContext: "subscribeReminder"}}); // Show admins a random version of the widget. Makes sure we notice if it's intrusive/bad. const [adminBranch, setAdminBranch] = useState(-1); const adminUiMessage = currentUser?.isAdmin ? <div className={classes.adminNotice}> You are seeing this UI element because you're an admin. Admins are shown a random version of the subscribe-reminder even if they're already subscribed, to make sure it still works and isn't annoying. </div>: null useEffect(() => { if (adminBranch === -1 && currentUser?.isAdmin) { // EA Forum only has 4 branches, LW has 5. Fortunately LW's extra branch // is the last one, so we can exclude it easily. setAdminBranch(randInt(isEAForum ? 4 : 5)); } }, [adminBranch, currentUser?.isAdmin]); // disable on AlignmentForum if (forumTypeSetting.get() === 'AlignmentForum') { return null; } // Placeholder to prevent SSR mismatch, changed on load. if (adminBranch === -1 && currentUser?.isAdmin) return <div/> // adjust functionality based on forum type let currentUserSubscribed = currentUser?.emailSubscribedToCurated; if (forumTypeSetting.get() === 'EAForum') { currentUserSubscribed = currentUser?.subscribedToDigest; } const maybeLaterButton = <Button className={classes.maybeLaterButton} onClick={() => { setHide(true) captureEvent("subscribeReminderButtonClicked",{buttonType: "maybeLaterButton"}) }} > Maybe Later </Button> const dontAskAgainButton = <span> {currentUser && <Button className={classes.dontAskAgainButton} onClick={() => { void updateCurrentUser({hideSubscribePoke: true}); setHide(true) captureEvent("subscribeReminderButtonClicked",{buttonType: "dontAskAgainButton"}) }} > Don't Ask Again </Button>} </span> if (hide || currentUser?.hideSubscribePoke) { return null; } const updateAndMaybeVerifyEmail = async () => { setLoading(true); // subscribe to different emails based on forum type const userSubscriptionData: Partial<MakeFieldsNullable<DbUser>> = forumTypeSetting.get() === 'EAForum' ? {subscribedToDigest: true} : {emailSubscribedToCurated: true}; // since they chose to subscribe to an email, make sure this is false userSubscriptionData.unsubscribeFromAll = false; // EA Forum does not care about email verification if (forumTypeSetting.get() !== 'EAForum' && !userEmailAddressIsVerified(currentUser)) { userSubscriptionData.whenConfirmationEmailSent = new Date(); } try { await updateCurrentUser(userSubscriptionData); setSubscriptionConfirmed(true); } catch(e) { flash(getGraphQLErrorMessage(e)); } setLoading(false); } const AnalyticsWrapper = ({children, branch}: {children: React.ReactNode, branch: string}) => { return <AnalyticsContext pageElementContext="subscribeReminder" branch={branch}> <AnalyticsInViewTracker eventProps={{inViewType: "subscribeReminder"}}> <div className={classes.root}> {children} </div> </AnalyticsInViewTracker> </AnalyticsContext> } // the EA Forum uses this prompt in most cases const eaForumSubscribePrompt = ( <> <div className={classes.message}> <MailOutline className={classes.mailIcon} /> Sign up for the Forum's email digest </div> <div className={classes.messageDescription}> You'll get a weekly email with the best posts from the past week. The Forum team selects the posts to feature based on personal preference and Forum popularity, and also adds some question posts that could use more answers. </div> </> ); if (loading) { return <div className={classes.root}> <Loading/> </div> } else if (subscriptionConfirmed) { // Show the confirmation after the user subscribes const confirmText = forumTypeSetting.get() === 'EAForum' ? "You're subscribed to the EA Forum Digest!" : "You are subscribed to the best posts of LessWrong!" return <AnalyticsWrapper branch="already-subscribed"> <div className={classes.message}> <CheckRounded className={classes.checkIcon} /> {confirmText} </div> </AnalyticsWrapper> } else if (verificationEmailSent) { // Clicked Subscribe in one of the other branches, and a confirmation email // was sent. You need to verify your email address to complete the subscription. const yourEmail = currentUser?.emails[0]?.address; return <AnalyticsWrapper branch="needs-email-verification-subscribed-in-other-branch"> <div className={classes.message}> We sent an email to {yourEmail}. Follow the link in the email to complete your subscription. </div> </AnalyticsWrapper> } else if (!currentUser || adminBranch===0) { // Not logged in. Show a create-account form and a brief pitch. const subscribeTextNode = forumTypeSetting.get() === 'EAForum' ? eaForumSubscribePrompt : ( <div className={classes.message}> To get the best posts emailed to you, create an account! {subscriptionDescription} </div> ); return <AnalyticsWrapper branch="logged-out"> {subscribeTextNode} <div className={classes.loginForm}> <WrappedLoginForm startingState="signup" /> </div> {adminUiMessage} </AnalyticsWrapper> } else if (!userHasEmailAddress(currentUser) || adminBranch===1) { const emailType = forumTypeSetting.get() === 'EAForum' ? 'our weekly digest email' : 'curated posts'; // Logged in, but no email address associated. Probably a legacy account. // Show a text box for an email address, with a submit button and a subscribe // checkbox. return <AnalyticsWrapper branch="missing-email"> <div className={classes.message}> Your account does not have an email address associated. Add an email address to subscribe to {emailType} and enable notifications. </div> <Input placeholder="Email address" inputRef={emailAddressInput} className={classes.emailInput} /> <SignupSubscribeToCurated defaultValue={true} onChange={(checked: boolean) => setSubscribeChecked(true)}/> <div className={classes.buttons}> <Button className={classes.subscribeButton} onClick={async (ev) => { const emailAddress = emailAddressInput.current; if (emailAddress && SimpleSchema.RegEx.Email.test(emailAddress?.value)) { setLoading(true); try { // subscribe to different emails based on forum type const userSubscriptionData: Partial<MakeFieldsNullable<DbUser>> = forumTypeSetting.get() === 'EAForum' ? {subscribedToDigest: subscribeChecked} : {emailSubscribedToCurated: subscribeChecked}; userSubscriptionData.email = emailAddress?.value; userSubscriptionData.unsubscribeFromAll = false; await updateCurrentUser(userSubscriptionData); if (forumTypeSetting.get() !== 'EAForum') { // Confirmation-email mutation is separate from the send-verification-email // mutation because otherwise it goes to the old email address (aka null) await updateCurrentUser({ whenConfirmationEmailSent: new Date(), }); } setSubscriptionConfirmed(true); } catch(e) { if (getGraphQLErrorID(e) === "users.email_already_taken") { flash("That email address is already taken by a different account."); } else { flash(e.message || e.id); } } setLoading(false); } else { flash("Please enter a valid email address."); } captureEvent("subscribeReminderButtonClicked", {buttonType: "subscribeButton"}); }}>Submit</Button> {adminUiMessage} <div className={classes.buttons}> {maybeLaterButton} {dontAskAgainButton} </div> </div> </AnalyticsWrapper> } else if (currentUser.unsubscribeFromAll || adminBranch===2) { // User has clicked unsubscribe-from-all at some point in the past. Pitch // on re-subscribing. A big Subscribe button, which clears the // unsubscribe-from-all option, activates curation emails (if not already // activated), and sends a confirmation email (if needed). const subscribeTextNode = forumTypeSetting.get() === 'EAForum' ? eaForumSubscribePrompt : ( <div className={classes.message}> You previously unsubscribed from all emails from LessWrong. Re-subscribe to get the best posts emailed to you! {subscriptionDescription} </div> ); return <AnalyticsWrapper branch="previously-unsubscribed"> {subscribeTextNode} <Button className={classes.subscribeButton} onClick={async (ev) => { await updateAndMaybeVerifyEmail(); captureEvent("subscribeReminderButtonClicked", {buttonType: "subscribeButton"}); }}>Subscribe</Button> {adminUiMessage} <div className={classes.buttons}> {maybeLaterButton} {dontAskAgainButton} </div> </AnalyticsWrapper> } else if (!currentUserSubscribed || adminBranch===3) { // User is logged in, and has an email address associated with their // account, but is not subscribed to curated posts. A Subscribe button which // sets the subscribe-to-curated option, and (if their email address isn't // verified) resends the verification email. const subscribeTextNode = forumTypeSetting.get() === 'EAForum' ? eaForumSubscribePrompt : ( <div className={classes.message}> Subscribe to get the best of LessWrong emailed to you. {subscriptionDescription} </div> ); return <AnalyticsWrapper branch="logged-in-not-subscribed"> {subscribeTextNode} <Button className={classes.subscribeButton} onClick={async (ev) => { await updateAndMaybeVerifyEmail(); captureEvent("subscribeReminderButtonClicked", {buttonType: "subscribeButton"}); }}>Subscribe</Button> {adminUiMessage} <div className={classes.buttons}> {maybeLaterButton} {dontAskAgainButton} </div> </AnalyticsWrapper> } else if ((!isEAForum && !userEmailAddressIsVerified(currentUser)) || adminBranch===4) { // User is subscribed, but they haven't verified their email address. Show // a resend-verification-email button. return <AnalyticsWrapper branch="needs-email-verification"> <div> <div className={classes.message}> Please verify your email address to activate your subscription to curated posts. </div> <div className={classes.buttons}> <Button className={classes.subscribeButton} onClick={async (ev) => { setLoading(true); try { await updateCurrentUser({ whenConfirmationEmailSent: new Date() }); } catch(e) { flash(getGraphQLErrorMessage(e)); } setLoading(false); setVerificationEmailSent(true); captureEvent("subscribeReminderButtonClicked", {buttonType: "resendVerificationEmailButton"}); }}>Resend Verification Email</Button> {adminUiMessage} <div className={classes.buttons}> {maybeLaterButton} {dontAskAgainButton} </div> </div> </div> </AnalyticsWrapper> } else { // Everything looks good-already subscribed to curated. No need to show anything. return null; } } const RecentDiscussionSubscribeReminderComponent = registerComponent( 'RecentDiscussionSubscribeReminder', RecentDiscussionSubscribeReminder, { styles, hocs: [withErrorBoundary], } ); declare global { interface ComponentTypes { RecentDiscussionSubscribeReminder: typeof RecentDiscussionSubscribeReminderComponent, } }
the_stack
import ChildProcess from 'child_process'; import FS from 'fs'; import Path from 'path'; import Util from 'util'; import type Stream from 'stream'; import FFMpeg from 'fluent-ffmpeg'; import GM from 'gm'; import Rimraf from 'rimraf'; import Config from '../config'; import type { BaseMedia, Media, MediaType, Metadata, SegmentMetadata } from '@vimtur/common'; import type { Response } from 'express'; export interface Quality { quality: number; copy: boolean; } // Nice level for low priority tasks const LOW_PRIORITY = 15; export interface TranscoderOptions { input: string; output: string | Stream.Writable; outputOptions: string[]; inputOptions?: string[]; important?: boolean; } export class ImportUtils { public static async getFileCreationTime(path: string): Promise<number> { const stat = await Util.promisify(FS.stat)(path); if (!stat) { throw new Error(`Failed to stat file: ${path}`); } const creationDate = stat.birthtime || stat.mtime; if (!creationDate) { throw new Error(`Failed to get creation date: ${path}`); } return Math.round(creationDate.getTime() / 1000); } public static async getVideoMetadata(absolutePath: string): Promise<Metadata> { // The ffprobe typings are broken with promisify. const data = await Util.promisify(FFMpeg.ffprobe as any)(absolutePath); const mediaData = data.streams.find((stream: any) => stream.codec_type === 'video'); if (!mediaData) { throw new Error('No video streams found to extract metadata from'); } const metadata: Metadata = { length: Math.ceil(data.format.duration), qualityCache: [], width: mediaData.width || mediaData.coded_width, height: mediaData.height || mediaData.coded_height, codec: mediaData.codec_name, ...(data.format.tags ? { artist: data.format.tags.artist || data.format.tags.album_artist, album: data.format.tags.album, title: data.format.tags.title, } : {}), }; // Delete them so they're not passed around as undefined. if (!metadata.artist) { delete metadata.artist; } if (!metadata.album) { delete metadata.album; } if (!metadata.title) { delete metadata.title; } return metadata; } public static async getImageMetadata(absolutePath: string): Promise<Metadata> { const gm = GM.subClass({ imageMagick: true })(absolutePath); const size: Record<string, number> = (await Util.promisify(gm.size.bind(gm))()) as any; return { width: size.width, height: size.height, }; } public static getType(filename: string): MediaType { const ext = Path.extname(filename || '').split('.'); switch (ext[ext.length - 1].toLowerCase()) { case 'png': case 'jpg': case 'jpeg': case 'bmp': case 'webp': return 'still'; case 'gif': return 'gif'; case 'avi': case 'mp4': case 'flv': case 'wmv': case 'mov': case 'webm': case 'mpeg': case 'mpg': return 'video'; default: throw new Error('Unknown filetype'); } } public static isMaxCopyEnabled(): boolean { return Config.get().transcoder.maxCopyEnabled; } public static getMinQualityForTranscode(): number { return Config.get().transcoder.minQuality; } public static getTranscodeQualities(): number[] { return [ ...new Set([ ...Config.get().transcoder.cacheQualities, ...Config.get().transcoder.streamQualities, ]), ]; } public static getMediaDesiredQualities(media: BaseMedia, qualities?: number[]): Quality[] { if (!qualities) { qualities = ImportUtils.getTranscodeQualities(); } const maxCopy = ImportUtils.isMaxCopyEnabled(); const minQualityForTranscode = ImportUtils.getMinQualityForTranscode(); if (!media.metadata) { throw new Error('Media metadata not found. Cannot calculate desired qualities.'); } const sourceHeight = media.metadata.height; const intermediate: number[] = []; for (const quality of qualities) { if (sourceHeight <= minQualityForTranscode) { intermediate.push(sourceHeight); continue; } if (quality > sourceHeight) { intermediate.push(sourceHeight); continue; } intermediate.push(quality); } const output: Quality[] = []; for (const quality of intermediate) { if (!output.find((el) => el.quality === quality)) { output.push({ quality: quality, copy: quality === sourceHeight && maxCopy, }); } } output.sort((a, b) => a.quality - b.quality); if (output.length === 0) { throw new Error(`No desired qualities for - ${media.hash}`); } return output; } public static setNice(pid: number, priority: number): void { const renice = ChildProcess.spawn('renice', [`${priority}`, `${pid}`]); renice.on('exit', (code: number) => { if (code !== 0) { console.debug(`Failed to set nice level of ${pid} to ${priority}: Exit code ${code}`); } }); } // You would think we'd just use fluent-ffmpeg's streaming functionality. // However, there appears to be a bug in streaming I can't track down // that corrupts that output stream even if piped to a file. public static async transcode(options: TranscoderOptions): Promise<void> { return new Promise<void>((resolve, reject) => { const args = []; if (options.inputOptions) { args.push(...options.inputOptions); } args.push(...['-i', options.input]); args.push(...options.outputOptions); if (typeof options.output === 'string') { args.push(options.output); } else { args.push('pipe:1'); } const proc = ChildProcess.spawn('ffmpeg', args); if (!options.important) { if (proc.pid === undefined) { console.warn('Failed to set transcode process to low priority. Missing PID.'); } else { ImportUtils.setNice(proc.pid, LOW_PRIORITY); } } let err = ''; proc.stderr.on('data', (data) => { err += data; }); proc.on('exit', (code) => { if (code === 0 || code === 255) { resolve(); } else { // This happens if stdout/the pipe is closed. Which can happen // when a HTTP request is cancelled. if ( err.includes('specified for output file #0 (pipe:1) has not been used for any stream') ) { resolve(); } else { console.error(`FFMPEG error: code (${code})`, err); reject(new Error(err)); } } }); if (typeof options.output !== 'string') { options.output.on('close', () => { // Wait slightly to avoid race condition under load. setTimeout(() => { proc.kill('SIGKILL'); }, 20); }); proc.stdout.pipe(options.output, { end: true }); } }); } public static async deleteFolder(path: string): Promise<void> { console.log(`Removing ${path}`); return Util.promisify(Rimraf)(path); } public static async exists(path: string): Promise<boolean> { try { await Util.promisify(FS.access)(path, FS.constants.R_OK); return true; } catch (err) { return false; } } public static async mkdir(path: string): Promise<void> { const exists = await ImportUtils.exists(path); if (!exists) { console.log(`Making directory ${path}`); try { await Util.promisify(FS.mkdir)(path); } catch (err) { // When done in parallel this gets a bit messy. if (err.code !== 'EEXIST') { throw err; } } } } public static calculateBandwidthFromQuality( quality: number, media: Media, round: boolean, ): number { if (!media.metadata) { throw new Error(`Can't calculate bandwidth without metadata: ${media.hash}`); } const resMultiplier = media.metadata.width / media.metadata.height; const pixels = quality * quality * resMultiplier; const bitrateMultiplier = Config.get().transcoder.bitrateMultiplier; if (!round) { return pixels * bitrateMultiplier; } // Round to the nearest .5M return Math.ceil((pixels * bitrateMultiplier) / 500000) * 500000; } public static generateStreamMasterPlaylist(media: Media): string { if (!media.metadata) { throw new Error(`Cannot stream media that hasn't been indexed: ${media.hash}`); } const mediaQuality = media.metadata.width > media.metadata.height ? media.metadata.height : media.metadata.width; const streamQualities = Config.get().transcoder.streamQualities.filter((quality) => { return quality <= mediaQuality; }); // Explicitly include qualities the medias cached at. const qualities = Array.from( new Set([...streamQualities, ...(media.metadata.qualityCache ?? [])]), ).sort(); // If it's less than the minimum stream quality and not cached. if (qualities.length === 0) { qualities.push(media.metadata.height); } let data = '#EXTM3U'; for (const quality of qualities.sort()) { // Can't round because otherwise they come out as needing the same bandwidth. const bandwidth = ImportUtils.calculateBandwidthFromQuality(quality, media, false); const height = quality; const width = Math.ceil((media.metadata.width / media.metadata.height) * height); const resolution = `${width}x${height}`; data = `${data}\n#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=${bandwidth},RESOLUTION=${resolution}`; data = `${data}\n${quality}/index.m3u8`; } return data; } public static async generateSegments(media: Media): Promise<SegmentMetadata> { if (!media.metadata) { throw new Error('Cannot generate playlist for media without metadatata'); } if (media.type !== 'video') { throw new Error('Cannot stream non-video type'); } if (!media.metadata.length) { throw new Error(`Can't stream 0 length video`); } // The reason we have to fetch the keyframes is to we can manually split the stream on keyframes. // This allows videos where the codec is copied rather than only supporting re-encoded videos. const keyframes = await ImportUtils.getKeyframes(media); const segments: SegmentMetadata = { standard: [], }; if (keyframes.length === 1 || media.metadata.length < 10) { segments.standard.push({ start: 0, end: media.metadata.length }); } else { let lastTimeIndex = 0; for (let i = 0; i < keyframes.length; i++) { if (keyframes[i] - keyframes[lastTimeIndex] > 10) { segments.standard.push({ start: keyframes[lastTimeIndex], end: keyframes[i] }); lastTimeIndex = i; } else if (i === keyframes.length - 1) { segments.standard.push({ start: keyframes[lastTimeIndex], end: media.metadata.length }); } } } return segments; } public static async generateStreamPlaylist( media: Media, segments: SegmentMetadata, ): Promise<string> { if (!media.metadata) { throw new Error('Cannot generate playlist for media without metadatata'); } if (media.type !== 'video') { throw new Error('Cannot stream non-video type'); } if (!media.metadata.length) { throw new Error(`Can't stream 0 length video`); } let data = ''; let longest = 0; for (const segment of segments.standard) { const length = segment.end - segment.start; if (length > longest) { longest = length; } data += `#EXTINF:${length.toFixed(6)},\ndata.ts?start=${segment.start}&end=${segment.end}\n`; } const header = `#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-TARGETDURATION:${Math.ceil( longest, )}\n#EXT-X-PLAYLIST-TYPE:VOD\n#EXT-X-MEDIA-SEQUENCE:0\n`; return `${header + data}#EXT-X-ENDLIST\n`; } public static getRedundanctCaches( desiredCachesInput: Quality[], actualCaches: number[], ): number[] { const desiredCaches = desiredCachesInput.map((el) => { return el.quality; }); const redundant: number[] = []; for (const quality of actualCaches) { if (!desiredCaches.includes(quality) && !redundant.includes(quality)) { redundant.push(quality); } } return redundant; } public static async wait(): Promise<void> { return new Promise<void>((resolve) => setTimeout(resolve, 0)); } public static async isExifRotated(path: string): Promise<boolean> { try { const gm = GM.subClass({ imageMagick: true })(path); const orientation: string = (await Util.promisify(gm.orientation.bind(gm))()) as any; switch (orientation.toLowerCase()) { case 'topleft': case 'unknown': return false; default: return true; } } catch (err) { console.error('isExifRotated failed', path, err); return false; } } public static loadImageAutoOrient( path: string, response: Response, scale?: { width: number; height: number }, ): void { let gm = GM.subClass({ nativeAutoOrient: true, imageMagick: true })(path).autoOrient(); if (scale) { gm = gm.scale(scale.width * 1.5, scale.height * 1.5).resize(scale.width, scale.height); } const format = path.toLowerCase().endsWith('gif') ? 'GIF' : 'PNG'; response.set('Content-Type', `image/${format.toLowerCase()}`); gm.stream(format).pipe(response); } private static async getKeyframes(media: Media): Promise<number[]> { if (media.type !== 'video') { throw new Error('Cannot stream non-video type'); } const results = await Util.promisify(ChildProcess.exec)( `ffprobe -fflags +genpts -loglevel error -skip_frame nokey -select_streams v:0 -show_entries frame=pkt_pts_time -of csv=print_section=0 "${media.absolutePath}"`, ); return results.stdout .split('\n') .filter((line) => Boolean(line)) .map((line) => Number(line)); } }
the_stack
import * as core from '@actions/core'; import NotImplementedException from './error/not-implemented-exception'; import System from './system'; import Versioning from './versioning'; afterEach(() => { jest.restoreAllMocks(); }); describe('Versioning', () => { describe('strategies', () => { it('returns an object', () => { expect(typeof Versioning.strategies).toStrictEqual('object'); }); it('has items', () => { expect(Object.values(Versioning.strategies).length).toBeGreaterThan(2); }); it('has an opt out option', () => { expect(Versioning.strategies).toHaveProperty('None'); }); it('has the semantic option', () => { expect(Versioning.strategies).toHaveProperty('Semantic'); }); it('has a strategy for tags', () => { expect(Versioning.strategies).toHaveProperty('Tag'); }); it('has an option that allows custom input', () => { expect(Versioning.strategies).toHaveProperty('Custom'); }); }); describe('branch', () => { it('returns headRef when set', () => { const headReference = jest.spyOn(Versioning, 'headRef', 'get').mockReturnValue('feature-branch-1'); expect(Versioning.branch).toStrictEqual('feature-branch-1'); expect(headReference).toHaveBeenCalledTimes(1); }); it('returns part of Ref when set', () => { jest.spyOn(Versioning, 'headRef', 'get').mockImplementation(); const reference = jest.spyOn(Versioning, 'ref', 'get').mockReturnValue('refs/heads/feature-branch-2'); expect(Versioning.branch).toStrictEqual('feature-branch-2'); expect(reference).toHaveBeenCalledTimes(2); }); it('prefers headRef over ref when set', () => { const headReference = jest.spyOn(Versioning, 'headRef', 'get').mockReturnValue('feature-branch-1'); const reference = jest.spyOn(Versioning, 'ref', 'get').mockReturnValue('refs/heads/feature-2'); expect(Versioning.branch).toStrictEqual('feature-branch-1'); expect(headReference).toHaveBeenCalledTimes(1); expect(reference).toHaveBeenCalledTimes(0); }); it('returns undefined when headRef and ref are not set', () => { const headReference = jest.spyOn(Versioning, 'headRef', 'get').mockImplementation(); const reference = jest.spyOn(Versioning, 'ref', 'get').mockImplementation(); expect(Versioning.branch).not.toBeDefined(); expect(headReference).toHaveBeenCalledTimes(1); expect(reference).toHaveBeenCalledTimes(1); }); }); describe('headRef', () => { it('does not throw', () => { expect(() => Versioning.headRef).not.toThrow(); }); }); describe('ref', () => { it('does not throw', () => { expect(() => Versioning.ref).not.toThrow(); }); }); describe('isDirtyAllowed', () => { it('does not throw', () => { expect(() => Versioning.isDirtyAllowed).not.toThrow(); }); it('returns false by default', () => { expect(Versioning.isDirtyAllowed).toStrictEqual(false); }); }); describe('logging git diff', () => { it('calls git diff', async () => { // allowDirtyBuild: true jest.spyOn(core, 'getInput').mockReturnValue('true'); jest.spyOn(Versioning, 'isShallow').mockResolvedValue(true); jest.spyOn(Versioning, 'isDirty').mockResolvedValue(false); jest.spyOn(Versioning, 'fetch').mockImplementation(); jest.spyOn(Versioning, 'hasAnyVersionTags').mockResolvedValue(true); jest .spyOn(Versioning, 'parseSemanticVersion') .mockResolvedValue({ match: '', tag: 'mocktag', commits: 'abcdef', hash: '75822BCAF' }); const logDiffSpy = jest.spyOn(Versioning, 'logDiff'); const gitSpy = jest.spyOn(System, 'run').mockImplementation(); await Versioning.generateSemanticVersion(); expect(logDiffSpy).toHaveBeenCalledTimes(1); expect(gitSpy).toHaveBeenCalledTimes(1); // Todo - this no longer works since typescript // const issuedCommand = System.run.mock.calls[0][2].input.toString(); // expect(issuedCommand.indexOf('diff')).toBeGreaterThan(-1); }); }); describe('descriptionRegex1', () => { it('is a valid regex', () => { expect(Versioning.descriptionRegex1).toBeInstanceOf(RegExp); }); test.each(['v1.1-1-g12345678', 'v0.1-2-g12345678', 'v0.0-500-gA9B6C3D0-dirty'])( 'is happy with valid %s', (description) => { expect(Versioning.descriptionRegex1.test(description)).toBeTruthy(); }, ); test.each(['1.1-1-g12345678', '0.1-2-g12345678', '0.0-500-gA9B6C3D0-dirty'])( 'accepts valid semantic versions without v-prefix %s', (description) => { expect(Versioning.descriptionRegex1.test(description)).toBeTruthy(); }, ); test.each(['v0', 'v0.1', 'v0.1.2', 'v0.1-2', 'v0.1-2-g'])('does not like %s', (description) => { expect(Versioning.descriptionRegex1.test(description)).toBeFalsy(); // Also, never expect without the v to work for any of these cases. expect(Versioning.descriptionRegex1.test(description?.slice(1))).toBeFalsy(); }); }); describe('determineBuildVersion', () => { test.each(['somethingRandom'])('throws for invalid strategy %s', async (strategy) => { await expect(Versioning.determineBuildVersion(strategy, '')).rejects.toThrowErrorMatchingSnapshot(); }); describe('opt out strategy', () => { it("returns 'none'", async () => { await expect(Versioning.determineBuildVersion('None', 'v1.0')).resolves.toMatchInlineSnapshot(`"none"`); }); }); describe('custom strategy', () => { test.each(['v0.1', '1', 'CamelCase', 'dashed-version'])( 'returns the inputVersion for %s', async (inputVersion) => { await expect(Versioning.determineBuildVersion('Custom', inputVersion)).resolves.toStrictEqual(inputVersion); }, ); }); describe('semantic strategy', () => { it('refers to generateSemanticVersion', async () => { const generateSemanticVersion = jest.spyOn(Versioning, 'generateSemanticVersion').mockResolvedValue('1.3.37'); await expect(Versioning.determineBuildVersion('Semantic', '')).resolves.toStrictEqual('1.3.37'); expect(generateSemanticVersion).toHaveBeenCalledTimes(1); }); }); describe('tag strategy', () => { it('refers to generateTagVersion', async () => { const generateTagVersion = jest.spyOn(Versioning, 'generateTagVersion').mockResolvedValue('0.1'); await expect(Versioning.determineBuildVersion('Tag', '')).resolves.toStrictEqual('0.1'); expect(generateTagVersion).toHaveBeenCalledTimes(1); }); }); describe('not implemented strategy', () => { it('throws a not implemented exception', async () => { const strategy = 'Test'; // @ts-ignore jest.spyOn(Versioning, 'strategies', 'get').mockReturnValue({ [strategy]: strategy }); await expect(Versioning.determineBuildVersion(strategy, '')).rejects.toThrowError(NotImplementedException); }); }); }); describe('generateTagVersion', () => { it('removes the v', async () => { jest.spyOn(Versioning, 'getTag').mockResolvedValue('v1.3.37'); await expect(Versioning.generateTagVersion()).resolves.toStrictEqual('1.3.37'); }); }); describe('parseSemanticVersion', () => { it('returns the named parts', async () => { jest.spyOn(Versioning, 'getVersionDescription').mockResolvedValue('v0.1-2-g12345678'); await expect(Versioning.parseSemanticVersion()).resolves.toMatchObject({ tag: '0.1', commits: '2', hash: '12345678', }); }); it('throws when no match could be made', async () => { jest.spyOn(Versioning, 'getVersionDescription').mockResolvedValue('no-match-can-be-made'); await expect(Versioning.parseSemanticVersion()).toMatchObject({}); }); }); describe('getVersionDescription', () => { it('returns the commands output', async () => { const runOutput = 'someValue'; jest.spyOn(System, 'run').mockResolvedValue(runOutput); await expect(Versioning.getVersionDescription()).resolves.toStrictEqual(runOutput); }); }); describe('isShallow', () => { it('returns true when the repo is shallow', async () => { const runOutput = 'true\n'; jest.spyOn(System, 'run').mockResolvedValue(runOutput); await expect(Versioning.isShallow()).resolves.toStrictEqual(true); }); it('returns false when the repo is not shallow', async () => { const runOutput = 'false\n'; jest.spyOn(System, 'run').mockResolvedValue(runOutput); await expect(Versioning.isShallow()).resolves.toStrictEqual(false); }); }); describe('fetch', () => { it('awaits the command', async () => { jest.spyOn(core, 'warning').mockImplementation(() => {}); jest.spyOn(System, 'run').mockImplementation(); await expect(Versioning.fetch()).resolves.not.toThrow(); }); it('falls back to the second strategy when the first fails', async () => { jest.spyOn(core, 'warning').mockImplementation(() => {}); const gitFetch = jest.spyOn(System, 'run').mockImplementation(); await expect(Versioning.fetch()).resolves.not.toThrow(); expect(gitFetch).toHaveBeenCalledTimes(1); }); }); describe('generateSemanticVersion', () => { it('returns a proper version from description', async () => { jest.spyOn(System, 'run').mockImplementation(); jest.spyOn(core, 'info').mockImplementation(() => {}); jest.spyOn(Versioning, 'isDirty').mockResolvedValue(false); jest.spyOn(Versioning, 'hasAnyVersionTags').mockResolvedValue(true); jest.spyOn(Versioning, 'getTotalNumberOfCommits').mockResolvedValue(2); jest.spyOn(Versioning, 'parseSemanticVersion').mockResolvedValue({ match: '0.1-2-g1b345678', tag: '0.1', commits: '2', hash: '1b345678', }); await expect(Versioning.generateSemanticVersion()).resolves.toStrictEqual('0.1.2'); }); it('throws when dirty', async () => { jest.spyOn(System, 'run').mockImplementation(); jest.spyOn(core, 'info').mockImplementation(() => {}); jest.spyOn(Versioning, 'isDirty').mockResolvedValue(true); await expect(Versioning.generateSemanticVersion()).rejects.toThrowError(); }); it('falls back to commits only, when no tags are present', async () => { const commits = Math.round(Math.random() * 10); jest.spyOn(System, 'run').mockImplementation(); jest.spyOn(core, 'info').mockImplementation(() => {}); jest.spyOn(Versioning, 'isDirty').mockResolvedValue(false); jest.spyOn(Versioning, 'hasAnyVersionTags').mockResolvedValue(false); jest.spyOn(Versioning, 'getTotalNumberOfCommits').mockResolvedValue(commits); await expect(Versioning.generateSemanticVersion()).resolves.toStrictEqual(`0.0.${commits}`); }); }); describe('isDirty', () => { it('returns true when there are files listed', async () => { const runOutput = 'file.ext\nfile2.ext'; jest.spyOn(System, 'run').mockResolvedValue(runOutput); await expect(Versioning.isDirty()).resolves.toStrictEqual(true); }); it('returns false when there is no output', async () => { const runOutput = ''; jest.spyOn(System, 'run').mockResolvedValue(runOutput); await expect(Versioning.isDirty()).resolves.toStrictEqual(false); }); }); describe('getTag', () => { it('returns the commands output', async () => { const runOutput = 'v1.0'; jest.spyOn(System, 'run').mockResolvedValue(runOutput); await expect(Versioning.getTag()).resolves.toStrictEqual(runOutput); }); }); describe('hasAnyVersionTags', () => { it('returns false when the command returns 0', async () => { const runOutput = '0'; jest.spyOn(System, 'run').mockResolvedValue(runOutput); await expect(Versioning.hasAnyVersionTags()).resolves.toStrictEqual(false); }); it('returns true when the command returns >= 0', async () => { const runOutput = '9'; jest.spyOn(System, 'run').mockResolvedValue(runOutput); await expect(Versioning.hasAnyVersionTags()).resolves.toStrictEqual(true); }); }); describe('getTotalNumberOfCommits', () => { it('returns a number from the command', async () => { jest.spyOn(System, 'run').mockResolvedValue('9'); await expect(Versioning.getTotalNumberOfCommits()).resolves.toStrictEqual(9); }); }); });
the_stack
import * as pino from 'pino' import * as nats from 'nats' import { Stream } from 'stream' declare namespace Hemera { type LogLevel = | 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silent' interface ErrioConfig { recursive?: boolean inherited?: boolean stack?: boolean private?: boolean exclude?: any include?: any } interface BloomrunConfig { indexing: 'insertion' | 'depth' lookupBeforeAdd: boolean } interface LogFn { (msg: string, ...args: any[]): void (obj: object, msg?: string, ...args: any[]): void } interface Logger { fatal: LogFn error: LogFn warn: LogFn info: LogFn debug: LogFn trace: LogFn } interface NodeCallback { (error?: Error | null | undefined, success?: any): void } interface HemeraMessagePayload { request: Request$ meta: any trace: Trace$ result: any error: Error | null } interface NatsTransport { driver(): any timeout( sid: number, timeout: number, expected: number, callback: (sid: number) => void ): void send( subject: string, msg?: string | Buffer, reply?: string, callback?: Function ): void close(): void flush(callback?: Function): void subscribe( subject: string, opts: nats.SubscribeOptions, callback: Function ): number unsubscribe(sid: number, max?: number): void request( subject: string, msg?: string, options?: nats.SubscribeOptions, callback?: Function ): number } interface Config { timeout?: number | 2000 pluginTimeout?: number tag?: string prettyLog?: boolean name?: string logLevel?: LogLevel childLogger?: boolean maxRecursion?: number logger?: Logger | Stream errio?: ErrioConfig bloomrun?: BloomrunConfig load?: LoadConfig traceLog?: boolean } interface LoadConfig { checkPolicy?: boolean shouldCrash?: boolean process?: LoadProcessConfig policy?: LoadPolicyConfig } interface LoadPolicyConfig { maxHeapUsedBytes?: number maxRssBytes?: number maxEventLoopDelay?: number } interface LoadProcessConfig { sampleInterval?: number } interface ClientPattern { topic: string pubsub$?: boolean timeout$?: number maxMessages$?: number expectedMessages$?: number [key: string]: any } interface ServerPattern { topic: string pubsub$?: boolean maxMessages$?: number [key: string]: any } type ClientResult = any type ActHandler = ( this: Hemera<ClientRequest, ClientResponse>, error: Error, response: ClientResult ) => void type Plugin = Function interface AddDefinition { schema: object pattern: ServerPattern action: Function sid: number transport: { topic: string pubsub: boolean maxMessages: number queue: string } // callback use( handler: ( request: Request, response: Response, next: Hemera.NodeCallback ) => void ): AddDefinition use( handler: (( request: Request, response: Response, next: Hemera.NodeCallback ) => void)[] ): AddDefinition // promise use( handler: (request: Request, response: Response) => Promise<void> ): AddDefinition use( handler: ((request: Request, response: Response) => Promise<void>)[] ): AddDefinition end(action: (request: ServerPattern, cb: NodeCallback) => void): void end(action: (request: ServerPattern) => Promise<any>): void } interface EncoderResult { value: string | Buffer error: Error } interface DecoderResult { value: object error: Error } type Response = null type Request = null interface ServerRequest { payload: HemeraMessagePayload error: Error } interface ClientRequest { payload: HemeraMessagePayload error: Error pattern: ClientPattern transport: { topic: string pubsub: boolean maxMessages: number expectedMessages: number } } interface ServerResponse { payload: HemeraMessagePayload error: Error } interface ClientResponse { payload: HemeraMessagePayload error: Error } interface Reply { log: pino.Logger | Logger payload: HemeraMessagePayload error: Error sent: boolean next: (message: Error | any) => void send: (message: Error | any) => void } type ActPromiseResult<T> = { data: T context: Hemera<ClientRequest, ClientResponse> } type NoContext = null interface Request$ { id: string type: 'pubsub' | 'request' } interface Trace$ { traceId: string parentSpanId: string spanId: string timestamp: number service: string method: string duration: number } } declare class Hemera<Request, Response> { constructor(transport: object, config: Hemera.Config) // act act(pattern: string | Hemera.ClientPattern, handler: Hemera.ActHandler): void act<T>(pattern: string | Hemera.ClientPattern): Promise<Hemera.ActPromiseResult<T>> // add add( pattern: string | Hemera.ServerPattern, handler: ( this: Hemera<Hemera.ServerRequest, Hemera.ServerResponse>, request: Hemera.ServerPattern, callback: Hemera.NodeCallback ) => void ): Hemera.AddDefinition add( pattern: string | Hemera.ServerPattern, handler: ( this: Hemera<Hemera.ServerRequest, Hemera.ServerResponse>, request: Hemera.ServerPattern ) => Promise<any> ): Hemera.AddDefinition add(pattern: string | Hemera.ServerPattern): Hemera.AddDefinition // plugin use( plugin: ( instance: Hemera<Hemera.NoContext, Hemera.NoContext>, opts: object, callback: Hemera.NodeCallback ) => void, options?: object ): void use( plugin: ( instance: Hemera<Hemera.NoContext, Hemera.NoContext>, opts: object ) => Promise<void>, options?: object ): void remove(topic: string | number, maxMessages: number): boolean list(Pattern: any, options: any): Array<Hemera.AddDefinition> fatal(): void close(closeListener: (error?: Error) => void): void close(): Promise<void> decorate( name: string, decoration: any, dependencies?: Array<string> ): Hemera<Hemera.NoContext, Hemera.NoContext> hasDecorator(name: string): Boolean expose( name: string, exposition: any, dependencies?: Array<string> ): Hemera<Hemera.NoContext, Hemera.NoContext> createError(name: string): any // application extensions ext( name: 'onAdd', handler: (addDefinition: Hemera.AddDefinition) => void ): Hemera<Hemera.NoContext, Hemera.NoContext> ext( name: 'onClose', handler: ( instance: Hemera<Hemera.NoContext, Hemera.NoContext>, next: Hemera.NodeCallback ) => void ): Hemera<Hemera.NoContext, Hemera.NoContext> ext(name: 'onClose'): Promise<void> // client extensions ext( name: 'onAct', handler: ( instance: Hemera<Hemera.ClientRequest, Hemera.ClientResponse>, next: Hemera.NodeCallback ) => void ): Hemera<Hemera.ClientRequest, Hemera.ClientResponse> ext( name: 'onAct', handler: ( instance: Hemera<Hemera.ClientRequest, Hemera.ClientResponse> ) => Promise<void> ): Hemera<Hemera.ClientRequest, Hemera.ClientResponse> ext( name: 'onActFinished', handler: ( instance: Hemera<Hemera.ClientRequest, Hemera.ClientResponse>, next: Hemera.NodeCallback ) => void ): Hemera<Hemera.ClientRequest, Hemera.ClientResponse> ext( name: 'onActFinished', handler: ( instance: Hemera<Hemera.ClientRequest, Hemera.ClientResponse> ) => Promise<void> ): Hemera<Hemera.ClientRequest, Hemera.ClientResponse> // server extensions ext( name: 'preHandler', handler: ( instance: Hemera<Hemera.ServerRequest, Hemera.ServerResponse>, request: Hemera.ServerRequest, reply: Hemera.Reply, next: Hemera.NodeCallback ) => void ): Hemera<Hemera.ServerRequest, Hemera.ServerResponse> ext( name: 'preHandler', handler: ( instance: Hemera<Hemera.ServerRequest, Hemera.ServerResponse>, request: Hemera.ServerRequest, reply: Hemera.Reply ) => Promise<void> ): Hemera<Hemera.ServerRequest, Hemera.ServerResponse> ext( name: 'onRequest', handler: ( instance: Hemera<Hemera.ServerRequest, Hemera.ServerResponse>, request: Hemera.ServerRequest, reply: Hemera.Reply, next: Hemera.NodeCallback ) => void ): Hemera<Hemera.ServerRequest, Hemera.ServerResponse> ext( name: 'onRequest', handler: ( instance: Hemera<Hemera.ServerRequest, Hemera.ServerResponse>, request: Hemera.ServerRequest, reply: Hemera.Reply ) => Promise<void> ): Hemera<Hemera.ServerRequest, Hemera.ServerResponse> ext( name: 'onSend', handler: ( instance: Hemera<Hemera.ServerRequest, Hemera.ServerResponse>, request: Hemera.ServerRequest, reply: Hemera.Reply, next: (err?: Error) => void ) => void ): Hemera<Hemera.ServerRequest, Hemera.ServerResponse> ext( name: 'onSend', handler: ( instance: Hemera<Hemera.ServerRequest, Hemera.ServerResponse>, request: Hemera.ServerRequest, reply: Hemera.Reply ) => Promise<void> ): Hemera<Hemera.ServerRequest, Hemera.ServerResponse> ext( name: 'onResponse', handler: ( instance: Hemera<Hemera.ServerRequest, Hemera.ServerResponse>, reply: Hemera.Reply, next: (err?: Error) => void ) => void ): Hemera<Hemera.ServerRequest, Hemera.ServerResponse> ext( name: 'onResponse', handler: ( instance: Hemera<Hemera.ServerRequest, Hemera.ServerResponse>, reply: Hemera.Reply ) => Promise<void> ): Hemera<Hemera.ServerRequest, Hemera.ServerResponse> ext( name: 'onError', handler: ( instance: Hemera<Hemera.ServerRequest, Hemera.ServerResponse>, payload: any, error: Error, next: (err?: Error) => void ) => void ): Hemera<Hemera.ServerRequest, Hemera.ServerResponse> ext( name: 'onResponse', handler: ( instance: Hemera<Hemera.ServerRequest, Hemera.ServerResponse>, payload: any, error: Error ) => Promise<void> ): Hemera<Hemera.ServerRequest, Hemera.ServerResponse> ready(): Promise<void> ready(readyListener: (err: Error) => void): void removeAll(): void // serialization setClientEncoder( encoder: (message: Object | Buffer) => Hemera.EncoderResult ): Hemera<Hemera.NoContext, Hemera.NoContext> setClientDecoder( encoder: (message: String | Buffer) => Hemera.DecoderResult ): Hemera<Hemera.NoContext, Hemera.NoContext> setServerEncoder( encoder: (message: Object | Buffer) => Hemera.EncoderResult ): Hemera<Hemera.NoContext, Hemera.NoContext> setServerDecoder( encoder: (message: String | Buffer) => Hemera.DecoderResult ): Hemera<Hemera.NoContext, Hemera.NoContext> setSchemaCompiler( compilerFunction: (schema: Object) => Function ): Hemera<Hemera.NoContext, Hemera.NoContext> setSchemaCompiler( compilerFunction: (schema: Object) => Promise<any> ): Hemera<Hemera.NoContext, Hemera.NoContext> setResponseSchemaCompiler( compilerFunction: (schema: Object) => Function ): Hemera<Hemera.NoContext, Hemera.NoContext> setResponseSchemaCompiler( compilerFunction: (schema: Object) => Promise<any> ): Hemera<Hemera.NoContext, Hemera.NoContext> setNotFoundPattern(pattern: string | Hemera.ServerPattern | null): void setErrorHandler(handler: (err: Error) => void): void setIdGenerator( generatorFunction: () => string ): Hemera<Hemera.NoContext, Hemera.NoContext> checkPluginDependencies(plugin: Hemera.Plugin): void log: pino.Logger | Hemera.Logger /** * Returns the Bloomrun instance * https://github.com/mcollina/bloomrun * * @type {*} * @memberof Hemera */ router: any /** * Returns the load propert from heavy instance * https://github.com/hapijs/heavy * * @type {*} * @memberof Hemera */ load: any errors: { [key: string]: Error } config: Hemera.Config topics: { [key: string]: number } transport: Hemera.NatsTransport notFoundPattern: Hemera.ServerPattern sid: number matchedAction: Hemera.AddDefinition request: Request response: Response context$: any meta$: any delegate$: any auth$: any trace$: Hemera.Trace$ request$: Hemera.Request$ } export = Hemera
the_stack
import { isNumber, isString } from 'lodash'; import { accessor, alwaysBoolean, alwaysNumber, alwaysString, applyDecorators, initString, nonenumerable as nonenumerableDecorator } from 'toxic-decorators'; import { isNumeric } from 'toxic-predicate-functions'; import { videoDomAttributes } from '../const/attribute'; import Dom from '../dispatcher/dom'; import Dispatcher from '../dispatcher/index'; import { IVideoKernelConstructor } from '../kernels/base'; import { SupportedKernelType, UserConfig, UserKernelsConfig } from '../typings/base'; // @ts-ignore: ignore property decorator problem const nonenumerable = nonenumerableDecorator as PropertyDecorator; // TODO: in config we should not need to care about videoconfigready // let dispatcher to handle this function stringOrVoid(value: any): string | void { return isString(value) ? value : undefined; } function accessorVideoProperty(property: string) { return accessor({ get(value: string | number | boolean | void) { return ((this as VideoConfig).dispatcher.videoConfigReady && (this as VideoConfig).inited) ? ((this as VideoConfig).dom.videoElement as any)[property] : value; }, set(value: string | number | boolean | void) { if (!(this as VideoConfig).dispatcher.videoConfigReady) { return value; } ((this as VideoConfig).dom.videoElement as any)[property] = value; return value; }, }); } function accessorVideoAttribute(attribute: string | { get: string, isBoolean?: boolean, set: string }) { const { set, get, isBoolean } = isString(attribute) ? { get: attribute, isBoolean: false, set: attribute, } : attribute; return accessor({ get(value: string | number | boolean | void) { return ((this as VideoConfig).dispatcher.videoConfigReady && (this as VideoConfig).inited) ? ((this as VideoConfig).dom.videoElement as any)[get] : value; }, set(value: string | number | boolean | void) { if (!(this as VideoConfig).dispatcher.videoConfigReady) { return value; } const val = isBoolean ? value ? '' : undefined /* istanbul ignore next */ : value === null ? undefined : value; (this as VideoConfig).dom.setAttr('videoElement', set, val); return value; }, }, { preSet: false, }); } function accessorCustomAttribute(attribute: string, isBoolean?: boolean) { return accessor({ get(value: string | number | boolean | void) { const attrValue = (this as VideoConfig).dom.getAttr('videoElement', attribute); return ((this as VideoConfig).dispatcher.videoConfigReady && (this as VideoConfig).inited) ? isBoolean ? !!attrValue : attrValue : value; }, set(value: string | number | boolean | void) { if (!(this as VideoConfig).dispatcher.videoConfigReady) { return value; } const val = isBoolean ? value || undefined : value === null ? undefined : value; (this as VideoConfig).dom.setAttr('videoElement', attribute, val); return value; }, }); } function accessorWidthAndHeight(property: string): (...args: any[]) => any { return accessor({ get(value: string | number | void) { if (!(this as VideoConfig).dispatcher.videoConfigReady || !(this as VideoConfig).inited) { return value; } const attr = (this as VideoConfig).dom.getAttr('videoElement', property); const prop = ((this as VideoConfig).dom.videoElement as any)[property]; if (isNumeric(attr) && isNumber(prop)) { return prop; } return attr || undefined; }, set(value: string | number | void) { if (!(this as VideoConfig).dispatcher.videoConfigReady) { return value; } let val; if (value === undefined || isNumber(value)) { val = value; } else if (isString(value) && !Number.isNaN(parseFloat(value))) { val = value; } (this as VideoConfig).dom.setAttr('videoElement', property, val); return val; }, }); } const accessorMap = { autoload: alwaysBoolean(), autoplay: [ alwaysBoolean(), accessorVideoProperty('autoplay'), ], controls: [ alwaysBoolean(), accessorVideoProperty('controls'), ], crossOrigin: [ accessor({ set: stringOrVoid }), accessorVideoAttribute({ set: 'crossorigin', get: 'crossOrigin' }), ], defaultMuted: [ alwaysBoolean(), accessorVideoAttribute({ get: 'defaultMuted', set: 'muted', isBoolean: true }), ], defaultPlaybackRate: [ accessorVideoProperty('defaultPlaybackRate'), alwaysNumber(1), ], disableRemotePlayback: [ alwaysBoolean(), accessorVideoProperty('disableRemotePlayback'), ], height: [ accessorWidthAndHeight('height'), ], loop: [ alwaysBoolean(), accessorVideoProperty('loop'), ], muted: [ alwaysBoolean(), accessorVideoProperty('muted'), ], playbackRate: [ alwaysNumber(1), accessorVideoProperty('playbackRate'), ], playsInline: [ accessor({ get(value: boolean) { const playsInline = ((this as VideoConfig).dom.videoElement as any).playsInline; return ((this as VideoConfig).dispatcher.videoConfigReady && (this as VideoConfig).inited) ? playsInline === undefined ? value : playsInline : value; }, set(value: boolean) { if (!(this as VideoConfig).dispatcher.videoConfigReady) { return value; } ((this as VideoConfig).dom.videoElement as any).playsInline = value; const val = value ? '' : undefined; (this as VideoConfig).dom.setAttr('videoElement', 'playsinline', val); (this as VideoConfig).dom.setAttr('videoElement', 'webkit-playsinline', val); (this as VideoConfig).dom.setAttr('videoElement', 'x5-playsinline', val); return value; }, }), alwaysBoolean(), ], poster: [ // 因为如果在 video 上随便加一个字符串,他会将其拼接到地址上,所以这里要避免 // 单元测试无法检测 alwaysString(), accessor({ get(value: string) { return ((this as VideoConfig).dispatcher.videoConfigReady && (this as VideoConfig).inited) ? (this as VideoConfig).dom.videoElement.poster : value; }, set(value: string) { if (!(this as VideoConfig).dispatcher.videoConfigReady) { return value; } if (value.length) { (this as VideoConfig).dom.setAttr('videoElement', 'poster', value); } return value; }, }), ], preload: [ accessor({ set(value: 'none' | 'auto' | 'metadata' | '') { const options = [ 'none', 'auto', 'metadata', '' ]; return options.indexOf(value) > -1 ? value : 'none'; }, }, { preSet: true, }), accessorVideoAttribute('preload'), ], src: [ alwaysString(), accessor({ set(val: string) { // must check val !== (this as VideoConfig).src here // as we will set config.src in the video // the may cause dead lock if ((this as VideoConfig).dispatcher.readySync && (this as VideoConfig).autoload && val !== (this as VideoConfig).src) { (this as VideoConfig).needToLoadSrc = true; } return val; }, }), accessor({ set(val: string) { if ((this as VideoConfig).needToLoadSrc) { // unlock it at first, to avoid deadlock (this as VideoConfig).needToLoadSrc = false; (this as VideoConfig).dispatcher.binder.emit({ id: 'dispatcher', name: 'load', target: 'plugin', }, val); } return val; }, }, { preSet: false }), ], volume: [ alwaysNumber(1), accessorVideoProperty('volume'), ], width: [ accessorWidthAndHeight('width'), ], x5VideoOrientation: [ accessor({ set: stringOrVoid }), accessorCustomAttribute('x5-video-orientation'), ], x5VideoPlayerFullscreen: [ accessor({ set(value: boolean) { return !!value; }, get(value: boolean) { return !!value; } }), accessorCustomAttribute('x5-video-player-fullscreen', true), ], x5VideoPlayerType: [ accessor({ set(value: 'h5' | undefined) { if (!(this as VideoConfig).dispatcher.videoConfigReady) { return value; } const val = value === 'h5' ? 'h5' : undefined; (this as VideoConfig).dom.setAttr('videoElement', 'x5-video-player-type', val); return value; }, get(value: 'h5' | undefined) { return ((this as VideoConfig).dispatcher.videoConfigReady && value) || ((this as VideoConfig).dom.getAttr('videoElement', 'x5-video-player-type') ? 'h5' : undefined); }, }), ], xWebkitAirplay: [ accessor({ set(value: boolean) { return !!value; }, get(value: boolean) { return !!value; } }), accessorCustomAttribute('x-webkit-airplay', true), ], }; export default class VideoConfig { public autoload: boolean = true; public autoplay: boolean = false; // 此处 box 只能置空,因为 kernel 会自动根据你的安装 kernel 和相关地址作智能判断。 // 曾经 bug 详见 https://github.com/Chimeejs/chimee-kernel/issues/1 @initString((str: string) => str.toLocaleLowerCase()) public box: 'mp4' | 'hls' | 'flv' | '' = ''; // TODO: the watchable flag should not be placed into config @nonenumerable public changeWatchable: boolean = true; public controls: boolean = false; public crossOrigin: string | void = undefined; public defaultMuted: boolean = false; public defaultPlaybackRate: number = 1; public disableRemotePlayback: boolean = false; public dispatcher: Dispatcher; public dom: Dom; public height: string | number | void = '100%'; // TODO: inited flag should not be placed into config @nonenumerable public inited: boolean = false; public isLive: boolean = false; // kernels 不在 videoConfig 上设置默认值,防止判断出错 public kernels: UserKernelsConfig; public loop: boolean = false; public muted: boolean = false; @nonenumerable public needToLoadSrc: boolean = false; public playbackRate: number = 1; public playsInline = false; public poster: string = undefined; public preload: 'none' | 'auto' | 'metadata' | '' = 'auto'; // 转为供 kernel 使用的内部参数 public preset: { [key in SupportedKernelType]?: IVideoKernelConstructor } = {}; public presetConfig: any = {}; public src: string = ''; public volume: number = 1; public width: string | number | void = '100%'; public x5VideoOrientation: 'landscape' | 'portrait' | undefined = undefined; public x5VideoPlayerFullscreen: boolean = false; public x5VideoPlayerType: 'h5' | undefined = undefined; public xWebkitAirplay: boolean = false; constructor(dispatcher: Dispatcher, config: UserConfig) { applyDecorators(this, accessorMap, { self: true }); Object.defineProperty(this, 'dispatcher', { configurable: false, enumerable: false, value: dispatcher, writable: false, }); Object.defineProperty(this, 'dom', { configurable: false, enumerable: false, value: dispatcher.dom, writable: false, }); Object.assign(this, config); // deepAssign(this, config); } public init() { videoDomAttributes.forEach((key) => { this[key] = this[key]; }); this.inited = true; } }
the_stack
import { mochaExpress, mochaTmpdir } from "@adpt/testutils"; import { MaybeArray, readJson5, toArray, waitForNoThrow } from "@adpt/utils"; import db from "debug"; import dedent from "dedent"; import fs from "fs-extra"; import path from "path"; import which from "which"; import { userConfigSchema } from "../../src/config/config"; import { createState } from "../../src/config/load"; import { hasSecurityFixes, UpgradeChecker, UpgradeCheckerConfig } from "../../src/upgrade/upgrade_checker"; import { VersionSummary } from "../../src/upgrade/versions"; import { clitest, expect } from "../common/fancy"; // tslint:disable-next-line: no-var-requires const pjson = require("../../../package.json"); const ONE_HOUR = 60 * 60 * 1000; const showOutput = false; const basicTestChain = clitest .stdout({ print: showOutput }) .stderr({ print: showOutput }) // fancy-test types are incorrect. See https://github.com/oclif/fancy-test/issues/113 .stub(process.stdout, "isTTY", false as any); // Turn off progress, etc const ttyTestChain = clitest .stdout({ print: showOutput }) .stderr({ print: showOutput }) // fancy-test types are incorrect. See https://github.com/oclif/fancy-test/issues/113 .stub(process.stdout, "isTTY", true as any); // Turn on upgrade output const testDebugOutput = basicTestChain .add("savedDebugs", () => { const saved = db.disable(); db.enable(saved + saved ? "," : "" + "adapt:upgrade"); return saved; }) .finally((ctx) => db.enable(ctx.savedDebugs)); const mockUpgradePath = "/path/to/check"; const latest101: VersionSummary = { name: "@adpt/cli", channelCurrent: { latest: "1.0.1", next: "1.0.2-next.1", security: "1.0.1-security.1", both: "1.0.1-both.1", }, versions: { "1.0.1": { channel: "latest", description: "Fixes for FooCloud", }, "1.0.2-next.1": { channel: "next", description: "Some new feature work", }, "1.0.1-security.1": { channel: "security", securityFixes: true, }, "1.0.1-both.1": { channel: "both", description: "Some new feature work", securityFixes: true, } } }; const badChannelCurrent = { ...latest101 }; (badChannelCurrent as any).channelCurrent = "badvalue"; async function readStateJson() { return readJson5(".state.json"); } async function readUpgradeLog() { const buf = await fs.readFile("upgrade-check.log"); return buf.toString(); } // Examples: 19.03.5 18.09.9-ce const dockerVerRegex = "\\d+\\.\\d+\\.\\d+(?:-[a-z]+)?"; // Example: v10.15.3 const nodeVerRegex = "v\\d+\\.\\d+\\.\\d+"; interface UaOptions { docker?: "client" | "both"; dev?: boolean; } function uaRegex(options: UaOptions = {}) { const { docker, dev } = options; const name = pjson.name.replace(/\//g, "-"); const dockerRe = docker === "client" ? ` Docker/${dockerVerRegex}` : docker === "both" ? ` Docker/${dockerVerRegex}\\+${dockerVerRegex}` : ""; const devRe = dev ? ` Dev/${dev}` : ""; const platform = process.platform === "win32" ? "Windows_NT" : "Linux"; // Only Windows runs tests without Docker const re = `^${name}/1.0.0 ${platform}/[^ ]+-x64 Node/${nodeVerRegex}${devRe}${dockerRe}$`; return RegExp(re); } function removeExesFromPath(exes: string[]): string { const pathSet = new Set(process.env.PATH!.split(path.delimiter)); for (const exe of exes) { const absExes = which.sync(exe, { all: true, nothrow: true }); if (!absExes) continue; for (const absExe of absExes) { pathSet.delete(path.dirname(absExe)); } } return [...pathSet].join(path.delimiter); } const pathNoGitOrDocker = removeExesFromPath(["docker", "git"]); function expressSaveRequests(fixture: mochaExpress.ExpressFixture, route: string, response: any) { const headerList: mochaExpress.Request[] = []; fixture.app.get(route, (req, res) => { headerList.push(req); res.send(response); }); return headerList; } describe("UpgradeChecker", function () { let state: ReturnType<typeof createState>; let ucConfig: UpgradeCheckerConfig; this.slow(3 * 1000); this.timeout(10 * 1000); mochaTmpdir.each("adapt-cli-test-upgrade"); const mockServer = mochaExpress.each(); beforeEach(() => { state = createState(process.cwd()); ucConfig = { channel: "latest", configDir: process.cwd(), logDir: process.cwd(), timeout: 1000, upgradeCheckInterval: 0, upgradeCheckUrl: mockServer.url + mockUpgradePath, upgradeRemindInterval: ONE_HOUR, upgradeIgnore: "", }; state.set("version", "1.0.0"); }); testDebugOutput .it("Should not check on first run", async (ctx) => { // The first check will not happen until this many ms have // passed since createState() was called initially. For this test, // an hour should be sufficiently far in the future. ucConfig.upgradeCheckInterval = ONE_HOUR; const checker = new UpgradeChecker(ucConfig, state); await checker.check(); expect(ctx.stderr).matches(/Not time to check/); }); async function runAndCheckSuccess(expVersion?: string) { const origState = await readStateJson(); expect(origState.upgrade).to.be.undefined; expect(origState.lastUpgradeCheck).to.be.a("number"); const checker = new UpgradeChecker(ucConfig, state); await checker.check(); await waitForNoThrow(5, 1, async () => { await readUpgradeLog(); expect(checker.upgrade).is.ok; }); const upgrade = checker.upgrade; if (!upgrade) throw expect(upgrade).to.be.ok; expect(upgrade.latest).to.be.a("string"); if (expVersion) expect(upgrade.latest).equals(expVersion); const newState = await readStateJson(); expect(newState.upgrade).is.ok; expect(newState.lastUpgradeCheck).is.greaterThan(origState.lastUpgradeCheck); return checker; } testDebugOutput .it("Should fetch upgrade URL", async (ctx) => { // Return a valid VersionSummary mockServer.app.get(mockUpgradePath, (_req, res) => res.json(latest101)); const checker = await runAndCheckSuccess("1.0.1"); expect(ctx.stderr).matches(/Spawning child/); // isTty is false, so there should be no message expect(await checker.notifyString()).to.be.undefined; }); basicTestChain .it("Should send headers with Dev and Docker client+server", async () => { const origState = await readStateJson(); expect(origState.installed).to.be.a("number"); const reqs = expressSaveRequests(mockServer, mockUpgradePath, latest101); await runAndCheckSuccess("1.0.1"); expect(reqs.length).is.greaterThan(0); const req = reqs[0]; expect(req.headers["user-agent"]).to.match(uaRegex({ dev: true, docker: "both", })); expect(req.query["x-installed"]).to.equal(origState.installed.toString()); }); testDebugOutput .env({ PATH: pathNoGitOrDocker, Path: pathNoGitOrDocker, // Ugh. Windows. }) .it("Should send headers without Dev and Docker", async () => { const origState = await readStateJson(); expect(origState.installed).to.be.a("number"); const reqs = expressSaveRequests(mockServer, mockUpgradePath, latest101); await runAndCheckSuccess("1.0.1"); expect(reqs.length).is.greaterThan(0); const req = reqs[0]; expect(req.headers["user-agent"]).to.match(uaRegex()); expect(req.query["x-installed"]).to.equal(origState.installed.toString()); }); const badDockerHost = process.platform === "win32" ? "npipe:///badhost" : "unix:///dev/null"; testDebugOutput .env({ DOCKER_HOST: badDockerHost }) .it("Should send headers with Dev and Docker client only", async () => { const origState = await readStateJson(); expect(origState.installed).to.be.a("number"); const reqs = expressSaveRequests(mockServer, mockUpgradePath, latest101); await runAndCheckSuccess("1.0.1"); expect(reqs.length).is.greaterThan(0); const req = reqs[0]; expect(req.headers["user-agent"]).to.match(uaRegex({ dev: true, docker: "client", })); expect(req.query["x-installed"]).to.equal(origState.installed.toString()); }); basicTestChain .it("Should fetch upgrade URL from test S3", async () => { ucConfig.upgradeCheckUrl = "https://adpt-temp-test.s3-us-west-2.amazonaws.com/latest101"; await runAndCheckSuccess("1.0.1"); }); basicTestChain .it("Should fetch upgrade URL from prod S3", async () => { ucConfig.upgradeCheckUrl = userConfigSchema.upgradeCheckUrl.default; await runAndCheckSuccess(); }); ttyTestChain .it("Should create message when newer version is available", async () => { mockServer.app.get(mockUpgradePath, (_req, res) => res.json(latest101)); const checker = await runAndCheckSuccess("1.0.1"); expect(await checker.notifyString()).equals(dedent `Upgrade available: 1.0.0 → 1.0.1 1.0.1: Fixes for FooCloud Upgrade: yarn add @adpt/cli@1.0.1 Ignore: adapt config:set upgradeIgnore 1.0.1 `); }); ttyTestChain .it("Should not create message when newer version is ignored", async () => { ucConfig.upgradeIgnore = "1.0.1"; mockServer.app.get(mockUpgradePath, (_req, res) => res.json(latest101)); const checker = await runAndCheckSuccess("1.0.1"); expect(await checker.notifyString()).is.undefined; }); ttyTestChain .it("Should create message when user sets channel to next and newer version is available", async () => { ucConfig.channel = "next"; mockServer.app.get(mockUpgradePath, (_req, res) => res.json(latest101)); const checker = await runAndCheckSuccess("1.0.2-next.1"); expect(await checker.notifyString()).equals(dedent `Upgrade available: 1.0.0 → 1.0.2-next.1 1.0.2-next.1: Some new feature work Upgrade: yarn add @adpt/cli@1.0.2-next.1 Ignore: adapt config:set upgradeIgnore 1.0.2-next.1 `); }); ttyTestChain .it("Should create message with security fixes", async () => { ucConfig.channel = "security"; mockServer.app.get(mockUpgradePath, (_req, res) => res.json(latest101)); const checker = await runAndCheckSuccess("1.0.1-security.1"); expect(await checker.notifyString()).equals(dedent `Upgrade available: 1.0.0 → 1.0.1-security.1 This upgrade contains security fixes Upgrade: yarn add @adpt/cli@1.0.1-security.1 Ignore: adapt config:set upgradeIgnore 1.0.1-security.1 `); }); ttyTestChain .it("Should create message with description and security fixes", async () => { ucConfig.channel = "both"; mockServer.app.get(mockUpgradePath, (_req, res) => res.json(latest101)); const checker = await runAndCheckSuccess("1.0.1-both.1"); expect(await checker.notifyString()).equals(dedent `Upgrade available: 1.0.0 → 1.0.1-both.1 1.0.1-both.1: Some new feature work This upgrade contains security fixes Upgrade: yarn add @adpt/cli@1.0.1-both.1 Ignore: adapt config:set upgradeIgnore 1.0.1-both.1 `); }); ttyTestChain .it("Should not create message when same version is available", async () => { state.set("version", "1.0.1"); mockServer.app.get(mockUpgradePath, (_req, res) => res.json(latest101)); const checker = await runAndCheckSuccess("1.0.1"); expect(await checker.notifyString()).is.undefined; }); ttyTestChain .it("Should not create message when older version is available", async () => { state.set("version", "1.0.2-next.1"); mockServer.app.get(mockUpgradePath, (_req, res) => res.json(latest101)); const checker = await runAndCheckSuccess("1.0.1"); expect(await checker.notifyString()).is.undefined; }); ttyTestChain .it("Should show message once per remind interval", async () => { mockServer.app.get(mockUpgradePath, (_req, res) => res.json(latest101)); const checker = await runAndCheckSuccess("1.0.1"); const msg = dedent `Upgrade available: 1.0.0 → 1.0.1 1.0.1: Fixes for FooCloud Upgrade: yarn add @adpt/cli@1.0.1 Ignore: adapt config:set upgradeIgnore 1.0.1 `; expect(await checker.notifyString()).equals(msg); // Should not show a second time expect(await checker.notifyString()).is.undefined; // Pretend last time we showed the message was an hour ago state.set("lastUpgradeReminder", Date.now() - ONE_HOUR); // Now should get the message again expect(await checker.notifyString()).equals(msg); }); /* * Error testing */ async function runAndCheckError(logMatches: MaybeArray<RegExp>) { const matches = toArray(logMatches); const origState = await readStateJson(); expect(origState.upgrade).to.be.undefined; expect(origState.lastUpgradeCheck).to.be.a("number"); const checker = new UpgradeChecker(ucConfig, state); await checker.check(); let log; // Wait for the child to fail await waitForNoThrow(5, 1, async () => { log = await readUpgradeLog(); expect(log).matches(/FAILED: Error running upgrade check/); }); for (const match of matches) { expect(log).matches(match); } const upgrade = checker.upgrade; expect(upgrade).to.be.undefined; const newState = await readStateJson(); expect(newState.upgrade).is.undefined; expect(newState.lastUpgradeCheck).to.equal(origState.lastUpgradeCheck); return log; } basicTestChain // Ensure child always logs even without DEBUG set .it("Should log error on 404", async () => { // Return a 404 mockServer.app.get(mockUpgradePath, (_req, res) => { res.status(404).send("Nope not here"); }); await runAndCheckError(/Status 404.*Nope not here/); }); basicTestChain .it("Should log error on non-JSON response", async () => { mockServer.app.get(mockUpgradePath, (_req, res) => res.send("Not JSON!\n")); await runAndCheckError([ /Invalid JSON response/, /Upgrade check response: Not JSON!\n/ ]); }); basicTestChain .it("Should log error on response with invalid channelCurrent", async () => { mockServer.app.get(mockUpgradePath, (_req, res) => res.json(badChannelCurrent)); await runAndCheckError(/Invalid response: Invalid channelCurrent property/); }); basicTestChain .it("Should log error on timeout", async () => { ucConfig.timeout = 100; mockServer.app.get(mockUpgradePath, (_req, res) => { // Delay longer than the configured timeout setTimeout(() => res.json(latest101), 150); }); await runAndCheckError(/Error fetching version information: network timeout/); }); }); const secSum: VersionSummary = { name: "@adpt/cli", channelCurrent: { }, versions: { "1.0.1-nofixes.0": { channel: "nofixes", }, "1.0.1-nofixes.1": { channel: "nofixes", }, "1.0.1-fixeslatest.0": { channel: "fixeslatest", }, "1.0.1-fixeslatest.1": { channel: "fixeslatest", securityFixes: true, }, "1.0.1-fixescurrent.0": { channel: "fixescurrent", securityFixes: true, }, "1.0.1-fixescurrent.1": { channel: "fixescurrent", }, "1.0.1-intermediate.0": { channel: "intermediate", }, "1.0.1-intermediate.1": { channel: "intermediate", securityFixes: true, }, "1.0.1-intermediate.2": { channel: "intermediate", }, } }; describe("hasSecurityFixes", () => { it("Should ignore wrong channel", () => { expect(hasSecurityFixes("1.0.1-nofixes.0", "1.0.1-nofixes.1", "nofixes", secSum)) .to.be.false; }); it("Should have fixes in latest", () => { expect(hasSecurityFixes("1.0.1-fixeslatest.0", "1.0.1-fixeslatest.1", "fixeslatest", secSum)) .to.be.true; }); it("Should not have fixes in current", () => { expect(hasSecurityFixes("1.0.1-fixescurrent.0", "1.0.1-fixescurrent.1", "fixescurrent", secSum)) .to.be.false; }); it("Should have fixes in intermediate releases", () => { expect(hasSecurityFixes("1.0.1-intermediate.0", "1.0.1-intermediate.2", "intermediate", secSum)) .to.be.true; }); });
the_stack
import * as ABIDecoder from "abi-decoder"; import * as _ from "lodash"; import * as omit from "lodash.omit"; import * as singleLineString from "single-line-string"; import * as Web3 from "web3"; // Utils import { BigNumber } from "../../utils/bignumber"; import { NULL_ADDRESS } from "../../utils/constants"; import * as TransactionUtils from "../../utils/transaction_utils"; import { Web3Utils } from "../../utils/web3_utils"; // Apis import { ContractsAPI } from "../apis"; // Invariants import { Assertions } from "../invariants"; // Types import { DebtOrderData, DebtRegistryEntry, RepaymentSchedule, TxData } from "../types"; import { CollateralizedLoanTerms } from "./collateralized_simple_interest_loan_terms"; import { SimpleInterestLoanOrder, SimpleInterestTermsContractParameters, } from "./simple_interest_loan_adapter"; import { SimpleInterestLoanTerms } from "./simple_interest_loan_terms"; import { Adapter } from "./adapter"; import { ERC20Contract } from "../wrappers"; const SECONDS_IN_DAY = 60 * 60 * 24; const TRANSFER_GAS_MAXIMUM = 200000; // Extend order to include parameters necessary for a collateralized terms contract. export interface CollateralizedSimpleInterestLoanOrder extends SimpleInterestLoanOrder { collateralTokenSymbol: string; collateralAmount: BigNumber; gracePeriodInDays: BigNumber; } export interface CollateralizedTermsContractParameters { collateralTokenIndex: BigNumber; collateralAmount: BigNumber; gracePeriodInDays: BigNumber; } export interface CollateralizedSimpleInterestTermsContractParameters extends SimpleInterestTermsContractParameters, CollateralizedTermsContractParameters {} export const CollateralizerAdapterErrors = { INVALID_TOKEN_INDEX: (tokenIndex: BigNumber) => singleLineString`Token Registry does not track a token at index ${tokenIndex.toString()}.`, COLLATERAL_AMOUNT_MUST_BE_POSITIVE: () => singleLineString`Collateral amount must be greater than zero.`, COLLATERAL_AMOUNT_EXCEEDS_MAXIMUM: () => singleLineString`Collateral amount exceeds maximum value of 2^92 - 1.`, INSUFFICIENT_COLLATERAL_TOKEN_ALLOWANCE: () => `Debtor has not granted sufficient allowance for collateral transfer.`, INSUFFICIENT_COLLATERAL_TOKEN_BALANCE: () => `Debtor does not have sufficient balance required for collateral transfer.`, GRACE_PERIOD_IS_NEGATIVE: () => singleLineString`The grace period cannot be negative.`, GRACE_PERIOD_EXCEEDS_MAXIMUM: () => singleLineString`The grace period exceeds the maximum value of 2^8 - 1`, INVALID_DECIMAL_VALUE: () => singleLineString`Values cannot be expressed as decimals.`, MISMATCHED_TOKEN_SYMBOL: (tokenAddress: string, symbol: string) => singleLineString`Terms contract parameters are invalid for the given debt order. Token at address ${tokenAddress} does not correspond to specified token with symbol ${symbol}`, MISMATCHED_TERMS_CONTRACT: (termsContractAddress: string) => singleLineString`Terms contract at address ${termsContractAddress} is not a CollateralizedSimpleInterestTermsContract. As such, this adapter will not interface with the terms contract as expected`, COLLATERAL_NOT_FOUND: (agreementId: string) => singleLineString`Collateral was not found for given agreement ID ${agreementId}. Make sure that the agreement ID is correct, and that the collateral has not already been withdrawn.`, DEBT_NOT_YET_REPAID: (agreementId: string) => singleLineString`Debt has not been fully repaid for loan with agreement ID ${agreementId}`, LOAN_NOT_IN_DEFAULT_FOR_GRACE_PERIOD: (agreementId: string) => singleLineString`Loan with agreement ID ${agreementId} is not currently in a state of default when adjusted for grace period`, }; export class CollateralizedSimpleInterestLoanAdapter implements Adapter { private assert: Assertions; private readonly contractsAPI: ContractsAPI; private simpleInterestLoanTerms: SimpleInterestLoanTerms; private collateralizedLoanTerms: CollateralizedLoanTerms; private web3Utils: Web3Utils; private web3: Web3; public constructor(web3: Web3, contractsAPI: ContractsAPI) { this.assert = new Assertions(web3, contractsAPI); this.web3Utils = new Web3Utils(web3); this.web3 = web3; this.contractsAPI = contractsAPI; this.simpleInterestLoanTerms = new SimpleInterestLoanTerms(web3, contractsAPI); this.collateralizedLoanTerms = new CollateralizedLoanTerms(web3, contractsAPI); } public async toDebtOrder( collateralizedSimpleInterestLoanOrder: CollateralizedSimpleInterestLoanOrder, ): Promise<DebtOrderData> { this.assert.schema.collateralizedSimpleInterestLoanOrder( "collateralizedSimpleInterestLoanOrder", collateralizedSimpleInterestLoanOrder, ); const { // destructure simple interest loan order params. principalTokenSymbol, principalAmount, interestRate, amortizationUnit, termLength, // destructure collateralized loan order params. collateralTokenSymbol, collateralAmount, gracePeriodInDays, } = collateralizedSimpleInterestLoanOrder; const principalToken = await this.contractsAPI.loadTokenBySymbolAsync(principalTokenSymbol); const principalTokenIndex = await this.contractsAPI.getTokenIndexBySymbolAsync( principalTokenSymbol, ); const collateralTokenIndex = await this.contractsAPI.getTokenIndexBySymbolAsync( collateralTokenSymbol, ); const collateralizedContract = await this.contractsAPI.loadCollateralizedSimpleInterestTermsContract(); let debtOrderData: DebtOrderData = omit(collateralizedSimpleInterestLoanOrder, [ // omit the simple interest parameters that will be packed // into the `termsContractParameters`. "principalTokenSymbol", "interestRate", "amortizationUnit", "termLength", // omit the collateralized parameters that will be packed into // the `termsContractParameters`. "collateralTokenSymbol", "collateralAmount", "gracePeriodInDays", ]); // Our final output is the perfect union of the packed simple interest params and the packed // collateralized params. const packedParams = this.packParameters( { principalTokenIndex, principalAmount, interestRate, amortizationUnit, termLength, }, { collateralTokenIndex, collateralAmount, gracePeriodInDays, }, ); debtOrderData = { ...debtOrderData, principalToken: principalToken.address, termsContract: collateralizedContract.address, termsContractParameters: packedParams, }; return TransactionUtils.applyNetworkDefaults(debtOrderData, this.contractsAPI); } /** * Validates that the basic invariants have been met for a given * CollateralizedSimpleInterestLoanOrder. * * @param {CollateralizedSimpleInterestLoanOrder} loanOrder * @returns {Promise<void>} */ public async validateAsync(loanOrder: CollateralizedSimpleInterestLoanOrder) { const unpackedParams = this.unpackParameters(loanOrder.termsContractParameters); this.collateralizedLoanTerms.assertValidParams(unpackedParams); await this.assertCollateralBalanceAndAllowanceInvariantsAsync(loanOrder); } /** * Given a valid debt order, returns a promise for a CollateralizedSimpleInterestLoanOrder, * which includes the DebtOrder information as well as as the contract terms (see documentation * on the `CollateralizedSimpleInterestLoanOrder` interface for more information.) * * @param {DebtOrderData} debtOrderData * @returns {Promise<CollateralizedSimpleInterestLoanOrder>} */ public async fromDebtOrder( debtOrderData: DebtOrderData, ): Promise<CollateralizedSimpleInterestLoanOrder> { this.assert.schema.debtOrderWithTermsSpecified("debtOrder", debtOrderData); const { principalTokenIndex, collateralTokenIndex, ...params } = this.unpackParameters( debtOrderData.termsContractParameters, ); const principalTokenSymbol = await this.contractsAPI.getTokenSymbolByIndexAsync( principalTokenIndex, ); const collateralTokenSymbol = await this.contractsAPI.getTokenSymbolByIndexAsync( collateralTokenIndex, ); // Assert that the principal token corresponds to the symbol we've unpacked. await this.assertTokenCorrespondsToSymbol( debtOrderData.principalToken, principalTokenSymbol, ); return { ...debtOrderData, principalTokenSymbol, collateralTokenSymbol, ...params, }; } /** * Given a valid DebtRegistryEntry, returns a CollateralizedSimpleInterestLoanOrder. * * @param {DebtRegistryEntry} entry * @returns {Promise<CollateralizedSimpleInterestLoanOrder>} */ public async fromDebtRegistryEntry( entry: DebtRegistryEntry, ): Promise<CollateralizedSimpleInterestLoanOrder> { await this.assertIsCollateralizedSimpleInterestTermsContract(entry.termsContract); const { principalTokenIndex, collateralTokenIndex, ...params } = this.unpackParameters( entry.termsContractParameters, ); const principalTokenSymbol = await this.contractsAPI.getTokenSymbolByIndexAsync( principalTokenIndex, ); const collateralTokenSymbol = await this.contractsAPI.getTokenSymbolByIndexAsync( collateralTokenIndex, ); const loanOrder: CollateralizedSimpleInterestLoanOrder = { principalTokenSymbol, collateralTokenSymbol, ...params, }; return loanOrder; } /** * Given a valid DebtRegistryEntry, returns an array of repayment dates (as unix timestamps.) * * @example * adapter.getRepaymentSchedule(debtEntry); * => [1521506879] * * @param {DebtRegistryEntry} debtEntry * @returns {number[]} */ public getRepaymentSchedule(debtEntry: DebtRegistryEntry): number[] { const { termsContractParameters, issuanceBlockTimestamp } = debtEntry; const { termLength, amortizationUnit } = this.unpackParameters(termsContractParameters); return new RepaymentSchedule( amortizationUnit, termLength, issuanceBlockTimestamp.toNumber(), ).toArray(); } /** * Seizes the collateral from the given debt agreement and * transfers it to the debt agreement's beneficiary. * * @param {string} agreementId * @param {TxData} options * @returns {Promise<string>} The transaction's hash. */ public async seizeCollateralAsync(agreementId: string, options?: TxData): Promise<string> { this.assert.schema.bytes32("agreementId", agreementId); const defaultOptions = await this.getTxDefaultOptions(); const transactionOptions = _.assign(defaultOptions, options); await this.assertDebtAgreementExists(agreementId); await this.assertCollateralSeizeable(agreementId); const collateralizerContract = await this.contractsAPI.loadCollateralizerAsync(); return collateralizerContract.seizeCollateral.sendTransactionAsync( agreementId, transactionOptions, ); } /** * Returns collateral to the debt agreement's original collateralizer * if and only if the debt agreement's term has lapsed and * the total expected repayment value has been repaid. * * @param {string} agreementId * @param {TxData} options * @returns {Promise<string>} The transaction's hash. */ public async returnCollateralAsync(agreementId: string, options?: TxData): Promise<string> { this.assert.schema.bytes32("agreementId", agreementId); await this.assertDebtAgreementExists(agreementId); await this.assertCollateralReturnable(agreementId); const defaultOptions = await this.getTxDefaultOptions(); const transactionOptions = _.assign(defaultOptions, options); const collateralizerContract = await this.contractsAPI.loadCollateralizerAsync(); return collateralizerContract.returnCollateral.sendTransactionAsync( agreementId, transactionOptions, ); } public unpackParameters( termsContractParameters: string, ): CollateralizedSimpleInterestTermsContractParameters { const simpleInterestParams = this.simpleInterestLoanTerms.unpackParameters( termsContractParameters, ); const collateralizedParams = this.collateralizedLoanTerms.unpackParameters( termsContractParameters, ); return { ...simpleInterestParams, ...collateralizedParams, }; } public packParameters( simpleTermsParams: SimpleInterestTermsContractParameters, collateralTermsParams: CollateralizedTermsContractParameters, ): string { const packedSimpleInterestParams = this.simpleInterestLoanTerms.packParameters( simpleTermsParams, ); const packedCollateralizedParams = this.collateralizedLoanTerms.packParameters( collateralTermsParams, ); // Our final output is the perfect union of the packed simple interest params and the packed // collateralized params. return packedSimpleInterestParams.substr(0, 39) + packedCollateralizedParams.substr(39, 27); } /** * Given an agreement ID for a valid collateralized debt agreement, returns true if the * collateral is returnable according to the terms of the agreement - I.E. the debt * has been repaid, and the collateral has not already been withdrawn. * * @example * await adapter.canReturnCollateral( * "0x21eee309abd17832e55d231fb4147334081ed6da543d226c035d4b2420c68a7f" * ); * => true * * @param {string} agreementId * @returns {Promise<boolean>} */ public async canReturnCollateral(agreementId: string): Promise<boolean> { try { await this.assertCollateralReturnable(agreementId); return true; } catch (e) { return false; } } /** * Given an agreement ID for a valid collateralized debt agreement, returns true if the * collateral can be seized by the creditor, according to the terms of the agreement. Collateral * is seizable if the collateral has not been withdrawn yet, and the loan has been in a state * of default for a duration of time greater than the grace period. * * @example * await adapter.canSeizeCollateral( * "0x21eee309abd17832e55d231fb4147334081ed6da543d226c035d4b2420c68a7f" * ); * => true * * @param {string} agreementId * @returns {Promise<boolean>} */ public async canSeizeCollateral(agreementId: string): Promise<boolean> { try { await this.assertCollateralSeizeable(agreementId); return true; } catch (e) { return false; } } /** * Returns true if the collateral associated with the given agreement ID * has already been seized or returned. * * @example * await adapter.isCollateralWithdrawn( * "0x21eee309abd17832e55d231fb4147334081ed6da543d226c035d4b2420c68a7f" * ); * => true * * @param {string} agreementId * @returns {Promise<boolean>} */ public async isCollateralWithdrawn(agreementId: string): Promise<boolean> { const collateralizerContract = await this.contractsAPI.loadCollateralizerAsync(); const collateralizerAddress = await collateralizerContract.agreementToCollateralizer.callAsync( agreementId, ); return collateralizerAddress === NULL_ADDRESS; } /** * Eventually returns true if the collateral associated with the given debt agreement ID * was returned to the debtor. * * @example * await adapter.isCollateralReturned("0x21eee309abd17832e55d231fb4147334081ed6da543d226c035d4b2420c68a7f") * => true * * @param {string} agreementId * @returns {Promise<boolean>} */ public async isCollateralReturned(agreementId: string): Promise<boolean> { return this.eventEmittedForAgreement("CollateralReturned", agreementId); } /** * Eventually returns true if the collateral associated with the given debt agreement ID * was seized by the creditor. * * @example * await adapter.isCollateralSeized("0x21eee309abd17832e55d231fb4147334081ed6da543d226c035d4b2420c68a7f") * => true * * @param {string} agreementId * @returns {Promise<boolean>} */ public async isCollateralSeized(agreementId: string): Promise<boolean> { return this.eventEmittedForAgreement("CollateralSeized", agreementId); } private async eventEmittedForAgreement( eventName: string, agreementId: string, ): Promise<boolean> { // We use the contract registry to get the address of the collateralizer contract. const contractRegistry = await this.contractsAPI.loadContractRegistryAsync(); // Collateralizer contract is required for decoding logs. const collateralizer = await this.contractsAPI.loadCollateralizerAsync(); const collateralizerAddress = await contractRegistry.collateralizer.callAsync(); return new Promise<boolean>((resolve, reject) => { this.web3.eth .filter({ address: collateralizerAddress, fromBlock: 1, toBlock: "latest", topics: [null, agreementId, null], }) .get((err, result) => { if (err) { reject(err); } ABIDecoder.addABI(collateralizer.abi); const decodedResults = ABIDecoder.decodeLogs(result); ABIDecoder.removeABI(collateralizer.abi); const collateralReturnedEvent = _.find(decodedResults, (log: any) => { const foundEvent = _.find(log.events, (event: any) => { return event.name === "agreementID" && event.value === agreementId; }); return log.name === eventName && foundEvent; }); resolve(!_.isUndefined(collateralReturnedEvent)); }); }); } private async assertTokenCorrespondsToSymbol( tokenAddress: string, symbol: string, ): Promise<void> { const doesTokenCorrespondToSymbol = await this.contractsAPI.doesTokenCorrespondToSymbol( tokenAddress, symbol, ); if (!doesTokenCorrespondToSymbol) { throw new Error( CollateralizerAdapterErrors.MISMATCHED_TOKEN_SYMBOL(tokenAddress, symbol), ); } } private async assertIsCollateralizedSimpleInterestTermsContract( termsContractAddress: string, ): Promise<void> { const collateralizedSimpleInterestTermsContract = await this.contractsAPI.loadCollateralizedSimpleInterestTermsContract(); if (termsContractAddress !== collateralizedSimpleInterestTermsContract.address) { throw new Error( CollateralizerAdapterErrors.MISMATCHED_TERMS_CONTRACT(termsContractAddress), ); } } private async assertDebtAgreementExists(agreementId: string): Promise<void> { const debtTokenContract = await this.contractsAPI.loadDebtTokenAsync(); return this.assert.debtAgreement.exists( agreementId, debtTokenContract, CollateralizerAdapterErrors.COLLATERAL_NOT_FOUND(agreementId), ); } /** * Collateral is seizable if the collateral has not been withdrawn yet, and the * loan has been in a state of default for a duration of time greater than the grace period. * * @param {string} agreementId * @returns {Promise<void>} */ private async assertCollateralSeizeable(agreementId: string): Promise<void> { const debtRegistry = await this.contractsAPI.loadDebtRegistryAsync(); const [termsContract, termsContractParameters] = await debtRegistry.getTerms.callAsync( agreementId, ); const unpackedParams = this.unpackParameters(termsContractParameters); this.collateralizedLoanTerms.assertValidParams(unpackedParams); await this.assertCollateralNotWithdrawn(agreementId); await this.assertDefaultedForGracePeriod(agreementId, unpackedParams.gracePeriodInDays); } /** * Collateral is returnable if the debt is repaid, and the collateral has not yet * been withdrawn. * * @param {string} agreementId * @returns {Promise<void>} */ private async assertCollateralReturnable(agreementId: string): Promise<void> { const debtRegistry = await this.contractsAPI.loadDebtRegistryAsync(); const [termsContract, termsContractParameters] = await debtRegistry.getTerms.callAsync( agreementId, ); const unpackedParams = this.unpackParameters(termsContractParameters); this.collateralizedLoanTerms.assertValidParams(unpackedParams); await this.assertCollateralNotWithdrawn(agreementId); await this.assertDebtRepaid(agreementId); } private async assertDebtRepaid(agreementId) { const debtRepaid = await this.debtRepaid(agreementId); if (!debtRepaid) { throw new Error(CollateralizerAdapterErrors.DEBT_NOT_YET_REPAID(agreementId)); } } private async assertDefaultedForGracePeriod(agreementId: string, gracePeriod: BigNumber) { const defaultedForGracePeriod = await this.defaultedForGracePeriod( agreementId, gracePeriod, ); if (!defaultedForGracePeriod) { throw new Error( CollateralizerAdapterErrors.LOAN_NOT_IN_DEFAULT_FOR_GRACE_PERIOD(agreementId), ); } } private async defaultedForGracePeriod( agreementId: string, gracePeriod: BigNumber, ): Promise<boolean> { const termsContract = await this.contractsAPI.loadCollateralizedSimpleInterestTermsContract(); const repaymentToDate = await termsContract.getValueRepaidToDate.callAsync(agreementId); const currentTime = await this.web3Utils.getCurrentBlockTime(); const timeAdjustedForGracePeriod = new BigNumber(currentTime).sub( gracePeriod.mul(SECONDS_IN_DAY), ); const minimumRepayment = await termsContract.getExpectedRepaymentValue.callAsync( agreementId, timeAdjustedForGracePeriod, ); return repaymentToDate.lt(minimumRepayment); } private async assertCollateralNotWithdrawn(agreementId) { const collateralWithdrawn = await this.isCollateralWithdrawn(agreementId); if (collateralWithdrawn) { throw new Error(CollateralizerAdapterErrors.COLLATERAL_NOT_FOUND(agreementId)); } } private async assertCollateralBalanceAndAllowanceInvariantsAsync( order: CollateralizedSimpleInterestLoanOrder, ) { const { collateralAmount, collateralTokenSymbol } = order; const collateralToken: ERC20Contract = await this.contractsAPI.loadTokenBySymbolAsync( collateralTokenSymbol, ); const tokenTransferProxy = await this.contractsAPI.loadTokenTransferProxyAsync(); await this.assert.order.sufficientCollateralizerAllowanceAsync( order, collateralToken, collateralAmount, tokenTransferProxy, CollateralizerAdapterErrors.INSUFFICIENT_COLLATERAL_TOKEN_ALLOWANCE(), ); await this.assert.order.sufficientCollateralizerBalanceAsync( order, collateralToken, collateralAmount, CollateralizerAdapterErrors.INSUFFICIENT_COLLATERAL_TOKEN_BALANCE(), ); } private async debtRepaid(agreementId: string): Promise<boolean> { const termsContract = await this.contractsAPI.loadCollateralizedSimpleInterestTermsContract(); const repaymentToDate = await termsContract.getValueRepaidToDate.callAsync(agreementId); const termEnd = await termsContract.getTermEndTimestamp.callAsync(agreementId); const expectedTotalRepayment = await termsContract.getExpectedRepaymentValue.callAsync( agreementId, termEnd, ); return repaymentToDate.gte(expectedTotalRepayment); } private async getTxDefaultOptions(): Promise<object> { const accounts = await this.web3Utils.getAvailableAddressesAsync(); // TODO: Add fault tolerance to scenario in which not addresses are available return { from: accounts[0], gas: TRANSFER_GAS_MAXIMUM, }; } }
the_stack
/// <reference path="guiobject.ts" /> module EZGUI { export class GUISprite extends GUIObject { public guiID: string; public userData: any; public draggable: PIXI.Container; public draghandle: any; public dragConstraint: string; public dragXInterval: number[] = [-Infinity, +Infinity]; public dragYInterval: number[] = [-Infinity, +Infinity]; public theme: Theme; //public container: PIXI.DisplayObjectContainer; protected textObj: any; protected rootSprite: any; //get settings(): string { // return this._settings; //} get text(): string { if (this.textObj) return this.textObj.text; } set text(val: string) { if (this.textObj) { if (Compatibility.PIXIVersion >= 3) { this.textObj.text = val; } else { this.textObj.setText(val); } if (this._settings.anchor) { this.textObj.position.x = 0; this.textObj.position.y = 0; if (this.textObj.anchor) { this.textObj.anchor.x = this._settings.anchor.x; this.textObj.anchor.y = this._settings.anchor.y; } else { //fake anchor for bitmap font this.textObj.position.x -= this.textObj.width / 2; this.textObj.position.y -= this.textObj.height / 2; } } else { this.textObj.position.x = (this._settings.width - this.textObj.width) / 2; this.textObj.position.y = (this._settings.height - this.textObj.height) / 2; if (this.textObj.anchor) { this.textObj.anchor.x = 0; this.textObj.anchor.y = 0; } } } } public _settings; //private savedSettings; constructor(public settings, public themeId:any) { super(); //this.container = new Compatibility.GUIContainer(); //this.addChild(this.container); this.userData = settings.userData; this.name = settings.name; if (themeId instanceof Theme) this.theme = themeId; else this.theme = EZGUI.themes[themeId]; if (!this.theme || !this.theme.ready) { console.error('[EZGUI ERROR]', 'Theme is not ready, nothing to display'); this.theme = new Theme({}); } //this.savedSettings = JSON.parse(JSON.stringify(_settings)); //this._settings = this.theme.applySkin(_settings); //this.parseSettings(); //this.draw(); //this.drawText(); //this.setupEvents(); //this.handleEvents(); this.rebuild(); } public erase() { this.container.children.length = 0;//clear all children this.children.length = 0; this.rootSprite = undefined; } public rebuild() { this.erase(); var _settings = JSON.parse(JSON.stringify(this.settings)); this._settings = this.theme.applySkin(_settings); this.parseSettings(); this.draw(); this.drawText(); this.setupEvents(); this.handleEvents(); } protected parsePercentageValue(str) { if (typeof str != 'string') return NaN; var val = NaN; var percentToken = str.split('%'); if (percentToken.length == 2 && percentToken[1] == '') { val = parseFloat(percentToken[0]); } return val; } protected parseSettings() { } protected prepareChildSettings(settings) { var padTop = this._settings['padding-top'] || this._settings.padding || 0; var padLeft = this._settings['padding-left'] || this._settings.padding || 0; var padBottom = this._settings['padding-bottom'] || this._settings.padding || 0; var padRight = this._settings['padding-right'] || this._settings.padding || 0; var padX = padRight + padLeft; var padY = padTop + padBottom; //var _psettings = this._settings; var _settings = JSON.parse(JSON.stringify(settings)); if (_settings) { //support percentage values for width and height if (typeof _settings.width == 'string') { var p = this.parsePercentageValue(_settings.width); if (p != NaN) _settings.width = (this.width - padX) * p / 100; } if (typeof _settings.height == 'string') { var p = this.parsePercentageValue(_settings.height); if (p != NaN) _settings.height = (this.height -padY) * p / 100; } if (typeof _settings.position == 'object') { if (typeof _settings.position.x == 'string') { var px = this.parsePercentageValue(_settings.position.x); if (px != NaN) _settings.position.x = (this.width - padX) * px / 100; } if (typeof _settings.position.y == 'string') { var py = this.parsePercentageValue(_settings.position.y); if (py != NaN) _settings.position.y = (this.height - padY) * py / 100; } } } return _settings; } public setDraggable(val=true) { if (val) this.draggable = this; else this.draggable = undefined; } protected handleEvents() { var __this = this; //var _this = this; this.draghandle = __this; if (__this._settings.draggable == true) { this.draggable = __this; } if (__this._settings.draggable == 'container') { this.draggable = __this.container; } if (__this._settings.dragX === false) { this.dragConstraint = 'y'; } if (__this._settings.dragY === false) { this.dragConstraint = 'x'; } //guiObj.on('mouseover', function () { // guiObj.setState('hover'); //}); //guiObj.on('mouseout', function () { // //EZGUI.dragging = null; // guiObj.setState('out'); //}); //handle drag stuff __this.on('mousedown', function (event: any) { if (__this.draggable) { if (__this.mouseInObj(event, __this.draghandle)) { //if PIXI 2 use event else use event.data var data = event.data || event; //guiObj.alpha = 0.9; EZGUI.dragging = __this; //console.log('set dragging', EZGUI.dragging.guiID); var pos = utils.getRealPos(event); EZGUI.dsx = pos.x; EZGUI.dsy = pos.y; EZGUI.startDrag.x = pos.x; EZGUI.startDrag.y = pos.y; } //event.stopped = true; } //only work in PIXI 3 ? //guiObj.setState('click'); }); __this.on('mouseup', function (event: any) { //guiObj.alpha = 1 EZGUI.dragging = null; __this.setState('default'); }); __this.on('mousemove', function (event) { if (EZGUI.dragging) { var dg = (<any>__this.draggable) ? (<any>__this.draggable).guiID : '' //console.log(' * dragging', dg, EZGUI.dragging.guiID, _this.guiID); } var PhaserDrag = typeof Phaser != 'undefined' && EZGUI.dragging; if (__this.draggable && EZGUI.dragging == __this || PhaserDrag) { var pos = utils.getRealPos(event); var dragObg = EZGUI.dragging; var draggable = EZGUI.dragging.draggable; var dpos = utils.getAbsPos(draggable); if (dragObg.dragConstraint != 'y') { var nextPos = draggable.position.x + pos.x - EZGUI.dsx; if (nextPos >= dragObg.dragXInterval[0] && nextPos <= dragObg.dragXInterval[1]) draggable.position.x = nextPos; } if (dragObg.dragConstraint != 'x') { var nextPos = draggable.position.y + pos.y - EZGUI.dsy; if (nextPos >= dragObg.dragYInterval[0] && nextPos <= dragObg.dragYInterval[1]) draggable.position.y = nextPos; } EZGUI.dsx = pos.x; EZGUI.dsy = pos.y; } }); } /** * Main draw function */ protected draw() { var settings = this._settings; if (settings) { this.guiID = settings.id; //add reference to component if (this.guiID) EZGUI.components[this.guiID] = this; for (var s = 0; s < Theme.imageStates.length; s++) { var stateId = Theme.imageStates[s]; var container = new Compatibility.GUIContainer(); var controls = this.createVisuals(settings, stateId); for (var i = 0; i < controls.length; i++) { container.addChild(controls[i]); } var texture = EZGUI.Compatibility.createRenderTexture(settings.width, settings.height); //texture.render(container); if (Compatibility.PIXIVersion >= 4) EZGUI.tilingRenderer.render(container, texture); else texture.render(container); //RenderTexture.render is now deprecated, please use renderer.render(displayObject, renderTexture) if (!this.rootSprite) { this.rootSprite = new MultistateSprite(texture); this.addChild(this.rootSprite); } else { this.rootSprite.addState(stateId, texture); } } var padding = settings.padding || 0; if (settings.position) { this.position.x = settings.position.x; this.position.y = settings.position.y; } else { this.position.x = 0; this.position.y = 0; } //this.container = new Compatibility.GUIContainer(); //this.addChild(this.container); if (settings.children) { for (var i = 0; i < settings.children.length; i++) { var btnObj = this.prepareChildSettings(settings.children[i]);// JSON.parse(JSON.stringify(settings.children[i])); var child:any = this.createChild(btnObj, i); if (!child) continue; //if (child.phaserGroup) this.container.addChild(child.phaserGroup); //else this.container.addChild(child); //force call original addChild to prevent conflict with local addchild super.addChild(child); child.guiParent = this; } } if (this._settings.anchor) { this.rootSprite.anchor.x = this._settings.anchor.x; this.rootSprite.anchor.y = this._settings.anchor.y; this.container.position.x -= this.rootSprite.width * this._settings.anchor.x; this.container.position.y -= this.rootSprite.height * this._settings.anchor.y; this.position.x += this.rootSprite.width * this._settings.anchor.x; this.position.y += this.rootSprite.height * this._settings.anchor.y; } //tint color if (this._settings.color) { var pixiColor = utils.ColorParser.parseToPixiColor(this._settings.color); if (pixiColor >= 0) { this.rootSprite.tint = pixiColor; } } //move container to top this.addChild(this.container); this.sortChildren(); } } protected sortChildren() { if (!this.container) return; var comparator: any = function (a, b) { if (a.guiSprite) a = a.guiSprite; if (b.guiSprite) b = b.guiSprite; a._settings.z = a._settings.z || 0; b._settings.z = b._settings.z || 0; return a._settings.z - b._settings.z; } this.container.children.sort(comparator); } /** * Text draw function * shared by all components */ protected drawText() { if (this._settings && this._settings.text!=undefined && this.rootSprite) { //var settings = this.theme.applySkin(this._settings); var settings = this._settings; if (Compatibility.BitmapText.fonts && Compatibility.BitmapText.fonts[settings.font.family]) { this.textObj = new Compatibility.BitmapText(this._settings.text, { font: settings.font.size + ' ' + settings.font.family }); var pixiColor = utils.ColorParser.parseToPixiColor(settings.font.color); if (pixiColor >= 0) { this.textObj.tint = pixiColor; this.textObj.dirty = true; } } else { var style = { fontSize: settings.font.size, fontFamily: settings.font.family, fill: settings.font.color}; for (var s in settings.font) { if (!style[s]) style[s] = settings.font[s]; } this.textObj = new PIXI.Text(this._settings.text, style); } //text.height = this.height; this.textObj.position.x = 0;//(this._settings.width - this.textObj.width) / 2; this.textObj.position.y = 0;//(this._settings.height - this.textObj.height) / 2; if (this._settings.anchor) { this.textObj.position.x = 0; this.textObj.position.y = 0; if (this.textObj.anchor) { this.textObj.anchor.x = this._settings.anchor.x; this.textObj.anchor.y = this._settings.anchor.y; } else { //fake anchor for bitmap font this.textObj.position.x -= this.textObj.width / 2; this.textObj.position.y -= this.textObj.height / 2; } } else { this.textObj.position.x = (this._settings.width - this.textObj.width) / 2; this.textObj.position.y = (this._settings.height - this.textObj.height) / 2; if (this.textObj.anchor) { this.textObj.anchor.x = 0; this.textObj.anchor.y = 0; } } this.rootSprite.addChild(this.textObj); } } public createChild(childSettings, order?) { if (!childSettings) return null; var i = order; var pos = childSettings.position; if (typeof pos == 'string') { var parts = pos.split(' '); var pos1 = parts[0]; var pos2 = parts[1]; //normalize pos if (parts[0] == parts[1]) { pos2 = undefined; } if ((parts[0] == 'top' && parts[2] == 'bottom') || (parts[0] == 'bottom' && parts[2] == 'top') || (parts[0] == 'left' && parts[2] == 'right') || (parts[0] == 'right' && parts[2] == 'left') ) { pos1 = 'center'; pos2 = 'undefined'; } if ((parts[0] == 'left' || parts[0] == 'right') && (parts[1] == 'top' || parts[1] == 'bottom')) { pos1 = parts[1]; pos2 = parts[0]; } if ((pos1 == 'left' || pos1 == 'right') && pos2 === undefined) { pos2 = pos1; pos1 = 'left'; } var padTop = this._settings['padding-top'] || this._settings.padding || 0; var padLeft = this._settings['padding-left'] || this._settings.padding || 0; childSettings.position = { x: 0, y: 0 }; if (pos1 == 'center') { //childSettings.anchor = { x: 0.5, y: 0.5 }; childSettings.position.x = (this._settings.width - childSettings.width) / 2; childSettings.position.y = (this._settings.height - childSettings.height + padTop) / 2; } switch (pos1) { case 'center': childSettings.position.y = (this._settings.height - childSettings.height + padTop) / 2; if (pos2 === undefined) childSettings.position.x = (this._settings.width - childSettings.width) / 2; break; case 'bottom': childSettings.position.y = this._settings.height - childSettings.height - this._settings.padding; break; } switch (pos2) { case 'center': childSettings.position.x = (this._settings.width - childSettings.width) / 2; break; case 'right': childSettings.position.x = this._settings.width - childSettings.width - this._settings.padding; break; } //childSettings.position.x += padLeft; //childSettings.position.y += padTop; } var child = EZGUI.create(childSettings, this.theme); return child; } /** * */ public setState(state= 'default') { for (var i = 0; i < this.children.length; i++) { var child: any = this.children[i]; if (child instanceof MultistateSprite /*|| child instanceof MultistateTilingSprite*/) { child.setState(state); } } } public animatePosTo(x, y, time = 1000, easing = EZGUI.Easing.Linear.None, callback?) { easing = easing || EZGUI.Easing.Linear.None; if (typeof callback == 'function') { var tween = new EZGUI.Tween(this.position) .to({ x: x, y: y }, time) .easing(easing) .onComplete(callback); } else { var tween = new EZGUI.Tween(this.position) .to({ x: x, y: y }, time) .easing(easing); } tween.start(); return tween; } public animateSizeTo(w, h, time = 1000, easing = EZGUI.Easing.Linear.None, callback?) { easing = easing || EZGUI.Easing.Linear.None; if (typeof callback == 'function') { var tween = new EZGUI.Tween(this) .to({ width: w, height: h }, time) .easing(easing) .onComplete(callback); } else { var tween = new EZGUI.Tween(this) .to({ width: w, height: h }, time) .easing(easing); } tween.start(); return tween; } /** * */ protected getFrameConfig(config, state) { var cfg = JSON.parse(JSON.stringify(config));//if (cfg.texture instanceof PIXI.Texture) return cfg; if (typeof cfg == 'string') { cfg = { default: cfg }; } var src = cfg[state] == null ? cfg['default'] : cfg[state]; var texture; if (src.trim() != '') { texture = PIXI.Texture.fromFrame(src); } cfg.texture = texture; return cfg; } protected getComponentConfig(component, part, side, state) { //var ctype = this.theme[type] || this.theme['default']; var skin = this.theme.getSkin(component); if (!skin) return; var scale = (skin.scale == undefined) ? 1 : skin.scale; var rotation = 0; //get configuration, if explicit configuration is defined then use it otherwise use theme config //var hasSide = this.settings[component + '-' + side] || ctype[component + '-' + side]; var cfg = this._settings[part + '-' + side] || skin[part + '-' + side] || this._settings[part] || skin[part]; if (!cfg) return; if (skin[part] && !skin[part + '-' + side]) { switch (side) { case 'tr': case 'r': rotation = 90 * Math.PI / 180; break; case 'bl': case 'l': rotation = -90 * Math.PI / 180; break; case 'br': case 'b': rotation = 180 * Math.PI / 180; break; } } cfg = this.getFrameConfig(cfg, state); cfg.rotation = cfg.rotation != undefined ? cfg.rotation : rotation; cfg.scale = cfg.scale != undefined ? cfg.scale : scale; var bgPadding = this._settings['bgPadding'] != undefined ? this._settings['bgPadding'] : skin['bgPadding']; cfg.bgPadding = bgPadding != undefined ? bgPadding : 0; //cfg.hoverTexture = cfg.hover ? PIXI.Texture.fromFrame(cfg.hover) : cfg.texture; return cfg; } protected createThemeCorner(settings, part, side, state) { var component = settings.skin || settings.component || 'default'; var cfg = this.getComponentConfig(component, part, side, state); if (!cfg || !cfg.texture) return; //var ctype = this.theme[type] || this.theme['default']; //var skin = this.theme.getSkin(component); var skin = settings; var hasSide = this._settings[part + '-' + side] || skin[part + '-' + side]; //var sprite = new MultistateSprite(cfg.texture, cfg.textures); var sprite = new PIXI.Sprite(cfg.texture); sprite.rotation = cfg.rotation; sprite.scale.x = cfg.scale; sprite.scale.y = cfg.scale; switch (side) { case 'tl': sprite.position.x = 0; sprite.position.y = 0; break; case 'tr': sprite.position.x = settings.width; sprite.position.y = 0; break; case 'bl': sprite.position.x = 0; sprite.position.y = settings.height; break; case 'br': sprite.position.x = settings.width; sprite.position.y = settings.height; break; } //needed for specific corner sides : corner-tl corner-tr corner-bl corner-br if (hasSide) { if (sprite.position.y != 0) sprite.anchor.y = 1; if (sprite.position.x != 0) sprite.anchor.x = 1; } return sprite; } protected createThemeSide(settings, side, state) { var component = settings.component; var cfg = this.getComponentConfig(component, side, '', state); if (!cfg || !cfg.texture) return; //var sprite = new MultistateSprite(cfg.texture, cfg.textures); var sprite = new PIXI.Sprite(cfg.texture); //sprite.rotation = cfg.rotation; sprite.scale.x = cfg.scale; sprite.scale.y = cfg.scale; sprite.height = settings.height; switch (side) { case 'left': sprite.position.x = 0; sprite.position.y = 0; break; case 'right': sprite.position.x = settings.width; sprite.position.y = 0; break; } return sprite; } protected createThemeBorder(settings, part, side, state) { var component = settings.skin || settings.component || 'default'; var cfg = this.getComponentConfig(component, part, side, state); if (!cfg || !cfg.texture) return; var tlCornerCfg = this.getComponentConfig(component, 'corner', 'tl', state); var blCornerCfg = this.getComponentConfig(component, 'corner', 'bl', state); if (!tlCornerCfg || !tlCornerCfg.texture) return; if (!blCornerCfg || !blCornerCfg.texture) return; //var ctype = this.theme[type] || this.theme['default']; //var ctype = this.theme.getSkin(component); var ctype = settings; var hasSide = this._settings[part + '-' + side] || ctype[part + '-' + side]; var cwidth, cheight; var twidth, theight; switch (side) { case 't': case 'b': cwidth = tlCornerCfg.texture.width * tlCornerCfg.scale; cheight = blCornerCfg.texture.height * blCornerCfg.scale; twidth = (settings.width - (cwidth * 2)) * 1 / cfg.scale; theight = cfg.texture.height; break; case 'r': case 'l': cwidth = tlCornerCfg.texture.height * tlCornerCfg.scale; twidth = (settings.height - (cwidth * 2)) * 1 / cfg.scale; theight = cfg.texture.height; if (hasSide) { cheight = tlCornerCfg.texture.width * tlCornerCfg.scale; twidth = tlCornerCfg.texture.width; theight = (settings.height - (cwidth * 2)) * 1 / cfg.scale; } break; } //var cwidth = cornerCfg.texture.width * cornerCfg.scale; //var line: any = new MultistateTilingSprite(cfg.texture, twidth, theight, cfg.textures); var line: any = new EZGUI.Compatibility.TilingSprite(cfg.texture, twidth, theight); //phaser 2.4 compatibility ///////////////////////////////// line.fixPhaser24(); //////////////////////////////////////////////////////////// switch (side) { case 't': line.position.x = cwidth; line.position.y = 0; break; case 'r': line.position.y = cwidth; if (!hasSide) { line.position.x = settings.width - cwidth; line.anchor.x = 0; line.anchor.y = 1; } else { line.position.x = settings.width; line.anchor.x = 1; line.anchor.y = 0; } break; case 'b': line.position.x = cwidth; if (!hasSide) { line.position.y = settings.height - cwidth; line.anchor.x = 1; line.anchor.y = 1; } else { line.position.y = settings.height - cheight; } break; case 'l': line.position.y = cwidth; if (!hasSide) { line.anchor.x = 1; line.anchor.y = 0; } else { line.anchor.x = 0; line.anchor.y = 0; } break; } line.scale.x = cfg.scale; line.scale.y = cfg.scale; line.rotation = cfg.rotation;//180 * Math.PI / 180; return line; } protected createThemeTilableBackground(settings, state) { var component = settings.skin || settings.component || 'default'; var cfg = this.getComponentConfig(component, 'bg', null, state); if (!cfg || !cfg.texture) return; //cfg.bgPadding = 0; //var bg: any = new MultistateTilingSprite(cfg.texture, settings.width - cfg.bgPadding * 2, settings.height - cfg.bgPadding * 2, cfg.textures); var bg: any = new EZGUI.Compatibility.TilingSprite(cfg.texture, settings.width - cfg.bgPadding * 2, settings.height - cfg.bgPadding * 2); //phaser 2.4 compatibility ///////////////////////////////// bg.fixPhaser24(); //////////////////////////////////////////////////////////// bg.position.x = cfg.bgPadding; bg.position.y = cfg.bgPadding; if (settings.bgTiling) { if (settings.bgTiling === "x") { bg.tileScale.y = (settings.height - cfg.bgPadding * 2) / cfg.texture.height; } else if (settings.bgTiling === "y") { bg.tileScale.x = (settings.width - cfg.bgPadding * 2) / cfg.texture.width; } else if (settings.bgTiling === "xy") { bg.tileScale.y = (settings.height - cfg.bgPadding * 2) / cfg.texture.height; bg.tileScale.x = (settings.width - cfg.bgPadding * 2) / cfg.texture.width; } } return bg; } protected createThemeBackground(settings, state, leftSide, rightSide?) { var component = settings.skin || settings.component || 'default'; var cfg = this.getComponentConfig(component, 'bg', null, state); if (!cfg || !cfg.texture) return; //cfg.bgPadding = 0; //var bg: any = new MultistateSprite(cfg.texture, cfg.textures); var bg: any = new PIXI.Sprite(cfg.texture); bg.position.x = leftSide.width; bg.position.y = 0; bg.scale.x = cfg.scale; bg.scale.y = cfg.scale; bg.width = settings.width - leftSide.width; bg.height = settings.height; return bg; } protected createThemeImage(settings, state, imagefield = 'image') { var component = settings.skin || settings.component || 'default'; //var ctype = this.theme[type] || this.theme['default']; var ctype = settings;//this.theme.getSkin(component); if (ctype[imagefield]) { var cfg: any = this.getFrameConfig(ctype[imagefield], state); //var img = new MultistateSprite(cfg.texture, cfg.textures); var img = new PIXI.Sprite(cfg.texture); img.width = settings.width; img.height = settings.height; return img; } return null; } protected createVisuals(settings, state) { if (settings.transparent === true) return []; //priority to image var img = this.createThemeImage(settings, state); if (img != null) return [img]; var controls = []; var leftSide = this.createThemeSide(settings, 'left', state); var rightSide = this.createThemeSide(settings, 'right', state); var bg = this.createThemeTilableBackground(settings, state); if (bg) controls.push(bg); //if (!leftSide && !rightSide) { // var bg = this.createThemeTilableBackground(settings, state); // if (bg) controls.push(bg); //} //else { // var bg = this.createThemeBackground(settings, state, leftSide); // if (bg) controls.push(bg); //} if (leftSide) { controls.push(leftSide); } else { var tl = this.createThemeCorner(settings, 'corner', 'tl', state); if (tl) controls.push(tl); var bl = this.createThemeCorner(settings, 'corner', 'bl', state); if (bl) controls.push(bl); var lineLeft = this.createThemeBorder(settings, 'line', 'l', state); if (lineLeft) controls.push(lineLeft); } if (rightSide) { controls.push(rightSide); } else { var tr = this.createThemeCorner(settings, 'corner', 'tr', state); if (tr) controls.push(tr); var br = this.createThemeCorner(settings, 'corner', 'br', state); if (br) controls.push(br); var lineRight = this.createThemeBorder(settings, 'line', 'r', state); if (lineRight) controls.push(lineRight); } if (!leftSide && !rightSide) { var lineTop = this.createThemeBorder(settings, 'line', 't', state); if (lineTop) controls.push(lineTop); var lineBottom = this.createThemeBorder(settings, 'line', 'b', state); if (lineBottom) controls.push(lineBottom); } return controls; } } EZGUI.registerComponents(GUISprite, 'default'); }
the_stack
import * as charts from './core' import { ChartLegendType, Chart, StandardTimeSeries, DashboardItem } from '../models/items' import Query from '../models/data/query' import { AxisScale } from '../models/axis' import { get_colors, get_palette } from './util' import { logger, extend } from '../util' import * as graphite from '../data/graphite' import * as app from '../app/app' import { render_legend } from './legend' import XYChart from '../models/items/xychart' declare var URI, $, d3, moment, ts const log = logger('charts.flot') export interface FlotRenderContext { plot: any item: Chart|DashboardItem query: Query renderer: charts.ChartRenderer } /* ============================================================================= Helpers ============================================================================= */ const FORMAT_STRING_STANDARD = ',.3s' const FORMAT_STANDARD = d3.format(FORMAT_STRING_STANDARD) const FORMAT_PERCENT = d3.format('.0%') const THREE_HOURS_MS = 1000 * 60 * 60 * 3 const ONE_HOUR_MS = 1000 * 60 * 60 * 1 const DEFAULT_LINE_WIDTH = 1.0 const DEFAULT_FILL = 0.8 function is_line_chart(item: Chart) : boolean { return ((item instanceof StandardTimeSeries) && ((<StandardTimeSeries>item).stack_mode === charts.StackMode.NONE)) } function is_area_chart(item: Chart) : boolean { return (item instanceof StandardTimeSeries) && ((<StandardTimeSeries>item).stack_mode !== charts.StackMode.NONE) && ((<StandardTimeSeries>item).stack_mode !== charts.StackMode.PERCENT) } function get_default_options() { let theme_colors = get_colors() let default_options = { colors: get_palette(), downsample: false, series: { lines: { show: true, lineWidth: ts.prefs.line_width || DEFAULT_LINE_WIDTH, steps: false, fill: false }, valueLabels: { show: false }, points: { show: false, fill: true, radius: 2, symbol: "circle" }, bars: { lineWidth: ts.prefs.line_width || DEFAULT_LINE_WIDTH, show: false }, stackD3: { show: false } }, xaxis: { mode: "time", timeBase: "milliseconds", tickColor: theme_colors.minorGridLineColor, tickLength: 0, font: { color: theme_colors.fgcolor, size: 12 } }, yaxes: [ { position: 'left', tickFormatter: FORMAT_STANDARD, tickLength: 0, reserveSpace: 30, labelWidth: 30, tickColor: theme_colors.minorGridLineColor, font: { color: theme_colors.fgcolor, size: 12 } }, { position: 'right', tickFormatter: FORMAT_STANDARD, font: { color: theme_colors.fgcolor, size: 12 } } ], shadowSize: 0, legend: { show: false }, grid: { borderWidth: 1, hoverable: true, clickable: true, autoHighlight: false, /* grid.color actually sets the color of the legend * text. WTH? */ color: theme_colors.fgcolor, tickColor: theme_colors.minorGridLineColor, borderColor: theme_colors.minorGridLineColor }, selection: { mode: "x", color: "red" }, multihighlight: { mode: "x" }, crosshair: { mode: "x", color: "#BBB", lineWidth: 1 } } return default_options } function log_transform(v) { return v === 0 ? v : (Math.log1p(Math.abs(v)) / Math.LN10) } function get_flot_options(item, base) { let options = item.options || {} let flot_options = extend(true, {}, get_default_options(), base) flot_options.colors = get_palette(options.palette) if (options.y1 && options.y1.min) flot_options.yaxes[0].min = options.y1.min if (options.y2 && options.y2.min) flot_options.yaxes[1].min = options.y2.min if (options.y1 && options.y1.max) flot_options.yaxes[0].max = options.y1.max if (options.y2 && options.y2.max) flot_options.yaxes[1].max = options.y2.max if (options.y1 && options.y1.label) flot_options.yaxes[0].axisLabel = options.y1.label if (options.y2 && options.y2.label) flot_options.yaxes[1].axisLabel = options.y2.label if (options.y1 && options.y1.scale === AxisScale.LOG) { flot_options.yaxes[0].transform = log_transform } if (options.y2 && options.y2.scale === AxisScale.LOG) { flot_options.yaxes[1].transform = log_transform } if (options.x && options.x.label) { flot_options.xaxis.axisLabel = options.x.label } if (item.show_max_value || item.show_min_value || item.show_last_value) { flot_options.series.valueLabels = { show: true, showMaxValue: item.show_max_value, showMinValue: item.show_min_value, showLastValue: item.show_last_value, showAsHtml: true, labelFormatter: FORMAT_STANDARD, yoffset: -20 } } return flot_options } function show_tooltip(x, y, contents, offset?) { let margin = 60 let top = y + (offset || 5) let left = x + (offset || 5) let el = $('<div id="ds-tooltip">' + contents + '</div>').css( { position: 'absolute', display: 'none', top: top, left: left }) el.appendTo("body").show() let width = el.outerWidth() if (left + width + margin > window.innerWidth) { el.css('left', x - (width + (margin * 2))) } } function setup_plugins(selector: string, context: FlotRenderContext) { $(selector).bind("multihighlighted", function(event, pos, items) { if ( !items ) return let is_percent = context.item['stack_mode'] && (context.item['stack_mode'] === charts.StackMode.PERCENT) let data = context.plot.getData() let item = items[0] let point = data[item.serieIndex].data[item.dataIndex] let items_to_plot = items.map((i) => { let s = data[i.serieIndex] if (context.item instanceof Chart && (<Chart>context.item).hide_zero_series && s.summation.sum === 0) return null let value = is_percent ? s.percents[i.dataIndex] : s.data[i.dataIndex][1] return { series: s, value: is_percent ? FORMAT_PERCENT(value) : FORMAT_STANDARD(value) } }).filter(i => !!i) if (context.item['stack_mode'] && (context.item['stack_mode'] !== charts.StackMode.NONE)) items_to_plot.reverse() let contents = ts.templates.flot.tooltip({ time: point[0], items: items_to_plot }) $("#ds-tooltip").remove() show_tooltip(pos.pageX, $(event.target).offset().top, contents) }) if (context.item instanceof XYChart) { $(selector).bind('plothover', (e, pos, event_item) => { if (event_item) { context.renderer.highlight_series(<Chart>context.item, event_item.seriesIndex) } else { context.renderer.unhighlight_series(<Chart>context.item) } }) } $(selector).bind("unmultihighlighted", function(event) { $("#ds-tooltip").remove() }) } /* ============================================================================= Chart renderer interface ============================================================================= */ export default class FlotChartRenderer extends charts.ChartRenderer { downsample: boolean = true downsampling_factor: number = 0.8 connected_lines: boolean = false constructor(data?: any) { super(extend({}, data, { name: 'flot', is_interactive: true, description: 'flot renders interactive charts using HTML canvas.' })) if (data) { if (typeof(data.downsample) !== 'undefined') { this.downsample = !!data.downsample } if (typeof(data.connected_lines) !== 'undefined') { this.connected_lines = !!data.connected_lines } this.downsampling_factor = data.downsampling_factor || this.downsampling_factor } } // // Sparkline // sparkline(selector: string, item: DashboardItem, query: Query, index: number, opt?: any) : FlotRenderContext { let context : FlotRenderContext = { plot: null, item: item, query: query, renderer: this } setup_plugins(selector, context) let data = [query.chart_data('flot')[index]] let options = extend(true, {}, { colors: get_palette(), series: { lines: { show: true, lineWidth: ts.prefs.line_width || DEFAULT_LINE_WIDTH, fill: 0.2 } }, grid: { show: false, hoverable: true }, multihighlight: { mode: 'x' }, crosshair: { mode: "x", color: "#BBB", lineWidth: 1 }, legend: { show: false }, shadowSize: 0, downsample: true }, opt) context.plot = $.plot($(selector), data, options) return context } render(selector: string, item: Chart, query: Query, options?: any, data?: any) : any { if (typeof(data) === 'undefined') data = query.chart_data('flot') let context : FlotRenderContext = { plot: null, item: item, query: query, renderer: this } setup_plugins(selector, context) let e = $(selector) if (this.downsample && options.downsample) { options.series.downsample = { threshold: Math.floor(e.width() * this.downsampling_factor) } } else { options.series.downsample = { threshold: 0 } } try { context.plot = $.plot(e, data, options) } catch (ex) { log.error('Error rendering item ' + item.item_id + ': ' + ex.message) log.error(ex.stack) } item.render_context = context options.interactive_legend = true render_legend(item, query, options) return context } cleanup(item: Chart) : void { if (item.render_context) { item.render_context.plot.shutdown() item.render_context.plot = null item.render_context = null } } // // Highlight // highlight_series(item: Chart, index: number) : void { if (!item.render_context) return let plot = item.render_context.plot if (item instanceof StandardTimeSeries) { let sts = <StandardTimeSeries> item let stacked = sts.stack_mode != charts.StackMode.NONE plot.getData().forEach((s, i) => { if (i == index) { s.lines.lineWidth = (sts.show_lines && !stacked) ? 3 : 0 s.points.radius = 3 s.highlighted = true if (stacked) { s.lines.fill = 0.8 } } else { this.unhighlight_series(item, i) if (stacked) { s.lines.fill = 0.2 } } }) } plot.draw() } // // Un-highlight // TODO: simplify this too // unhighlight_series(item: Chart, index?: number) : void { if (!item.render_context) return let plot = item.render_context.plot if (item instanceof StandardTimeSeries) { let sts = <StandardTimeSeries> item let stacked = sts.stack_mode != charts.StackMode.NONE if (index) { let s = plot.getData()[index] s.lines.lineWidth = sts.show_lines ? ts.prefs.line_width || DEFAULT_LINE_WIDTH : 0 s.points.radius = 2 if (stacked) { s.lines.fill = item.fill || ts.prefs.opacity || DEFAULT_FILL } s.highlighted = false } else { plot.getData().forEach((s, i) => { s.lines.lineWidth = sts.show_lines ? ts.prefs.line_width || DEFAULT_LINE_WIDTH : 0 s.points.radius = 2 s.highlighted = false if (stacked) { s.lines.fill = item.fill || ts.prefs.opacity || DEFAULT_FILL } }) } } plot.draw() } process_series(series: graphite.DataSeries) : any { let result : any = {} if (series.summation) { result.summation = series.summation } result.label = series.target result.data = series.datapoints.map(function(point) { return [point[1] * 1000, point[0]] }) if (this.connected_lines) { result.data = result.data.filter(function(point) { return point[1] != null }) } return result } // // Simple Line Chart // simple_line_chart(selector: string, item: Chart, query: Query) : void { let options = get_flot_options(item, { grid: { show: false }, series: { lines: { fill: item.fill } }, downsample: true }) return this.render(selector, item, query, options, [query.chart_data('flot')[0]]) } // // Standard Line Chart // standard_line_chart(selector: string, item: Chart, query: Query) : void { query.chart_data('flot').forEach(function(series) { // Hide series with no data from display if (series.summation.sum === 0) { series.lines = { lineWidth: 0, fill: 0.0 } } }) this.render(selector, item, query, get_flot_options(item, { downsample: true })) } // // Simple Area Chart // simple_area_chart(selector: string, item: Chart, query: Query) : void { let options = get_flot_options(item, { downsample: true, grid: { show: false }, series: { lines: { fill: item.fill || ts.prefs.opacity || DEFAULT_FILL }, grid: { show: false } } }) return this.render(selector, item, query, options, [query.chart_data('flot')[0]]) } // // Stacked Area Chart // stacked_area_chart(selector: string, item: Chart, query: Query) : void { let options = get_flot_options(item, { downsample: true, series: { lines: { fill: item.fill || ts.prefs.opacity || DEFAULT_FILL || 1.0 }, stackD3: { show: true, offset: 'zero' } } }) if (item instanceof StandardTimeSeries) { let sts = <StandardTimeSeries> item if (!sts.show_lines) options.series.lines.lineWidth = 0 options.series.points.show = sts.show_points } if (item['stack_mode']) { let mode = item['stack_mode'] if (mode === charts.StackMode.PERCENT) { options.series.stackD3.offset = 'expand' options.yaxes[0].max = 1 options.yaxes[0].min = 0 options.yaxes[0].tickFormatter = FORMAT_PERCENT } else if (mode == charts.StackMode.STREAM) { options.series.stackD3.offset = 'wiggle' } else if (mode == charts.StackMode.NONE) { options.series.stackD3.show = false options.series.lines.fill = 0.0 } } query.chart_data('flot').forEach(function(series, i) { if (series.summation.sum === 0) { series.lines = { lineWidth: 0 } } series.points = series.points || {} series.points.fillColor = options.colors[i % options.colors.length] }) return this.render(selector, item, query, options) } // // Donut (Pie) Chart // donut_chart(selector: string, item: Chart, query: Query) { let options = get_flot_options(item, { crosshair: { mode: null }, multihighlight: { mode: null }, series: { lines: { show: false }, pie: { show: true, radius: 'auto', innerRadius: item['is_pie'] ? 0 : 0.35, label: { show: item['labels'] }, highlight: { opacity: 0.4 } } }, grid: { show: false, hoverable: true, autoHighlight: true } }) let transform = item['transform'] || 'sum' let data = query.chart_data('flot').map(function(series) { if (item.hide_zero_series && series.summation.sum === 0) { return undefined } return { label: series.label, summation: series.summation, data: [ series.label, series.summation[transform] ] } }).filter(function(item) { return item }) let context = this.render(selector, item, query, options, data) var null_count = 0 // HACK: workaround for flot 3's plothover bug $(selector).bind('plothover', function(event, pos, event_item) { if (event_item) { null_count = 0 let contents = ts.templates.flot.donut_tooltip({ series: event_item.series, value: FORMAT_STANDARD(event_item.datapoint[1][0][1]), percent: FORMAT_PERCENT(event_item.series.percent / 100) }) $("#ds-tooltip").remove() show_tooltip(pos.pageX, pos.pageY, contents) } else { if (++null_count >= 2) { $("#ds-tooltip").remove() } } }) return context } // // Timeseries Bar Chart // bar_chart(selector: string, item: Chart, query: Query) : void { let series = query.chart_data('flot')[0] let ts_start = series.data[0][0] let ts_end = series.data[series.data.length - 1][0] let ts_length = ts_end - ts_start let sample_size = ts_length / series.data.length let bar_scaling = 0.85 if (ts_length > THREE_HOURS_MS) { bar_scaling = 0.15 } else if (ts_length > ONE_HOUR_MS) { bar_scaling = 0.65 } else { bar_scaling = 0.85 } let options = get_flot_options(item, { series: { xaxis: { min: ts_start, max: ts_end, autoScale: "none" }, lines: { show: false }, stackD3: { show: true, offset: 'zero' }, bars: { show: true, // barWidth: sample_size * bar_scaling, fill: 0.8 } } }) if (item['stack_mode']) { let mode = item['stack_mode'] if (mode === charts.StackMode.PERCENT) { options.series.stackD3.offset = 'expand' options.yaxes[0].max = 1 options.yaxes[0].min = 0 options.yaxes[0].tickFormatter = FORMAT_PERCENT } else if (mode == charts.StackMode.STREAM) { options.series.stackD3.offset = 'wiggle' } else if (mode == charts.StackMode.NONE) { options.series.stackD3.show = false options.series.lines.fill = false } } return this.render(selector, item, query, options) } // // Discrete Bar Chart // discrete_bar_chart(selector: any, item: Chart, query: Query) : void { let is_horizontal = item['orientation'] === 'horizontal' let format = d3.format(item['format'] || FORMAT_STRING_STANDARD) let options = get_flot_options(item, { xaxis: { mode: null }, multihighlight: { mode: null }, crosshair: { mode: null }, grid: { borderWidth: 0, color: 'transparent', borderColor: 'transparent', labelMargin: 10 }, series: { lines: { show: false }, bars: { horizontal: is_horizontal, show: true, // barWidth: 0.8, align: 'center', fill: item.fill || ts.prefs.opacity || DEFAULT_FILL, numbers: { show: item['show_numbers'], font: '10pt Helvetica', fontColor: '#f9f9f9', // TODO: get from theme formatter: format, yAlign: function(y) { return y }, xAlign: function(x) { return x } } } } }) let transform = item['transform'] || 'sum' let index = 0 let data = query.chart_data('flot').map(function(series) { if (item.hide_zero_series && series.summation.sum === 0) { return undefined } return { label: series.label, data: [ is_horizontal ? [ series.summation[transform], index] : [index, series.summation[transform]] ], color: options.colors[options.colors % index++] } }).filter(function(item) { return item }) index = 0 let ticks = data.map(function(series) { return is_horizontal ? [series.label, index++] : [index++, series.label] }) if (is_horizontal) { options.yaxes[0].tickLength = 0 options.yaxes[0].ticks = ticks options.xaxis.mode = null options.xaxis.tickFormatter = null options.series.bars.numbers.xOffset = -18 if (item['show_grid']) { options.xaxis.axisLabel = options.yaxes[0].axisLabel options.yaxes[0].axisLabel = transform.charAt(0).toUpperCase() + transform.substring(1) } else { options.xaxis.ticks = [] options.yaxes[0].axisLabel = null } } else { options.xaxis.tickLength = 0 options.xaxis.ticks = ticks options.series.bars.numbers.yOffset = 12 if (!item['show_grid']) { options.yaxes[0].ticks = [] options.yaxes[0].axisLabel = null } else { options.xaxis.axisLabel = transform.charAt(0).toUpperCase() + transform.substring(1) } } let context = this.render(selector, item, query, options, data) $(selector).bind('plothover', function(event, pos, event_item) { if (event_item) { let contents = ts.templates.flot.discrete_bar_tooltip({ series: event_item.series, value: format(is_horizontal ? event_item.datapoint[0] : event_item.datapoint[1]) }) $("#ds-tooltip").remove() show_tooltip(pos.pageX, pos.pageY, contents) } else { $("#ds-tooltip").remove() } }) return context } // // Scatter Plot // scatter_plot(selector: string, item: Chart, query: Query) : void { let options = get_flot_options(item, { series: { lines: { show: true, lineWidth: 0 }, bars: { show: false }, points: { show: true, fill: true, radius: 2, symbol: "circle" } } }) options.series.points.fillColor = options.colors[0] options.xaxis.mode = null options.xaxis.tickFormatter = null let data = query.chart_data('flot') let series_x = data[0].data.map(d => { return d[1] }) let series_y = data[1].data.map(d => { return d[1] }) let series = series_x.map((e, i) => { return [e, series_y[i]] }) let scatter_data = [data[0]] scatter_data[0].data = series return this.render(selector, item, query, options, scatter_data) } }
the_stack
import {Component, PropsWithChildren} from 'react'; import * as PropTypes from 'prop-types'; import {connect} from 'react-redux'; import {addRootFilesAction, FileIndexReducerType} from '../redux/fileIndexReducer'; import { getAllFilesFromStore, getBundleIdFromStore, getTabletopIdFromStore, GtoveDispatchProp, ReduxStoreType } from '../redux/mainReducer'; import googleAPI from '../util/googleAPI'; import * as constants from '../util/constants'; import DriveTextureLoader from '../util/driveTextureLoader'; import { DriveMetadata, isDriveFileShortcut, RootDirAppProperties, TabletopObjectProperties } from '../util/googleDriveUtils'; import FileAPIContextBridge from '../context/fileAPIContextBridge'; import InputButton from '../presentation/inputButton'; import {setCreateInitialStructureAction} from '../redux/createInitialStructureReducer'; import {PromiseModalContext} from '../context/promiseModalContextBridge'; import {promiseSleep} from '../util/promiseSleep'; interface DriveFolderComponentProps extends GtoveDispatchProp{ files: FileIndexReducerType; tabletopId: string; bundleId: string | null; } interface DriveFolderComponentState { loading: string; migrating: string; } class DriveFolderComponent extends Component<PropsWithChildren<DriveFolderComponentProps>, DriveFolderComponentState> { static DATA_VERSION = 2; static contextTypes = { promiseModal: PropTypes.func }; context: PromiseModalContext; private textureLoader: DriveTextureLoader; constructor(props: DriveFolderComponentProps) { super(props); this.state = { loading: ': Loading...', migrating: '' }; this.textureLoader = new DriveTextureLoader(); } async componentDidMount() { await googleAPI.loadRootFiles((files: DriveMetadata[]) => {this.props.dispatch(addRootFilesAction(files))}); const rootId = this.props.files.roots[constants.FOLDER_ROOT]; if (rootId) { const rootMetadata = this.props.files.driveMetadata[rootId] as DriveMetadata<RootDirAppProperties, void>; const dataVersion = (rootMetadata.appProperties && +rootMetadata.appProperties.dataVersion) || 1; await this.verifyUserDriveContents([rootId], dataVersion); } this.setState({loading: ''}); } private async recursivelyAddFilesInFolder(folder: string, fileId: string, result: DriveMetadata[]) { this.setState({migrating: 'Scanning ' + folder}); let filesInFolder: DriveMetadata[] = []; await googleAPI.loadFilesInFolder(fileId, (result) => {filesInFolder = result}); if (filesInFolder.length > 0) { for (let file of filesInFolder) { const isFolder = (file.mimeType === constants.MIME_TYPE_DRIVE_FOLDER); if (isFolder) { await this.recursivelyAddFilesInFolder(folder + '/' + file.name, file.id, result); } else { result.push(file); } } } } private async migrateAppPropertiesToProperties(): Promise<boolean> { const folderFiles: {[folder: string]: DriveMetadata[]} = {}; let migrateCount = 0; const folderList = [constants.FOLDER_MAP, constants.FOLDER_MINI, constants.FOLDER_TEMPLATE]; // Recursively search the different folders for (let folder of folderList) { folderFiles[folder] = []; await this.recursivelyAddFilesInFolder(folder, this.props.files.roots[folder], folderFiles[folder]); migrateCount += folderFiles[folder].length; } if (migrateCount > 0) { if (!this.context.promiseModal?.isAvailable()) { return false; } const proceedAnswer = 'Migrate my data!'; const answer = await this.context.promiseModal({ children: ( <div> <h2>gTove Data Migration</h2> <p> The location that gTove stores its metadata has changed! Your Drive has {migrateCount} files which need to be updated to the new format. This may take some time (a few seconds for each file). </p> <p> This migration is part of the change which allows gTove to reduce the permissions it needs... you no longer need to give the app read access to your entire Drive! This improvement is hopefully worth the inconvenience of the migration. </p> <p> You can migrate your data now, or skip this operation. Note that until your old files are migrated, they will appear as if you just uploaded or created them... the will not appear on your tabletops, and will be marked as "NEW" in the file browsers. </p> <p> Any new maps, minis or templates you upload or create from now on will use the new format, and can be used as normal, even if you do not migrate your old data now. </p> </div> ), options: [proceedAnswer, 'Skip migration for now'] }); if (answer !== proceedAnswer) { return false; } let count = 0; for (let folder of folderList) { const oldFiles = folderFiles[folder]; oldFiles.sort((f1, f2) => (f1.name < f2.name ? -1 : f1.name > f2.name ? 1 : 0)); for (let file of oldFiles) { ++count; if (file.appProperties || (file.properties && !(file.properties as TabletopObjectProperties).rootFolder)) { // Only migrate files which need migrating this.setState({migrating: `Migrating ${count} of ${migrateCount} - ${folder}: ${file.name}`}); file.properties = {...file.appProperties, ...file.properties, rootFolder: folder} as any; if (file.appProperties) { file.appProperties = Object.keys(file.appProperties as any).reduce((clean, key) => { clean[key] = null; return clean; }, {}) as any; } if (isDriveFileShortcut(file) && file.properties.ownedMetadataId) { file.id = file.properties.ownedMetadataId; // @ts-ignore deleting non-optional field of DriveFileShortcut delete(file.properties.ownedMetadataId); } await googleAPI.uploadFileMetadata(file); } else { this.setState({migrating: `Skipping ${count} of ${migrateCount} - ${folder}: ${file.name}`}); await promiseSleep(10); } } } } return true; } async migrateDriveData(rootId: string, dataVersion: number) { let migrated = true; this.setState({migrating: '...'}); switch (dataVersion) { // @ts-ignore falls through case 1: migrated = migrated && await this.migrateAppPropertiesToProperties(); // falls through default: break; } this.setState({migrating: ''}); if (migrated && dataVersion !== DriveFolderComponent.DATA_VERSION) { await googleAPI.uploadFileMetadata({id: rootId, appProperties: {rootFolder: 'true', dataVersion: DriveFolderComponent.DATA_VERSION.toString()}}); } } async verifyUserDriveContents(parents: string[], dataVersion: number) { const missingFolders = constants.topLevelFolders.filter((folderName) => (!this.props.files.roots[folderName])); let newFolders: DriveMetadata[] = []; for (let folderName of missingFolders) { this.setState({loading: `: Creating ${folderName} folder...`}); newFolders.push(await googleAPI.createFolder(folderName, {parents})); } this.props.dispatch(addRootFilesAction(newFolders)); // Check if we need to migrate their existing data. await this.migrateDriveData(parents[0], dataVersion); } async createInitialStructure() { this.props.dispatch(setCreateInitialStructureAction(true)); this.setState({loading: '...'}); const metadata = await googleAPI.createFolder(constants.FOLDER_ROOT, {appProperties: {rootFolder: 'true', dataVersion: DriveFolderComponent.DATA_VERSION.toString()}}); this.props.dispatch(addRootFilesAction([metadata])); await this.verifyUserDriveContents([metadata.id], DriveFolderComponent.DATA_VERSION); this.setState({loading: ''}); } render() { if (this.state.migrating) { return ( <div> <p>gTove is migrating your existing data. Please wait...</p> <p>{this.state.migrating}</p> </div> ); } else if (this.state.loading) { return ( <div> Waiting on Google Drive{this.state.loading} </div> ); } else if ((this.props.files && Object.keys(this.props.files.roots).length > 0) || (this.props.tabletopId && this.props.tabletopId !== this.props.bundleId)) { return ( <FileAPIContextBridge fileAPI={googleAPI} textureLoader={this.textureLoader}> {this.props.children} </FileAPIContextBridge> ); } else { return ( <div> <p> gTove saves its data in a folder structure created in your Google Drive. Click the button below to create these folders. After they are created, you can rename the top-level folder and move it elsewhere in your Drive without breaking anything (but don't move or rename the files and folders inside). </p> <InputButton type='button' onChange={() => { this.createInitialStructure(); }}> Create "{constants.FOLDER_ROOT}" folder in Drive </InputButton> <InputButton type='button' onChange={() => { googleAPI.signOutFromFileAPI(); }}> Sign out </InputButton> </div> ); } } } function mapStoreToProps(store: ReduxStoreType) { return { files: getAllFilesFromStore(store), tabletopId: getTabletopIdFromStore(store), bundleId: getBundleIdFromStore(store) } } export default connect(mapStoreToProps)(DriveFolderComponent);
the_stack
import * as treeDescription from "./tree-description"; import {TreeDescription, TreeNode, Crosslink, collapseAllChildren, streamline} from "./tree-description"; import {typesafeXMLParse, ParsedXML} from "./xml"; import {assert} from "./loader-utils"; // Convert JSON as returned by xml2js parser to d3 tree format function convertXML(xml: ParsedXML) { const children = [] as any[]; const properties = new Map<string, string>(); let text: string | undefined; const tag = xml["#name"]; if (xml.$) { for (const key of Object.getOwnPropertyNames(xml.$)) { properties.set(key, xml.$[key]); } } if (xml._) { text = xml._; } if (xml.$$) { for (const child of xml.$$) { children.push(convertXML(child)); } } return { tag: tag, properties: properties, text: text, children: children, }; } // Function to generate nodes' display names based on their properties const generateDisplayNames = (function() { // Get the first non-null, non-empty string function fallback(...args: (string | undefined)[]) { for (const arg of args) { if (arg !== undefined && arg.length !== 0) { return arg; } } } // Function to eliminate node function eliminateNode(node: TreeNode) { const parent = node.parent; if (!parent) { return; } assert(parent.children !== undefined); let nodeIndex = parent.children.indexOf(node); parent.children.splice(nodeIndex, 1); if (node.children) { for (let i = 0; i < node.children.length; i++) { node.children[i].parent = parent; parent.children.splice(nodeIndex++, 0, node.children[i]); } } } // properties.class are the expressions function handleLogicalExpression(node: TreeNode) { const clazz = node.properties?.get("class"); switch (clazz) { case "identifier": node.name = node.text; node.class = "identifier"; break; case "funcall": node.name = node.properties?.get("function"); node.class = "function"; break; case "literal": node.name = node.properties?.get("datatype") + ":" + node.text; break; default: node.name = clazz; break; } } // tags are the expressions function handleLogicalExpression2(node: TreeNode) { switch (node.tag) { case "identifierExp": node.name = node.properties?.get("identifier"); node.class = "identifier"; break; case "funcallExp": node.name = node.properties?.get("function"); node.class = "function"; break; case "literalExp": node.name = node.properties?.get("datatype") + ":" + node.properties?.get("value"); break; case "referenceExp": node.name = "ref:" + node.properties?.get("ref"); node.class = "reference"; break; default: node.name = node.tag?.replace(/Exp$/, ""); break; } } function handleQueryExpression(node: TreeNode) { const clazz = node.properties?.get("class"); switch (clazz) { case "identifier": node.name = node.text; node.class = "identifier"; break; case "funcall": node.name = node.properties?.get("function"); node.class = "function"; break; case "literal": node.name = node.properties?.get("datatype") + ":" + node.text; break; default: node.name = clazz; break; } } function handleQueryFunction(node: TreeNode) { const clazz = node.properties?.get("class"); switch (clazz) { case "table": node.name = node.properties?.get("table"); node.class = "relation"; break; default: node.name = clazz; break; } } // properties.class are the operators function handleLogicalOperator(node: TreeNode) { const clazz = node.properties?.get("class"); switch (clazz) { case "join": node.name = node.properties?.get("name"); node.class = "join"; break; case "relation": node.name = node.properties?.get("name"); node.class = "relation"; break; case "tuples": { const alias = node.properties?.get("alias"); if (alias) { node.name = clazz + ":" + alias; } else { node.name = clazz; } break; } default: node.name = clazz; break; } } // tags are the operators function handleLogicalOperator2(node: TreeNode) { switch (node.tag) { case "joinOp": node.name = node.tag.replace(/Op$/, ""); node.class = "join"; break; case "referenceOp": node.name = "ref:" + node.properties?.get("ref"); node.class = "reference"; break; case "relationOp": node.name = node.properties?.get("name"); node.class = "relation"; break; case "tuplesOp": { const alias = node.properties?.get("alias"); if (alias) { node.name = node.tag.replace(/Op$/, "") + ":" + alias; } else { node.name = node.tag.replace(/Op$/, ""); } break; } default: node.name = node.tag?.replace(/Op$/, ""); break; } } // properties.class are the operators function handleFedOp(node: TreeNode) { const clazz = node.properties?.get("class"); switch (clazz) { case "createtemptable": case "createtemptablefromquery": case "createtemptablefromtuples": node.name = fallback(node.properties?.get("table"), clazz); node.class = "createtemptable"; break; default: node.name = clazz; break; } } // extensions for calculation-language expression trees function handleExpression(node: TreeNode) { if (node.text) { node.name = node.text; } else if (node.properties?.has("name")) { node.name = node.properties.get("name"); } else if (node.properties?.has("value")) { node.name = node.properties.get("value"); if (node.properties.get("type") === "string") { node.name = "'" + node.name + "'"; } } else if (node.properties?.has("class")) { node.name = node.properties.get("class"); } else { eliminateNode(node); } } function generateDisplayNames(node: TreeNode) { // In-order traversal. Leaf node don't have children if (node.children !== undefined) { for (let i = 0; i < node.children.length; i++) { generateDisplayNames(node.children[i]); } } switch (node.tag) { case "table-parameters": eliminateNode(node); break; case "arguments": eliminateNode(node); break; case "logical-expression": handleLogicalExpression(node); break; case "query-expression": handleQueryExpression(node); break; case "query-function": handleQueryFunction(node); break; case "fed-op": handleFedOp(node); break; case "logical-operator": handleLogicalOperator(node); break; case "calculation": node.name = node.properties?.get("formula"); break; case "condition": node.name = fallback(node.properties?.get("op"), node.tag); break; case "field": node.name = fallback(node.text, node.properties?.get("name"), "field{}"); break; case "binding": node.name = fallback(node.properties?.get("name"), node.properties?.get("ref"), node.tag); break; case "relation": node.name = fallback(node.properties?.get("name"), node.tag); node.class = "relation"; break; case "column": case "runquery-column": node.name = fallback(node.properties?.get("name"), node.tag); break; case "dimensions": node.name = fallback(node.text, node.properties?.get("type"), node.tag); break; case "expression": handleExpression(node); break; case "tuple": case "value": node.name = fallback(node.text, node.tag); break; case "attribute": case "table": case "type": if (node.text) { node.name = node.tag + ":" + node.text; } else if (node.properties?.get("name")) { node.name = node.tag + ":" + node.properties.get("name"); } else { node.name = node.tag; } break; case "function": case "identifier": fallback(node.properties?.get("name"), node.tag); break; case "literal": node.name = node.properties?.get("type") + ":" + node.properties?.get("value"); break; default: switch (node.properties?.get("class")) { case "logical-expression": handleLogicalExpression2(node); break; case "logical-operator": handleLogicalOperator2(node); break; default: if (node.tag) { node.name = node.tag; } else { node.name = JSON.stringify(node); } break; } break; } } return generateDisplayNames; })(); // Assign symbols & classes to the nodes function assignSymbolsAndClasses(root: TreeNode) { treeDescription.visitTreeNodes( root, (n: TreeNode) => { // Assign symbols if (n.class === "join" && n.properties?.has("join")) { n.symbol = n.properties.get("join") + "-join-symbol"; } else if (n.tag === "join-inner") { n.symbol = "inner-join-symbol"; } else if (n.tag === "join-left") { n.symbol = "left-join-symbol"; } else if (n.tag === "join-right") { n.symbol = "right-join-symbol"; } else if (n.tag === "join-full") { n.symbol = "full-join-symbol"; } else if (n.class && n.class === "relation") { n.symbol = "table-symbol"; } else if (n.class && n.class === "createtemptable") { n.symbol = "temp-table-symbol"; } else if (n.tag == "selectOp") { n.symbol = "filter-symbol"; } else if (n.name && n.name === "runquery") { n.symbol = "run-query-symbol"; } // Assign classes for incoming edge if (n.tag === "binding" || n.class === "createtemptable" || (n.tag === "expression" && n.properties?.has("name"))) { assert(n.children !== undefined); n.children.forEach(c => { c.edgeClass = "qg-link-and-arrow"; }); } else if (n.name === "runquery") { assert(n.children !== undefined); n.children.forEach(c => { if (c.class === "createtemptable") { c.edgeClass = "qg-dotted-link"; } }); } }, treeDescription.allChildren, ); } function collapseNodes(root: TreeNode, graphCollapse?: unknown) { const streamlineOrCollapse = graphCollapse === "s" ? streamline : collapseAllChildren; if (graphCollapse !== "n") { treeDescription.visitTreeNodes( root, d => { switch (d.name) { case "condition": case "conditions": case "datasource": case "expressions": case "field": case "groupbys": case "group-bys": case "imports": case "measures": case "column-names": case "replaced-columns": case "renamed-columns": case "new-columns": case "metadata-record": case "metadata-records": case "orderbys": case "order-bys": case "filter": case "predicate": case "restrictions": case "runquery-columns": case "selects": case "schema": case "tid": case "top": case "aggregates": case "join-conditions": case "join-condition": case "arguments": case "function-node": case "type": case "tuples": streamlineOrCollapse(d); return; } switch (d.class) { case "relation": collapseAllChildren(d); return; } }, function(d): TreeNode[] { return d.children && d.children.length > 0 ? d.children.slice(0) : []; }, ); } } function getFederationConnectionType(node: TreeNode) { const connection = node.properties?.get("connection"); return connection ? connection.split(".")[0] : undefined; } // Color graph per federated connections function colorFederated(node: TreeNode, federatedType?: string) { if (node.tag === "fed-op") { federatedType = getFederationConnectionType(node) ?? federatedType; } if (federatedType !== undefined) { node.nodeClass = "qg-" + federatedType; } for (const child of treeDescription.allChildren(node)) { colorFederated(child, federatedType); } } // Prepare the loaded data for visualization function prepareTreeData(xml: ParsedXML, graphCollapse?: unknown): TreeNode { const treeData = convertXML(xml); // Tag the tree root if (!treeData.tag) { treeData.tag = "result"; } treeDescription.createParentLinks(treeData); generateDisplayNames(treeData); assignSymbolsAndClasses(treeData); colorFederated(treeData); collapseNodes(treeData, graphCollapse); return treeData; } // Function to add crosslinks between related nodes function addCrosslinks(root: TreeNode): Crosslink[] { interface UnresolvedCrosslink { source: TreeNode; targetName: string; } const unresolvedLinks: UnresolvedCrosslink[] = []; const operatorsByName = new Map<string, TreeNode>(); treeDescription.visitTreeNodes( root, node => { // Build map from potential target operator name/ref to node const ref = node.properties?.get("ref"); if (getFederationConnectionType(node) === "fedeval_dataengine_connection" && node.class === "relation" && node.name) { operatorsByName.set(node.name, node); } else if (node.tag === "binding" && ref !== undefined) { operatorsByName.set("ref", node); } // Identify source operators switch (node.tag) { case "fed-op": { const table = node.properties?.get("table"); if (node.properties?.get("class") === "createtemptable" && table !== undefined) { unresolvedLinks.push({source: node, targetName: table}); } break; } case "referenceOp": case "referenceExp": { const ref = node.properties?.get("ref"); if (ref !== undefined) { unresolvedLinks.push({source: node, targetName: ref}); } break; } default: break; } }, treeDescription.allChildren, ); // Add crosslinks from source to matching target node const crosslinks = [] as Crosslink[]; for (const link of unresolvedLinks) { const target = operatorsByName.get(link.targetName); if (target !== undefined) { crosslinks.push({source: link.source, target: target}); } } return crosslinks; } export function loadTableauPlan(graphString: string, graphCollapse?: unknown): TreeDescription { const xml = typesafeXMLParse(graphString); const root = prepareTreeData(xml, graphCollapse); const crosslinks = addCrosslinks(root); return {root: root, crosslinks: crosslinks}; }
the_stack
import * as util from "../../util.js"; import { repr, bySecondElem } from "./javascript.js"; import type { Request, Warnings } from "../../util.js"; const supportedArgs = new Set([ "url", "request", "user-agent", "cookie", "data", "data-raw", "data-ascii", "data-binary", "data-urlencode", "json", "form", "form-string", "referer", "get", "header", "head", "no-head", "user", "proxy", "proxy-user", "max-time", ]); // TODO: @ const _getDataString = (request: Request): [string | null, string | null] => { if (!request.data) { return [null, null]; } const originalStringRepr = repr(request.data); const contentType = util.getContentType(request); // can have things like ; charset=utf-8 which we want to preserve const exactContentType = util.getHeader(request, "content-type"); if (contentType === "application/json") { const parsed = JSON.parse(request.data); // Only arrays and {} can be passed to axios to be encoded as JSON // TODO: check this in other generators if (typeof parsed !== "object" || parsed === null) { return [originalStringRepr, null]; } const roundtrips = JSON.stringify(parsed) === request.data; const jsonAsJavaScript = repr(parsed, 1); if ( roundtrips && exactContentType === "application/json" && util.getHeader(request, "accept") === "application/json, text/plain, */*" ) { util.deleteHeader(request, "content-type"); util.deleteHeader(request, "accept"); } return [jsonAsJavaScript, roundtrips ? null : originalStringRepr]; } if (contentType === "application/x-www-form-urlencoded") { const query = util.parseQueryString(request.data); const queryDict = query[1]; if ( queryDict && Object.values(queryDict).every((v) => typeof v === "string") ) { // Technically axios sends // application/x-www-form-urlencoded;charset=utf-8 if (exactContentType === "application/x-www-form-urlencoded") { util.deleteHeader(request, "content-type"); } // TODO: check roundtrip, add a comment return ["new URLSearchParams(" + repr(queryDict, 1) + ")", null]; } else { return [originalStringRepr, null]; } } return [null, null]; }; const getDataString = (request: Request): [string | null, string | null] => { if (!request.data) { return [null, null]; } let dataString = null; let commentedOutDataString = null; try { [dataString, commentedOutDataString] = _getDataString(request); } catch {} if (!dataString) { dataString = repr(request.data); } return [dataString, commentedOutDataString]; }; const buildConfigObject = ( request: Request, method: string, methods: string[], dataMethods: string[], hasSearchParams: boolean, warnings: Warnings ): string => { let code = "{\n"; if (!methods.includes(method)) { // Axios uppercases methods code += " method: " + repr(method) + ",\n"; } if (hasSearchParams) { // code += " params,\n"; code += " params: params,\n"; } else if (request.queryDict) { code += " params: " + repr(request.queryDict, 1) + ",\n"; } const [dataString, commentedOutDataString] = getDataString(request); // can delete headers if ((request.headers && request.headers.length) || request.multipartUploads) { code += " headers: {\n"; if (request.multipartUploads) { code += " ...form.getHeaders(),\n"; } for (const [key, value] of request.headers || []) { code += " " + repr(key) + ": " + repr(value || "") + ",\n"; } if (code.endsWith(",\n")) { code = code.slice(0, -2); code += "\n"; } code += " },\n"; } if (request.auth) { const [username, password] = request.auth; code += " auth: {\n"; code += " username: " + repr(username); if (password) { code += ",\n"; code += " password: " + repr(password) + "\n"; } else { code += "\n"; } code += " },\n"; } if (!dataMethods.includes(method)) { if (request.data) { if (commentedOutDataString) { code += " // data: " + commentedOutDataString + ",\n"; } code += " data: " + dataString + ",\n"; // OPTIONS is the only other http method that sends data if (method !== "options") { warnings.push([ "no-data-method", "axios doesn't send data: with " + method + " requests", ]); } } else if (request.multipartUploads) { code += " data: form,\n"; if (method !== "options") { warnings.push([ "no-data-method", "axios doesn't send data: with " + method + " requests", ]); } } } if (request.timeout) { const timeout = parseFloat(request.timeout); if (!isNaN(timeout) && timeout > 0) { code += " timeout: " + timeout * 1000 + ",\n"; } } if (request.proxy === "") { // TODO: this probably won't be set if it's empty // TODO: could have --socks5 proxy code += " proxy: false,\n"; } else if (request.proxy) { // TODO: do this parsing in utils.ts const proxy = request.proxy.includes("://") ? request.proxy : "http://" + request.proxy; let [protocol, host] = proxy.split(/:\/\/(.*)/s, 2); protocol = protocol.toLowerCase() === "socks" ? "socks4" : protocol.toLowerCase(); host = host ? host : ""; let port = "1080"; const proxyPart = host.match(/:([0-9]+$)/); if (proxyPart) { host = host.slice(0, proxyPart.index); port = proxyPart[1]; } const portInt = parseInt(port); code += " proxy: {\n"; code += " protocol: " + repr(protocol) + ",\n"; code += " host: " + repr(host) + ",\n"; if (!isNaN(portInt)) { code += " port: " + port + ",\n"; } else { code += " port: " + repr(port) + ",\n"; } if (request.proxyAuth) { const [proxyUser, proxyPassword] = request.proxyAuth.split(/:(.*)/s, 2); code += " auth: {\n"; code += " user: " + repr(proxyUser); if (proxyPassword !== undefined) { code += ",\n"; code += " password: " + repr(proxyPassword) + "\n"; } else { code += "\n"; } code += " },\n"; } if (code.endsWith(",\n")) { code = code.slice(0, -2); code += "\n"; } code += " },\n"; } if (code.endsWith(",\n")) { code = code.slice(0, -2); } code += "\n}"; return code; }; export const _toNodeAxios = ( request: Request, warnings: Warnings = [] ): string => { let importCode = "const axios = require('axios');\n"; const imports: Set<[string, string]> = new Set(); let code = ""; const hasSearchParams = request.query && (!request.queryDict || // https://stackoverflow.com/questions/42898009/multiple-fields-with-same-key-in-query-params-axios-request Object.values(request.queryDict).some((qv) => Array.isArray(qv))); if (hasSearchParams && request.query) { code += "const params = new URLSearchParams();\n"; for (const [key, value] of request.query) { const val = value ? value : ""; code += "params.append(" + repr(key) + ", " + repr(val) + ");\n"; } code += "\n"; } if (request.multipartUploads) { imports.add(["FormData", "form-data"]); code += "const form = new FormData();\n"; for (const m of request.multipartUploads) { code += "form.append(" + repr(m.name) + ", "; if ("contentFile" in m) { imports.add(["fs", "fs"]); if (m.contentFile === "-") { code += "fs.readFileSync(0).toString()"; } else { code += "fs.readFileSync(" + repr(m.contentFile) + ")"; } if ("filename" in m && m.filename) { code += ", " + repr(m.filename); } } else { code += repr(m.content); } code += ");\n"; } code += "\n"; } const method = request.method.toLowerCase(); const methods = ["get", "delete", "head", "options", "post", "put", "patch"]; code += "const response = await axios"; if (methods.includes(method)) { code += "." + method; } code += "("; const url = request.queryDict || hasSearchParams ? request.urlWithoutQuery : request.url; // axios only supports posting data with these HTTP methods // You can also post data with OPTIONS, but that has to go in the config object const dataMethods = ["post", "put", "patch"]; let needsConfig = !!( request.query || request.queryDict || request.headers || request.auth || request.multipartUploads || (request.data && !dataMethods.includes(method)) || request.timeout || request.proxy ); const needsData = dataMethods.includes(method) && (request.data || request.multipartUploads || needsConfig); let dataString, commentedOutDataString; if (needsData) { code += "\n"; code += " " + repr(url) + ",\n"; if (request.data) { try { [dataString, commentedOutDataString] = getDataString(request); if (!dataString) { dataString = repr(request.data); } } catch { dataString = repr(request.data); } if (commentedOutDataString) { code += " // " + commentedOutDataString + ",\n"; } code += " " + dataString; } else if (request.multipartUploads) { code += " form"; } else if (needsConfig) { // TODO: this works but maybe undefined would be more correct? code += " ''"; } } else { code += repr(url); } // getDataString() can delete a header, so we can end up with an empty config needsConfig = !!( request.query || request.queryDict || (request.headers && request.headers.length) || request.auth || request.multipartUploads || (request.data && !dataMethods.includes(method)) || request.timeout || request.proxy ); if (needsConfig) { const config = buildConfigObject( request, method, methods, dataMethods, !!hasSearchParams, warnings ); if (needsData) { code += ",\n"; for (const line of config.split("\n")) { code += " " + line + "\n"; } } else { code += ", "; code += config; } } else if (needsData) { code += "\n"; } code += ");\n"; for (const [varName, imp] of Array.from(imports).sort(bySecondElem)) { importCode += "const " + varName + " = require(" + repr(imp) + ");\n"; } return importCode + "\n" + code; }; export const toNodeAxiosWarn = ( curlCommand: string | string[], warnings: Warnings = [] ): [string, Warnings] => { const request = util.parseCurlCommand(curlCommand, supportedArgs, warnings); const nodeAxios = _toNodeAxios(request, warnings); return [nodeAxios, warnings]; }; export const toNodeAxios = (curlCommand: string | string[]): string => { return toNodeAxiosWarn(curlCommand)[0]; };
the_stack
export interface Vehicle { id: string; vehicleID: number; [key: string]: string | number | boolean | null; } export interface Credentials { username: string; password: string; mfaPassCode?: string | undefined; mfaDeviceName?: string | undefined; } export interface TokenResponse { response: object; body: object; authToken: string; refreshToken: string; } export type nodeBack = (error: Error, data: any) => any; export interface optionsType { authToken: string; vehicleID: string; carIndex?: number | undefined; } export interface Result { reason: string; result: boolean; } export const streamingPortal: string; export const portal: string; export const API_LOG_ALWAYS: number; export const API_ERR_LEVEL: number; export const API_CALL_LEVEL: number; export const API_RETURN_LEVEL: number; export const API_BODY_LEVEL: number; export const API_REQUEST_LEVEL: number; export const API_RESPONSE_LEVEL: number; export const API_LOG_ALL: number; export const CHARGE_STORAGE: number; export const CHARGE_DAILY: number; export const CHARGE_STANDARD: number; export const CHARGE_RANGE: number; export const SUNROOF_VENT: string; export const SUNROOF_CLOSED: string; export const MIN_TEMP: number; export const MAX_TEMP: number; export const FRUNK: string; export const TRUNK: string; export const streamingColumns: string[]; export function setLogLevel(level: number): void; export function getLogLevel(): number; export function setPortalBaseURI(uri: string): void; export function getPortalBaseURI(): string; export function setStreamingBaseURI(uri: string): void; export function getStreamingBaseURI(): string; export function getModel(vehicle: Vehicle): string; export function vinDecode(vehicle: Vehicle): object; export function getPaintColor(vehicle: Vehicle): string; export function getVin(vehicle: Vehicle): string; export function getShortVin(vehicle: Vehicle): string; export function login(credentials: Credentials, callback: nodeBack): void; export function loginAsync(credentials: Credentials): Promise<TokenResponse>; export function refreshToken(refresh_token: string, callback: nodeBack): void; export function refreshTokenAsync(refresh_token: string): Promise<TokenResponse>; export function logout(authToken: string, callback: nodeBack): void; export function logoutAsync(authToken: string): Promise<void>; export function vehicle(options: optionsType, callback: nodeBack): Vehicle; export function vehicleAsync(options: optionsType): Promise<Vehicle>; export function vehicles(options: optionsType, callback: nodeBack): void; export function vehiclesAsync(options: optionsType): Promise<Array<{[key: string]: string | number | boolean | null}>>; export function get_command(options: optionsType, command: string, callback: nodeBack): void; export function get_commandAsync(options: optionsType, command: string): Promise<any>; export function post_command(options: optionsType, command: string, body: object, callback: nodeBack): void; export function post_commandAsync(options: optionsType, command: string, body: object): Promise<any>; export function vehicleData(options: optionsType, callback: nodeBack): void; export function vehicleDataAsync(options: optionsType): Promise<object>; export function vehicleConfig(options: optionsType, callback: nodeBack): void; export function vehicleConfigAsync(options: optionsType): Promise<object>; export function vehicleState(options: optionsType, callback: nodeBack): void; export function vehicleStateAsync(options: optionsType): Promise<object>; export function climateState(options: optionsType, callback: nodeBack): void; export function climateStateAsync(options: optionsType): Promise<object>; export function nearbyChargers(options: optionsType, callback: nodeBack): void; export function nearbyChargersAsync(options: optionsType): Promise<object>; export function driveState(options: optionsType, callback: nodeBack): void; export function driveStateAsync(options: optionsType): Promise<object>; export function chargeState(options: optionsType, callback: nodeBack): void; export function chargeStateAsync(options: optionsType): Promise<object>; export function guiSettings(options: optionsType, callback: nodeBack): void; export function guiSettingsAsync(options: optionsType): Promise<object>; export function mobileEnabled(options: optionsType, callback: nodeBack): void; export function mobileEnabledAsync(options: optionsType): Promise<{ response: boolean }>; export function honkHorn(options: optionsType, callback: nodeBack): void; export function honkHornAsync(options: optionsType): Promise<Result>; export function flashLights(options: optionsType, callback: nodeBack): void; export function flashLightsAsync(options: optionsType): Promise<Result>; export function startCharge(options: optionsType, callback: nodeBack): void; export function startChargeAsync(options: optionsType): Promise<Result>; export function stopCharge(options: optionsType, callback: nodeBack): void; export function stopChargeAsync(options: optionsType): Promise<Result>; export function openChargePort(options: optionsType, callback: nodeBack): void; export function openChargePortAsync(options: optionsType): Promise<Result>; export function closeChargePort(options: optionsType, callback: nodeBack): void; export function closeChargePortAsync(options: optionsType): Promise<Result>; export function scheduleSoftwareUpdate(options: optionsType, offset: number, callback: any): any; export function scheduleSoftwareUpdateAsync(options: optionsType): Promise<Result>; export function cancelSoftwareUpdate(options: optionsType, callback: any): any; export function cancelSoftwareUpdateAsync(options: optionsType): Promise<Result>; export function navigationRequest(options: optionsType, subject: string, text: string, locale: string, callback: any): any; export function navigationRequestAsync(options: optionsType, subject: string, text: string, locale: string): Promise<Result>; export function mediaTogglePlayback(options: optionsType, callback: any): any; export function mediaTogglePlaybackAsync(options: optionsType): Promise<Result>; export function mediaPlayNext(options: optionsType, callback: any): any; export function mediaPlayNextAsync(options: optionsType): Promise<Result>; export function mediaPlayPrevious(options: optionsType, callback: any): any; export function mediaPlayPreviousAsync(options: optionsType): Promise<Result>; export function mediaPlayNextFavorite(options: optionsType, callback: any): any; export function mediaPlayNextFavoriteAsync(options: optionsType): Promise<Result>; export function mediaPlayPreviousFavorite(options: optionsType, callback: any): any; export function mediaPlayPreviousFavoriteAsync(options: optionsType): Promise<Result>; export function mediaVolumeUp(options: optionsType, callback: any): any; export function mediaVolumeUpAsync(options: optionsType): Promise<Result>; export function mediaVolumeDown(options: optionsType, callback: any): any; export function mediaVolumeDownAsync(options: optionsType): Promise<Result>; export function speedLimitActivate(options: optionsType, pin: number, callback: any): any; export function speedLimitActivateAsync(options: optionsType, pin: number): Promise<Result>; export function speedLimitDeactivate(options: optionsType, pin: number, callback: any): any; export function speedLimitDeactivateAsync(options: optionsType, pin: number): Promise<Result>; export function speedLimitClearPin(options: optionsType, pin: number, callback: any): any; export function speedLimitClearPinAsync(options: optionsType, pin: number): Promise<Result>; export function speedLimitSetLimit(options: optionsType, limit: number, callback: any): any; export function speedLimitSetLimitAsync(options: optionsType, limit: number): Promise<Result>; export function setSentryMode(options: optionsType, onoff: boolean, callback: any): any; export function setSentryModeAsync(options: optionsType, onoff: boolean): Promise<Result>; export function seatHeater(options: optionsType, heater: number, level: number, callback: any): any; export function seatHeaterAsync(options: optionsType, heater: number, level: number): Promise<Result>; export function steeringHeater(options: optionsType, level: number, callback: any): any; export function steeringHeaterAsync(options: optionsType, level: number): Promise<Result>; export function maxDefrost(options: optionsType, onoff: boolean, callback: any): any; export function maxDefrostAsync(options: optionsType, onoff: boolean): Promise<Result>; export function windowControl(options: optionsType, command: string, callback: any): any; export function windowControlAsync(options: optionsType, command: string): Promise<Result>; export function setChargeLimit(options: optionsType, amt: any, callback: nodeBack): void; export function setChargeLimitAsync(options: optionsType, amt: any): Promise<Result>; export function chargeStandard(options: optionsType, callback: nodeBack): void; export function chargeStandardAsync(options: optionsType): Promise<Result>; export function chargeMaxRange(options: optionsType, callback: nodeBack): void; export function chargeMaxRangeAsync(options: optionsType): Promise<Result>; export function doorLock(options: optionsType, callback: nodeBack): void; export function doorLockAsync(options: optionsType): Promise<Result>; export function doorUnlock(options: optionsType, callback: nodeBack): void; export function doorUnlockAsync(options: optionsType): Promise<Result>; export function climateStart(options: optionsType, callback: nodeBack): void; export function climateStartAsync(options: optionsType): Promise<Result>; export function climateStop(options: optionsType, callback: nodeBack): void; export function climateStopAsync(options: optionsType): Promise<Result>; export function sunRoofControl(options: optionsType, state: string, callback: nodeBack): void; export function sunRoofControlAsync(options: optionsType, state: string): Promise<Result>; export function sunRoofMove(options: optionsType, percent: any, callback: nodeBack): void; export function sunRoofMoveAsync(options: optionsType, percent: any): Promise<Result>; export function setTemps(options: optionsType, driver: number, pass: number, callback: nodeBack): void; export function setTempsAsync(options: optionsType, driver: number, pass: number): Promise<Result>; export function remoteStart(options: optionsType, password: string, callback: nodeBack): void; export function remoteStartAsync(options: optionsType, password: string): Promise<Result>; export function openTrunk(options: optionsType, which: string, callback: nodeBack): void; export function openTrunkAsync(options: optionsType, which: string): Promise<Result>; export function wakeUp(options: optionsType, callback: nodeBack): void; export function wakeUpAsync(options: optionsType): Promise<object>; export function setValetMode(options: optionsType, onoff: boolean, pin: any, callback: nodeBack): void; export function setValetModeAsync(options: optionsType, onoff: boolean, pin: any): Promise<Result>; export function resetValetPin(options: optionsType, callback: nodeBack): void; export function resetValetPinAsync(options: optionsType): Promise<Result>; export function calendar(options: optionsType, entry: any, callback: nodeBack): void; export function calendarAsync(options: optionsType, entry: any): Promise<Result>; export function makeCalendarEntry(eventName: string, location: string, startTime: number, endTime: number, accountName: string, phoneName: string): object; export function homelink(options: optionsType, lat: number, long: number, token: string, callback: nodeBack): void; export function homelinkAsync(options: optionsType, lat: number, long: number, token: string): Promise<Result>; export function products(options: optionsType, callback: nodeBack): void; export function productsAsync(options: optionsType): Promise<object[]>; export function solarStatus(options: optionsType, callback: nodeBack): void; export function solarStatusAsync(options: optionsType): Promise<object>; export function startStreaming(options: any, callback: nodeBack, onDataCb: nodeBack): any;
the_stack
import { ManagedEvent } from "../../core"; import { UIComponentEvent, UIComponentEventHandler, UIRenderable, UIRenderableConstructor, } from "../UIComponent"; import { UIStyle } from "../UIStyle"; import { UITheme } from "../UITheme"; import { UIContainer } from "./UIContainer"; /** Slowdown factor at which scrolling will begin to snap */ const SNAP_SLOWDOWN = 0.75; /** Event that is emitted on a scroll container component, to be handled by a platform specific renderer (observer) to modify scroll positions. Instances should not be reused. */ export class UIScrollTargetEvent extends ManagedEvent { /** Create a new event for given component */ constructor( source: UIScrollContainer, target?: UIScrollTargetEvent["target"], yOffset?: number, xOffset?: number ) { super("UIScrollTarget"); this.source = source; this.target = target; this.yOffset = yOffset; this.xOffset = xOffset; } /** Event source UI component */ readonly source: UIScrollContainer; /** Scroll target, optional */ readonly target?: "top" | "bottom"; /** Y offset (top/bottom scroll position), optional */ yOffset?: number; /** X offset (left/right scroll position), optional */ xOffset?: number; } /** Event that is emitted when the user scrolls up or down in a `UIScrollContainer */ export class UIScrollEvent extends UIComponentEvent<UIScrollContainer> { /** Vertical scroll offset; platform-dependent value, should not be used for positioning but can be used with `UIScrollContainer.scrollTo()` */ yOffset!: number; /** Horizontal scroll offset; platform-dependent value, may change with text direction, should not be used for positioning but can be used with `UIScrollContainer.scrollTo()` */ xOffset!: number; /** Horizontal scrolling velocity (screen widths per second) */ horizontalVelocity!: number; /** Horizontal scrolling velocity (screen heights per second) */ verticalVelocity!: number; /** True if (last) scrolled down */ scrolledDown?: boolean; /** True if (last) scrolled up */ scrolledUp?: boolean; /** True if (last) scrolled left for LTR text direction, right for RTL */ scrolledHorizontalStart?: boolean; /** True if (last) scrolled right for LTR text direction, left for RTL */ scrolledHorizontalEnd?: boolean; /** True if the `UIScrollContainer` is scrolled to the top */ atTop?: boolean; /** True if the `UIScrollContainer` is scrolled to the bottom */ atBottom?: boolean; /** True if the `UIScrollContainer` is scrolled to the left for LTR text direction, right for RTL */ atHorizontalStart?: boolean; /** True if the `UIScrollContainer` is scrolled to the right for LTR text direction, left for RTL */ atHorizontalEnd?: boolean; } /** Represents a UI component that contains other components and allows scrolling horizontally and/or vertically, and emits throttled scroll events (`Scroll` and `ScrollEnd`, see `UIScrollEvent`) */ export class UIScrollContainer extends UIContainer { static preset( presets: UIScrollContainer.Presets, ...components: Array<UIRenderableConstructor | undefined> ): Function { return super.preset(presets, ...components); } /** Create a new scroll container view component */ constructor(...content: UIRenderable[]) { super(...content); this.style = UITheme.getStyle("container", "scroll"); } /** Padding around contained elements (in dp or CSS string, or separate offset values) */ padding?: UIStyle.Offsets; /** Vertical scroll snap mode: `start` (snap to start of first 'mostly' visible component), `center` (snap container center to center of component closest to the center), or `end` (snap to end of last 'mostly' visible component) */ verticalSnap?: "start" | "center" | "end"; /** Horizontal scroll snap mode: `start` (snap to start of first 'mostly' visible component), `center` (snap container center to center of component closest to the center), or `end` (snap to end of last 'mostly' visible component) */ horizontalSnap?: "start" | "center" | "end"; /** Vertical threshold (in pixels) until which `UIScrollEvent.atTop` is set, defaults to 0 */ topThreshold = 0; /** Vertical threshold (in pixels) until which `UIScrollEvent.atBottom` is set, defaults to 0 */ bottomThreshold = 0; /** Horizontal threshold (in pixels) until which `UIScrollEvent.atHorizontalStart` or `UIScrollEvent.atHorizontalEnd` is set, defaults to 0 */ horizontalThreshold = 0; /** True if vertical scrolling should be enabled if necessary, defaults to true */ verticalScrollEnabled = true; /** True if horizontal scrolling should be enabled if necessary, defaults to true */ horizontalScrollEnabled = true; /** Scroll to the given pair of vertical and horizontal offset values; positioning is platform dependent and may also change with text direction, use only values taken from `UIScrollEvent.yOffset` and `UIScrollEvent.xOffset` */ scrollTo(yOffset?: number, xOffset?: number) { this.emit(new UIScrollTargetEvent(this, undefined, yOffset, xOffset).freeze()); } /** Scroll to the top of the scrollable content, if possible; may be handled asynchronously */ scrollToTop() { this.emit(new UIScrollTargetEvent(this, "top").freeze()); } /** Scroll to the bottom of the scrollable content, if possible; may be handled asynchronously */ scrollToBottom() { this.emit(new UIScrollTargetEvent(this, "bottom").freeze()); } /** Handle given scroll event to snap scroll position to content components; called automatically when the container is scrolled, but may be overridden */ public handleScrollSnap(e: UIScrollEvent) { if (this.horizontalSnap || this.verticalSnap) { let vert = this._vertScrollState; let horz = this._horzScrollState; if (e.name === "ScrollEnd") { // reset all values vert.up = vert.down = false; horz.start = horz.end = false; vert.high = 0; horz.high = 0; } else { // update vertical state if ((e.scrolledUp && vert.up) || (e.scrolledDown && vert.down)) { if (e.verticalVelocity >= vert.velocity) { vert.slowing = 0; if (e.verticalVelocity > vert.high) vert.high = e.verticalVelocity; } else { vert.slowing++; // emit ScrollSnap* events which are picked up by the renderer // together with ScrollEnd to snap up/down if (vert.slowing > 1 && e.verticalVelocity < vert.high * SNAP_SLOWDOWN) { vert.slowing = vert.high = 0; if (vert.up && this.verticalSnap === "start") { this.emitAction("ScrollSnapUp", e); } if (vert.down && this.verticalSnap === "end") { this.emitAction("ScrollSnapDown", e); } } } } else { vert.slowing = 0; vert.high = 0; } vert.up = !!e.scrolledUp; vert.down = !!e.scrolledDown; vert.velocity = e.verticalVelocity; // update horizontal state if ( (e.scrolledHorizontalStart && horz.start) || (e.scrolledHorizontalEnd && horz.end) ) { if (e.horizontalVelocity >= horz.velocity) { horz.slowing = 0; if (e.horizontalVelocity > horz.high) horz.high = e.horizontalVelocity; } else { horz.slowing++; // emit ScrollSnap* events which are picked up by the renderer // together with ScrollEnd to snap left/right if (horz.slowing > 1 && e.horizontalVelocity < horz.high * SNAP_SLOWDOWN) { horz.slowing = horz.high = 0; // TODO: localize for RTL containers (?) if (horz.start && this.horizontalSnap === "start") { this.emitAction("ScrollSnapHorizontalStart", e); } if (horz.end && this.horizontalSnap === "end") { this.emitAction("ScrollSnapHorizontalEnd", e); } } } } else { horz.slowing = 0; horz.high = 0; } horz.start = !!e.scrolledHorizontalStart; horz.end = !!e.scrolledHorizontalEnd; horz.velocity = e.horizontalVelocity; } } } // keep track of scroll states, used above private _vertScrollState = { up: false, down: false, slowing: 0, high: 0, velocity: 0, }; private _horzScrollState = { start: false, end: false, slowing: 0, high: 0, velocity: 0, }; } // handle scroll snap using an event handler and the implementation method UIScrollContainer.addEventHandler(function (e) { if (e instanceof UIScrollEvent) this.handleScrollSnap(e); }); export namespace UIScrollContainer { /** UIScrollContainer presets type, for use with `Component.with` */ export interface Presets extends UIContainer.Presets { /** Padding around contained elements (in dp or CSS string, or separate offset values) */ padding?: UIStyle.Offsets; /** True if vertical scrolling should be enabled, defaults to true */ verticalScrollEnabled?: boolean; /** True if horizontal scrolling should be enabled, defaults to true */ horizontalScrollEnabled?: boolean; /** Vertical scroll snap mode: `start` (snap to start of first 'mostly' visible component), `center` (snap container center to center of component closest to the center), or `end` (snap to end of last 'mostly' visible component) */ verticalSnap?: "start" | "center" | "end"; /** Horizontal scroll snap mode: `start` (snap to start of first 'mostly' visible component), `center` (snap container center to center of component closest to the center), or `end` (snap to end of last 'mostly' visible component) */ horizontalSnap?: "start" | "center" | "end"; /** Vertical threshold (in pixels) until which `UIScrollEvent.atTop` is set, defaults to 0 */ topThreshold?: number; /** Vertical threshold (in pixels) until which `UIScrollEvent.atBottom` is set, defaults to 0 */ bottomThreshold?: number; /** Horizontal threshold (in pixels) until which `UIScrollEvent.atHorizontalStart` or `UIScrollEvent.atHorizontalEnd` is set, defaults to 0 */ horizontalThreshold?: number; /** Event handler for Scroll events */ onScroll?: UIComponentEventHandler; /** Event handler for ScrollEnd events */ onScrollEnd?: UIComponentEventHandler; } }
the_stack
import { browser, protractor, $} from 'protractor'; import { Login } from '../page-objects/login.po'; import { OverviewCompliance } from '../page-objects/overview.po'; import { CompliancePolicy } from '../page-objects/compliance-policy.po'; import { PolicyDetails } from '../page-objects/policy-details.po'; import { AssetDetails } from '../page-objects/asset-details.po'; import { AssetList } from '../page-objects/asset-list.po'; import { PolicyViolationsDetail } from '../page-objects/policy-violations-detail.po'; const timeOutHigh = 180000; describe('CompliancePolicy', () => { let login_po: Login; let OverviewCompliance_po: OverviewCompliance; let AssetDetails_po: AssetDetails; let AssetList_po: AssetList; let CompliancePolicy_po: CompliancePolicy; let policyDetailspo: PolicyDetails; let violationDetails_po: PolicyViolationsDetail; const EC = protractor.ExpectedConditions; beforeAll(() => { login_po = new Login(); OverviewCompliance_po = new OverviewCompliance(); policyDetailspo = new PolicyDetails(); CompliancePolicy_po = new CompliancePolicy(); AssetDetails_po = new AssetDetails(); AssetList_po = new AssetList(); violationDetails_po = new PolicyViolationsDetail(); }); it('Check page title', () => { browser.wait(EC.visibilityOf( OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh); browser.wait(EC.elementToBeClickable( OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh); OverviewCompliance_po.navigateToOverviewCompliance().click(); browser.wait(EC.visibilityOf( OverviewCompliance_po.policyTitleSort()), timeOutHigh); OverviewCompliance_po.policyTitleSort().click(); browser.wait(EC.visibilityOf( OverviewCompliance_po.getSixthRowCell()), timeOutHigh); OverviewCompliance_po.getSixthRowCell().click(); const page_title = CompliancePolicy_po.getTitle().getText(); expect(page_title).toEqual('Policy Compliance'); }); it('Check if percentage lies in range 0-100', () => { browser.wait(EC.visibilityOf( CompliancePolicy_po.getCompliancePercent()), timeOutHigh); CompliancePolicy_po.getCompliancePercent().getText().then(function (text) { let checkPercentRange = false; if (parseInt(text, 10) >= 0 && parseInt(text, 10) <= 100) { checkPercentRange = true; } expect(checkPercentRange).toEqual(true); }); }); it('Verify list table filter search', () => { browser.wait(EC.visibilityOf( CompliancePolicy_po.getListTableFirstTotal()), timeOutHigh); CompliancePolicy_po.getSearchInput().click(); browser.sleep(401); browser.wait(EC.visibilityOf(CompliancePolicy_po.getSearchInput()), timeOutHigh); CompliancePolicy_po.getSearchInput().sendKeys('my'); CompliancePolicy_po.getFirstRowCell().getText().then(function (text) { expect(text.toLowerCase()).toContain('my'); }); browser.sleep(401); CompliancePolicy_po.getSearchInput().sendKeys(''); }); it('Verify table filter search', () => { browser.wait(EC.visibilityOf( CompliancePolicy_po.getPolicyName()), timeOutHigh); CompliancePolicy_po.getSearchLabel().click(); browser.sleep(401); browser.wait(EC.visibilityOf(CompliancePolicy_po.getTableSearchInput()), timeOutHigh); CompliancePolicy_po.getTableSearchInput().sendKeys('amazon'); browser.actions().sendKeys(protractor.Key.ENTER).perform(); browser.wait(EC.visibilityOf(CompliancePolicy_po.getTableSearchInput()), timeOutHigh); CompliancePolicy_po.getPolicyName().getText().then(function (text) { expect(text.toLowerCase()).toContain('amazon'); }); browser.sleep(401); CompliancePolicy_po.getSearchInput().sendKeys(''); browser.actions().sendKeys(protractor.Key.ENTER).perform(); $('label.search-label img').click(); }); it('Verify redirect to policy details page', () => { browser.wait(EC.visibilityOf(CompliancePolicy_po.getDataLoad()), timeOutHigh); browser.wait(EC.elementToBeClickable(CompliancePolicy_po.getDataLoad()), timeOutHigh); CompliancePolicy_po.getMoreArrow().click(); CompliancePolicy_po.getViewMore().click(); browser.wait(EC.visibilityOf(policyDetailspo.getPolicyDetailsHeading()), timeOutHigh); expect(policyDetailspo.getPolicyDetailsHeading().getText()).toEqual('Policy Details'); browser.wait(EC.elementToBeClickable(policyDetailspo.getBackArrow()), timeOutHigh); policyDetailspo.getBackArrow().click(); }); it('Verify redirect to asset listing page', () => { browser.wait(EC.visibilityOf(CompliancePolicy_po.getListTableFirstTotal()), timeOutHigh); CompliancePolicy_po.getListTableFirstTotal().click(); browser.wait(EC.visibilityOf(AssetList_po.getAssetHeaderText()), timeOutHigh); expect(AssetList_po.getAssetHeaderText().getText()).toEqual('Asset List'); browser.wait(EC.elementToBeClickable(AssetList_po.goBack()), timeOutHigh); AssetList_po.goBack().click(); }); it('Verify total number match to asset listing page', () => { browser.wait(EC.visibilityOf(CompliancePolicy_po.getListTableFirstTotal()), timeOutHigh); const first_list_total = CompliancePolicy_po.getListTableFirstTotal().getText(); CompliancePolicy_po.getListTableFirstTotal().click(); browser.wait(EC.visibilityOf(AssetList_po.getAssetTotalRows()), timeOutHigh); expect(AssetList_po.getAssetTotalRows().getText()).toEqual(first_list_total); browser.wait(EC.elementToBeClickable(AssetList_po.goBack()), timeOutHigh); AssetList_po.goBack().click(); }); it('Verify redirect to policy details page from table', () => { browser.wait(EC.visibilityOf(CompliancePolicy_po.getPolicyName()), timeOutHigh); browser.wait(EC.elementToBeClickable(CompliancePolicy_po.getPolicyName()), timeOutHigh); CompliancePolicy_po.getPolicyName().click(); expect(policyDetailspo.getPolicyDetailsHeading().getText()).toEqual('Policy Details'); policyDetailspo.getBackArrow().click(); }); it('Verify redirect to policy violation details page from table', () => { browser.wait(EC.visibilityOf(CompliancePolicy_po.getIssueId()), timeOutHigh); browser.wait(EC.elementToBeClickable(CompliancePolicy_po.getIssueId()), timeOutHigh); CompliancePolicy_po.getIssueId().click(); expect(violationDetails_po.getPolicyViolationDetailHeading().getText()).toEqual('Policy Violations Details'); violationDetails_po.getBackArrow().click(); }); it('Verify redirect to asset details page from table', () => { browser.wait(EC.visibilityOf(CompliancePolicy_po.getResourceId()), timeOutHigh); browser.wait(EC.elementToBeClickable(CompliancePolicy_po.getResourceId()), timeOutHigh); CompliancePolicy_po.getResourceId().click(); browser.wait(EC.visibilityOf(AssetDetails_po.getAssetHeaderText()), timeOutHigh); expect(AssetDetails_po.getAssetHeaderText().getText()).toEqual('Asset Details'); browser.sleep(401); browser.wait(EC.elementToBeClickable(AssetDetails_po.getBackArrow()), timeOutHigh); AssetDetails_po.getBackArrow().click(); }); it('Check table sort functionality', () => { browser.wait(EC.visibilityOf( CompliancePolicy_po.getPolicyName()), timeOutHigh); CompliancePolicy_po.resourceIdSort().click(); let first_row; browser.wait(EC.visibilityOf( CompliancePolicy_po.getResourceId()), timeOutHigh); CompliancePolicy_po.getResourceId().getText().then(function (text) { first_row = text.toLowerCase(); }); let second_row; browser.wait(EC.visibilityOf( CompliancePolicy_po.getSecondResourceId()), timeOutHigh); CompliancePolicy_po.getSecondResourceId().getText().then(function (text) { second_row = text.toLowerCase(); expect(first_row < second_row).toEqual(true); }); }); it('Check compliance percent calculation', () => { browser.wait(EC.visibilityOf( CompliancePolicy_po.getCompliancePercent()), timeOutHigh); let percent; let passed; let total; CompliancePolicy_po.getCompliancePercent().getText().then(function (text) { percent = parseInt(text.replace(/,/g, ''), 10); }); browser.wait(EC.visibilityOf( CompliancePolicy_po.getPassedAssets()), timeOutHigh); CompliancePolicy_po.getPassedAssets().getText().then(function (text) { passed = parseInt(text.replace(/,/g, ''), 10); }); browser.wait(EC.visibilityOf( CompliancePolicy_po.getTotalAssets()), timeOutHigh); CompliancePolicy_po.getTotalAssets().getText().then(function (text) { total = parseInt(text.replace(/,/g, ''), 10); expect(percent).toEqual(Math.floor((100 * passed / total))); }); }); it('Check if sum of total passed and failed equals Total', () => { browser.wait(EC.visibilityOf(CompliancePolicy_po.getTotalAssets()), timeOutHigh); let total_percent = 0; let passed_percent; let failed_percent; CompliancePolicy_po.getTotalAssets().getText().then(function (text) { total_percent = parseInt(text.replace(/,/g, ''), 10); }); browser.wait(EC.visibilityOf( CompliancePolicy_po.getPassedAssets()), timeOutHigh); CompliancePolicy_po.getPassedAssets().getText().then(function (text) { passed_percent = parseInt(text.replace(/,/g, ''), 10); }); browser.wait(EC.visibilityOf( CompliancePolicy_po.getFailedAssets()), timeOutHigh); CompliancePolicy_po.getFailedAssets().getText().then(function (text) { failed_percent = parseInt(text.replace(/,/g, ''), 10); expect(total_percent.toString()).toEqual((passed_percent + failed_percent).toString()); }); }); it('Check if sum of passed and failed equals Total in list table', () => { browser.wait(EC.visibilityOf(CompliancePolicy_po.getListTableFirstTotal()), timeOutHigh); let total_percent = 0; let passed_percent; let failed_percent; CompliancePolicy_po.getListTableFirstTotal().getText().then(function (text) { total_percent = parseInt(text.replace(/,/g, ''), 10); }); browser.wait(EC.visibilityOf( CompliancePolicy_po.getListTableFirstPassed()), timeOutHigh); CompliancePolicy_po.getListTableFirstPassed().getText().then(function (text) { passed_percent = parseInt(text.replace(/,/g, ''), 10); }); browser.wait(EC.visibilityOf( CompliancePolicy_po.getListTableFirstFailed()), timeOutHigh); CompliancePolicy_po.getListTableFirstFailed().getText().then(function (text) { failed_percent = parseInt(text.replace(/,/g, ''), 10); expect(total_percent.toString()).toEqual((passed_percent + failed_percent).toString()); }); }); it('Check filter tags', () => { browser.wait(EC.visibilityOf(CompliancePolicy_po.getListTableFirstPassed()), timeOutHigh); let appl_name; CompliancePolicy_po.getFirstRowCell().getText().then(function(text) { appl_name = text.toLowerCase(); }); CompliancePolicy_po.getListTableFirstPassed().click(); browser.wait(EC.visibilityOf(AssetList_po.getFirstFilter()), timeOutHigh); AssetList_po.getAllFilters().then(function(items) { for (let i = 1; i <= items.length; i++) { $('.floating-widgets-filter-wrapper .each-filter:nth-child(' + i + ')').getText().then(function(text) { if (text.toLowerCase().match(appl_name.toLowerCase())) { expect(text.toLowerCase()).toContain(appl_name.toLowerCase()); } }); } browser.wait(EC.elementToBeClickable(AssetList_po.goBack()), timeOutHigh); AssetList_po.goBack().click(); }); }); it('Check if sum of all passed in list table equals table total passed', () => { browser.wait(EC.visibilityOf(CompliancePolicy_po.getPassedAssets()), timeOutHigh); let total_passed = 0; let each_pass = 0; CompliancePolicy_po.getPassedAssets().getText().then(function (text) { total_passed = parseInt(text.replace(/,/g, ''), 10); }); browser.wait(EC.visibilityOf( CompliancePolicy_po.getListTableFirstTotal()), timeOutHigh); CompliancePolicy_po.getAllList().then(function(items) { for (let i = 1; i < items.length; i++) { browser.executeScript('arguments[0].scrollIntoView();', $('.list-table-inner-wrapper .list-table-each-list:nth-child(' + (i + 1) + ') .list-table-value .list-table-count-each:nth-child(2)').getWebElement()); $('.list-table-inner-wrapper .list-table-each-list:nth-child(' + (i + 1) + ') .list-table-value .list-table-count-each:nth-child(2)').getText().then(function (text) { each_pass = each_pass + parseInt(text, 10); if ( i === items.length - 1) { expect(each_pass).toEqual(total_passed); } }); } }); }); it('Check if sum of all failed in list table equals table total failed', () => { browser.wait(EC.visibilityOf(CompliancePolicy_po.getFailedAssets()), timeOutHigh); let total_failed = 0; let each_fail = 0; CompliancePolicy_po.getFailedAssets().getText().then(function (text) { total_failed = parseInt(text.replace(/,/g, ''), 10); }); browser.wait(EC.visibilityOf( CompliancePolicy_po.getListTableFirstTotal()), timeOutHigh); CompliancePolicy_po.getAllList().then(function(items) { for (let i = 1; i < items.length; i++) { browser.executeScript('arguments[0].scrollIntoView();', $('.list-table-inner-wrapper .list-table-each-list:nth-child(' + (i + 1) + ') .list-table-value .list-table-count-each:nth-child(3)').getWebElement()); $('.list-table-inner-wrapper .list-table-each-list:nth-child(' + (i + 1) + ') .list-table-value .list-table-count-each:nth-child(3)').getText().then(function (text) { each_fail = each_fail + parseInt(text, 10); if ( i === items.length - 1) { expect(each_fail).toEqual(total_failed); } }); } }); }); it('Check if sum of all total in list table equals table total in summary', () => { browser.wait(EC.visibilityOf(CompliancePolicy_po.getTotalAssets()), timeOutHigh); let total_assets = 0; let each_total = 0; CompliancePolicy_po.getTotalAssets().getText().then(function (text) { total_assets = parseInt(text.replace(/,/g, ''), 10); }); browser.wait(EC.visibilityOf( CompliancePolicy_po.getListTableFirstTotal()), timeOutHigh); CompliancePolicy_po.getAllList().then(function(items) { for (let i = 1; i < items.length; i++) { browser.executeScript('arguments[0].scrollIntoView();', $('.list-table-inner-wrapper .list-table-each-list:nth-child(' + (i + 1) + ') .list-table-value .list-table-count-each:nth-child(1)').getWebElement()); $('.list-table-inner-wrapper .list-table-each-list:nth-child(' + (i + 1) + ') .list-table-value .list-table-count-each:nth-child(1)').getText().then(function (text) { each_total = each_total + parseInt(text, 10); if ( i === items.length - 1) { expect(each_total).toEqual(total_assets); } }); } }); }); it('Verify CSV download', () => { let download_successful = false; browser.wait(EC.presenceOf(CompliancePolicy_po.getPolicyName()), timeOutHigh); const filename = process.cwd() + '/e2e/downloads/List of Violations.csv'; const fs = require('fs'); const myDir = process.cwd() + '/e2e/downloads'; if (!CompliancePolicy_po.checkDirExists(myDir)) { fs.mkdirSync(myDir); } else if ((fs.readdirSync(myDir).length) > 0 && fs.existsSync(filename)) { fs.unlinkSync(filename); } browser.wait(EC.visibilityOf(CompliancePolicy_po.getdownloadIcon()), timeOutHigh); CompliancePolicy_po.getdownloadIcon().click(); browser.wait(EC.visibilityOf(CompliancePolicy_po.getToastMsg()), timeOutHigh).then(function() { browser.wait(EC.invisibilityOf(CompliancePolicy_po.getDownloadRunningIcon()), 600000).then(function() { browser.sleep(1001); browser.driver.wait(function() { if (fs.existsSync(filename)) { download_successful = true; const fileContent = fs.readFileSync(filename, { encoding: 'utf8' }); expect(fileContent.toString().indexOf('\n')).toBeGreaterThan(0); } expect(download_successful).toEqual(true); return fs.existsSync(filename); }, timeOutHigh); }); }); }); });
the_stack
import React, { useLayoutEffect, useState, useRef, SyntheticEvent, ComponentProps, } from "react"; import omit from "lodash/omit"; import debounce from "lodash/debounce"; import get from "lodash/get"; import { Button, Checkbox, Flex, Popup, Menu, MenuButton, PropsOfElement, ProviderConsumer as FluentUIThemeConsumer, ShorthandCollection, Table as FluentUITable, TableCellProps, TableRowProps, Text, dialogBehavior, gridNestedBehavior, gridCellWithFocusableElementBehavior, ButtonProps, } from "@fluentui/react-northstar"; import { ArrowDownIcon, ArrowUpIcon, AcceptIcon, ChevronDownIcon, MoreIcon, OpenOutsideIcon, } from "@fluentui/react-icons-northstar"; import { SiteVariablesPrepared } from "@fluentui/styles"; import Icon, { IIconProps } from "../../lib/Icon"; import Avatar, { IAvatarProps } from "../../lib/Avatar"; import { TableTheme } from "./TableTheme"; import getBreakpoints, { IColumn, accessoryWidth, columnMinWidth, TSortable, } from "./tableBreakpoints"; import { TActions, actionKey, TTextObject, TLocale, EButtonVariants, } from "../.."; import { TeamsTheme } from "../../themes"; import { TTranslations, getText } from "../../translations"; export type columnKey = string; export type rowKey = string; type sortOrder = [columnKey | "__rowKey__", "asc" | "desc"]; export type TSelected = Set<rowKey>; export interface IIconOrnament extends IIconProps { type: "icon"; } export interface IAvatarOrnament extends Pick<IAvatarProps, "image" | "variant"> { type: "avatar"; name: TTextObject; } /** * Table cell content ornaments can be avatars or icons. */ export type TContentOrnament = IAvatarOrnament | IIconOrnament; /** * Content for a table cell can specify optional elements to display before and after the cell’s * text content. */ export interface ICellContent { before?: TContentOrnament; content: TTextObject; after?: TContentOrnament; } /** * Content for a table cell can be a button. When clicked, buttons emit an Interaction event. */ export interface ICellButtonContent extends Pick<ButtonProps, "iconPosition" | "disabled" | "iconOnly"> { type: "button"; actionId: string; content: TTextObject; variant?: EButtonVariants; icon?: string; } /** * The content for a table cell */ export type TCellContent = TTextObject | ICellContent | ICellButtonContent; /** * A collection of data to display for a row, keyed by the column ID except for `actions`, which * contains the collection of actions to make available in the row’s overflow menu. * @public */ export interface IRow { [columnKey: string]: TCellContent | TActions | undefined; actions?: TActions; } /** * An interaction payload emitted by Table. * @public */ export type TTableInteraction = { event: "click"; target: "table"; subject: rowKey | rowKey[]; action: actionKey; }; /** * The Table component is used by the List template as its primary content. * @public */ export interface ITableProps extends PropsOfElement<"div"> { /** * A collection of columns to display, keyed by column ID. */ columns: { [columnKey: string]: IColumn }; /** * A collection of rows to display, keyed by row ID. */ rows: { [rowKey: string]: IRow }; /** * If true, limits content to a single line and truncate with the language’s default ellipsis, * or if false, content in each cell wraps exhaustively. */ truncate?: boolean; /** * Whether the user can select rows. In the context of a List component, this supplies any actions * all rows have in common in the Toolbar instance above the Table. */ selectable?: boolean; /** * @internal */ onSelectedChange?: (selected: TSelected) => TSelected; /** * @internal */ findQuery?: string; /** * @internal */ filterBy?: (row: IRow) => boolean; /** * An interaction handler for the Table. Interactions are triggered when the user clicks on an * action in a row. If the Table is not rendered on its own, this may be proxied from its parent * component, e.g. the parent List. */ onInteraction?: (interaction: TTableInteraction) => void; } interface ISortOrderIndicatorProps { columnKey: columnKey; sortOrder: sortOrder; } const SortOrderIndicator = ({ columnKey, sortOrder, }: ISortOrderIndicatorProps) => { const [sortOrderKey, sortOrderDirection] = sortOrder; if (columnKey === sortOrderKey) { if (sortOrderDirection === "asc") return ( <> <ArrowUpIcon outline styles={{ marginRight: ".25rem", marginLeft: ".5rem" }} /> <ChevronDownIcon outline size="small" /> </> ); else return ( <> <ArrowDownIcon outline styles={{ marginRight: ".25rem", marginLeft: ".5rem" }} /> <ChevronDownIcon outline size="small" /> </> ); } else return <ChevronDownIcon outline size="small" />; }; const ariaSort = ({ columnKey, sortOrder, }: ISortOrderIndicatorProps): { "aria-sort": "ascending" | "descending" | undefined; } => { const [sortOrderKey, sortOrderDirection] = sortOrder; if (columnKey === sortOrderKey) { if (sortOrderDirection === "asc") return { "aria-sort": "ascending" }; else return { "aria-sort": "descending" }; } else return { "aria-sort": undefined }; }; const defaultSortOrder: sortOrder = ["__rowKey__", "desc"]; const passThrough = (arg: any) => arg; const CellContentOrnament = ({ type, ...props }: TContentOrnament) => { switch (type) { case "avatar": return ( <Avatar {...(props as IAvatarProps)} styles={{ margin: "-0.375rem 0 -0.375rem 0" }} /> ); case "icon": return <Icon {...(props as IIconProps)} />; default: return null; } }; interface ICellContentProps { locale: TLocale; rtl: boolean; cell: TCellContent; onInteraction: ((interaction: TTableInteraction) => void) | undefined; rowKey: rowKey; } const CellContent = ({ locale, rtl, cell, onInteraction, rowKey, }: ICellContentProps) => { if (!cell) return null; if (get(cell, "type") === "button") { const buttonCell = cell as ICellButtonContent; const textContent = getText(locale, buttonCell.content); let props: ComponentProps<typeof Button> = { title: textContent, style: { margin: "-.8125rem 0", transform: "translateY(-.125rem)" }, ...(buttonCell.disabled && { disabled: true }), ...(buttonCell.iconOnly ? { iconOnly: true } : { content: textContent }), ...(onInteraction && { onClick: () => onInteraction({ event: "click", target: "table", subject: rowKey, action: buttonCell.actionId, }), }), ...(buttonCell.icon && { icon: <Icon icon={buttonCell.icon} /> }), ...(buttonCell.iconPosition && { iconPosition: buttonCell.iconPosition }), }; switch (buttonCell.variant) { case EButtonVariants.primary: props = { ...props, primary: true, }; break; case EButtonVariants.text: props = { ...props, text: true, }; break; case EButtonVariants.tinted: props = { ...props, tinted: true, }; break; case EButtonVariants.default: default: break; } return <Button {...props} />; } if (cell.hasOwnProperty("content")) { const ornamentedCell = cell as ICellContent; return ( <Flex vAlign="center"> {ornamentedCell.before && ( <CellContentOrnament {...ornamentedCell.before} {...(ornamentedCell.before.hasOwnProperty("name") && { name: getText( locale, (ornamentedCell.before as IAvatarOrnament).name ), })} /> )} <Text styles={{ marginLeft: ornamentedCell.hasOwnProperty(rtl ? "after" : "before") ? ".5rem" : 0, marginRight: ornamentedCell.hasOwnProperty(rtl ? "before" : "after") ? ".5rem" : 0, }} > {getText(locale, ornamentedCell.content)} </Text> {ornamentedCell.after && ( <CellContentOrnament {...ornamentedCell.after} {...(ornamentedCell.after.hasOwnProperty("name") && { name: getText( locale, (ornamentedCell.after as IAvatarOrnament).name ), })} /> )} </Flex> ); } else { return <Text>{getText(locale, cell as TTextObject)}</Text>; } }; /** * @public */ export const Table = (props: ITableProps) => { const rowKeys = Object.keys(props.rows); const columnKeys = Object.keys(props.columns); const [sortOrder, setSortOrder] = useState<sortOrder>(defaultSortOrder); const [selected, setSelected] = useState<TSelected>(new Set()); const propagateSetSelected = (selected: TSelected) => setSelected((props.onSelectedChange || passThrough)(selected)); const selectedIndeterminate = selected.size > 0 && selected.size < rowKeys.length; const hasActions = rowKeys.findIndex((rowKey) => props.rows[rowKey].hasOwnProperty("actions") ) >= 0; const breakpoints = getBreakpoints( props.columns, hasActions, !!props.selectable ); const $tableWrapper = useRef<HTMLDivElement | null>(null); const [inFlowColumns, setInFlowColumns] = useState<Set<columnKey>>( // start by displaying all columns (in case of SSR) breakpoints.get(Infinity)! ); const onResize = () => { if ($tableWrapper.current !== null) { const widths = Array.from(breakpoints.keys()).sort( (a: number, b: number) => a - b ); const firstBreak = widths.findIndex( (width) => width > $tableWrapper.current!.clientWidth ); // use the last width to not be greater than the client width, or zero if they all were const nextInFlowColumns = breakpoints.get( widths[Math.max(0, firstBreak - 1)] )!; setInFlowColumns(nextInFlowColumns); } }; useLayoutEffect(() => { const debouncedResize = debounce(onResize, 100); window.addEventListener("resize", debouncedResize); onResize(); return () => window.removeEventListener("resize", debouncedResize); }, []); const rowWidthStyles = (truncate: boolean, selectable: boolean) => { const minWidth = Array.from(inFlowColumns).reduce( (acc, columnKey) => acc + columnMinWidth(columnKey, props.columns), 0 ); return { padding: "0 1.25rem", minWidth: `${minWidth}px`, ...(selectable && { cursor: "pointer" }), }; }; const columnWidthStyles = (columnKey: string, truncate: boolean) => { const minWidth = columnMinWidth(columnKey, props.columns); return { flexGrow: minWidth, minWidth: `${minWidth}px`, }; }; const accessoryStyles = { flexShrink: 0, flexGrow: 0, width: `${accessoryWidth}px`, minWidth: `${accessoryWidth}px`, display: "flex", justifyContent: "center", height: "calc(3rem - 2px)", }; const columnOrder = ["selection", ...columnKeys, "overflow"]; const rowOrder = sortOrder[0] === defaultSortOrder[0] ? rowKeys : rowKeys.sort((rowKeyA, rowKeyB) => { let rowKeyI = rowKeyA, rowKeyJ = rowKeyB; if (sortOrder[1] === "asc") { rowKeyI = rowKeyB; rowKeyJ = rowKeyA; } return (props.rows[rowKeyI][sortOrder[0]] as string).localeCompare( props.rows[rowKeyJ]![sortOrder[0]] as string ); }); const hiddenColumns = new Set( columnKeys.filter((columnKey) => !inFlowColumns.has(columnKey)) ); const setRowSelected = (rowSelected: boolean, rowKey: rowKey) => { if (rowSelected) propagateSetSelected(new Set(selected.add(rowKey))); else { selected.delete(rowKey); propagateSetSelected(new Set(selected)); } }; const includeRow = (row: IRow) => props.filterBy ? props.filterBy(row) : true; const sortableLabelDesc = (t: TTranslations, sortable: TSortable): string => t[`sort-order ${sortable} descending`]; const sortableLabelAsc = (t: TTranslations, sortable: TSortable): string => t[`sort-order ${sortable} ascending`]; return ( <FluentUIThemeConsumer render={(globalTheme) => { const { t, rtl } = globalTheme.siteVariables; return ( <TableTheme globalTheme={globalTheme}> <div ref={$tableWrapper} style={{ width: "100%", overflowX: "auto" }} > <FluentUITable header={{ key: "header", compact: true, variables: { compactRow: true }, styles: { ...rowWidthStyles(!!props.truncate, false), backgroundColor: globalTheme.siteVariables.colorScheme.default.background2, }, items: columnOrder.reduce( (acc: ShorthandCollection<TableCellProps>, columnKey) => { const column = props.columns[columnKey]; if (inFlowColumns.has(columnKey)) switch (columnKey) { case "overflow": acc.push({ key: "header__overflow", content: "", styles: accessoryStyles, "data-is-focusable": false, }); break; case "selection": acc.push({ key: "header__selection", accessibility: gridCellWithFocusableElementBehavior, content: ( <Checkbox aria-label="Select all" checked={selected.size > 0} variables={{ margin: 0, indeterminate: selectedIndeterminate, }} onChange={(_e, props) => { if (props?.checked) propagateSetSelected(new Set(rowKeys)); else if (selectedIndeterminate) propagateSetSelected(new Set(rowKeys)); else propagateSetSelected(new Set()); }} styles={{ gridTemplateColumns: "1fr", }} /> ), styles: { ...accessoryStyles, height: "calc(2.5rem - 2px)", }, }); break; default: const columnTitle = column?.icon ? ( <Flex vAlign="center"> <Icon icon={column.icon} /> <Text style={{ [rtl ? "marginRight" : "marginLeft"]: ".5rem", }} > {getText(t.locale, column.title)} </Text> </Flex> ) : ( <Text>{getText(t.locale, column.title)}</Text> ); acc.push({ key: `header__${columnKey}`, content: column.sortable ? ( <MenuButton menu={[ { content: sortableLabelDesc( globalTheme.siteVariables.t, column.sortable ), onClick: () => { setSortOrder( sortOrder[0] === columnKey && sortOrder[1] === "desc" ? defaultSortOrder : [columnKey, "desc"] ); }, ...(sortOrder[0] === columnKey && { icon: ( <AcceptIcon outline styles={{ visibility: sortOrder[1] === "desc" ? "visible" : "hidden", }} /> ), }), }, { content: sortableLabelAsc( globalTheme.siteVariables.t, column.sortable ), onClick: () => { setSortOrder( sortOrder[0] === columnKey && sortOrder[1] === "asc" ? defaultSortOrder : [columnKey, "asc"] ); }, ...(sortOrder[0] === columnKey && { icon: ( <AcceptIcon outline styles={{ visibility: sortOrder[1] === "asc" ? "visible" : "hidden", }} /> ), }), }, ]} trigger={ <Button content={columnTitle} icon={ <SortOrderIndicator {...{ sortOrder, columnKey }} /> } iconPosition="after" text fluid styles={{ padding: 0, height: "100%", justifyContent: "flex-start", }} /> } styles={{ display: "block", height: "100%" }} /> ) : ( columnTitle ), styles: columnWidthStyles( columnKey, !!props.truncate ), variables: { flush: !!column.sortable }, ...(column.sortable ? { accessibility: gridCellWithFocusableElementBehavior, ...ariaSort({ sortOrder, columnKey }), } : {}), }); break; } return acc; }, [] ), }} rows={rowOrder.reduce( (acc: ShorthandCollection<TableRowProps>, rowKey: rowKey) => { const row = props.rows[rowKey]; const rowActionKeys = (hiddenColumns.size ? ["__details__"] : [] ).concat(row.actions ? Object.keys(row.actions!) : []); if (includeRow(row)) acc.push({ key: rowKey, styles: rowWidthStyles( !!props.truncate, !!props.selectable ), variables: ({ colorScheme, theme, }: SiteVariablesPrepared) => selected.has(rowKey) && theme !== TeamsTheme.HighContrast ? { backgroundColor: colorScheme.grey.backgroundFocus, color: colorScheme.grey.foregroundFocus, } : { backgroundColor: colorScheme.default.background2, }, onClickCapture: (e: SyntheticEvent<HTMLElement>) => { if (props.selectable) { const aaClass = (e.target as HTMLElement).getAttribute( "data-aa-class" ); if (aaClass && aaClass.startsWith("Table")) { e.stopPropagation(); setRowSelected(!selected.has(rowKey), rowKey); } } }, items: columnOrder.reduce( ( acc: ShorthandCollection<TableCellProps>, columnKey ) => { if (inFlowColumns.has(columnKey)) switch (columnKey) { case "overflow": acc.push({ key: `${rowKey}__overflow`, content: rowActionKeys.length ? ( <Popup trigger={ <Button icon={<MoreIcon outline />} text aria-label="More actions" styles={{ color: "currentColor" }} /> } content={ <Menu items={rowActionKeys.map( (rowActionKey) => { switch (rowActionKey) { case "__details__": return { key: `${rowKey}__details__`, icon: ( <OpenOutsideIcon outline /> ), content: "Details", ...(props.onInteraction && { onClick: () => props.onInteraction!({ event: "click", target: "table", subject: rowKey, action: rowActionKey, }), }), }; default: return { key: `${rowKey}__${rowActionKey}`, icon: ( <Icon icon={ row.actions![ rowActionKey ].icon } /> ), content: row.actions![ rowActionKey ].title, ...(props.onInteraction && { onClick: () => props.onInteraction!({ event: "click", target: "table", subject: rowKey, action: rowActionKey, }), }), }; } } )} vertical /> } offset={[-4, 4]} position="below" accessibility={dialogBehavior} autoFocus={true} /> ) : ( "" ), styles: accessoryStyles, accessibility: gridCellWithFocusableElementBehavior, }); break; case "selection": acc.push({ key: `${rowKey}__selection`, content: ( <Checkbox aria-label="Select" variables={{ margin: 0 }} checked={selected.has(rowKey)} onChange={(_e, props) => { setRowSelected( !!props?.checked, rowKey ); }} styles={{ gridTemplateColumns: "1fr", }} /> ), accessibility: gridCellWithFocusableElementBehavior, styles: accessoryStyles, }); break; default: const cell = row[columnKey]; acc.push({ key: `${rowKey}__${columnKey}`, content: ( <CellContent locale={t.locale} rtl={t.rtl} cell={cell as TCellContent} {...{ rowKey, onInteraction: props.onInteraction, }} /> ), truncateContent: !!props.truncate, styles: columnWidthStyles( columnKey, !!props.truncate ), ...(get(cell, "type") === "button" && { accessibility: gridCellWithFocusableElementBehavior, }), }); break; } return acc; }, [] ), }); return acc; }, [] )} variables={({ theme, colorScheme }: SiteVariablesPrepared) => { return { // box model compactRowHeight: "2.5rem", defaultRowMinHeight: "3rem", defaultRowVerticalPadding: ".8125rem", ...(props.truncate ? { defaultRowHeight: "3rem", } : { defaultRowHeight: "auto", cellVerticalAlignment: "flex-start", }), // colors backgroundColor: theme === TeamsTheme.HighContrast ? colorScheme.grey.background : colorScheme.grey.background2, ...(theme === TeamsTheme.HighContrast ? { rowBorderColor: colorScheme.grey.foreground, rowBorderHoverColor: colorScheme.grey.foreground, } : {}), }; }} styles={{ width: "auto", }} accessibility={gridNestedBehavior} {...omit(props, [ "columns", "rows", "truncate", "selectable", "onSelectedChange", "findQuery", "filterBy", ])} /> </div> </TableTheme> ); }} /> ); };
the_stack
import { RequestUtil } from "mesosphere-shared-reactjs"; import AppDispatcher from "#SRC/js/events/AppDispatcher"; import Config from "#SRC/js/config/Config"; import Util from "#SRC/js/utils/Util"; import { REQUEST_MARATHON_GROUP_CREATE_ERROR, REQUEST_MARATHON_GROUP_CREATE_SUCCESS, REQUEST_MARATHON_GROUP_DELETE_ERROR, REQUEST_MARATHON_GROUP_DELETE_SUCCESS, REQUEST_MARATHON_GROUP_EDIT_ERROR, REQUEST_MARATHON_GROUP_EDIT_SUCCESS, REQUEST_MARATHON_GROUPS_SUCCESS, REQUEST_MARATHON_GROUPS_ERROR, REQUEST_MARATHON_DEPLOYMENTS_SUCCESS, REQUEST_MARATHON_DEPLOYMENTS_ERROR, REQUEST_MARATHON_DEPLOYMENT_ROLLBACK_ERROR, REQUEST_MARATHON_DEPLOYMENT_ROLLBACK_SUCCESS, REQUEST_MARATHON_POD_INSTANCE_KILL_ERROR, REQUEST_MARATHON_POD_INSTANCE_KILL_SUCCESS, REQUEST_MARATHON_QUEUE_SUCCESS, REQUEST_MARATHON_QUEUE_ERROR, REQUEST_MARATHON_INSTANCE_INFO_ERROR, REQUEST_MARATHON_INSTANCE_INFO_SUCCESS, REQUEST_MARATHON_SERVICE_CREATE_ERROR, REQUEST_MARATHON_SERVICE_CREATE_SUCCESS, REQUEST_MARATHON_SERVICE_DELETE_ERROR, REQUEST_MARATHON_SERVICE_DELETE_SUCCESS, REQUEST_MARATHON_SERVICE_EDIT_ERROR, REQUEST_MARATHON_SERVICE_EDIT_SUCCESS, REQUEST_MARATHON_SERVICE_RESET_DELAY_ERROR, REQUEST_MARATHON_SERVICE_RESET_DELAY_SUCCESS, REQUEST_MARATHON_SERVICE_RESTART_ERROR, REQUEST_MARATHON_SERVICE_RESTART_SUCCESS, REQUEST_MARATHON_SERVICE_VERSION_SUCCESS, REQUEST_MARATHON_SERVICE_VERSION_ERROR, REQUEST_MARATHON_SERVICE_VERSIONS_SUCCESS, REQUEST_MARATHON_SERVICE_VERSIONS_ERROR, REQUEST_MARATHON_TASK_KILL_SUCCESS, REQUEST_MARATHON_TASK_KILL_ERROR, } from "../constants/ActionTypes"; import MarathonUtil from "../utils/MarathonUtil"; import Pod from "../structs/Pod"; import PodSpec from "../structs/PodSpec"; import Service from "../structs/Service"; function buildURI(path) { return `${Config.rootUrl}${Config.marathonAPIPrefix}${path}`; } const MarathonActions = { createGroup(data) { RequestUtil.json({ url: buildURI("/groups"), method: "POST", data, success() { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_GROUP_CREATE_SUCCESS, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_GROUP_CREATE_ERROR, data: RequestUtil.getErrorFromXHR(xhr), xhr, }); }, }); }, deleteGroup(groupId, force) { groupId = encodeURIComponent(groupId); let url = buildURI(`/groups/${groupId}`); if (force === true) { url += "?force=true"; } RequestUtil.json({ url, method: "DELETE", success() { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_GROUP_DELETE_SUCCESS, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_GROUP_DELETE_ERROR, data: RequestUtil.parseResponseBody(xhr), xhr, }); }, }); }, editGroup(data, force) { const groupId = encodeURIComponent(data.id); let url = buildURI(`/groups/${groupId}`); data = Util.omit(data, ["id"]); if (force === true) { url += "?force=true"; } RequestUtil.json({ url, method: "PUT", data, success() { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_GROUP_EDIT_SUCCESS, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_GROUP_EDIT_ERROR, data: RequestUtil.parseResponseBody(xhr), xhr, }); }, }); }, /** * Create a service (app, framework, or pod) * * @param {ServiceSpec} spec */ createService(spec) { // TODO (DCOS-9621): Validate input and only accept instances of ServiceSpec // Always default to the `/apps` endpoint to create services let url = buildURI("/apps"); if (spec instanceof PodSpec) { url = buildURI("/pods"); } RequestUtil.json({ url, method: "POST", data: spec, success() { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_SERVICE_CREATE_SUCCESS, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_SERVICE_CREATE_ERROR, data: RequestUtil.parseResponseBody(xhr), xhr, }); }, }); }, /** * Delete a service (app, framework, or pod) * * @param {Service} service - the service you want to delete * @param {Boolean} force - force delete even if deploying */ deleteService(service, force) { let url = buildURI(`/apps/${service.getId()}`); if (service instanceof Pod) { url = buildURI(`/pods/${service.getId()}`); } if (force === true) { url += "?force=true"; } RequestUtil.json({ url, method: "DELETE", success() { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_SERVICE_DELETE_SUCCESS, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_SERVICE_DELETE_ERROR, data: RequestUtil.parseResponseBody(xhr), xhr, }); }, }); }, /** * Edit service (app, framework, or pod) * * @param {Service} service - the service you wish to edit * @param {ServiceSpec} spec - the new service spec * @param {Boolean} force - force deploy change */ editService(service, spec, force) { // TODO (DCOS-9621): Only accept instances of ServiceSpec for spec if (!(service instanceof Service)) { if (process.env.NODE_ENV !== "production") { throw new TypeError("service is not an instance of Service"); } return; } let url = buildURI(`/apps/${service.getId()}`); const params = { force, partialUpdate: false, // Switching Marathon edit endpoint into proper PUT }; if (service instanceof Pod) { url = buildURI(`/pods/${service.getId()}`); } url = url + Util.objectToGetParams(params); RequestUtil.json({ url, method: "PUT", data: spec, success() { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_SERVICE_EDIT_SUCCESS, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_SERVICE_EDIT_ERROR, data: RequestUtil.parseResponseBody(xhr), xhr, }); }, }); }, resetDelayedService(service) { if (!(service instanceof Service)) { if (process.env.NODE_ENV !== "production") { throw new TypeError("service is not an instance of Service"); } return; } const url = buildURI(`/queue/${service.getId()}/delay`); RequestUtil.json({ url, method: "DELETE", success() { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_SERVICE_RESET_DELAY_SUCCESS, serviceName: service.getName(), }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_SERVICE_RESET_DELAY_ERROR, serviceName: service.getName(), data: RequestUtil.parseResponseBody(xhr), xhr, }); }, }); }, restartService(service, force = false) { if (!(service instanceof Service)) { if (process.env.NODE_ENV !== "production") { throw new TypeError("service is not an instance of Service"); } return; } let url = buildURI(`/apps/${service.getId()}/restart`); if (service instanceof Pod) { url = buildURI(`/pods/${service.getId()}/restart`); } if (force === true) { url += "?force=true"; } RequestUtil.json({ url, method: "POST", data: force, success() { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_SERVICE_RESTART_SUCCESS, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_SERVICE_RESTART_ERROR, data: RequestUtil.parseResponseBody(xhr), xhr, }); }, }); }, fetchGroups: RequestUtil.debounceOnError( Config.getRefreshRate(), (resolve, reject) => () => { const url = buildURI("/groups"); const embed = [ { name: "embed", value: "group.groups" }, { name: "embed", value: "group.apps" }, { name: "embed", value: "group.pods" }, { name: "embed", value: "group.apps.deployments" }, { name: "embed", value: "group.apps.counts" }, { name: "embed", value: "group.apps.tasks" }, { name: "embed", value: "group.apps.taskStats" }, { name: "embed", value: "group.apps.lastTaskFailure" }, ]; RequestUtil.json({ url, data: embed, success(response) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_GROUPS_SUCCESS, data: MarathonUtil.parseGroups(response), }); resolve(); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_GROUPS_ERROR, data: xhr.message, xhr, }); reject(); }, }); }, { delayAfterCount: Config.delayAfterErrorCount } ), fetchDeployments: RequestUtil.debounceOnError( Config.getRefreshRate(), (resolve, reject) => () => { RequestUtil.json({ url: buildURI("/deployments"), success(response) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_DEPLOYMENTS_SUCCESS, data: response, }); resolve(); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_DEPLOYMENTS_ERROR, data: xhr.message, xhr, }); reject(); }, }); }, { delayAfterCount: Config.delayAfterErrorCount } ), fetchServiceVersion(serviceID, versionID) { RequestUtil.json({ url: buildURI(`/apps/${serviceID}/versions/${versionID}`), success(response) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_SERVICE_VERSION_SUCCESS, data: { serviceID, versionID, version: response }, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_SERVICE_VERSION_ERROR, data: RequestUtil.getErrorFromXHR(xhr), xhr, }); }, }); }, fetchServiceVersions(serviceID) { RequestUtil.json({ url: buildURI(`/apps/${serviceID}/versions`), success(response) { const { versions } = response; AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_SERVICE_VERSIONS_SUCCESS, data: { serviceID, versions }, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_SERVICE_VERSIONS_ERROR, data: RequestUtil.getErrorFromXHR(xhr), xhr, }); }, }); }, fetchMarathonInstanceInfo() { RequestUtil.json({ url: buildURI("/info"), success(response) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_INSTANCE_INFO_SUCCESS, data: response, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_INSTANCE_INFO_ERROR, data: RequestUtil.getErrorFromXHR(xhr), xhr, }); }, }); }, fetchQueue: RequestUtil.debounceOnError( Config.getRefreshRate(), (resolve, reject) => (options = {}) => { const queryParams = options.params || ""; RequestUtil.json({ url: buildURI(`/queue${queryParams}`), success(response) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_QUEUE_SUCCESS, data: response, }); resolve(); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_QUEUE_ERROR, data: xhr.message, xhr, }); reject(); }, }); }, { delayAfterCount: Config.delayAfterErrorCount } ), revertDeployment(deploymentID) { RequestUtil.json({ url: buildURI(`/deployments/${deploymentID}`), method: "DELETE", success(response) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_DEPLOYMENT_ROLLBACK_SUCCESS, data: { originalDeploymentID: deploymentID, ...response, }, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_DEPLOYMENT_ROLLBACK_ERROR, data: { originalDeploymentID: deploymentID, error: RequestUtil.parseResponseBody(xhr), }, xhr, }); }, }); }, killTasks(taskIDs, scaleTask, force) { let params = []; if (scaleTask) { params.push("scale=true"); } if (force) { params.push("force=true"); } if (params.length > 0) { params = `?${params.join("&")}`; } RequestUtil.json({ url: buildURI(`/tasks/delete${params}`), data: { ids: taskIDs }, method: "POST", success() { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_TASK_KILL_SUCCESS, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_TASK_KILL_ERROR, data: RequestUtil.parseResponseBody(xhr), xhr, }); }, }); }, killPodInstances(pod, instanceIDs, force) { const podID = pod.getId().replace(/^\//, ""); let params = ""; if (force) { params = "?force=true"; } RequestUtil.json({ url: buildURI(`/pods/${podID}::instances${params}`), data: instanceIDs, method: "DELETE", success() { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_POD_INSTANCE_KILL_SUCCESS, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_MARATHON_POD_INSTANCE_KILL_ERROR, data: RequestUtil.parseResponseBody(xhr), xhr, }); }, }); }, }; if (Config.useFixtures) { const groupsFixtureImportPromise = import( /* webpackChunkName: "groupsFixture" */ "../../../../../tests/_fixtures/marathon-pods/groups" ); if (!window.actionTypes) { window.actionTypes = {}; } groupsFixtureImportPromise.then((groupsFixture) => { window.actionTypes.MarathonActions = { createService: { event: "success", success: { response: {} }, }, deleteService: { event: "success", success: { response: {} }, }, editService: { event: "success", success: { response: {} }, }, restartService: { event: "success", success: { response: {} }, }, fetchGroups: { event: "success", success: { response: groupsFixture }, }, }; Object.keys(window.actionTypes.MarathonActions).forEach((method) => { MarathonActions[method] = RequestUtil.stubRequest( MarathonActions, "MarathonActions", method ); }); }); } export default MarathonActions;
the_stack
import { colord, getFormat, extend, Colord } from "../src/"; import a11yPlugin from "../src/plugins/a11y"; import cmykPlugin from "../src/plugins/cmyk"; import harmoniesPlugin, { HarmonyType } from "../src/plugins/harmonies"; import hwbPlugin from "../src/plugins/hwb"; import labPlugin from "../src/plugins/lab"; import lchPlugin from "../src/plugins/lch"; import minifyPlugin from "../src/plugins/minify"; import mixPlugin from "../src/plugins/mix"; import namesPlugin from "../src/plugins/names"; import xyzPlugin from "../src/plugins/xyz"; describe("a11y", () => { extend([a11yPlugin]); it("Returns the perceived luminance of a color", () => { expect(colord("#000000").luminance()).toBe(0); expect(colord("#e42189").luminance()).toBe(0.19); expect(colord("#ff0000").luminance()).toBe(0.21); expect(colord("#808080").luminance()).toBe(0.22); expect(colord("#aabbcc").luminance()).toBe(0.48); expect(colord("#ccddee").luminance()).toBe(0.71); expect(colord("#ffffff").luminance()).toBe(1); }); it("Calculates a contrast ratio for a color pair", () => { // https://webaim.org/resources/contrastchecker/ expect(colord("#000000").contrast()).toBe(21); expect(colord("#ffffff").contrast("#000000")).toBe(21); expect(colord("#777777").contrast()).toBe(4.47); expect(colord("#ff0000").contrast()).toBe(3.99); expect(colord("#00ff00").contrast()).toBe(1.37); expect(colord("#2e2e2e").contrast()).toBe(13.57); expect(colord("#0079ad").contrast()).toBe(4.84); expect(colord("#0079ad").contrast("#2e2e2e")).toBe(2.8); expect(colord("#e42189").contrast("#0d0330")).toBe(4.54); expect(colord("#fff4cc").contrast("#3a1209")).toBe(15); expect(colord("#fff4cc").contrast(colord("#3a1209"))).toBe(15); }); it("Check readability", () => { // https://webaim.org/resources/contrastchecker/ expect(colord("#000").isReadable()).toBe(true); expect(colord("#777777").isReadable()).toBe(false); expect(colord("#e60000").isReadable("#ffff47")).toBe(true); expect(colord("#af085c").isReadable("#000000")).toBe(false); expect(colord("#af085c").isReadable("#000000", { size: "large" })).toBe(true); expect(colord("#d53987").isReadable("#000000")).toBe(true); expect(colord("#d53987").isReadable("#000000", { level: "AAA" })).toBe(false); expect(colord("#e9dddd").isReadable("#864b7c", { level: "AA" })).toBe(true); expect(colord("#e9dddd").isReadable("#864b7c", { level: "AAA" })).toBe(false); expect(colord("#e9dddd").isReadable("#864b7c", { level: "AAA", size: "large" })).toBe(true); expect(colord("#e9dddd").isReadable("#67325e", { level: "AAA" })).toBe(true); expect(colord("#e9dddd").isReadable(colord("#67325e"), { level: "AAA" })).toBe(true); }); }); describe("cmyk", () => { extend([cmykPlugin]); it("Parses CMYK color object", () => { expect(colord({ c: 0, m: 0, y: 0, k: 100 }).toHex()).toBe("#000000"); expect(colord({ c: 16, m: 8, y: 0, k: 20, a: 1 }).toHex()).toBe("#abbccc"); expect(colord({ c: 51, m: 47, y: 0, k: 33, a: 0.5 }).toHex()).toBe("#545bab80"); expect(colord({ c: 0, m: 0, y: 0, k: 0, a: 1 }).toHex()).toBe("#ffffff"); }); it("Parses CMYK color string", () => { expect(colord("device-cmyk(0% 0% 0% 100%)").toHex()).toBe("#000000"); expect(colord("device-cmyk(0% 61% 72% 0% / 50%)").toHex()).toBe("#ff634780"); expect(colord("device-cmyk(0 0.61 0.72 0 / 0.5)").toHex()).toBe("#ff634780"); }); it("Converts a color to CMYK object", () => { // https://htmlcolors.com/color-converter expect(colord("#000000").toCmyk()).toMatchObject({ c: 0, m: 0, y: 0, k: 100, a: 1 }); expect(colord("#ff0000").toCmyk()).toMatchObject({ c: 0, m: 100, y: 100, k: 0, a: 1 }); expect(colord("#00ffff").toCmyk()).toMatchObject({ c: 100, m: 0, y: 0, k: 0, a: 1 }); expect(colord("#665533").toCmyk()).toMatchObject({ c: 0, m: 17, y: 50, k: 60, a: 1 }); expect(colord("#feacfa").toCmyk()).toMatchObject({ c: 0, m: 32, y: 2, k: 0, a: 1 }); expect(colord("#ffffff").toCmyk()).toMatchObject({ c: 0, m: 0, y: 0, k: 0, a: 1 }); }); it("Converts a color to CMYK string", () => { // https://en.wikipedia.org/wiki/CMYK_color_model expect(colord("#999966").toCmykString()).toBe("device-cmyk(0% 0% 33% 40%)"); expect(colord("#99ffff").toCmykString()).toBe("device-cmyk(40% 0% 0% 0%)"); expect(colord("#00336680").toCmykString()).toBe("device-cmyk(100% 50% 0% 60% / 0.5)"); }); it("Supported by `getFormat`", () => { expect(getFormat({ c: 0, m: 0, y: 0, k: 100 })).toBe("cmyk"); }); }); describe("harmonies", () => { extend([harmoniesPlugin]); const check = (type: HarmonyType | undefined, input: string, expected: string[]) => { const harmonies = colord(input).harmonies(type); const hexes = harmonies.map((value) => value.toHex()); return expect(hexes).toEqual(expected); }; it("Generates harmony colors", () => { check(undefined, "#ff0000", ["#ff0000", "#00ffff"]); // "complementary" check("analogous", "#ff0000", ["#ff0080", "#ff0000", "#ff8000"]); check("complementary", "#ff0000", ["#ff0000", "#00ffff"]); check("double-split-complementary", "#ff0000", [ "#ff0080", "#ff0000", "#ff8000", "#00ff80", "#0080ff", ]); check("rectangle", "#ff0000", ["#ff0000", "#ffff00", "#00ffff", "#0000ff"]); check("tetradic", "#ff0000", ["#ff0000", "#80ff00", "#00ffff", "#8000ff"]); check("triadic", "#ff0000", ["#ff0000", "#00ff00", "#0000ff"]); check("split-complementary", "#ff0000", ["#ff0000", "#00ff80", "#0080ff"]); }); }); describe("hwb", () => { extend([hwbPlugin]); it("Parses HWB color object", () => { expect(colord({ h: 0, w: 0, b: 100 }).toHex()).toBe("#000000"); expect(colord({ h: 210, w: 67, b: 20, a: 1 }).toHex()).toBe("#abbbcc"); expect(colord({ h: 236, w: 33, b: 33, a: 0.5 }).toHex()).toBe("#545aab80"); expect(colord({ h: 0, w: 100, b: 0, a: 1 }).toHex()).toBe("#ffffff"); }); it("Converts a color to HWB object", () => { // https://htmlcolors.com/color-converter expect(colord("#000000").toHwb()).toMatchObject({ h: 0, w: 0, b: 100, a: 1 }); expect(colord("#ff0000").toHwb()).toMatchObject({ h: 0, w: 0, b: 0, a: 1 }); expect(colord("#00ffff").toHwb()).toMatchObject({ h: 180, w: 0, b: 0, a: 1 }); expect(colord("#665533").toHwb()).toMatchObject({ h: 40, w: 20, b: 60, a: 1 }); expect(colord("#feacfa").toHwb()).toMatchObject({ h: 303, w: 67, b: 0, a: 1 }); expect(colord("#ffffff").toHwb()).toMatchObject({ h: 0, w: 100, b: 0, a: 1 }); }); it("Parses HWB color string", () => { // https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/hwb() // https://en.wikipedia.org/wiki/HWB_color_model expect(colord("hwb(194 0% 0%)").toHex()).toBe("#00c3ff"); expect(colord("hwb(194 0% 0% / .5)").toHex()).toBe("#00c3ff80"); expect(colord("hwb(-90deg 40% 40% / 50%)").toHex()).toBe("#7f669980"); }); it("Ignores invalid syntax", () => { // comma syntax is not documented expect(colord("hwb(194, 0%, 0%, .5)").isValid()).toBe(false); // missing percents expect(colord("hwb(-90deg 40 40)").isValid()).toBe(false); }); it("Converts a color to HWB string", () => { // https://en.wikipedia.org/wiki/HWB_color_model expect(colord("#999966").toHwbString()).toBe("hwb(60 40% 40%)"); expect(colord("#99ffff").toHwbString()).toBe("hwb(180 60% 0%)"); expect(colord("#00336680").toHwbString()).toBe("hwb(210 0% 60% / 0.5)"); }); it("Supports all valid CSS angle units", () => { // https://developer.mozilla.org/en-US/docs/Web/CSS/angle expect(colord("hwb(90deg 20% 20%)").toHwb().h).toBe(90); expect(colord("hwb(100grad 20% 20%)").toHwb().h).toBe(90); expect(colord("hwb(1.25turn 20% 20%)").toHwb().h).toBe(90); expect(colord("hwb(1.5708rad 20% 20%)").toHwb().h).toBe(90); }); it("Supported by `getFormat`", () => { expect(getFormat("hwb(180deg 50% 50%)")).toBe("hwb"); expect(getFormat({ h: 0, w: 0, b: 100 })).toBe("hwb"); }); }); describe("lab", () => { extend([labPlugin]); it("Parses CIE LAB color object", () => { // https://cielab.xyz/colorconv/ expect(colord({ l: 100, a: 0, b: 0 }).toHex()).toBe("#ffffff"); expect(colord({ l: 0, a: 0, b: 0 }).toHex()).toBe("#000000"); expect(colord({ l: 54.29, a: 80.81, b: 69.89 }).toHex()).toBe("#ff0000"); expect(colord({ l: 15.05, a: 6.68, b: 14.59, alpha: 0.5 }).toHex()).toBe("#33221180"); expect(colord({ l: 50.93, a: 64.96, b: -6.38, alpha: 1 }).toHex()).toBe("#d53987"); }); it("Converts a color to CIE LAB object", () => { // https://cielab.xyz/colorconv/ expect(colord("#ffffff").toLab()).toMatchObject({ l: 100, a: 0, b: 0, alpha: 1 }); expect(colord("#00000000").toLab()).toMatchObject({ l: 0, a: 0, b: 0, alpha: 0 }); expect(colord("#ff0000").toLab()).toMatchObject({ l: 54.29, a: 80.81, b: 69.89, alpha: 1 }); expect(colord("#00ff00").toLab()).toMatchObject({ l: 87.82, a: -79.29, b: 80.99, alpha: 1 }); expect(colord("#ffff00").toLab()).toMatchObject({ l: 97.61, a: -15.75, b: 93.39, alpha: 1 }); expect(colord("#aabbcc").toLab()).toMatchObject({ l: 74.97, a: -3.4, b: -10.7, alpha: 1 }); expect(colord("#33221180").toLab()).toMatchObject({ l: 15.05, a: 6.68, b: 14.59, alpha: 0.5 }); expect(colord("#d53987").toLab()).toMatchObject({ l: 50.93, a: 64.96, b: -6.38, alpha: 1 }); }); it("Calculates the the perceived color difference", () => { /** * Test results: https://cielab.xyz/colordiff.php * * All tests done using RGB. * Inner state is RGB, it is discrete thus all model transformations become discrete * and some accuracy is lost. * * After migrating the state to XYZ or handling the rounding problem, tests using other color models should be added. */ expect(colord("#3296fa").delta("#197dc8")).toBe(0.099); expect(colord("#faf0c8").delta("#fff")).toBe(0.145); expect(colord("#afafaf").delta("#b4b4b4")).toBe(0.014); expect(colord("#000").delta("#fff")).toBe(1); expect(colord("#000").delta("#c8cdd7")).toBe(0.737); expect(colord("#c8cdd7").delta("#000")).toBe(0.737); expect(colord("#f4f4f4").delta("#fafafa")).toBe(0.012); expect(colord("#f4f4f4").delta("#f4f4f4")).toBe(0); }); it("Supported by `getFormat`", () => { expect(getFormat({ l: 50, a: 0, b: 0, alpha: 1 })).toBe("lab"); }); }); describe("lch", () => { extend([lchPlugin]); it("Parses CIE LCH color object", () => { // https://www.w3.org/TR/css-color-4/#specifying-lab-lch expect(colord({ l: 0, c: 0, h: 0, a: 0 }).toHex()).toBe("#00000000"); expect(colord({ l: 100, c: 0, h: 0 }).toHex()).toBe("#ffffff"); expect(colord({ l: 29.2345, c: 44.2, h: 27 }).toHex()).toBe("#7d2329"); expect(colord({ l: 52.2345, c: 72.2, h: 56.2 }).toHex()).toBe("#c65d06"); expect(colord({ l: 60.2345, c: 59.2, h: 95.2 }).toHex()).toBe("#9d9318"); expect(colord({ l: 62.2345, c: 59.2, h: 126.2 }).toHex()).toBe("#68a639"); expect(colord({ l: 67.5345, c: 42.5, h: 258.2, a: 0.5 }).toHex()).toBe("#62acef80"); }); it("Parses CIE LCH color string", () => { // https://cielab.xyz/colorconv/ // https://www.w3.org/TR/css-color-4/ expect(colord("lch(0% 0 0 / 0)").toHex()).toBe("#00000000"); expect(colord("lch(100% 0 0)").toHex()).toBe("#ffffff"); expect(colord("lch(52.2345% 72.2 56.2 / 1)").toHex()).toBe("#c65d06"); expect(colord("lch(37% 105 305)").toHex()).toBe("#6a27e7"); expect(colord("lch(56.2% 83.6 357.4 / 93%)").toHex()).toBe("#fe1091ed"); }); it("Converts a color to CIE LCH object", () => { // https://cielab.xyz/colorconv/ expect(colord("#00000000").toLch()).toMatchObject({ l: 0, c: 0, h: 0, a: 0 }); expect(colord("#ffffff").toLch()).toMatchObject({ l: 100, c: 0, h: 0, a: 1 }); expect(colord("#7d2329").toLch()).toMatchObject({ l: 29.16, c: 44.14, h: 26.48, a: 1 }); expect(colord("#c65d06").toLch()).toMatchObject({ l: 52.31, c: 72.21, h: 56.33, a: 1 }); expect(colord("#9d9318").toLch()).toMatchObject({ l: 60.31, c: 59.2, h: 95.46, a: 1 }); expect(colord("#68a639").toLch()).toMatchObject({ l: 62.22, c: 59.15, h: 126.15, a: 1 }); expect(colord("#62acef80").toLch()).toMatchObject({ l: 67.67, c: 42.18, h: 257.79, a: 0.5 }); }); it("Converts a color to CIE LCH string (CSS functional notation)", () => { // https://cielab.xyz/colorconv/ expect(colord("#00000080").toLchString()).toBe("lch(0% 0 0 / 0.5)"); expect(colord("#ffffff").toLchString()).toBe("lch(100% 0 0)"); expect(colord("#c65d06ed").toLchString()).toBe("lch(52.31% 72.21 56.33 / 0.93)"); expect(colord("#aabbcc").toLchString()).toBe("lch(74.97% 11.22 252.37)"); }); it("Supports all valid CSS angle units", () => { // https://developer.mozilla.org/en-US/docs/Web/CSS/angle expect(colord("lch(50% 50 90deg)").toLch().h).toBe(90); expect(colord("lch(50% 50 100grad)").toLch().h).toBe(90); expect(colord("lch(50% 50 0.25turn)").toLch().h).toBe(90); expect(colord("lch(50% 50 1.5708rad)").toLch().h).toBe(90); }); it("Supported by `getFormat`", () => { expect(getFormat("lch(50% 50 180deg)")).toBe("lch"); expect(getFormat({ l: 50, c: 50, h: 180 })).toBe("lch"); }); }); describe("minify", () => { extend([minifyPlugin, namesPlugin]); it("Minifies a color", () => { expect(colord("#000000").minify()).toBe("#000"); expect(colord("black").minify()).toBe("#000"); expect(colord("#112233").minify()).toBe("#123"); expect(colord("darkgray").minify()).toBe("#a9a9a9"); expect(colord("rgba(200,200,200,0.55)").minify()).toBe("hsla(0,0%,78%,.55)"); expect(colord("rgba(200,200,200,0.55)").minify({ hsl: false })).toBe("rgba(200,200,200,.55)"); }); it("Supports alpha hexes", () => { expect(colord("hsla(0, 100%, 50%, .5)").minify()).toBe("rgba(255,0,0,.5)"); expect(colord("hsla(0, 100%, 50%, .5)").minify({ alphaHex: true })).toBe("#ff000080"); expect(colord("rgba(0, 0, 255, 0.4)").minify({ alphaHex: true })).toBe("#00f6"); }); it("Performs lossless minification (handles alpha hex issues)", () => { expect(colord("rgba(0,0,0,.4)").minify({ alphaHex: true })).toBe("#0006"); expect(colord("rgba(0,0,0,.075)").minify({ alphaHex: true })).toBe("rgba(0,0,0,.075)"); expect(colord("hsla(0,0%,50%,.515)").minify({ alphaHex: true })).toBe("hsla(0,0%,50%,.515)"); }); it("Supports names", () => { expect(colord("#f00").minify({ name: true })).toBe("red"); expect(colord("#000080").minify({ name: true })).toBe("navy"); expect(colord("rgb(255,0,0)").minify({ name: true })).toBe("red"); expect(colord("hsl(0, 100%, 50%)").minify({ name: true })).toBe("red"); }); it("Supports `transparent` keyword", () => { expect(colord("rgba(0,0,0,0)").minify()).toBe("rgba(0,0,0,0)"); expect(colord("rgba(0,0,0,0.0)").minify({ name: true })).toBe("rgba(0,0,0,0)"); expect(colord("hsla(0,0%,0%,0)").minify({ transparent: true })).toBe("transparent"); expect(colord("rgba(0,0,0,0)").minify({ transparent: true })).toBe("transparent"); expect(colord("rgba(0,0,0,0)").minify({ transparent: true, alphaHex: true })).toBe("#0000"); }); }); describe("mix", () => { extend([mixPlugin]); it("Mixes two colors", () => { expect(colord("#000000").mix("#ffffff").toHex()).toBe("#777777"); expect(colord("#dc143c").mix("#000000").toHex()).toBe("#6a1b21"); expect(colord("#800080").mix("#dda0dd").toHex()).toBe("#af5cae"); expect(colord("#228b22").mix("#87cefa").toHex()).toBe("#60ac8f"); expect(colord("#cd853f").mix("#eee8aa", 0.6).toHex()).toBe("#e3c07e"); expect(colord("#483d8b").mix("#00bfff", 0.35).toHex()).toBe("#4969b2"); }); it("Returns the same color if ratio is 0 or 1", () => { expect(colord("#cd853f").mix("#ffffff", 0).toHex()).toBe("#cd853f"); expect(colord("#ffffff").mix("#cd853f", 1).toHex()).toBe("#cd853f"); }); it("Return the color if both values are equal", () => { expect(colord("#ffffff").mix("#ffffff").toHex()).toBe("#ffffff"); expect(colord("#000000").mix("#000000").toHex()).toBe("#000000"); }); const check = (colors: Colord[], expected: string[]) => { const hexes = colors.map((value) => value.toHex()); return expect(hexes).toEqual(expected); }; it("Generates a tints palette", () => { check(colord("#ff0000").tints(2), ["#ff0000", "#ffffff"]); check(colord("#ff0000").tints(3), ["#ff0000", "#ff9f80", "#ffffff"]); check(colord("#ff0000").tints(), ["#ff0000", "#ff6945", "#ff9f80", "#ffd0be", "#ffffff"]); expect(colord("#aabbcc").tints(499)).toHaveLength(499); }); it("Generates a shades palette", () => { check(colord("#ff0000").shades(2), ["#ff0000", "#000000"]); check(colord("#ff0000").shades(3), ["#ff0000", "#7a1b0b", "#000000"]); check(colord("#ff0000").shades(), ["#ff0000", "#ba1908", "#7a1b0b", "#3f1508", "#000000"]); expect(colord("#aabbcc").shades(333)).toHaveLength(333); }); it("Generates a tones palette", () => { check(colord("#ff0000").tones(2), ["#ff0000", "#808080"]); check(colord("#ff0000").tones(3), ["#ff0000", "#c86147", "#808080"]); check(colord("#ff0000").tones(), ["#ff0000", "#e54729", "#c86147", "#a87363", "#808080"]); expect(colord("#aabbcc").tones(987)).toHaveLength(987); }); }); describe("names", () => { extend([namesPlugin]); it("Parses valid CSS color names", () => { expect(colord("white").toHex()).toBe("#ffffff"); expect(colord("red").toHex()).toBe("#ff0000"); expect(colord("rebeccapurple").toHex()).toBe("#663399"); }); it("Ignores the case and extra whitespaces", () => { expect(colord("White ").toHex()).toBe("#ffffff"); expect(colord(" YELLOW").toHex()).toBe("#ffff00"); expect(colord(" REbeccapurpLE ").toHex()).toBe("#663399"); }); it("Converts a color to CSS name", () => { expect(colord("#F00").toName()).toBe("red"); expect(colord("#663399").toName()).toBe("rebeccapurple"); }); it("Gets the closest CSS color keyword", () => { expect(colord("#AAA").toName({ closest: true })).toBe("darkgray"); expect(colord("#fd0202").toName({ closest: true })).toBe("red"); expect(colord("#00008d").toName({ closest: true })).toBe("darkblue"); expect(colord("#fe0000").toName({ closest: true })).toBe("red"); expect(colord("#FFF").toName({ closest: true })).toBe("white"); }); it("Does not crash when name is not found", () => { expect(colord("#123456").toName()).toBe(undefined); expect(colord("myownpurple").toHex()).toBe("#000000"); }); it("Processes 'transparent' color properly", () => { expect(colord("transparent").alpha()).toBe(0); expect(colord("transparent").toHex()).toBe("#00000000"); expect(colord("rgba(0, 0, 0, 0)").toName()).toBe("transparent"); expect(colord("rgba(255, 255, 255, 0)").toName()).toBeUndefined(); }); it("Works properly in pair with the built-in validation", () => { expect(colord("transparent").isValid()).toBe(true); expect(colord("red").isValid()).toBe(true); expect(colord("yellow").isValid()).toBe(true); expect(colord("sunyellow").isValid()).toBe(false); }); it("Supported by `getFormat`", () => { expect(getFormat("transparent")).toBe("name"); expect(getFormat("yellow")).toBe("name"); }); }); describe("xyz", () => { extend([xyzPlugin]); it("Parses XYZ color object", () => { // https://www.nixsensor.com/free-color-converter/ expect(colord({ x: 0, y: 0, z: 0 }).toHex()).toBe("#000000"); expect(colord({ x: 50, y: 50, z: 50 }).toHex()).toBe("#beb9cf"); expect(colord({ x: 96.42, y: 100, z: 82.52, a: 1 }).toHex()).toBe("#ffffff"); }); it("Converts a color to CIE XYZ object", () => { // https://www.easyrgb.com/en/convert.php // https://cielab.xyz/colorconv/ expect(colord("#ffffff").toXyz()).toMatchObject({ x: 96.42, y: 100, z: 82.52, a: 1 }); expect(colord("#5cbf54").toXyz()).toMatchObject({ x: 26, y: 40.27, z: 11.54, a: 1 }); expect(colord("#00000000").toXyz()).toMatchObject({ x: 0, y: 0, z: 0, a: 0 }); }); it("Supported by `getFormat`", () => { expect(getFormat({ x: 50, y: 50, z: 50 })).toBe("xyz"); }); });
the_stack
import * as React from 'react'; import { connect } from 'react-redux'; import { Dispatch } from 'redux'; import { addExpressionUI, clearExpressionsUI, removeListUI, } from '../../../redux/Actions'; import { cadLog, getMatchedExpressions, getSetting, validateExpressionDomain, } from '../../../services/Libs'; import { ReduxAction } from '../../../typings/ReduxConstants'; import ExpressionTable from '../../common_components/ExpressionTable'; import IconButton from '../../common_components/IconButton'; import { downloadObjectAsJSON } from '../../UILibs'; import SettingsTooltip from './SettingsTooltip'; const styles = { buttonStyle: { height: 'max-content', padding: '0.75em', width: 'max-content', }, tableContainer: { height: `${window.innerHeight - 210}px`, overflow: 'auto', }, }; interface OwnProps { style?: React.CSSProperties; } interface StateProps { bName: browserName; contextualIdentities: boolean; debug: boolean; lists: StoreIdToExpressionList; } interface DispatchProps { onClearExpressions: (lists: StoreIdToExpressionList) => void; onNewExpression: (expression: Expression) => void; onRemoveList: (list: keyof StoreIdToExpressionList) => void; } type ExpressionProps = OwnProps & StateProps & DispatchProps; class InitialState { public contextualIdentitiesObjects: browser.contextualIdentities.ContextualIdentity[] = []; public error = ''; public expressionInput = ''; public storeId = 'default'; public success = ''; } class Expressions extends React.Component<ExpressionProps> { public state = new InitialState(); // Import the expressions into the list public importExpressions(importFile: File) { const { onNewExpression } = this.props; // Do check for import first! if (importFile.type !== 'application/json') { this.setError( new Error( `${browser.i18n.getMessage('importFileTypeInvalid')}: ${ importFile.name } (${importFile.type})`, ), ); return; } const reader = new FileReader(); reader.onload = (file) => { try { if (!file.target) { this.setError( new Error( browser.i18n.getMessage('importFileNotFound', [importFile.name]), ), ); return; } // https://stackoverflow.com/questions/35789498/new-typescript-1-8-4-build-error-build-property-result-does-not-exist-on-t const target: any = file.target; const result: string = target.result; const newExpressions: StoreIdToExpressionList = JSON.parse(result); const storeIds = Object.keys(newExpressions); const errExps: string[] = []; let validExps = 0; storeIds.forEach((storeId) => { if (!Array.isArray(newExpressions[storeId])) { errExps.push( `- ${browser.i18n.getMessage('importListNotArray', [storeId])}`, ); return; } newExpressions[storeId].forEach((expression) => { const exps = this.parseRawExpression(expression); exps.forEach((exp) => { const e = exp.trim(); if (!e) return; const result = validateExpressionDomain(e).trim(); if (result) { // invalid errExps.push(`- ${e} (${storeId}) -> ${result}`); } else { // valid validExps += 1; onNewExpression({ ...expression, expression: e, }); } }); }); }); this.setState({ error: errExps.length > 0 ? `${browser.i18n.getMessage( 'importInvalidExpressions', )}\n${errExps.join('\n')}` : '', success: validExps > 0 ? `${browser.i18n.getMessage('importValidExpressions', [ validExps.toString(), importFile.name, ])}` : '', }); } catch (error) { this.setState({ error: `${importFile.name} - ${error.toString()}.`, success: '', }); } }; reader.readAsText(importFile); } // Add the expression using the + button or the Enter key public addExpressionByInput(payload: Expression) { const { onNewExpression } = this.props; const exps = this.parseRawExpression(payload); const invalidInputs: string[] = []; const inputReasons: string[] = []; const validInputs: string[] = []; exps.forEach((exp) => { const expTrim = exp.trim(); if (!expTrim) return; const result = validateExpressionDomain(expTrim).trim(); if (result) { // invalid invalidInputs.push(expTrim); inputReasons.push(`- ${expTrim} -> ${result}`); } else { // valid validInputs.push(`- ${expTrim}`); onNewExpression({ ...payload, expression: expTrim, }); } }); this.setState({ expressionInput: invalidInputs.join(', '), success: validInputs.length > 0 ? `${browser.i18n.getMessage('inputAddSuccess', [ validInputs.length.toString(), browser.i18n.getMessage( `${payload.listType.toLowerCase()}ListWordText`, ), ])}\n${validInputs.join(', ')}` : '', error: inputReasons.length > 0 ? `${browser.i18n.getMessage( 'invalidNewExpressions', )}\n${inputReasons.join('\n')}` : '', }); } private parseRawExpression(exp: Expression): string[] { const exps = exp.expression.split(','); const expressions: string[] = []; let skipTimes = 0; exps.forEach((e, i, a) => { // Ignore if expression was a continuation of regex but had a comma if (skipTimes > 0) { skipTimes--; return; } // skipTimes should be 0 at this point let ee = e.trim(); // Check for regex slash start if (ee.startsWith('/')) { // Continue to parse next set of comma-separated values until the next end slash while (!ee.endsWith('/')) { skipTimes++; if (i + skipTimes >= a.length) { // We have reached the end of the array and did not find an end slash. // We will import as combined. break; } ee += `,${a[i + skipTimes].trim()}`; } } // At this point it should be either a complete regex with start and end // slash, or a domain. expressions.push(ee); }); return expressions; } public clearListsConfirmation(lists: StoreIdToExpressionList) { const { debug, onClearExpressions } = this.props; const listKeys = Object.keys(lists); let expCount = 0; listKeys.forEach((k) => { expCount += lists[k].length; }); if (listKeys.length === 0 && expCount === 0) { this.setState({ error: browser.i18n.getMessage('removeAllExpressionsNoneFound'), }); } else { const r = window.prompt( browser.i18n.getMessage('removeAllExpressionsConfirm', [ expCount.toString(), listKeys.length.toString(), ]), ); cadLog( { msg: `Clear Expressions Prompt returned [ ${r} ]`, type: 'info', }, debug, ); if (r !== null && r === expCount.toString()) { onClearExpressions(this.props.lists); this.setState({ success: browser.i18n.getMessage('removeAllExpressions'), }); } } } public removeListConfirmation( list: keyof StoreIdToExpressionList, expressions: ReadonlyArray<Expression>, ) { const { debug, onRemoveList } = this.props; const expCount = (expressions || []).length; if (expCount === 0) { this.setState({ error: browser.i18n.getMessage('removeAllExpressionsNoneFound'), }); } else { const r = window.prompt( browser.i18n.getMessage('removeAllExpressionsConfirm', [ expCount.toString(), list.toString(), ]), ); cadLog( { msg: `Remove Expressions Prompt for ${list} returned [ ${r} ]`, type: 'info', }, debug, ); if (r !== null && r === expCount.toString()) { onRemoveList(list); this.setState({ success: `${browser.i18n.getMessage('removeListText')}: ${list}`, }); } } } public createDefaultOptions() { const { bName, contextualIdentities, lists, onNewExpression } = this.props; const { contextualIdentitiesObjects } = this.state; const containers = new Set<string>(Object.keys(lists)); if (contextualIdentities) { contextualIdentitiesObjects.forEach((c) => containers.add(c.cookieStoreId), ); } containers.add( ((browser) => { switch (browser) { case browserName.Chrome: case browserName.Opera: return '0'; case browserName.Firefox: default: return 'firefox-default'; } })(bName), ); containers.forEach((id) => { [ListType.GREY, ListType.WHITE].forEach((lt) => { onNewExpression({ expression: `_Default:${lt}`, listType: lt, storeId: id, }); }); }); } public getDerivedStateFromProps(nextProps: ExpressionProps) { if (!nextProps.contextualIdentities) { this.changeStoreIdTab('default'); } } // Change the id of the storeId for the container tabs public changeStoreIdTab(storeId: string) { this.setState({ storeId, }); } public async componentDidMount() { if (this.props.contextualIdentities) { const contextualIdentitiesObjects = await browser.contextualIdentities.query( {}, ); this.setState({ contextualIdentitiesObjects, }); } } public render() { const { style, lists, contextualIdentities } = this.props; const { error, contextualIdentitiesObjects, storeId, success } = this.state; const mapIDtoName: { [k: string]: string | undefined } = {}; if (contextualIdentities) { contextualIdentitiesObjects.forEach((c) => { mapIDtoName[c.cookieStoreId] = c.name; }); Object.keys(lists).forEach((list) => { if (list === 'default') return; const container = contextualIdentitiesObjects.find((c) => { return c.cookieStoreId === list; }); if (!container) { mapIDtoName[list] = undefined; } }); } return ( <div className="col" style={style}> <h1>{browser.i18n.getMessage('expressionListText')}</h1> <div className="row"> <input style={{ display: 'inline', width: '100%', }} value={this.state.expressionInput} onChange={(e) => this.setState({ expressionInput: e.target.value, }) } placeholder={browser.i18n.getMessage('domainPlaceholderText')} onKeyUp={(e) => { if (e.key.toLowerCase() === 'enter') { this.addExpressionByInput({ expression: this.state.expressionInput, listType: e.shiftKey ? ListType.GREY : ListType.WHITE, storeId, }); } }} type="url" id="formText" autoFocus={true} className="form-control" formNoValidate={true} /> </div> <div className="row"> <a target="_blank" rel="help noreferrer noopener" href="https://github.com/Cookie-AutoDelete/Cookie-AutoDelete/wiki/Documentation#enter-expression" > {browser.i18n.getMessage('questionExpression')} <SettingsTooltip hrefURL="#enter-expression" /> </a> </div> <div className="row" style={{ columnGap: '0.5em', justifyContent: 'space-between', paddingBottom: '8px', paddingTop: '8px', }} > <div className="col-sm col-md-auto"> <div className="row justify-content-sm-center justify-content-md-start" style={{ paddingLeft: 0, paddingRight: 0, }} > <IconButton className="btn-primary" iconName="download" role="button" onClick={() => downloadObjectAsJSON(this.props.lists, 'Expressions') } title={browser.i18n.getMessage('exportTitleTimestamp')} text={browser.i18n.getMessage('exportURLSText')} styleReact={styles.buttonStyle} /> <IconButton tag="input" className="btn-info" iconName="upload" type="file" accept="application/json" onChange={(e) => this.importExpressions(e.target.files[0])} text={browser.i18n.getMessage('importURLSText')} title={browser.i18n.getMessage('importURLSText')} styleReact={styles.buttonStyle} /> </div> <div className="w-100" /> <div className="row justify-content-sm-center justify-content-md-start" style={{ marginTop: '5px', marginBottom: '5px', paddingLeft: 0, paddingRight: 0, }} > <IconButton tag="button" className="btn-danger" iconName="trash" role="button" onClick={() => this.clearListsConfirmation(this.props.lists)} text={browser.i18n.getMessage('removeAllExpressions')} title={browser.i18n.getMessage('removeAllExpressions')} styleReact={styles.buttonStyle} /> <IconButton tag="button" className="btn-dark" iconName="list-alt" role="button" onClick={() => this.createDefaultOptions()} text={browser.i18n.getMessage( 'createDefaultExpressionOptionsText', )} title={browser.i18n.getMessage( 'createDefaultExpressionOptionsText', )} styleReact={styles.buttonStyle} /> {contextualIdentities && ( <IconButton tag="button" className="btn-danger" iconName="trash" role="button" onClick={() => { this.removeListConfirmation( storeId, this.props.lists[storeId], ); }} text={browser.i18n.getMessage('removeListText')} title={browser.i18n.getMessage('removeListText')} styleReact={styles.buttonStyle} /> )} </div> </div> <div className="col-sm col-md-auto" style={{ justifyContent: 'flex-end', paddingLeft: 0, paddingRight: 0, }} > <IconButton className="btn-secondary" onClick={() => { this.addExpressionByInput({ expression: this.state.expressionInput, listType: ListType.GREY, storeId, }); }} styleReact={styles.buttonStyle} iconName="plus" title={browser.i18n.getMessage('toGreyListText')} text={browser.i18n.getMessage('greyListWordText')} /> <IconButton className="btn-primary" onClick={() => { this.addExpressionByInput({ expression: this.state.expressionInput, listType: ListType.WHITE, storeId, }); }} styleReact={styles.buttonStyle} iconName="plus" title={browser.i18n.getMessage('toWhiteListText')} text={browser.i18n.getMessage('whiteListWordText')} /> </div> </div> {error !== '' ? ( <div onClick={() => this.setState({ error: '' })} className="row alert alert-danger alertPreWrap" > {error} </div> ) : ( '' )} {success !== '' ? ( <div onClick={() => this.setState({ success: '' })} className="row alert alert-success alertPreWrap" > {success} </div> ) : ( '' )} {contextualIdentities && ( <h5> {browser.i18n.getMessage('currentContainerInfo', [ storeId === 'default' ? browser.i18n.getMessage('defaultText') : storeId, mapIDtoName[storeId] || browser.i18n.getMessage( storeId === 'default' ? 'defaultContainerText' : 'missingContainerText', ), ])} </h5> )} {contextualIdentities && ( <ul className="row nav nav-tabs flex-column flex-sm-row"> <li onClick={() => { this.changeStoreIdTab('default'); }} className="nav-item" > <a className={`nav-link ${storeId === 'default' ? 'active' : ''}`} href="#tabExpressionList" > {browser.i18n.getMessage('defaultText')} </a> </li> {Object.entries(mapIDtoName).map(([cookieStoreId, name]) => ( <li key={`navTab-${cookieStoreId}`} onClick={() => { this.changeStoreIdTab(cookieStoreId); }} className="nav-item" > <a className={`nav-link ${ storeId === cookieStoreId ? 'active' : '' } ${name ? '' : 'text-danger'}`} href="#tabExpressionList" > {name || browser.i18n.getMessage('missingContainerText')} </a> </li> ))} </ul> )} <div className="row" style={styles.tableContainer}> <ExpressionTable expressionColumnTitle={browser.i18n.getMessage( 'domainExpressionsText', )} expressions={getMatchedExpressions( lists, storeId, this.state.expressionInput, true, )} storeId={storeId} emptyElement={ <span> {browser.i18n.getMessage( this.state.expressionInput.trim().length === 0 ? 'noExpressionsText' : 'noSearchExpressionsFound', )} </span> } /> </div> </div> ); } private setError(e: Error): void { this.setState({ error: e.toString(), success: '', }); } } const mapStateToProps = (state: State) => { const { cache, lists } = state; return { bName: cache.browserDetect || (browserDetect() as browserName), cache, contextualIdentities: getSetting( state, SettingID.CONTEXTUAL_IDENTITIES, ) as boolean, debug: getSetting(state, SettingID.DEBUG_MODE) as boolean, lists, }; }; const mapDispatchToProps = (dispatch: Dispatch<ReduxAction>) => ({ onClearExpressions(payload: StoreIdToExpressionList) { dispatch(clearExpressionsUI(payload)); }, onNewExpression(payload: Expression) { dispatch(addExpressionUI(payload)); }, onRemoveList(payload: keyof StoreIdToExpressionList) { dispatch(removeListUI(payload)); }, }); export default connect(mapStateToProps, mapDispatchToProps)(Expressions);
the_stack
'use strict'; export enum AF { UNSPEC = 0, LOCAL = 1, UNIX = 1, FILE = 1, INET = 2, INET6 = 10, } export enum SOCK { STREAM = 1, DGRAM = 2, } export interface Stat { dev: number; mode: number; nlink: number; uid: number; gid: number; rdev: number; blksize: number; ino: number; size: number; blocks: number; atime: Date; mtime: Date; ctime: Date; birthtime: Date; } // from BrowserFS. Copied to avoid this module pulling in any dependencies export enum ErrorCode { EPERM, ENOENT, EIO, EBADF, EACCES, EBUSY, EEXIST, ENOTDIR, EISDIR, EINVAL, EFBIG, ENOSPC, EROFS, ENOTEMPTY, ENOTSUP } // from BrowserFS. Copied to avoid this module pulling in any dependencies let fsErrors: {[n: string]: string} = { EPERM: 'Operation not permitted.', ENOENT: 'No such file or directory.', EIO: 'Input/output error.', EBADF: 'Bad file descriptor.', EACCES: 'Permission denied.', EBUSY: 'Resource busy or locked.', EEXIST: 'File exists.', ENOTDIR: 'File is not a directory.', EISDIR: 'File is a directory.', EINVAL: 'Invalid argument.', EFBIG: 'File is too big.', ENOSPC: 'No space left on disk.', EROFS: 'Cannot modify a read-only file system.', ENOTEMPTY: 'Directory is not empty.', ENOTSUP: 'Operation is not supported.', }; // from BrowserFS. Copied to avoid this module pulling in any dependencies export class ApiError { type: ErrorCode; message: string; code: string; /** * Represents a BrowserFS error. Passed back to applications after a failed * call to the BrowserFS API. * * Error codes mirror those returned by regular Unix file operations, which is * what Node returns. * @constructor ApiError * @param type The type of the error. * @param [message] A descriptive error message. */ constructor(type: ErrorCode, message?: string) { this.type = type; this.code = ErrorCode[type]; if (message != null) { this.message = message; } else { this.message = fsErrors[type]; } } public toString(): string { return this.code + ": " + fsErrors[this.code] + " " + this.message; } } function convertApiErrors(e: any): any { if (!e) return e; // if it looks like an ApiError, and smells like an ApiError... if (!e.hasOwnProperty('type') || !e.hasOwnProperty('message') || !e.hasOwnProperty('code')) return e; return new ApiError(e.type, e.message); } export class SyscallResponse { private static requiredOnData: string[] = ['id', 'name', 'args']; static From(ev: MessageEvent): SyscallResponse { if (!ev.data) return; for (let i = 0; i < SyscallResponse.requiredOnData.length; i++) { if (!ev.data.hasOwnProperty(SyscallResponse.requiredOnData[i])) return; } let args: any[] = ev.data.args.map(convertApiErrors); return new SyscallResponse(ev.data.id, ev.data.name, args); } constructor( public id: number, public name: string, public args: any[]) {} } export interface SyscallCallback { (...args: any[]): void; } interface UOutstandingMap { [i: number]: SyscallCallback; } export interface SignalHandler { (data: SyscallResponse): void; } export class USyscalls { private msgIdSeq: number = 1; private port: MessagePort; private outstanding: UOutstandingMap = {}; private signalHandlers: {[name: string]: SignalHandler[]} = {}; constructor(port: MessagePort) { this.port = port; this.port.onmessage = this.resultHandler.bind(this); } exit(code: number): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = function(...args: any[]): void { console.log('received callback for exit(), should clean up'); }; this.post(msgId, 'exit', code); } fork(heap: ArrayBuffer, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'fork', heap); } kill(pid: number, sig: number, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'kill', pid, sig); } wait4(pid: number, options: number, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'wait4', pid, options); } socket(domain: AF, type: SOCK, protocol: number, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'socket', domain, type, protocol); } getsockname(fd: number, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'getsockname', fd); } getpeername(fd: number, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'getpeername', fd); } bind(fd: number, sockInfo: Uint8Array, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'bind', fd, sockInfo); } listen(fd: number, backlog: number, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'listen', fd, backlog); } accept(fd: number, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'accept', fd); } connect(fd: number, addr: Uint8Array, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'connect', fd, addr); } getcwd(cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'getcwd'); } getpid(cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'getpid'); } getppid(cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'getppid'); } spawn(cwd: string, name: string, args: string[], env: string[], files: number[], cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'spawn', cwd, name, args, env, files); } pipe2(flags: number, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'pipe2', flags); } getpriority(which: number, who: number, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'getpriority', which, who); } setpriority(which: number, who: number, prio: number, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'setpriority', which, who, prio); } open(path: string|Uint8Array, flags: number|string, mode: number, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'open', path, flags, mode); } unlink(path: string, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'unlink', path); } utimes(path: string, atime: number, mtime: number, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'utimes', path, atime, mtime); } futimes(fd: number, atime: number, mtime: number, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'futimes', fd, atime, mtime); } rmdir(path: string, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'rmdir', path); } mkdir(path: string, mode: number, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'mkdir', path); } close(fd: number, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'close', fd); } pwrite(fd: number, buf: string|Uint8Array, pos: number, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'pwrite', fd, buf, pos); } readdir(path: string, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'readdir', path); } fstat(fd: number, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'fstat', fd); } lstat(path: string, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'lstat', path); } chdir(path: string, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'chdir', path); } stat(path: string, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'stat', path); } ioctl(fd: number, request: number, length: number, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'ioctl', fd, request, length); } readlink(path: string|Uint8Array, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'readlink', path); } getdents(fd: number, length: number, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'getdents', fd, length); } pread(fd: number, length: number, offset: number, cb: SyscallCallback): void { const msgId = this.nextMsgId(); this.outstanding[msgId] = cb; this.post(msgId, 'pread', fd, length, offset); } addEventListener(type: string, handler: SignalHandler): void { if (!handler) return; if (this.signalHandlers[type]) this.signalHandlers[type].push(handler); else this.signalHandlers[type] = [handler]; } private resultHandler(ev: MessageEvent): void { let response = SyscallResponse.From(ev); if (!response) { console.log('bad usyscall message, dropping'); console.log(ev); return; } // signals are named, everything else is a response // to a message _we_ sent. Signals include the // 'init' message with our args + environment. if (response.name) { let handlers = this.signalHandlers[response.name]; if (handlers) { for (let i = 0; i < handlers.length; i++) handlers[i](response); } else { console.log('unhandled signal ' + response.name); } return; } // TODO: handle reject this.complete(response.id, response.args); } private complete(id: number, args: any[]): void { let cb = this.outstanding[id]; delete this.outstanding[id]; if (cb) { cb.apply(undefined, args); } else { console.log('unknown callback for msg ' + id + ' - ' + args); } } private nextMsgId(): number { return ++this.msgIdSeq; } private post(msgId: number, name: string, ...args: any[]): void { this.port.postMessage({ id: msgId, name: name, args: args, }); } } declare var global: any; export function getGlobal(): any { // logic from gopherjs if (typeof window !== "undefined") { /* web page */ return <any>window; } else if (typeof self !== "undefined") { /* web worker */ return <any>self; } else if (typeof global !== "undefined") { /* Node.js */ return <any>global; } else { /* others (e.g. Nashorn) */ return <any>this; } } export const syscall = new USyscalls(getGlobal());
the_stack
import { HTMLDataV1 } from '../../htmlLanguageTypes'; export const ismlData: HTMLDataV1 = { "version": 1.1, "tags": [{ name: 'isprint', attributes: [{ name: 'value', values: [{ name: '${}' }], description: { kind: "markdown", value: 'Allowed data type: expression only. String is not allowed output is an expression that resolves to the text you want to output.' } }, { name: 'encoding', valueSet: 'oe', description: { kind: "markdown", value: 'Default value is on. With this attribute, you can explicitly switch automatic encoding on and off. Salesforce B2C Commerce supports encoding in HTML, XML and WML. Even if encoding is turned off, you an use the StringUtil API to encode individual strings.\n' + 'The context element enables you to encode data to avoid cross-site scripting attacks in areas such as HTML attributes, XML, JavaScript, and JSON. Each value maps to a method in the SecureEncoder Class.\n' + ' * `htmlcontent`: encodes a given input for use in a general context.\n' + ' * `htmlsinglequote`: encodes a given input for use in an HTML Attribute guarded by a single quote.\n' + ' * `htmldoublequote`: encodes a given input for use in an HTML Attribute guarded by a double quote.\n' + ' * `htmlunquote`: encodes a given input for use in an HTML Attribute left unguarded.\n' + ' * `jshtml`: encodes a given input for use in JavaScript inside an HTML context.\n' + ' * `jsattribute`: encodes a given input for use in JavaScript inside an HTML attribute.\n' + ' * `jsblock`: encodes a given input for use in JavaScript inside an HTML block.\n' + ' * `jssource`: encodes a given input for use in JavaScript inside a JavaScript source file.\n' + ' * `jsonvalue`: encodes a given input for use in a JSON Object Value to prevent escaping into a trusted context.\n' + ' * `uricomponent`: encodes a given input for use as a component of a URI.\n' + ' * `uristrict`: encodes a given input for use as a component of a URI.\n' + ' * `xmlcontent`: encodes a given input for use in an XML comments.\n' + ' * `xmlsinglequote`: encodes a given input for use in an XML attribute guarded by a single quote.\n' + ' * `xmldoublequote`: encodes a given input for use in an XML attribute guarded by a double quote.\n' + ' * `xmlcomment`: encodes a given input for use in a general XML context.\n' } }, { name: 'timezone', valueSet: 'tz', description: { kind: "markdown", value: 'specify a particular time zone used for printing dates. This attribute enables to specify whether you want to print dates with the instance time zone, the site time zone or without time zone conversion.\n\n' + 'Example: \n\n```html' + '<isprint value="${new Date()}" style="DATE_LONG" timezone="SITE">\n' + '<isprint value="${new Date()}" style="DATE_LONG" timezone="INSTANCE">\n' + '<isprint value="${customer.birthday}" style="DATE_SHORT" timezone="utc"/>\n```' } }, { name: 'padding', description: { kind: "markdown", value: 'used only with mail templates, which are templates using plain rather than html type, to define field width and other spacing issues. For example, when printing a list of product names using a loop statement, you can define a constant field width for every element of the list. The value for padding can be any positive or negative number. The absolute value of padding_constant defines the field width. A positive value produces left-aligned output; a negative value produces right-aligned output. If the output string is greater than the field size, the output string is truncated at its right end.' } }, { name: 'style', description: { kind: "markdown", value: 'specifies a style identifier. Instead of using the style parameter, you can alternatively define a formatter string with the formatter attribute.' }, valueSet: 'pst' }, { name: 'formatter', description: { kind: "markdown", value: 'defines a formatting string to control how <isprint> outputs expression results. For information on building your own formatter string, refer to Formatting Expression Results (which follows). If formatter is used, style must be omitted.' }, valueSet: 'pst' }], description: { kind: "markdown", value: 'The `<isprint />` tag outputs the result of expressions and template variables. Even though it is possible to output expression results without `<isprint />`, you should always use it because it contributes to optimizing your template code.', }, references: [{ name: 'SFCC Docs', url: 'https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/ISML/isprint.html' }] }, { name: 'isset', references: [{ name: 'SFCC Docs', url: 'https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/ISML/isset.html' }], description: { kind: "markdown", value: `'<isset>' can be used to define and set a user-defined variable. In B2C Commerce, every user-defined variable is of a specific scope, which defines the visibility and lifetime of the variable. B2C Commerce distinguishes between user-defined variables of the request, pdict, session and page scope. Scope session means that the variable is accessible to all templates during a particular storefront session. The lifetime of a session variable ends with a session. A session variable can be used in expressions. The first occurrence of <isset> in a template declares and sets the variable, there is no other special tag needed for declaration. If the variable already exists, <isset> resets it to the specified value.` }, attributes: [{ name: 'name' }, { name: 'value', values: [{ name: '${}' }] }, { name: 'scope', valueSet: 'sc' }] }, { name: 'isif', description: { kind: "markdown", value: 'Creating conditional template code and controlling the flow of business logic. The <isif> tag group allows you to create conditional programming constructs using custom tags.' }, attributes: [{ name: 'condition', description: 'expression evaluates to a boolean value. If the <isif> condition is `true`, the system executes the code immediately following the <isif> tag, ignoring the enclosed <iselseif> and <iselse> tags. If the <isif> condition is `false`, the system ignores the code immediately following the <isif> tag, and then tests each <iselseif> condition in order. When the system finds a true <iselseif> condition, the system executes the code immediately following the <iselseif> tag and ignores any remaining <iselseif> and <iselse> tags. If all <iselseif> conditions are `false`, the system executes the code following the <iselse> tag.', values: [{ name: '${}' }] }], references: [{ name: 'SFCC Docs', url: 'https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/ISML/isif.html' }] }, { name: 'isloop', description: { kind: "markdown", value: 'Creating loops for flow control. \nWith `<isloop>` you can loop through the elements of a specified iterator. As an example, you can list data like categories, products, shipping and payment methods. `<isloop>` statements can be nested in one another.' + '\n Supporting Tags \n * Use `<isbreak/>` to unconditionally terminate a loop.\n * Use `<isnext/>` to jump forward in a loop' }, references: [{ name: 'SFCC Docs', url: 'https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/ISML/isloop.html' }], attributes: [ { name: 'items', description: { kind: "markdown", value: 'expression that returns an object to iterate over. Attributes iterator and items can be used interchangeably.' } }, { name: 'iterator', description: { kind: "markdown", value: 'expression that returns an object to iterate over. Attributes iterator and items can be used interchangeably.' } }, { name: 'alias', description: { kind: "markdown", value: 'Name of the variable referencing the object in the iterable collection referenced in the current iteration.' } }, { name: 'var', description: { kind: "markdown", value: 'Name of the variable referencing the object in the iterable collection referenced in the current iteration.' } }, { name: 'status', description: { kind: "markdown", value: 'variable name referencing the loop status object. The loop status is used to query information such as the counter or whether its the first item.\n\n' + 'If status is specified, a loop status object is assigned to the given variable name. Below are the properties of the loop status object:\n\n' + '| Attribute | Description |\n' + '| --------- | ----------- |\n' + '|count|The number of iterations, starting with 1.|\n' + '|index|The current index into the set of items, while iterating.|\n' + '|first|`true`, if this is the first item while iterating (count == 1).|\n' + '|last|`true`, if this is the last item while iterating.|\n' + '|odd|`true`, if count is an odd value.|\n' + '|even|`true`, if count is an even value.|\n' } }, { name: 'begin', description: { kind: "markdown", value: 'expression specifying a begin index for the loop. If the begin is greater than 0, the <isloop> skips the first x items and starts looping at the begin index. If begin is smaller than 0, 0 is used as the begin value.' } }, { name: 'end', description: { kind: "markdown", value: 'expression specifying an end index (inclusive). If end is smaller than begin, the <isloop> is skipped.' } }, { name: 'step', description: { kind: "markdown", value: 'expression specifying the step used to increase the index. If step is smaller than one, one is used as the step value.' } } ] }, { name: 'iscomment', attributes: [], description: { kind: 'markdown', value: 'Use <iscomment> to document your templates, to include reminders or instructions for yourself and others who work with the system without making them available to anyone who "views source" on the page. Anything enclosed in an <iscomment>... </iscomment> structure isn\'t parsed by the template processor and doesn\'t appear in the generated storefront page. \n\n' + ' HTML comments created by surrounding the text with the character strings <!-- and --> are now deprecated. This is because this commenting method provides no confidentiality. Anyone can use a browsers View | Source menu to see the HTML code, including the comments.' }, references: [{ name: 'SFCC Docs', url: 'https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/ISML/iscomment.html' }] }, { name: 'isreplace', attributes: [], description: { kind: 'markdown', value: 'The decorator template uses the tag <isreplace/> to identify where the decorated content is to be included. Typically, only one tag (<isreplace/>) is used in the decorator template. However, multiple or zero <isreplace/> tags can also be used.' + '\nIf the decorating template doesn\'t have an <isreplace/> tag, the decorated content is, effectively, omitted from the resultant output. If the decorator template has multiple <isreplace/> tags, the content to be decorated is included for each <isreplace/> tag.' }, references: [{ name: 'SFCC Docs', url: 'https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/ISML/isreplace.html' }] }, { name: 'isdecorate', attributes: [{ name: 'template', description: { kind: 'plaintext', value: 'the name of the decorator template that is used to decorate the contents.' } }], description: { kind: 'markdown', value: 'This tag lets you decorate the enclosed content with the contents of the specified (decorator) template.\n' + 'The decorator template has the tag <isreplace/> identifying where the decorated content shall be included. Typically, only one tag (<isreplace/>) is used in the decorator template. However, multiple or zero <isreplace/> tags can also be used. If the decorating template doesn\'t have an <isreplace/> tag, the decorated content is omitted from the resultant output. If the decorator template has multiple <isreplace/> tags, the content to be decorated will be included for each <isreplace/> tag.' }, references: [{ name: 'SFCC Docs', url: 'https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/ISML/isdecorate.html' }] }, { name: 'isscript', attributes: [], description: { kind: 'markdown', value: 'The <isscript> tag supports server-side scripts for scriptlets and inline script expressions, using ${ } syntax. The script expressions are supported everywhere expressions are supported, including in tags and inline.' }, references: [{ name: 'SFCC Docs', url: 'https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/ISML/isscript.html' }] }, { name: 'isinclude', attributes: [{ name: "template", description: { kind: 'plaintext', value: 'specifies the name and location of the included template. Use a fixed value or an expression. This is a local include.' } }, { name: "url", description: { kind: 'plaintext', value: ' specifies a URL via a literal string or an expression. This includes the content of this URL, typically a URL from the same server. This is a remote include.' } }, { name: "sf-toolkit", valueSet: 'o' }], description: { kind: "markdown", value: 'Includes the contents of one template inside another or the contents of another URL. The template being included can be as complex as an entire page template, or as simple as a single line of HTML code.\n\n' + 'Iterators used in the including template can be referenced from the included template. This is particularly useful if you want to use an included template in a loop statement. To avoid infinite template processing caused by self-includes, the maximum include depth is fixed to 10.' }, references: [{ name: 'SFCC Docs', url: 'https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/ISML/isinclude.html' }] }, { name: 'iscontent', description: { kind: 'plaintext', value: 'modifies the HTTP header (sets the content type) of the generated output stream sent to the browser or email client. The HTTP header is identified by its MIME type.' }, attributes: [{ name: 'type', values: [{ name: 'text/html' }], description: { kind: 'markdown', value: 'specifies the MIME type of the generated output stream. If no type is specified, the MIME_type is set to `text/html`. Generally, storefront pages and email output are set to `text/html`.Use an expression for dynamic content types. You can set the encoding explicitly using the charset attribute, or determine it implicitly from the content type.' } }, { name: 'encoding', valueSet: 'contentenc' }, { name: 'compact', valueSet: 'b' }, { name: 'charset', 'values': [{ name: 'UTF-8' }] }], references: [{ name: 'SFCC Docs', url: 'https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/ISML/iscontent.html' }] }, { name: 'iscache', attributes: [{ name: 'status', values: [{ name: 'on' }], description: { kind: 'plaintext', value: 'Before <iscache status="off"/> was deprecated, it was necessary to set <iscache status="on"/> to enable page caching. Now the presence of the <iscache/> tag implicitly enables page caching, and it is no longer necessary to set <iscache status="on"/>.' } }, { name: 'type', valueSet: 'sttype', }, { name: 'hour', }, { name: 'minute' }, { name: 'varyby', valueSet: 'varyby', description: { kind: 'plaintext', value: 'lets you mark a page as personalized. Salesforce B2C Commerce identifies unique pages based on a combination of price book, promotion, sorting rule and customization*, caches the different variants of the page, and then delivers the correct version to the user. If a page is personalized by means other than price book, promotion, sorting rule and customization, the page must not be cached, because the wrong variants of the page would be delivered to the user. For performance reasons, a page should be only marked with the varyby property if the page is personalized. Otherwise, the performance can unnecessarily degrade.' } }, { name: 'if', description: { kind: 'plaintext', value: 'This must be a boolean expression. Anything else returns an error.' } }], description: { kind: 'markdown', value: 'To improve the performance of the online storefront by caching pages and also enable developers to disable page caching.\n\n' + 'The requested storefront page is retrieved from the cache without running the pipeline that invokes the template and generates the desired page.\n\n' + ' Note: It isn\'t always possible or desirable to cache a page. For example, there are restrictions for caching pages that contain buyer-related data, such as address or basket information, or for pages containing framesets. See also Page Caching.\n\n' + 'If you want a storefront page to be cached after the response is generated to the first request for the template, you must include the <iscache> tag in the template. The tag allows you to specify when the cached page should expire from the cache; after a fixed period or daily at a particular time, for example.\n\n' + 'The tag can be located anywhere in the template. If the tag occurs several times in one template, the one set to cache off or the one with the shortest cache time is used as the cache setting for the resulting page. This is a safety mechanism, whereby content that isn\'t explicitly labeled for caching is never cached.' }, references: [{ name: 'SFCC Docs', url: 'https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/ISML/iscache.html' }] }, { name: 'iselse', attributes: [], description: { kind: 'markdown', value: 'Use with `<isif>` to specify what happens if neither the `<isif>` condition nor any `<iselseif>` conditions evaluate to true.' }, references: [{ name: 'SFCC Docs', url: 'https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/ISML/iselse.html' }] }, { name: 'iselseif', attributes: [{ name: 'condition', description: { kind: 'markdown', value: 'evaluates to a boolean value. If the `<isif>` condition is `true`, the system executes the code immediately following the `<isif>` tag, ignoring the enclosed `<iselseif>` and `<iselse>` tags. If the `<isif>` condition is `false`, the system ignores the code immediately following the `<isif>` tag, and then tests each `<iselseif>` condition in order. When the system finds a `true` `<iselseif>` condition, the system executes the code immediately following the `<iselseif>` tag and ignores any remaining `<iselseif>` and `<iselse>` tags. If all `<iselseif>` conditions are `false`, the system executes the code following the `<iselse>` tag.' } }], description: { kind: 'markdown', value: 'Use with `<iselseif>` to specify a subcondition off an `<isif>` tag.' }, references: [{ name: 'SFCC Docs', url: 'https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/ISML/iselseif.html' }] }, { name: 'isredirect', attributes: [{ name: 'location', description: 'specifies a target URL used by the browser to send a new request.' }, { name: 'permanent', valueSet: 'b', description: ' causes the system to generate an HTTP 301 response code if set to true or HTTP 302 in case false' }], description: { kind: 'markdown', value: 'Use `<isredirect>` to redirect the browser to a specified URL.\n\n' + ' *Note*: `<isredirect>` appears before `<iscache>` in templates, because it clears the response created up to that point.' }, references: [{ name: 'SFCC Docs', url: 'https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/ISML/isredirect.html' }] }, { name: 'iscontinue', attributes: [], description: { kind: 'markdown', value: 'Stops processing the current item in the loop and starts the next item in loop. The `<iscontinue/>` tag differs from the `<isnext/>` tag in that `isnext` just moves the iterator forward one and continues processing next line of code. `<iscontinue>` breaks out of the processing and then moves to top of loop to start processing again, if there are other items to process.\n\n' + '`<iscontinue/>` can be used only within an <isloop>... </isloop> loop structure. It\'s similar to "continue" in Java.' }, references: [{ name: 'SFCC Docs', url: 'https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/ISML/iscontinue.html' }] }, { name: 'ismodule', description: '', attributes: [{ name: 'template', description: 'Defines a path and a name for the template implementing the tag. Relative paths are expanded from the server\'s template root directory.' }, { name: 'name', description: 'the name of the custom tag. Custom tags are always declared without the is prefix, for example, mytag. However, when using the custom tag in a template, you must include the is prefix like this: <ismytag>. Custom tags can use either case.' }, { name: 'attribute', description: 'Specifies attributes you want your custom tag to have. You can have as many attributes as you want. Attributes are not required.' }], references: [{ name: 'SFCC Docs', url: 'https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/ISML/ismodule.html' }] }, { name: 'isbreak', attributes: [], description: { kind: 'markdown', value: 'Terminating loops unconditionally.\n' + '`<isbreak/>` can be used within a loop (defined by an <isloop> tag) to terminate a loop unconditionally. For more information on creating loops see `<isloop>`. If `<isbreak>` is used in a nested loop, it terminates only the inner loop.' }, references: [{ name: 'SFCC Docs', url: 'https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/ISML/isbreak.html' }] }, { name: 'isslot', description: { kind: 'markdown', value: '<isslot> can be used as a placeholder for where the content should appear. The id attribute is used by Business Manager to identify the slot in one or more slot configurations. The context attribute specifies the scope of the slot. The context-object attribute is required when the scope of the context attribute is either category or folder. The context-object attribute is used to lookup the slot configuration for the given slot. Use the description attribute to describe the slot.\n\n' + 'In Business Manager, slots are grouped by context scope. Global slots are grouped together, category slots are grouped together, and folder slots are grouped together.\n\n' + 'For *Global* slots, Business Manager shows the following values:\n' + ' * Slot ID\n' + ' * Description\n' + ' * Number of slot configurations created\n\n' + 'For *Category* slots, Business Manager shows the following values:\n' + ' * Category (assuming the category\'s configuration specifies a template that includes the <isslot> tag)\n' + ' * Category name\n' + ' * Rendering template name\n' + ' * Slot ID\n' + ' * Description\n' + ' * Number of slot configurations created\n\n' + 'For *Folder* slots, Business Manager shows the following values:\n' + ' * Folder ID (assuming the folder\'s configuration specifies a template that includes the <isslot> tag)\n' + ' * Folder name\n'+ ' * Rendering template name\n'+ ' * Slot ID\n'+ ' * Description\n'+ ' * Number of slot configurations created\n\n'+ 'When no slot is defined in the database for a given slot ID, the <isslot> tag does not render any content. An entry is written to the log file to identify this occurrence.' }, attributes: [{ name: 'id', description: 'identifies the slot in a slot configuration.' }, { name: 'context', valueSet: 'sltcontext', description: 'Scope of the slot' }, { name: 'context-object', description: 'expression that evaluates to a category or folder object' }, { name: 'description', description: 'describes the slot for the business user who needs to configure it' }, { name: 'preview-url', description: 'identifies the URL used within Business Manager to preview the content slot. It you don\'t specify a value, a default URL is used.' }], references: [{ name: 'SFCC Docs', url: 'https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/ISML/isslot.html' }] }], "globalAttributes": [], "valueSets": [ { "name": "b", "values": [ { "name": "true" }, { "name": "false" } ] }, { "name": "u", "values": [ { "name": "true" }, { "name": "false" }, { "name": "undefined" } ] }, { "name": "o", "values": [ { "name": "on" }, { "name": "off" } ] }, { "name": "oe", "values": [ { name: "on" }, { name: "off" }, { name: "htmlcontent" }, { name: "htmlsinglequote" }, { name: "htmldoublequote" }, { name: "htmlunquote" }, { name: "jshtml" }, { name: "jsattribute" }, { name: "jsblock" }, { name: "jssource" }, { name: "jsonvalue" }, { name: "uricomponent" }, { name: "uristrict" }, { name: "xmlcontent" }, { name: "xmlsinglequote" }, { name: "xmldoublequote" }, { name: "xmlcomment" } ] }, { "name": "y", "values": [ { "name": "yes" }, { "name": "no" } ] }, { "name": "sc", "values": [ { name: "session" }, { name: "request" }, { name: "page" } ] }, { "name": "tz", "values": [ { name: "SITE" }, { name: "INSTANCE" }, { name: "utc" } ] }, { "name": "pst", "values": [ { name: 'MONEY_SHORT' }, { name: 'MONEY_LONG' }, { name: 'EURO_SHORT' }, { name: 'EURO_LONG' }, { name: 'EURO_COMBINED' }, { name: 'INTEGER' }, { name: 'DECIMAL' }, { name: 'QUANTITY_SHORT' }, { name: 'QUANTITY_LONG' }, { name: 'DATE_SHORT' }, { name: 'DATE_LONG' }, { name: 'DATE_TIME' } ] }, { "name": "contentenc", "values": [ { name: "on" }, { name: "off" }, { name: "html" }, { name: "xml" }, { name: "wml" } ] }, { "name": "ston", "values": [ { "name": "on" } ] }, { "name": "sttype", "values": [ { "name": "relative" }, { "name": "daily" } ] }, { "name": "varyby", "values": [ { "name": "price_promotion" } ] }, { "name": "sltcontext", "values": [ { "name": "global" }, { "name": "category" }, { "name": "folder" } ] } ] };
the_stack
"use strict"; // uuid: 57f31321-69a9-4170-96a1-6baac731403b // ------------------------------------------------------------------------ // Copyright (c) 2018 Alexandre Bento Freire. All rights reserved. // Licensed under the MIT License+uuid License. See License.txt for details // ------------------------------------------------------------------------ // Implements a list of built-in text Tasks /** @module end-user | The lines bellow convey information for the end-user */ /** * ## Description * * A **text task** transforms text elements or creates complex text animation. * * This plugin has the following built-in text tasks: * * - `text-split` - Wraps words or characters with `span` tags, allowing to later * animate individual words or characters. * * - `typewriter` - Creates the typewriter effect by typing individual characters * or words one by one followed by a cursor. * * - `decipher` - Generates a random list of texts that gradually reveal the hidden text. */ namespace ABeamer { // #generate-group-section // ------------------------------------------------------------------------ // Text Tasks // ------------------------------------------------------------------------ // The following section contains data for the end-user // generated by `gulp build-definition-files` // ------------------------------- // #export-section-start: release export type TextTaskName = /** @see #TextSplitTaskParams */ | 'text-split' /** @see #TypewriterTaskParams */ | 'typewriter' /** @see #DecipherTaskParams */ | 'decipher' ; export type TextTaskParams = | TextSplitTaskParams | TypewriterTaskParams | DecipherTaskParams ; export interface TextSplitTaskParams extends AnyParams { text?: string; splitBy?: | 'char' | 'word' ; /** * If realign is true, it sets the left property of each new element * in a way that are align side by side. * * Use it if the element position is absolute. * * Main purpose is to use with transformations. * * Valid only for DOM elements. */ realign?: boolean; } export interface TypewriterTaskParams extends TextSplitTaskParams { cursor?: boolean; cursorChar?: string; } /** * List of the directions that instruct how the text can be revealed. */ export enum RevealDir { disabled, toRight, toLeft, toCenter, } export interface DecipherTaskParams extends AnyParams { upperCharRanges?: [number, number][]; lowerCharRanges?: [number, number][]; iterations: uint; revealCharIterations?: uint; revealDirection?: RevealDir | string; text: string; } // #export-section-end: release // ------------------------------- // ------------------------------------------------------------------------ // Implementation // ------------------------------------------------------------------------ pluginManager.addPlugin({ id: 'abeamer.text-tasks', uuid: '8b547eff-a0de-446a-9753-fb8b39d8031a', author: 'Alexandre Bento Freire', email: 'abeamer@a-bentofreire.com', jsUrls: ['plugins/text-tasks/text-tasks.js'], teleportable: true, }); // ------------------------------------------------------------------------ // Tools // ------------------------------------------------------------------------ function _textSplitter(params: TextSplitTaskParams): string[] { const text = params.text; return params.splitBy === 'word' ? text.replace(/(\s+)/g, '\0$1').split(/\0/) : text.split(''); } // ------------------------------------------------------------------------ // text-split Task // ------------------------------------------------------------------------ pluginManager.addTasks([['text-split', _textSplit]]); /** Implements the Text Split Task */ function _textSplit(anime: Animation, _wkTask: WorkTask, params: TextSplitTaskParams, stage: uint, args?: ABeamerArgs): TaskResult { switch (stage) { case TS_INIT: const inTextArray = _textSplitter(params); const elAdapters = args.scene.getElementAdapters(anime.selector); const inTextHtml = inTextArray.map((item, index) => `<span data-index="${index}" data="${item.replace(/[\n"']/g, '')}">` + `${item.replace(/ /g, '&nbsp;').replace(/\n/g, '<br>')}</span>`, ); elAdapters.forEach(elAdapter => { elAdapter.setProp('html', inTextHtml.join(''), args); if (params.realign && !elAdapter.isVirtual) { const $spans = $((elAdapter as _DOMElementAdapter).htmlElement).find('span'); let left = 0; $spans.each((_index: uint, domEl: HTMLElement) => { domEl.style.left = `${left}px`; left += domEl.clientWidth; }); } }); return TR_EXIT; } } // ------------------------------------------------------------------------ // typewriter Task // ------------------------------------------------------------------------ pluginManager.addTasks([['typewriter', _typewriter]]); /** Implements the Typewriter Task */ function _typewriter(anime: Animation, _wkTask: WorkTask, params: TypewriterTaskParams, stage: uint, _args?: ABeamerArgs): TaskResult { switch (stage) { case TS_INIT: const textInter = []; const inTextArray = _textSplitter(params); const len = inTextArray.length; const hasCursor = params.cursor !== undefined; const cursorChar = hasCursor ? params.cursorChar || '▐' : ''; let accText = ''; for (let i = 0; i < len; i++) { accText += inTextArray[i]; textInter.push(accText + cursorChar); } if (hasCursor) { textInter.push(accText); } if (!anime.props) { anime.props = []; } anime.props.push({ prop: 'text', valueText: textInter }); return TR_DONE; } } // ------------------------------------------------------------------------ // decipher Task // ------------------------------------------------------------------------ pluginManager.addTasks([['decipher', _decipherTask]]); /** Implements the Decipher Task */ function _decipherTask(anime: Animation, _wkTask: WorkTask, params: DecipherTaskParams, stage: uint, _args?: ABeamerArgs): TaskResult { function isInsideRange(code: uint, ranges: [number, number][]): [number, number][] { return ranges.findIndex(range => range[0] <= code && range[1] >= code) !== -1 ? ranges : undefined; } function reveal(textInter: string[][], text: string, _textLen: uint, rangesByIndex: [number, number][][], _revealDir: RevealDir, revealCharIterations: uint, i: uint, scale: uint) { if (rangesByIndex[i]) { scale++; let textInterPos = textInter.length - 1; const downCounter = revealCharIterations * scale; for (let j = 0; j < downCounter; j++) { if (textInterPos < 0) { return; } textInter[textInterPos][i] = text[i]; textInterPos--; } } return scale; } switch (stage) { case TS_INIT: const cc_A = 'A'.charCodeAt(0); const cc_Z = 'Z'.charCodeAt(0); const cc_a = 'a'.charCodeAt(0); const cc_z = 'z'.charCodeAt(0); const cc_0 = '0'.charCodeAt(0); const cc_9 = '9'.charCodeAt(0); const iterations = params.iterations; const text = params.text; const textLen = text.length; const upperCharRanges = params.upperCharRanges || [[cc_A, cc_Z]]; const lowerCharRanges = params.lowerCharRanges || [[cc_a, cc_z]]; const digitRanges: [number, number][] = [[cc_0, cc_9]]; const revealCharIterations = params.revealCharIterations || 1; const revealDir = parseEnum(params.revealDirection, RevealDir, RevealDir.disabled); throwIfI8n(!isPositiveNatural(iterations), Msgs.MustNatPositive, { p: 'iterations' }); throwIfI8n(!textLen, Msgs.NoEmptyField, { p: 'text' }); // let usableCharsCount = 0; const rangesByIndex: [number, number][][] = []; for (let charI = 0; charI < textLen; charI++) { const charCode = text.charCodeAt(charI); const ranges = isInsideRange(charCode, upperCharRanges) || isInsideRange(charCode, lowerCharRanges) || isInsideRange(charCode, digitRanges); // if (ranges) { // usableCharsCount++; // } rangesByIndex.push(ranges); } const textInter: string[][] = []; for (let i = 0; i < iterations - 1; i++) { const dText = text.split(''); for (let charI = 0; charI < textLen; charI++) { const ranges = rangesByIndex[charI]; if (ranges) { const charRangesLen = ranges.length; const charRangesIndex = charRangesLen === 1 ? 0 : Math.floor(Math.random() * charRangesLen); const charRange = ranges[charRangesIndex]; const range = charRange[1] - charRange[0]; const winnerChar = String.fromCharCode(Math.round(Math.random() * range) + charRange[0]); dText[charI] = winnerChar; } } textInter.push(dText); } let scale = 0; switch (revealDir) { case RevealDir.toLeft: for (let i = textLen - 1; i >= 0; i--) { scale = reveal(textInter, text, textLen, rangesByIndex, revealDir, revealCharIterations, i, scale); } break; case RevealDir.toRight: for (let i = 0; i < textLen; i++) { scale = reveal(textInter, text, textLen, rangesByIndex, revealDir, revealCharIterations, i, scale); } break; case RevealDir.toCenter: const midLen = Math.floor(textLen / 2); for (let i = midLen - 1; i >= 0; i--) { scale = reveal(textInter, text, textLen, rangesByIndex, revealDir, revealCharIterations, i, scale); scale = reveal(textInter, text, textLen, rangesByIndex, revealDir, revealCharIterations, textLen - i - 1, scale); } break; } textInter.push(text.split('')); if (!anime.props) { anime.props = []; } anime.props.push({ prop: 'text', valueText: textInter.map(inter => inter.join('')) }); return TR_DONE; } } }
the_stack
import { decorateWithTemplateLanguageService, Logger, TemplateContext, TemplateLanguageService, } from "typescript-template-language-service-decorator"; import * as ts from "typescript/lib/tsserverlibrary"; import * as vscode from "vscode-languageserver-types"; import { TailwindConfig, TwClassDictionary } from "@xwind/core"; import xwind, { requireTailwindConfig } from "./xwind"; import { createLogger } from "./logger"; import { TailwindContext, getTailwindContextFromPosition, getTailwindContextFromTemplateContext, } from "./tailwindContext"; import { translateCompletionItemsToCompletionEntryDetails, translateCompletionEntry, translateHoverItemsToQuickInfo, } from "./translate"; import { Root } from "postcss"; let tailwindConfig: TailwindConfig | undefined; let tailwindData: | { twClassDictionary: TwClassDictionary; screens: string[]; variants: string[]; generateCssFromText: (text: string) => Root[]; } | undefined; let watcher: ts.FileWatcher | undefined; function updateXwind(logger: Logger, configPath?: string) { try { logger.log(`CONFIG PATH:${configPath}`); if (configPath) { if (watcher) { watcher.close(); } watcher = ts.sys.watchFile?.( configPath, (fileName: string, eventKind: ts.FileWatcherEventKind) => { logger.log(`Watchfile config update: ${configPath}`); updateXwind(logger, fileName); } ); } tailwindConfig = requireTailwindConfig(logger, configPath); tailwindData = xwind(tailwindConfig); } catch (err) { logger.log(`ERROR: ${err}`); } } function xwindLanguageService( info: ts.server.PluginCreateInfo, logger: Logger ): TemplateLanguageService { try { logger.log(`INFO CONFIG ${JSON.stringify(info.config)}`); updateXwind(logger, info.config?.config); return { getSyntacticDiagnostics(context: TemplateContext): ts.Diagnostic[] { if (!tailwindData) { return []; } const maxNumberOfProblems = 100; let problems = 0; const diagnostics: ts.Diagnostic[] = []; const NESTED_ANGLE_BRACKET_REGEXP = /(\[([^\[\]]){0,}\[)|(\]([^\[\]]){0,}\])/g; const IGNORE_ERRORS = pluginConfig.ignoreErrors ? new RegExp(info.config.ignoreErrors) : null; const nestedMath = context.text.match(NESTED_ANGLE_BRACKET_REGEXP); if (nestedMath?.length) { problems++; let diagnostic: ts.Diagnostic = { file: context.node.getSourceFile(), code: 1, category: ts.DiagnosticCategory.Error, start: nestedMath.index, length: nestedMath[0].length, messageText: `Nested variants arrays are not allowed.`, source: "xwind", }; diagnostics.push(diagnostic); } const tailwindContext = getTailwindContextFromTemplateContext( context, tailwindConfig?.separator ?? ":" ); for (const templateContextClass of tailwindContext) { if (problems > maxNumberOfProblems) break; if (IGNORE_ERRORS?.test(templateContextClass.text)) break; if (templateContextClass.type === "array") { for (const twClass of templateContextClass.classes) { const twObject = tailwindData.twClassDictionary[twClass.text]; if (!twObject) { diagnostics.push({ file: context.node.getSourceFile(), code: 2, category: ts.DiagnosticCategory.Error, start: twClass.index, length: twClass.text.length, messageText: `${twClass.text} is not a tailwind class.`, source: "xwind", }); problems++; } } } if (templateContextClass.type === "variant") { const twObject = tailwindData.twClassDictionary[templateContextClass.class.text]; if (!twObject) { diagnostics.push({ file: context.node.getSourceFile(), code: 2, category: ts.DiagnosticCategory.Error, start: templateContextClass.class.index, length: templateContextClass.class.text.length, messageText: `${templateContextClass.class.text} is not a tailwind class.`, source: "xwind", }); problems++; } } if (templateContextClass.type === "class") { if (!tailwindData.twClassDictionary[templateContextClass.text]) { diagnostics.push({ file: context.node.getSourceFile(), code: 5, category: ts.DiagnosticCategory.Error, start: templateContextClass.index, length: templateContextClass.text.length, messageText: `${templateContextClass.text} is not a tailwind class.`, source: "xwind", }); problems++; } } if ( templateContextClass.type === "array" || templateContextClass.type === "variant" ) { //first:second:...other const [first, second, ...other] = templateContextClass.variant; const getVariantType = (variant?: string) => { if (variant) { if (tailwindData?.screens.includes(variant)) { return "screen"; } if (tailwindData?.variants.includes(variant)) { return "variants"; } } }; const firstType = getVariantType(first); const secondType = getVariantType(second); // if (other.length) { // diagnostics.push({ // file: context.node.getSourceFile(), // code: 6, // category: ts.DiagnosticCategory.Error, // start: templateContextClass.index, // length: templateContextClass.variant.join( // tailwindConfig?.separator ?? ":" // ).length, // messageText: `${templateContextClass.variant.join( // tailwindConfig?.separator ?? ":" // )} is not a valid tailwind variant. The selector has more than 2 variants: ${other}.`, // source: "xwind", // }); // problems++; // continue; // } // if (secondType && firstType === "variants") { // diagnostics.push({ // file: context.node.getSourceFile(), // code: 7, // category: ts.DiagnosticCategory.Error, // start: templateContextClass.index, // length: templateContextClass.variant.join( // tailwindConfig?.separator ?? ":" // ).length, // messageText: `${templateContextClass.variant.join( // tailwindConfig?.separator ?? ":" // )} is not a valid tailwind variant. "${first}" should be a screen variant`, // source: "xwind", // }); // problems++; // continue; // } if (!firstType && !secondType) { diagnostics.push({ file: context.node.getSourceFile(), code: 8, category: ts.DiagnosticCategory.Error, start: templateContextClass.index, length: templateContextClass.variant.join( tailwindConfig?.separator ?? ":" ).length, messageText: `${templateContextClass.variant.join( tailwindConfig?.separator ?? ":" )} is not a tailwind variant.`, source: "xwind", }); problems++; continue; } if (firstType === "screen" && secondType === "screen") { diagnostics.push({ file: context.node.getSourceFile(), code: 9, category: ts.DiagnosticCategory.Error, start: templateContextClass.index, length: templateContextClass.variant.join( tailwindConfig?.separator ?? ":" ).length, messageText: `${templateContextClass.variant.join( tailwindConfig?.separator ?? ":" )} is not a valid tailwind variant. "${second}" should be a variant, not a screen variant`, source: "xwind", }); problems++; continue; } } } return diagnostics; }, getCompletionsAtPosition( context: TemplateContext, position: ts.LineAndCharacter ): ts.CompletionInfo { if (!tailwindData) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: [], }; } const tailwindContexts = getTailwindContextFromTemplateContext( context, tailwindConfig?.separator ?? ":" ); const twContext = getTailwindContextFromPosition( tailwindContexts, position ); //todo add check for is tailwind class const entries: ts.CompletionEntry[] = []; for (const key of Object.keys(tailwindData.twClassDictionary)) { const entry = translateCompletionEntry({ label: key, kind: vscode.CompletionItemKind.Text, }); if (twContext) { if (twContext.type === "array") { const twContextClass = getTailwindContextFromPosition( twContext.classes, position ); if (twContextClass) { entry.replacementSpan = { start: twContextClass.index, length: twContextClass.text.length, }; } } else { const endsWithSeparator = twContext.text.endsWith( tailwindConfig?.separator ?? ":" ); if (!endsWithSeparator) { entry.replacementSpan = { start: twContext.index, length: twContext.text.length, }; } } } entries.push(entry); } for (const variant of [ ...tailwindData.screens, ...tailwindData.variants, ]) { const variantEntry = translateCompletionEntry({ label: variant, kind: vscode.CompletionItemKind.Function, }); entries.push(variantEntry); } return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries, }; }, getCompletionEntryDetails( context: TemplateContext, position: ts.LineAndCharacter, name: string ): ts.CompletionEntryDetails { if (!tailwindData) { return { displayParts: [], kind: ts.ScriptElementKind.unknown, kindModifiers: "", name, }; } const twObject = tailwindData.twClassDictionary[name]; if (twObject) { return translateCompletionItemsToCompletionEntryDetails({ label: name, kind: vscode.CompletionItemKind.Text, documentation: { kind: vscode.MarkupKind.Markdown, value: [ "```css", twObject.toString().replace(/ /g, " "), "```", ].join("\n"), }, }); } return { displayParts: [], kind: ts.ScriptElementKind.unknown, kindModifiers: "", name, }; }, getQuickInfoAtPosition( context: TemplateContext, position: ts.LineAndCharacter ): ts.QuickInfo | undefined { if (!tailwindData) { return; } const tailwindContexts = getTailwindContextFromTemplateContext( context, tailwindConfig?.separator ?? ":" ); const twContext = getTailwindContextFromPosition( tailwindContexts, position ); const getQuickInfo = ( twContext: TailwindContext, twObjectRoots: Root[] ) => { return translateHoverItemsToQuickInfo({ start: twContext.index, label: twContext.text, kind: vscode.CompletionItemKind.Text, documentation: { kind: vscode.MarkupKind.Markdown, value: [ "```css", ...twObjectRoots.map((twObjectRoot: Root) => [ twObjectRoot.toString().replace(/ /g, " "), ]), "```", ].join("\n"), }, }); }; if (twContext) { const twObjectRoots = tailwindData.generateCssFromText( twContext.text ); return getQuickInfo(twContext, twObjectRoots); } }, }; } catch (err) { logger.log(`ERROR: ${err}`); throw err; } } interface PluginConfig { config: string; ignoreErrors: string | null; tags: string[]; } let pluginConfig: PluginConfig; export = (mod: { typescript: typeof ts }): ts.server.PluginModule => { let logger: Logger; return { create(info: ts.server.PluginCreateInfo): ts.LanguageService { logger = createLogger(info); logger.log(`XwindTsPlugin is starting.`); pluginConfig = info.config; return decorateWithTemplateLanguageService( mod.typescript, info.languageService, info.project, xwindLanguageService(info, logger), { tags: info.config?.tags ?? ["tw", "xw"] }, { logger } ); }, onConfigurationChanged(newPluginConfig: PluginConfig) { if (logger) { logger.log( `Config has changed ${typeof newPluginConfig} ${JSON.stringify( newPluginConfig )}` ); } pluginConfig = newPluginConfig; updateXwind(logger, newPluginConfig.config); }, }; };
the_stack
import { encode, decode } from "@stablelib/hex"; import { concat } from "@stablelib/bytes"; import { oneTimeAuth, Poly1305 } from "./poly1305"; const testVectors = [ { data: "48656C6C6F20776F726C6421", key: "746869732069732033322D62797465206B657920666F7220506F6C7931333035", mac: "A6F745008F81C916A20DCC74EEF2B2F0" }, { data: "0000000000000000000000000000000000000000000000000000000000000000", key: "746869732069732033322D62797465206B657920666F7220506F6C7931333035", mac: "49EC78090E481EC6C26B33B91CCC0307" }, { data: new Array(2007 + 1).join("00"), key: "746869732069732033322D62797465206B657920666F7220506F6C7931333035", mac: "DA84BCAB02676C38CDB015604274C2AA" }, { data: new Array(2007 + 1).join("00"), key: "0000000000000000000000000000000000000000000000000000000000000000", mac: "00000000000000000000000000000000" }, { data: "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F" + "202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F" + "404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F" + "606162636465666768696A6B6C6D6E6F", key: "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F", mac: "B98AD2F7EC2AE52AFBA1E66FE9133817" }, /* * RFC7539 */ { data: "43727970746F6772617068696320466F72756D2052657365617263682047726F7570", key: "85D6BE7857556D337F4452FE42D506A80103808AFB0DB2FD4ABFF6AF4149F51B", mac: "A8061DC1305136C6C22B8BAF0C0127A9" }, /* * Test vectors from "The Poly1305-AES message-authentication Code" */ { data: "F3F6", key: "851FC40C3467AC0BE05CC20404F3F700580B3B0F9447BB1E69D095B5928B6DBC", mac: "F4C633C3044FC145F84F335CB81953DE" }, { data: "", key: "A0F3080000F46400D0C7E9076C834403DD3FAB2251F11AC759F0887129CC2EE7", mac: "DD3FAB2251F11AC759F0887129CC2EE7" }, { data: "663CEA190FFB83D89593F3F476B6BC24D7E679107EA26ADB8CAF6652D0656136", key: "48443D0BB0D21109C89A100B5CE2C20883149C69B561DD88298A1798B10716EF", mac: "0EE1C16BB73F0F4FD19881753C01CDBE" }, { data: "AB0812724A7F1E342742CBED374D94D136C6B8795D45B3819830F2C04491FAF0" + "990C62E48B8018B2C3E4A0FA3134CB67FA83E158C994D961C4CB21095C1BF9", key: "12976A08C4426D0CE8A82407C4F4820780F8C20AA71202D1E29179CBCB555A57", mac: "5154AD0D2CB26E01274FC51148491F1B" }, /* * Self-generated */ { data: "AB0812724A7F1E342742CBED374D94D136C6B8795D45B3819830F2C04491FAF0" + "990C62E48B8018B2C3E4A0FA3134CB67FA83E158C994D961C4CB21095C1BF9AF", key: "12976A08C4426D0CE8A82407C4F4820780F8C20AA71202D1E29179CBCB555A57", mac: "812059A5DA198637CAC7C4A631BEE466" }, { data: "AB0812724A7F1E342742CBED374D94D136C6B8795D45B3819830F2C04491FAF0" + "990C62E48B8018B2C3E4A0FA3134CB67", key: "12976A08C4426D0CE8A82407C4F4820780F8C20AA71202D1E29179CBCB555A57", mac: "5B88D7F6228B11E2E28579A5C0C1F761" }, { data: "AB0812724A7F1E342742CBED374D94D136C6B8795D45B3819830F2C04491FAF0" + "990C62E48B8018B2C3E4A0FA3134CB67FA83E158C994D961C4CB21095C1BF9AF" + "663CEA190FFB83D89593F3F476B6BC24D7E679107EA26ADB8CAF6652D0656136", key: "12976A08C4426D0CE8A82407C4F4820780F8C20AA71202D1E29179CBCB555A57", mac: "BBB613B2B6D753BA07395B916AAECE15" }, { data: "AB0812724A7F1E342742CBED374D94D136C6B8795D45B3819830F2C04491FAF0" + "990C62E48B8018B2C3E4A0FA3134CB67FA83E158C994D961C4CB21095C1BF9AF" + "48443D0BB0D21109C89A100B5CE2C20883149C69B561DD88298A1798B10716EF" + "663CEA190FFB83D89593F3F476B6BC24", key: "12976A08C4426D0CE8A82407C4F4820780F8C20AA71202D1E29179CBCB555A57", mac: "C794D7057D1778C4BBEE0A39B3D97342" }, { data: "AB0812724A7F1E342742CBED374D94D136C6B8795D45B3819830F2C04491FAF0" + "990C62E48B8018B2C3E4A0FA3134CB67FA83E158C994D961C4CB21095C1BF9AF" + "48443D0BB0D21109C89A100B5CE2C20883149C69B561DD88298A1798B10716EF" + "663CEA190FFB83D89593F3F476B6BC24D7E679107EA26ADB8CAF6652D0656136", key: "12976A08C4426D0CE8A82407C4F4820780F8C20AA71202D1E29179CBCB555A57", mac: "FFBCB9B371423152D7FCA5AD042FBAA9" }, { data: "AB0812724A7F1E342742CBED374D94D136C6B8795D45B3819830F2C04491FAF0" + "990C62E48B8018B2C3E4A0FA3134CB67FA83E158C994D961C4CB21095C1BF9AF" + "48443D0BB0D21109C89A100B5CE2C20883149C69B561DD88298A1798B10716EF" + "663CEA190FFB83D89593F3F476B6BC24D7E679107EA26ADB8CAF6652D0656136" + "812059A5DA198637CAC7C4A631BEE466", key: "12976A08C4426D0CE8A82407C4F4820780F8C20AA71202D1E29179CBCB555A57", mac: "069ED6B8EF0F207B3E243BB1019FE632" }, { data: "AB0812724A7F1E342742CBED374D94D136C6B8795D45B3819830F2C04491FAF0" + "990C62E48B8018B2C3E4A0FA3134CB67FA83E158C994D961C4CB21095C1BF9AF" + "48443D0BB0D21109C89A100B5CE2C20883149C69B561DD88298A1798B10716EF" + "663CEA190FFB83D89593F3F476B6BC24D7E679107EA26ADB8CAF6652D0656136" + "812059A5DA198637CAC7C4A631BEE4665B88D7F6228B11E2E28579A5C0C1F761", key: "12976A08C4426D0CE8A82407C4F4820780F8C20AA71202D1E29179CBCB555A57", mac: "CCA339D9A45FA2368C2C68B3A4179133" }, { data: "AB0812724A7F1E342742CBED374D94D136C6B8795D45B3819830F2C04491FAF0" + "990C62E48B8018B2C3E4A0FA3134CB67FA83E158C994D961C4CB21095C1BF9AF" + "48443D0BB0D21109C89A100B5CE2C20883149C69B561DD88298A1798B10716EF" + "663CEA190FFB83D89593F3F476B6BC24D7E679107EA26ADB8CAF6652D0656136" + "812059A5DA198637CAC7C4A631BEE4665B88D7F6228B11E2E28579A5C0C1F761" + "AB0812724A7F1E342742CBED374D94D136C6B8795D45B3819830F2C04491FAF0" + "990C62E48B8018B2C3E4A0FA3134CB67FA83E158C994D961C4CB21095C1BF9AF" + "48443D0BB0D21109C89A100B5CE2C20883149C69B561DD88298A1798B10716EF" + "663CEA190FFB83D89593F3F476B6BC24D7E679107EA26ADB8CAF6652D0656136", key: "12976A08C4426D0CE8A82407C4F4820780F8C20AA71202D1E29179CBCB555A57", mac: "53F6E828A2F0FE0EE815BF0BD5841A34" }, { data: "AB0812724A7F1E342742CBED374D94D136C6B8795D45B3819830F2C04491FAF0" + "990C62E48B8018B2C3E4A0FA3134CB67FA83E158C994D961C4CB21095C1BF9AF" + "48443D0BB0D21109C89A100B5CE2C20883149C69B561DD88298A1798B10716EF" + "663CEA190FFB83D89593F3F476B6BC24D7E679107EA26ADB8CAF6652D0656136" + "812059A5DA198637CAC7C4A631BEE4665B88D7F6228B11E2E28579A5C0C1F761" + "AB0812724A7F1E342742CBED374D94D136C6B8795D45B3819830F2C04491FAF0" + "990C62E48B8018B2C3E4A0FA3134CB67FA83E158C994D961C4CB21095C1BF9AF" + "48443D0BB0D21109C89A100B5CE2C20883149C69B561DD88298A1798B10716EF" + "663CEA190FFB83D89593F3F476B6BC24D7E679107EA26ADB8CAF6652D0656136" + "812059A5DA198637CAC7C4A631BEE4665B88D7F6228B11E2E28579A5C0C1F761", key: "12976A08C4426D0CE8A82407C4F4820780F8C20AA71202D1E29179CBCB555A57", mac: "B846D44E9BBD53CEDFFBFBB6B7FA4933" }, { /* * poly1305_ieee754.c failed this in final stage */ data: "842364E156336C0998B933A6237726180D9E3FDCBDE4CD5D17080FC3BEB49614" + "D7122C037463FF104D73F19C12704628D417C4C54A3FE30D3C3D7714382D43B0" + "382A50A5DEE54BE844B076E8DF88201A1CD43B90EB21643FA96F39B518AA8340" + "C942FF3C31BAF7C9BDBF0F31AE3FA096BF8C63030609829FE72E179824890BC8" + "E08C315C1CCE2A83144DBBFF09F74E3EFC770B54D0984A8F19B14719E6363564" + "1D6B1EEDF63EFBF080E1783D32445412114C20DE0B837A0DFA33D6B82825FFF4" + "4C9A70EA54CE47F07DF698E6B03323B53079364A5FC3E9DD034392BDDE86DCCD" + "DA94321C5E44060489336CB65BF3989C36F7282C2F5D2B882C171E74", key: "95D5C005503E510D8CD0AA072C4A4D066EABC52D11653DF47FBF63AB198BCC26", mac: "F248312E578D9D58F8B7BB4D19105431" }, /* * AVX2 in poly1305-x86.pl failed this with 176+32 split */ { data: "248AC31085B6C2ADAAA38259A0D7192C5C35D1BB4EF39AD94C38D1C82479E2DD" + "2159A077024B0589BC8A20101B506F0A1AD0BBAB76E83A83F1B94BE6BEAE74E8" + "74CAB692C5963A75436B776121EC9F62399A3E66B2D22707DAE81933B6277F3C" + "8516BCBE26DBBD86F373103D7CF4CAD1888C952118FBFBD0D7B4BEDC4AE4936A" + "FF91157E7AA47C54442EA78D6AC251D324A0FBE49D89CC3521B66D16E9C66A37" + "09894E4EB0A4EEDC4AE19468E66B81F2" + "71351B1D921EA551047ABCC6B87A901FDE7DB79FA1818C11336DBC07244A40EB", key: "000102030405060708090A0B0C0D0E0F00000000000000000000000000000000", mac: "BC939BC5281480FA99C6D68C258EC42F" }, /* * test vectors from Google */ { data: "", key: "C8AFAAC331EE372CD6082DE134943B174710130E9F6FEA8D72293850A667D86C", mac: "4710130E9F6FEA8D72293850A667D86C", }, { data: "48656C6C6F20776F726C6421", key: "746869732069732033322D62797465206B657920666F7220506F6C7931333035", mac: "A6F745008F81C916A20DCC74EEF2B2F0" }, { data: "0000000000000000000000000000000000000000000000000000000000000000", key: "746869732069732033322D62797465206B657920666F7220506F6C7931333035", mac: "49EC78090E481EC6C26B33B91CCC0307" }, /* * test vectors from Andrew Moon */ { /* nacl */ data: "8E993B9F48681273C29650BA32FC76CE48332EA7164D96A4476FB8C531A1186A" + "C0DFC17C98DCE87B4DA7F011EC48C97271D2C20F9B928FE2270D6FB863D51738" + "B48EEEE314A7CC8AB932164548E526AE90224368517ACFEABD6BB3732BC0E9DA" + "99832B61CA01B6DE56244A9E88D5F9B37973F622A43D14A6599B1F654CB45A74" + "E355A5", key: "EEA6A7251C1E72916D11C2CB214D3C252539121D8E234E652D651FA4C8CFF880", mac: "F3FFC7703F9400E52A7DFB4B3D3305D9" }, { /* wrap 2^130-5 */ data: "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", key: "0200000000000000000000000000000000000000000000000000000000000000", mac: "03000000000000000000000000000000" }, { /* wrap 2^128 */ data: "02000000000000000000000000000000", key: "02000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", mac: "03000000000000000000000000000000" }, { /* limb carry */ data: "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" + "11000000000000000000000000000000", key: "0100000000000000000000000000000000000000000000000000000000000000", mac: "05000000000000000000000000000000" }, { /* 2^130-5 */ data: "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFEFEFEFEFEFEFEFEFEFEFEFEFEFEFE" + "01010101010101010101010101010101", key: "0100000000000000000000000000000000000000000000000000000000000000", mac: "00000000000000000000000000000000" }, { /* 2^130-6 */ data: "FDFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", key: "0200000000000000000000000000000000000000000000000000000000000000", mac: "FAFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" }, { /* 5*H+L reduction intermediate */ data: "E33594D7505E43B900000000000000003394D7505E4379CD0100000000000000" + "0000000000000000000000000000000001000000000000000000000000000000", key: "0100000000000000040000000000000000000000000000000000000000000000", mac: "14000000000000005500000000000000" }, { /* 5*H+L REDUCTION FINAL */ data: "E33594D7505E43B900000000000000003394D7505E4379CD0100000000000000" + "00000000000000000000000000000000", key: "0100000000000000040000000000000000000000000000000000000000000000", mac: "13000000000000000000000000000000" } ]; describe("poly1305", () => { it("should produce correct values", () => { testVectors.forEach(v => { const mac = oneTimeAuth(decode(v.key), decode(v.data)); expect(encode(mac)).toBe(v.mac); }); }); it('multiple update should produce the same result as a single update', () => { const key = new Uint8Array(32); for (let i = 0; i < key.length; i++) { key[i] = i; } const data = new Uint8Array(4 + 64 + 169); for (let i = 0; i < data.length; i++) { data[i] = i; } const d1 = data.subarray(0, 4); const d2 = data.subarray(4, 4 + 64); const d3 = data.subarray(4 + 64); expect(encode(concat(d1, d2, d3))).toBe(encode(data)); const p1 = new Poly1305(key); p1.update(data); const r1 = p1.digest(); const p2 = new Poly1305(key); p2.update(d1); p2.update(d2); p2.update(d3); const r2 = p2.digest(); expect(encode(r1)).toBe(encode(r2)); }); });
the_stack
import {interpret, State} from 'xstate'; import {Guid} from 'guid-typescript'; import { StateChannelsNotification, StateChannelsResponse, StateChannelsErrorResponse } from '@statechannels/client-api-schema'; import {filter, take} from 'rxjs/operators'; import { Payload, isOpenChannel, OpenChannel, Address, DirectFunder, makeAddress, RichObjectiveEvent, RichObjective } from '@statechannels/wallet-core'; import _ from 'lodash'; import {TriggerObjectiveEvent, UpdateUI, Workflow} from './channel-wallet-types'; import {serializeChannelEntry} from './utils/wallet-core-v0.8.0'; import {AppRequestEvent} from './event-types'; import {Store} from './store'; import {ApproveBudgetAndFund, CloseLedgerAndWithdraw, Application} from './workflows'; import {ethereumEnableWorkflow} from './workflows/ethereum-enable'; import { MessagingService, MessagingServiceInterface, supportedFundingStrategyOrThrow } from './messaging'; import {ADD_LOGS, WALLET_VERSION} from './config'; import {logger} from './logger'; import {ChainWatcher} from './chain'; export class ChannelWallet { public workflows: Workflow[]; /** * * @param chainAddress Ethereum address for the wallet * @param updateUI Callback that will be invoked when the channel wallet wants to update UI * @param setTriggerObjectiveEvent The invoker of the create API might wish to send objective events to the wallet. The wallet * calls setTriggerObjectiveEvent to hand back the invoker the callback to use for objective events. * @returns */ static async create( chainAddress?: Address, updateUI?: UpdateUI, setTriggerObjectiveEvent?: (callback: TriggerObjectiveEvent) => void ): Promise<ChannelWallet> { const chain = new ChainWatcher(chainAddress); const store = new Store(chain); await store.initialize(); const wallet = new ChannelWallet( store, new MessagingService(store), updateUI, setTriggerObjectiveEvent ); return wallet; } constructor( private store: Store, private messagingService: MessagingServiceInterface, protected updateUI?: UpdateUI, setTriggerObjectiveEvent?: (callback: TriggerObjectiveEvent) => void ) { setTriggerObjectiveEvent?.(_.bind(this.crankRichObjective, this)); this.workflows = []; // Whenever the store wants to send something call sendMessage store.outboxFeed.subscribe(async (m: Payload) => { this.messagingService.sendMessageNotification(m); }); store.richObjectiveEventFeed.subscribe(_.bind(this.crankRichObjective, this)); // Whenever an OpenChannel objective is received // we alert the user that there is a new channel // It is up to the app to call JoinChannel this.store.objectiveFeed.pipe(filter(isOpenChannel)).subscribe(async objective => { const channelEntry = await this.store .channelUpdatedFeed(objective.data.targetChannelId) .pipe(take(1)) .toPromise(); // TODO: Currently receiving a duplicate JOIN_CHANNEL event if (this.isWorkflowIdInUse(this.calculateWorkflowId(objective))) { logger.warn( `There is already a workflow running with id ${this.calculateWorkflowId( objective )}, no new workflow will be spawned` ); } else { const fundingStrategy = supportedFundingStrategyOrThrow(objective.data.fundingStrategy); // Note that it's important to start the workflow first, before sending ChannelProposed. // This way, the workflow is listening to JOIN_CHANNEL right from the get go. this.startWorkflow( Application.workflow(this.store, this.messagingService, { type: 'JOIN_CHANNEL', fundingStrategy, channelId: objective.data.targetChannelId, applicationDomain: 'TODO' // FIXME }), this.calculateWorkflowId(objective) ); this.messagingService.sendChannelNotification('ChannelProposed', { ...serializeChannelEntry(channelEntry) }); } }); this.store.richObjectiveFeed.subscribe(objective => this.updateUI?.({objective})); this.messagingService.requestFeed.subscribe(x => this.handleRequest(x)); } private isWorkflowIdInUse(workflowId: string): boolean { return this.workflows.map(w => w.id).indexOf(workflowId) > -1; } public getWorkflow(workflowId: string): Workflow { const workflow = this.workflows.find(w => w.id === workflowId); if (!workflow) throw Error('Workflow not found'); return workflow; } // Deterministic workflow ids for certain workflows allows us to avoid spawning a duplicate workflow if the app sends duplicate requests private calculateWorkflowId(request: AppRequestEvent | OpenChannel): string { switch (request.type) { case 'JOIN_CHANNEL': return `${request.type}-${request.channelId}`; case 'OpenChannel': return `JOIN_CHANNEL-${request.data.targetChannelId}`; case 'APPROVE_BUDGET_AND_FUND': return `${request.type}-${request.player.participantId}-${request.hub.participantId}`; default: return `${request.type}-${Guid.create().toString()}`; } } private handleRequest(request: AppRequestEvent) { const workflowId = this.calculateWorkflowId(request); switch (request.type) { case 'CREATE_CHANNEL': { // This is wallet 1.0 logic. Leaving for now for reference. /** if (!this.isWorkflowIdInUse(workflowId)) { this.startWorkflow( Application.workflow(this.store, this.messagingService, request), workflowId ); } else { // TODO: To allow RPS to keep working we just warn about duplicate events // Eventually this could probably be an error logger.warn( `There is already a workflow running with id ${workflowId}, no new workflow will be spawned` ); } */ // This wallet 2.0 logic this.store.createAndStoreOpenChannelObjective({ ...request, appDefinition: makeAddress(request.appDefinition) }); break; } case 'JOIN_CHANNEL': // This is wallet 1.0 logic. Leaving for now for reference. // this.getWorkflow(this.calculateWorkflowId(request)).service.send(request); // This wallet 2.0 logic this.approveRichObjective(request.channelId); break; case 'APPROVE_BUDGET_AND_FUND': { const workflow = this.startWorkflow( ApproveBudgetAndFund.machine(this.store, this.messagingService, { player: request.player, hub: request.hub, budget: request.budget, requestId: request.requestId }), workflowId, true // devtools ); workflow.service.send(request); break; } case 'CLOSE_AND_WITHDRAW': { this.startWorkflow( CloseLedgerAndWithdraw.workflow(this.store, this.messagingService, { opponent: request.hub, player: request.player, requestId: request.requestId, domain: request.domain }), workflowId ); break; } case 'ENABLE_ETHEREUM': { this.startWorkflow( ethereumEnableWorkflow(this.store, this.messagingService, {requestId: request.requestId}), workflowId ); break; } } } private startWorkflow(machineConfig: any, workflowId: string, devTools = false): Workflow { if (this.isWorkflowIdInUse(workflowId)) { throw new Error(`There is already a workflow running with id ${workflowId}`); } const service = interpret(machineConfig, {devTools}) .onTransition((state, event) => ADD_LOGS && logTransition(state, event, workflowId)) .onDone(() => (this.workflows = this.workflows.filter(w => w.id !== workflowId))) .start(); this.updateUI?.({service}); const workflow = {id: workflowId, service, domain: 'TODO'}; this.workflows.push(workflow); return workflow; } public onSendMessage( callback: ( jsonRpcMessage: StateChannelsNotification | StateChannelsResponse | StateChannelsErrorResponse ) => void ) { this.messagingService.outboxFeed.subscribe(m => callback(m)); } public getAddress(): Promise<string> { return this.store.getAddress(); } public async pushMessage(jsonRpcMessage: object, fromDomain: string) { // Update any workflows waiting on an observable await this.messagingService.receiveRequest(jsonRpcMessage, fromDomain); } /** * START of wallet 2.0 */ private async crankRichObjective(event: RichObjectiveEvent): Promise<void> { // TODO: this should invoke a store method const richObjective = this.store.richObjectives[event.channelId]; if (!richObjective) { throw new Error(`Unable to map event ${JSON.stringify(event)} to an objective`); } const channelId = richObjective.channelId; const result = DirectFunder.openChannelCranker( richObjective, event, await this.store.getPrivateKey(await this.store.getAddress()) ); this.store.richObjectives[channelId] = result.objective; for (const action of result.actions) { switch (action.type) { case 'sendStates': await Promise.all(action.states.map(state => this.store.addState(state, true))); break; case 'deposit': const fundingMilestones = DirectFunder.utils.fundingMilestone( richObjective.openingState, richObjective.openingState.participants[richObjective.myIndex].destination ); const txHash = await this.store.chain.deposit( channelId, fundingMilestones.targetBefore, action.amount ); this.crankRichObjective({ channelId: channelId, type: 'DepositSubmitted', tx: txHash ?? '', attempt: 0, submittedAt: Date.now() }); break; default: throw new Error('Not expected to reach here'); } this.updateUI?.({objective: this.store.richObjectives[channelId]}); // TODO: we might want to first crank the objective, gather all states that need to be sent, and then send // both the objective and the new states if (event.type === 'Approval') this.sendObjective(this.store.richObjectives[channelId]); } } private async sendObjective(richObjective: RichObjective) { // TODO: need a better way to figure out when to broadcast an objective // since we don't know here if we are the creator of the objective or received the objective from elsewhere const amCreator = richObjective.myIndex === 0; if (amCreator) { // TODO: generalize to other objectives const objectiveToSend: OpenChannel = { type: 'OpenChannel', participants: richObjective.openingState.participants, data: {targetChannelId: richObjective.channelId, fundingStrategy: 'Direct'} }; await this.messagingService.sendMessageNotification({ walletVersion: WALLET_VERSION, objectives: [objectiveToSend] }); } } public async approveRichObjective(channelId: string): Promise<void> { // TODO: it seems that an objective event should have an objective id or a channel id associated with the event this.crankRichObjective({type: 'Approval', channelId: channelId}); } public getRichObjectives() { return this.store.richObjectives; } /** * Only used for testing */ public destroy(): void { this.store.chain.destroy(); } /** * END of wallet 2.0 */ } const alreadyLogging = {}; const key = (v, id) => `${JSON.stringify(v)}-${id}`; const transitionLogger = logger.child({module: 'wallet'}); const log = transitionLogger.trace.bind(transitionLogger); export function logTransition(state: State<any, any, any, any>, event, id?: string): void { const k = key(state.value, id); if (alreadyLogging[k]) return; alreadyLogging[k] = true; const eventType = event.type ? event.type : event; const {context, value: to} = state; if (!state.history) { log( {id, workflow: state.configuration[0].id, to, context, event}, 'WORKFLOW STARTED id %s event %s', id, eventType ); } else { const from = state.history.value; log({id, from, to, context, event}, 'WORKFLOW TRANSITION id %s event %o', id, event.type); } // TODO: this is commented out with the upgrade to xstate@4.17.1 since child.state property does not exist // Object.keys(state.children).forEach(k => { // const child = state.children[k]; // if (child.state && 'onTransition' in child) { // const subId = (child as any).state.configuration[0].id; // (child as any).onTransition((state, event) => logTransition(state, event, `${id}/${subId}`)); // } // }); }
the_stack
import { TestingUtils } from '@nestjs-bff/global-utils-dev/lib/testing.utils'; import * as cacheManager from 'cache-manager'; import _ = require('lodash'); import * as mongoose from 'mongoose'; import { NestjsBffConfig } from '../../../config/nestjs-bff.config'; import { CacheStore } from '../../../shared/caching/cache-store.shared'; import { AppError } from '../../../shared/exceptions/app.exception'; import { AuthorizationError } from '../../../shared/exceptions/authorization.exception'; import { ValidationError } from '../../../shared/exceptions/validation.exception'; import { LoggerConsoleSharedService } from '../../../shared/logging/console-logger.shared.service'; import { LoggerSharedService } from '../../../shared/logging/logger.shared.service'; import { getLogger } from '../../../shared/logging/logging.shared.module'; import { TestAuthorizationLiterals, TestFooEntityLiterals } from '../../../shared/testing/test-literals.constants'; import { IFooModel } from '../../_foo/model/foo.model'; import { FooSchema } from '../../_foo/model/foo.schema'; import { FooRepo } from '../../_foo/repo/foo.repo'; // // Global Scoped Variables Setup // // @ts-ignore const logger = getLogger(); describe('GIVEN a Repo', () => { let fooRepo: FooRepo; let memCache: CacheStore; let loggerService: LoggerSharedService; let fooModel: mongoose.Model<IFooModel>; beforeAll(async () => { loggerService = new LoggerConsoleSharedService(NestjsBffConfig); fooModel = mongoose.model<IFooModel>('Foo', FooSchema); }); // // ------------------------------------------- // beforeEach(async () => { memCache = cacheManager.caching({ store: 'memory', max: 100, ttl: 10 /*seconds*/, }); fooRepo = new FooRepo(loggerService, NestjsBffConfig, memCache, fooModel); }); // // ------------------------------------------- // // FindById Tests // // ------------------------------------------- // describe('WHEN findById is called with an org-scoped and user-scoped Repo', () => { it(`WITH valid authorization THEN a Foo should be returned`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbFindById').mockImplementation(id => { return TestFooEntityLiterals.FE_Ua2Oa; }); try { result = await fooRepo.findById(TestFooEntityLiterals.FE_Ua2Oa.id, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember }); } catch (e) { error = e; } expect(error).toBeUndefined(); expect(result).toEqual(TestFooEntityLiterals.FE_Ua2Oa); }); // // ------------------------------------------- // it(`WITH valid authorization FOR an entity that does not exist THEN an error should be thrown`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbFindById').mockImplementation(id => { return null; }); try { result = await fooRepo.findById(TestFooEntityLiterals.FE_Ua2Oa.id, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember }); } catch (e) { error = e; } expect(error).toBeInstanceOf(AppError); expect(result).toBeUndefined(); }); // // ------------------------------------------- // it(`WITH no authorization THEN an error should be thrown`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbFindById').mockImplementation(id => { return TestFooEntityLiterals.FE_Ua2Oa; }); try { result = await fooRepo.findById(TestFooEntityLiterals.FE_Ua2Oa.id); } catch (e) { error = e; } expect(error).toBeInstanceOf(AuthorizationError); expect(result).toBeUndefined(); }); // // ------------------------------------------- // it(`WITH no authorization WITH options.skipAuthorization = true THEN an Foo should be returned`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbFindById').mockImplementation(id => { return TestFooEntityLiterals.FE_Ua2Oa; }); try { result = await fooRepo.findById(TestFooEntityLiterals.FE_Ua2Oa.id, { skipAuthorization: true }); } catch (e) { error = e; } expect(error).toBeUndefined(); expect(result).toEqual(TestFooEntityLiterals.FE_Ua2Oa); }); }); // // ------------------------------------------- // ------------------------------------------- // describe('WHEN findOne is called twice with an org-scoped and user-scoped Repo', () => { it(`WITH valid authorization THEN _dbFindOne should only be triggered once (the other is from cache) `, async () => { let error; // @ts-ignore const spyDbFindOne = jest.spyOn(fooRepo, '_dbFindById').mockImplementation(conditions => { return TestFooEntityLiterals.FE_Ua2Oa; }); try { await fooRepo.findById(TestFooEntityLiterals.FE_Ua2Oa.id, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember }); await fooRepo.findById(TestFooEntityLiterals.FE_Ua2Oa.id, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember }); } catch (e) { error = e; } expect(error).toBeUndefined(); expect(spyDbFindOne).toBeCalledTimes(1); }); // // ------------------------------------------- // it(`WITH valid authorization AND options.skipCache = true THEN _dbFindOne should be triggered twice (cache not used) `, async () => { let error; // @ts-ignore const spyDbFindOne = jest.spyOn(fooRepo, '_dbFindById').mockImplementation(conditions => { return TestFooEntityLiterals.FE_Ua2Oa; }); try { await fooRepo.findById(TestFooEntityLiterals.FE_Ua2Oa.id, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember, skipCache: true }); await fooRepo.findById(TestFooEntityLiterals.FE_Ua2Oa.id, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember, skipCache: true }); } catch (e) { error = e; } expect(error).toBeUndefined(); expect(spyDbFindOne).toBeCalledTimes(2); }); }); // // ------------------------------------------- // // ------------------------------------------- // // FindOne Tests // // ------------------------------------------- // describe('WHEN findOne is called with an org-scoped and user-scoped Repo', () => { it(`WITH valid authorization THEN a Foo should be returned`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbFindOne').mockImplementation(conditions => { return TestFooEntityLiterals.FE_Ua2Oa; }); try { result = await fooRepo.findOne( { alwaysDefinedSlug: TestFooEntityLiterals.FE_Ua2Oa.alwaysDefinedSlug }, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember }, ); } catch (e) { error = e; } expect(error).toBeUndefined(); expect(result).toEqual(TestFooEntityLiterals.FE_Ua2Oa); }); // // ------------------------------------------- // it(`WITH valid authorization FOR an entity that does not exist THEN an error should be thrown`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbFindOne').mockImplementation(conditions => { return null; }); try { result = await fooRepo.findOne( { alwaysDefinedSlug: TestFooEntityLiterals.FE_Ua2Oa.alwaysDefinedSlug }, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember }, ); } catch (e) { error = e; } expect(error).toBeInstanceOf(AppError); expect(result).toBeUndefined(); }); // // ------------------------------------------- // it(`WITH no authorization THEN an error should be thrown`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbFindOne').mockImplementation(conditions => { return TestFooEntityLiterals.FE_Ua2Oa; }); try { result = await fooRepo.findOne({ alwaysDefinedSlug: TestFooEntityLiterals.FE_Ua2Oa.alwaysDefinedSlug }); } catch (e) { error = e; } expect(error).toBeInstanceOf(AuthorizationError); expect(result).toBeUndefined(); }); // // ------------------------------------------- // it(`WITH no authorization WITH options.skipAuthorization = true THEN an Foo should be returned`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbFindOne').mockImplementation(conditions => { return TestFooEntityLiterals.FE_Ua2Oa; }); try { result = await fooRepo.findOne({ alwaysDefinedSlug: TestFooEntityLiterals.FE_Ua2Oa.alwaysDefinedSlug }, { skipAuthorization: true }); } catch (e) { error = e; } expect(error).toBeUndefined(); expect(result).toEqual(TestFooEntityLiterals.FE_Ua2Oa); }); }); // // ------------------------------------------- // ------------------------------------------- // describe('WHEN findOne is called twice with an org-scoped and user-scoped Repo', () => { it(`WITH valid authorization THEN _dbFindOne should only be triggered once (the other is from cache) `, async () => { let error; // @ts-ignore const spyDbFindOne = jest.spyOn(fooRepo, '_dbFindOne').mockImplementation(conditions => { return TestFooEntityLiterals.FE_Ua2Oa; }); try { await fooRepo.findOne({ alwaysDefinedSlug: TestFooEntityLiterals.FE_Ua2Oa.alwaysDefinedSlug }, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember }); await fooRepo.findOne({ alwaysDefinedSlug: TestFooEntityLiterals.FE_Ua2Oa.alwaysDefinedSlug }, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember }); } catch (e) { error = e; } expect(error).toBeUndefined(); expect(spyDbFindOne).toBeCalledTimes(1); }); // // ------------------------------------------- // it(`WITH valid authorization AND options.skipCache = true THEN _dbFindOne should be triggered twice (cache not used) `, async () => { let error; // @ts-ignore const spyDbFindOne = jest.spyOn(fooRepo, '_dbFindOne').mockImplementation(conditions => { return TestFooEntityLiterals.FE_Ua2Oa; }); try { await fooRepo.findOne( { alwaysDefinedSlug: TestFooEntityLiterals.FE_Ua2Oa.alwaysDefinedSlug }, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember, skipCache: true }, ); await fooRepo.findOne( { alwaysDefinedSlug: TestFooEntityLiterals.FE_Ua2Oa.alwaysDefinedSlug }, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember, skipCache: true }, ); } catch (e) { error = e; } expect(error).toBeUndefined(); expect(spyDbFindOne).toBeCalledTimes(2); }); }); // // ------------------------------------------- // // // ------------------------------------------- // // Find Tests // // ------------------------------------------- // describe('WHEN find is called with an org-scoped and user-scoped Repo', () => { it(`WITH valid authorization THEN a Foo array should be returned`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbFind').mockImplementation(conditions => { return [TestFooEntityLiterals.FE_Ua2Oa]; }); try { result = await fooRepo.find({ name: TestFooEntityLiterals.FE_Ua2Oa.name }, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember }); } catch (e) { error = e; } expect(error).toBeUndefined(); expect(result).toEqual([TestFooEntityLiterals.FE_Ua2Oa]); }); // // ------------------------------------------- // it(`WITH valid authorization FOR no matching entities THEN an empty array should be returned`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbFind').mockImplementation(conditions => { return []; }); try { result = await fooRepo.find({ id: TestFooEntityLiterals.FE_Ua2Oa.id }, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember }); } catch (e) { error = e; } expect(error).toBeUndefined(); expect(result).toEqual([]); }); // // ------------------------------------------- // it(`WITH no authorization THEN an error should be thrown`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbFind').mockImplementation(conditions => { return [TestFooEntityLiterals.FE_Ua2Oa]; }); try { result = await fooRepo.find({ name: TestFooEntityLiterals.FE_Ua2Oa.name }); } catch (e) { error = e; } expect(error).toBeInstanceOf(AuthorizationError); expect(result).toBeUndefined(); }); // // ------------------------------------------- // it(`WITH no authorization WITH options.skipAuthorization = true THEN an Foo array should be returned`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbFind').mockImplementation(conditions => { return [TestFooEntityLiterals.FE_Ua2Oa]; }); try { result = await fooRepo.find({ name: TestFooEntityLiterals.FE_Ua2Oa.name }, { skipAuthorization: true }); } catch (e) { error = e; } expect(error).toBeUndefined(); expect(result).toEqual([TestFooEntityLiterals.FE_Ua2Oa]); }); }); // // ------------------------------------------- // ------------------------------------------- // describe('WHEN find is called twice with an org-scoped and user-scoped Repo', () => { it(`WITH valid authorization THEN _dbFind should only be triggered once (the other is from cache) `, async () => { let error; // @ts-ignore const spyDbFind = jest.spyOn(fooRepo, '_dbFind').mockImplementation(conditions => { return [TestFooEntityLiterals.FE_Ua2Oa]; }); try { await fooRepo.find({ name: TestFooEntityLiterals.FE_Ua2Oa.name }, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember }); await fooRepo.find({ name: TestFooEntityLiterals.FE_Ua2Oa.name }, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember }); } catch (e) { error = e; } expect(error).toBeUndefined(); expect(spyDbFind).toBeCalledTimes(1); }); // // ------------------------------------------- // it(`WITH valid authorization AND options.skipCache = true THEN _dbFind should be triggered twice (cache not used) `, async () => { let error; // @ts-ignore const spyDbFind = jest.spyOn(fooRepo, '_dbFind').mockImplementation(conditions => { return [TestFooEntityLiterals.FE_Ua2Oa]; }); try { await fooRepo.find({ name: TestFooEntityLiterals.FE_Ua2Oa.name }, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember, skipCache: true }); await fooRepo.find({ name: TestFooEntityLiterals.FE_Ua2Oa.name }, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember, skipCache: true }); } catch (e) { error = e; } expect(error).toBeUndefined(); expect(spyDbFind).toBeCalledTimes(2); }); }); // // ------------------------------------------- // // Create Tests // // ------------------------------------------- // describe('WHEN create is called with an org-scoped and user-scoped Repo', () => { it(`WITH valid authorization THEN a Foo should be returned`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbSave').mockImplementation(entity => { return entity; }); const newFoo = _.clone(TestFooEntityLiterals.FE_Ua2Oa); newFoo.id = ''; try { result = await fooRepo.create(newFoo, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember }); } catch (e) { error = e; } // delete id, to prep object for comparison delete newFoo.id; expect(error).toBeUndefined(); expect(TestingUtils.objectIdsToStrings(result)).toMatchObject(newFoo); }); // // ------------------------------------------- // it(`WITH no authorization THEN an error should be thrown`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbSave').mockImplementation(entity => { return entity; }); const newFoo = _.clone(TestFooEntityLiterals.FE_Ua2Oa); newFoo.id = ''; try { result = await fooRepo.create(newFoo); } catch (e) { error = e; } expect(error).toBeInstanceOf(AuthorizationError); expect(result).toBeUndefined(); }); // // ------------------------------------------- // it(`WITH invalid authorization THEN an error should be thrown`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbSave').mockImplementation(entity => { return entity; }); const newFoo = _.clone(TestFooEntityLiterals.FE_Ua2Oa); newFoo.id = ''; try { result = await fooRepo.create(newFoo, { accessPermissions: TestAuthorizationLiterals.Az_Ub1user_ObAdmin }); } catch (e) { error = e; } expect(error).toBeInstanceOf(AuthorizationError); expect(result).toBeUndefined(); }); }); // // ------------------------------------------- // // Patch Tests // // ------------------------------------------- // describe('WHEN patch is called with an org-scoped and user-scoped Repo', () => { it(`WITH valid authorization THEN a Foo should be returned`, async () => { let error; let result; const fooToBeUpdated = _.clone(TestFooEntityLiterals.FE_Ua2Oa); // @ts-ignore jest.spyOn(fooRepo, '_dbFindById').mockImplementation(entityId => { return fooToBeUpdated; }); // @ts-ignore jest.spyOn(fooRepo, '_dbSave').mockImplementation(entity => { return entity; }); const patchFoo = { id: fooToBeUpdated.id, name: fooToBeUpdated.name + ' updated', }; try { result = await fooRepo.patch(patchFoo, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember }); } catch (e) { error = e; } const expectedFoo = fooToBeUpdated; expectedFoo.name = expectedFoo.name + ' updated'; expect(error).toBeUndefined(); expect(TestingUtils.objectIdsToStrings(result)).toMatchObject(expectedFoo); }); // // ------------------------------------------- // it(`WITH no authorization THEN an error should be thrown`, async () => { let error; let result; const fooToBeUpdated = _.clone(TestFooEntityLiterals.FE_Ua2Oa); // @ts-ignore jest.spyOn(fooRepo, '_dbFindById').mockImplementation(entityId => { return fooToBeUpdated; }); // @ts-ignore jest.spyOn(fooRepo, '_dbSave').mockImplementation(entity => { return entity; }); const patchFoo = { id: fooToBeUpdated.id, name: fooToBeUpdated.name + ' updated', }; try { result = await fooRepo.patch(patchFoo); } catch (e) { error = e; } const expectedFoo = fooToBeUpdated; expectedFoo.name = expectedFoo.name + ' updated'; expect(error).toBeInstanceOf(AuthorizationError); expect(result).toBeUndefined(); }); // // ------------------------------------------- // it(`WITH invalid authorization THEN an error should be thrown`, async () => { let error; let result; const fooToBeUpdated = _.clone(TestFooEntityLiterals.FE_Ua2Oa); // @ts-ignore jest.spyOn(fooRepo, '_dbFindById').mockImplementation(entityId => { return fooToBeUpdated; }); // @ts-ignore jest.spyOn(fooRepo, '_dbSave').mockImplementation(entity => { return entity; }); const patchFoo = { id: fooToBeUpdated.id, name: fooToBeUpdated.name + ' updated', }; try { result = await fooRepo.patch(patchFoo, { accessPermissions: TestAuthorizationLiterals.Az_Ub1user_ObAdmin }); } catch (e) { error = e; // logger.debug('patch error', JSON.stringify(error, null, 2)); } const expectedFoo = fooToBeUpdated; expectedFoo.name = expectedFoo.name + ' updated'; expect(error).toBeInstanceOf(AuthorizationError); expect(result).toBeUndefined(); }); }); // // ------------------------------------------- // // Update Tests // // ------------------------------------------- // describe('WHEN update is called with an org-scoped and user-scoped Repo', () => { it(`WITH valid authorization THEN a Foo should be returned`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbFindOneAndReplace').mockImplementation(entity => { return entity; }); try { result = await fooRepo.update(TestFooEntityLiterals.FE_Ua2Oa, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember }); } catch (e) { error = e; } expect(error).toBeUndefined(); expect(TestingUtils.objectIdsToStrings(result)).toMatchObject(TestFooEntityLiterals.FE_Ua2Oa); }); // // ------------------------------------------- // it(`WITH no orgId THEN a validation error should be thrown`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbFindOneAndReplace').mockImplementation(entity => { return entity; }); const fooWithMissingOrgId = _.clone(TestFooEntityLiterals.FE_Ua2Oa); delete fooWithMissingOrgId.orgId; try { result = await fooRepo.update(fooWithMissingOrgId, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember }); } catch (e) { error = e; } expect(error).toBeInstanceOf(ValidationError); expect(result).toBeUndefined(); }); // // ------------------------------------------- // it(`WITH no authorization THEN an authorization error should be thrown`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbFindOneAndReplace').mockImplementation(entity => { return entity; }); try { result = await fooRepo.update(TestFooEntityLiterals.FE_Ua2Oa); } catch (e) { error = e; } expect(error).toBeInstanceOf(AuthorizationError); expect(result).toBeUndefined(); }); // // ------------------------------------------- // it(`WITH invalid authorization THEN an authorization error should be thrown`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbFindOneAndReplace').mockImplementation(entity => { return entity; }); try { result = await fooRepo.update(TestFooEntityLiterals.FE_Ua2Oa, { accessPermissions: TestAuthorizationLiterals.Az_Ub1user_ObAdmin }); } catch (e) { error = e; } expect(error).toBeInstanceOf(AuthorizationError); expect(result).toBeUndefined(); }); }); // // ------------------------------------------- // // Delete Tests // // ------------------------------------------- // describe('WHEN delete is called with an id for an org-scoped and user-scoped Repo', () => { it(`WITH valid authorization THEN a Foo should be returned`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbFindById').mockImplementation(entityId => { return TestFooEntityLiterals.FE_Ua2Oa; }); // @ts-ignore jest.spyOn(fooRepo, '_dbRemove').mockImplementation(entity => { return entity; }); try { result = await fooRepo.delete(TestFooEntityLiterals.FE_Ua2Oa.id, { accessPermissions: TestAuthorizationLiterals.Az_Ua2User_OaMember }); } catch (e) { error = e; } expect(error).toBeUndefined(); expect(TestingUtils.objectIdsToStrings(result)).toMatchObject(TestFooEntityLiterals.FE_Ua2Oa); }); // // ------------------------------------------- // it(`WITH valid groupAdmin authorization THEN a Foo should be returned`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbFindById').mockImplementation(entityId => { return TestFooEntityLiterals.FE_Ua2Oa; }); // @ts-ignore jest.spyOn(fooRepo, '_dbRemove').mockImplementation(entity => { return entity; }); try { result = await fooRepo.delete(TestFooEntityLiterals.FE_Ua2Oa.id, { accessPermissions: TestAuthorizationLiterals.Az_Uc1GroupAdmin_OcMember_OaFacilitator }); } catch (e) { error = e; } expect(error).toBeUndefined(); expect(TestingUtils.objectIdsToStrings(result)).toMatchObject(TestFooEntityLiterals.FE_Ua2Oa); }); // // ------------------------------------------- // it(`WITH no authorization THEN an authorization error should be thrown`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbFindById').mockImplementation(entityId => { return TestFooEntityLiterals.FE_Ua2Oa; }); // @ts-ignore jest.spyOn(fooRepo, '_dbRemove').mockImplementation(entity => { return entity; }); try { result = await fooRepo.delete(TestFooEntityLiterals.FE_Ua2Oa.id); } catch (e) { error = e; } expect(error).toBeInstanceOf(AuthorizationError); expect(result).toBeUndefined(); }); // // ------------------------------------------- // it(`WITH invalid authorization THEN an authorization error should be thrown`, async () => { let error; let result; // @ts-ignore jest.spyOn(fooRepo, '_dbFindById').mockImplementation(entityId => { return TestFooEntityLiterals.FE_Ua2Oa; }); // @ts-ignore jest.spyOn(fooRepo, '_dbRemove').mockImplementation(entity => { return entity; }); try { result = await fooRepo.delete(TestFooEntityLiterals.FE_Ua2Oa.id, { accessPermissions: TestAuthorizationLiterals.Az_Ub1user_ObAdmin }); } catch (e) { error = e; } expect(error).toBeInstanceOf(AuthorizationError); expect(result).toBeUndefined(); }); }); }); // // Unused Snippets // // Instantiate Object Via NestJS /* const module = await Test.createTestingModule({ imports: [DomainCoreModule, DomainFooModule], }).compile(); fooRepo = await module.get<FooRepo>(FooRepo); */
the_stack
import { browser, by, element, protractor, $ } from 'protractor'; import { Login } from '../page-objects/login.po'; import { OverviewCompliance } from '../page-objects/overview.po'; import { TaggingCompliance } from '../page-objects/tagging-compliance.po'; import { AssetList } from '../page-objects/asset-list.po'; import { Menu } from '../page-objects/menu.po'; const timeOutHigh = 1800000; describe('Tagging Compliance', () => { let login_po: Login; let OverviewCompliance_po: OverviewCompliance; let menu_po: Menu; const EC = protractor.ExpectedConditions; let taggingcompliance_po: TaggingCompliance; let assetList_po: AssetList; let tag_percent_summary; let tag_percent_compliance; let asset_count1; let asset_count2; let asset_count3; let Temp; beforeAll(() => { login_po = new Login(); OverviewCompliance_po = new OverviewCompliance(); menu_po = new Menu(); taggingcompliance_po = new TaggingCompliance(); assetList_po = new AssetList(); }); it('SSO login', () => { OverviewCompliance_po.navigateToOverviewComplianceGet(); // browser.wait(EC.elementToBeClickable(login_po.getLoginButton()), timeOutHigh); // login_po.getLoginButton().click(); // login_po.clickNext().sendKeys('pacbot@t-mobile.com'); // login_po.submitNext().click(); // OverviewCompliance_po.navigateToOverviewCompliance().click(); const page_title = OverviewCompliance_po.getPageTitle().getText(); expect(page_title).toEqual('Overview'); }); it('Check if Untagged Assets by App (Environment Untagged counts) matches Asset List Table', () => { // browser.wait(EC.elementToBeClickable(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh); // OverviewCompliance_po.navigateToOverviewCompliance().click(); taggingcompliance_po.navigateToTaggingCompliance().click(); browser.wait(EC.visibilityOf(taggingcompliance_po.getApplicationfirstValue()), timeOutHigh); browser.wait(EC.elementToBeClickable(taggingcompliance_po.getApplicationfirstValue()), timeOutHigh); taggingcompliance_po.getAllListUntaggedAssetsTable().then(function(items) { for (let i = 1; i < 8; i++) { browser.executeScript('arguments[0].scrollIntoView();', $('.data-table-inner-wrap .data-table-rows:nth-child(' + i + ') .row-cells:nth-child(2) .column-wrapper a').getWebElement()); $('.data-table-inner-wrap .data-table-rows:nth-child(' + i + ') .row-cells:nth-child(2) .column-wrapper a').getText().then(function (text) { $('.data-table-inner-wrap .data-table-rows:nth-child(' + i + ') .row-cells:nth-child(2) .column-wrapper a').click(); browser.wait(EC.visibilityOf(assetList_po.getAssetTotalRows()), timeOutHigh); asset_count1 = text; assetList_po.getAssetTotalRows().getText().then(function(bottomText) { expect(asset_count1).toEqual(bottomText); assetList_po.goBack().click(); }); }); } }); }); it('Check if Untagged Assets by App (Role Untagged counts) matches Asset List Table', () => { // browser.wait(EC.elementToBeClickable(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh); // OverviewCompliance_po.navigateToOverviewCompliance().click(); taggingcompliance_po.navigateToTaggingCompliance().click(); browser.wait(EC.visibilityOf(taggingcompliance_po.getApplicationfirstValue()), timeOutHigh); browser.wait(EC.elementToBeClickable(taggingcompliance_po.getApplicationfirstValue()), timeOutHigh); taggingcompliance_po.getAllListUntaggedAssetsTable().then(function(items) { for (let i = 1; i < items.length; i++) { browser.executeScript('arguments[0].scrollIntoView();', $('.data-table-inner-wrap .data-table-rows:nth-child(' + i + ') .row-cells:nth-child(3) .column-wrapper a').getWebElement()); $('.data-table-inner-wrap .data-table-rows:nth-child(' + i + ') .row-cells:nth-child(3) .column-wrapper a').getText().then(function (text) { $('.data-table-inner-wrap .data-table-rows:nth-child(' + i + ') .row-cells:nth-child(3) .column-wrapper a').click(); browser.wait(EC.visibilityOf(assetList_po.getAssetTotalRows()), timeOutHigh); asset_count1 = text; assetList_po.getAssetTotalRows().getText().then(function(subtext) { expect(asset_count1).toEqual(subtext); assetList_po.goBack().click(); }); }); } }); }); it('Check if Untagged Assets by App (Stack Untagged counts) matches Asset List Table', () => { // browser.wait(EC.elementToBeClickable(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh); // OverviewCompliance_po.navigateToOverviewCompliance().click(); taggingcompliance_po.navigateToTaggingCompliance().click(); browser.wait(EC.visibilityOf(taggingcompliance_po.getApplicationfirstValue()), timeOutHigh); browser.wait(EC.elementToBeClickable(taggingcompliance_po.getApplicationfirstValue()), timeOutHigh); taggingcompliance_po.getAllListUntaggedAssetsTable().then(function(items) { for (let i = 1; i < items.length; i++) { browser.executeScript('arguments[0].scrollIntoView();', $('.data-table-inner-wrap .data-table-rows:nth-child(' + i + ') .row-cells:nth-child(4) .column-wrapper a').getWebElement()); $('.data-table-inner-wrap .data-table-rows:nth-child(' + i + ') .row-cells:nth-child(4) .column-wrapper a').getText().then(function (text) { $('.data-table-inner-wrap .data-table-rows:nth-child(' + i + ') .row-cells:nth-child(4) .column-wrapper a').click(); browser.wait(EC.visibilityOf(assetList_po.getAssetTotalRows()), timeOutHigh); asset_count1 = text; assetList_po.getAssetTotalRows().getText().then(function(subtext) { expect(asset_count1).toEqual(subtext); assetList_po.goBack().click(); }); }); } }); }); it('Check if Tagging across target types for Tagging matches Asset List Table', () => { // browser.wait(EC.elementToBeClickable(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh); // OverviewCompliance_po.navigateToOverviewCompliance().click(); taggingcompliance_po.navigateToTaggingCompliance().click(); browser.wait(EC.visibilityOf(taggingcompliance_po.getApplicationfirstValue()), timeOutHigh); taggingcompliance_po.getAllListUntaggedAssetsTable().then(function(items) { for (let i = 1; i <= 2; i++) { browser.executeScript('arguments[0].scrollIntoView();', $('.tiles-wrapper .container-parent li:nth-child(' + i + ') .tagging-info-wrapper .left-wrapper .count').getWebElement()); $('.tiles-wrapper .container-parent li:nth-child(' + i + ') .tagging-info-wrapper .left-wrapper .count').getText().then(function (text) { $('.tiles-wrapper .container-parent li:nth-child(' + i + ') .tagging-info-wrapper .left-wrapper .count').click(); browser.wait(EC.visibilityOf(assetList_po.getAssetTotalRows()), timeOutHigh); asset_count1 = text; assetList_po.getAssetTotalRows().getText().then(function(subtext) { expect(asset_count1).toEqual(subtext); assetList_po.goBack().click(); }); }); } }); }); it('Check if Tagging across target types for Untagging matches Asset List Table', () => { // browser.wait(EC.elementToBeClickable(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh); // OverviewCompliance_po.navigateToOverviewCompliance().click(); taggingcompliance_po.navigateToTaggingCompliance().click(); browser.wait(EC.visibilityOf(taggingcompliance_po.getApplicationfirstValue()), timeOutHigh); taggingcompliance_po.getAllListUntaggedAssetsTable().then(function(items) { for (let i = 1; i <= 2; i++) { browser.executeScript('arguments[0].scrollIntoView();', $('.tiles-wrapper .container-parent li:nth-child(' + (i + 1) + ') .tagging-info-wrapper .right-wrapper .count').getWebElement()); $('.tiles-wrapper .container-parent li:nth-child(' + (i + 1) + ') .tagging-info-wrapper .right-wrapper .count').getText().then(function (text) { $('.tiles-wrapper .container-parent li:nth-child(' + (i + 1) + ') .tagging-info-wrapper .right-wrapper .count').click(); browser.wait(EC.visibilityOf(assetList_po.getAssetTotalRows()), timeOutHigh); asset_count1 = text; assetList_po.getAssetTotalRows().getText().then(function(subtext) { expect(asset_count1).toEqual(subtext); assetList_po.goBack().click(); }); }); } }); }); it('Verify Tagging Percent ', () => { // browser.wait(EC.elementToBeClickable(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh); // OverviewCompliance_po.navigateToOverviewCompliance().click(); taggingcompliance_po.navigateToTaggingCompliance().click(); browser.wait(EC.visibilityOf(taggingcompliance_po.getTaggingPercent()), timeOutHigh); tag_percent_summary = taggingcompliance_po.getTaggingPercent().getText().then(function (text) { text = text.replace(/,/g, ''); tag_percent_summary = parseInt(text, 10); }); browser.wait(EC.visibilityOf(taggingcompliance_po.getTotalTaggingPercent()), timeOutHigh); taggingcompliance_po.getTotalTaggingPercent().getText().then(function (text) { text = text.replace(/,/g, ''); tag_percent_compliance = parseInt(text, 10); expect(tag_percent_summary).toEqual(tag_percent_compliance); }); }); it('Verify Total Asset Count', () => { browser.wait(EC.presenceOf(menu_po.MenuClick()), timeOutHigh); browser.wait(EC.elementToBeClickable(menu_po.MenuClick()), timeOutHigh); menu_po.MenuClick().click(); browser.wait(EC.visibilityOf(menu_po.TaggingClick()), timeOutHigh); browser.wait(EC.elementToBeClickable(menu_po.TaggingClick()), timeOutHigh); menu_po.TaggingClick().click(); browser.wait(EC.visibilityOf(taggingcompliance_po.getOverallAssets()), timeOutHigh); taggingcompliance_po.getOverallAssets().getText().then(function (text) { text = text.replace(/,/g, ''); asset_count1 = text; }); taggingcompliance_po.getOverallAssets().click(); browser.wait(EC.visibilityOf(assetList_po.getAssetTotalRows()), timeOutHigh); Temp = assetList_po.getAssetTotalRows().getText().then(function (text) { text = text.replace(/,/g, ''); expect(asset_count1).toEqual(text); }); browser.wait(EC.elementToBeClickable(assetList_po.getBackArrowEle()), timeOutHigh); assetList_po.getBackArrow().click(); }); it('Verify Total Tagging Count', () => { browser.wait(EC.elementToBeClickable(taggingcompliance_po.getOverallAssets()), timeOutHigh); taggingcompliance_po.navigateToTaggingCompliance().click(); browser.wait(EC.visibilityOf(taggingcompliance_po.getOverallTagging()), timeOutHigh); browser.wait(EC.elementToBeClickable(taggingcompliance_po.getOverallTagging()), timeOutHigh); taggingcompliance_po.getOverallTagging().getText().then(function (text) { text = text.replace(/,/g, ''); asset_count2 = text; }); taggingcompliance_po.getOverallTagging().click(); browser.wait(EC.visibilityOf(assetList_po.getAssetTotalRows()), timeOutHigh); Temp = assetList_po.getAssetTotalRows().getText().then(function (text) { text = text.replace(/,/g, ''); expect(asset_count2).toEqual(text); }); browser.wait(EC.elementToBeClickable(assetList_po.getBackArrowEle()), timeOutHigh); assetList_po.getBackArrow().click(); }); it('Verify Total Untagging Count', () => { browser.wait(EC.elementToBeClickable(taggingcompliance_po.getOverallAssets()), timeOutHigh); taggingcompliance_po.navigateToTaggingCompliance().click(); browser.wait(EC.visibilityOf(taggingcompliance_po.getOverallunTagging()), timeOutHigh); browser.wait(EC.elementToBeClickable(taggingcompliance_po.getOverallunTagging()), timeOutHigh); taggingcompliance_po.getOverallunTagging().getText().then(function (text) { text = text.replace(/,/g, ''); asset_count3 = text; }); taggingcompliance_po.getOverallunTagging().click(); browser.wait(EC.visibilityOf(assetList_po.getAssetTotalRows()), timeOutHigh); Temp = assetList_po.getAssetTotalRows().getText().then(function (text) { text = text.replace(/,/g, ''); expect(asset_count3).toEqual(text); }); browser.wait(EC.elementToBeClickable(assetList_po.getBackArrowEle()), timeOutHigh); assetList_po.getBackArrow().click(); }); it('Verify Total Tagging Sum', () => { browser.wait(EC.elementToBeClickable(taggingcompliance_po.getOverallAssets()), timeOutHigh); taggingcompliance_po.navigateToTaggingCompliance().click(); browser.wait(EC.visibilityOf(taggingcompliance_po.getOverallunTagging()), timeOutHigh); asset_count1 = taggingcompliance_po.getOverallAssets().getText().then(function (text) { text = text.replace(/,/g, ''); asset_count1 = text; }); asset_count2 = taggingcompliance_po.getOverallTagging().getText().then(function (text) { text = text.replace(/,/g, ''); asset_count2 = text; }); asset_count3 = taggingcompliance_po.getOverallunTagging().getText().then(function (text) { text = text.replace(/,/g, ''); asset_count3 = text; Temp = parseInt(asset_count2, 10) + parseInt(asset_count3, 10); expect(Temp).toEqual(Number.parseInt(asset_count1, 10)); }); }); it('verify untagged assets by app table name and headers', () => { browser.wait(EC.visibilityOf(taggingcompliance_po.getTableHeader()), timeOutHigh); browser.wait(EC.visibilityOf(taggingcompliance_po.getApplicationHeader()), timeOutHigh); const application_path = taggingcompliance_po.getApplicationHeader().getText(); expect(application_path).toEqual('application'); const environment_path = taggingcompliance_po.getEnvironmentUntagged().getText(); expect(environment_path).toEqual('environment Untagged'); const role_path = taggingcompliance_po.getRoleUntagged().getText(); expect(role_path).toEqual('role Untagged'); const stack_path = taggingcompliance_po.getStackUntagged().getText(); expect(stack_path).toEqual('stack Untagged'); }); it('verify appearance of additional details', () => { browser.wait(EC.visibilityOf(taggingcompliance_po.getApplicationfirstValue()), timeOutHigh); taggingcompliance_po.getApplicationfirstValue().click(); browser.wait(EC.visibilityOf(taggingcompliance_po.getAdditionalDetailsHeaderText()), timeOutHigh); const additional_detail_path = taggingcompliance_po.getAdditionalDetailsHeaderText().getText(); expect(additional_detail_path).toEqual('Additional Details'); browser.wait(EC.elementToBeClickable(taggingcompliance_po.getAdditionaldetailsCrossMark()), timeOutHigh); taggingcompliance_po.getAdditionaldetailsCrossMark().click(); }); it('verify csv download', () => { let download_successful = false; browser.wait(EC.presenceOf( taggingcompliance_po.getAssetTotalRows()), timeOutHigh); const filename = process.cwd() + '/e2e/downloads/Tagging Untagged Assets.csv'; const fs = require('fs'); const myDir = process.cwd() + '/e2e/downloads'; if (!taggingcompliance_po.checkDirExists(myDir)) { fs.mkdirSync(myDir); } else if ((fs.readdirSync(myDir).length) > 0 && fs.existsSync(filename)) { fs.unlinkSync(filename); } browser.wait(EC.visibilityOf(taggingcompliance_po.getAssetTotalRows()), timeOutHigh); taggingcompliance_po.getdownloadIcon().click(); browser.wait(EC.visibilityOf(taggingcompliance_po.getToastMsg()), timeOutHigh).then(function() { browser.wait(EC.invisibilityOf(taggingcompliance_po.getDownloadRunningIcon()), 600000).then(function() { browser.sleep(4000); browser.driver.wait(function() { if (fs.existsSync(filename)) { download_successful = true; const fileContent = fs.readFileSync(filename, { encoding: 'utf8' }); expect(fileContent.toString().indexOf('\n')).toBeGreaterThan(0); } expect(download_successful).toEqual(true); return fs.existsSync(filename); }, timeOutHigh); }); }); }); it('verify Untagged Assets by App table search', () => { browser.wait(EC.visibilityOf(taggingcompliance_po.getSearchLabel()), timeOutHigh); browser.wait(EC.elementToBeClickable(taggingcompliance_po.getSearchLabel()), timeOutHigh); taggingcompliance_po.getSearchLabel().click(); browser.wait(EC.visibilityOf(taggingcompliance_po.getSearchInput()), timeOutHigh); taggingcompliance_po.getSearchInput().sendKeys('datalake'); browser.actions().sendKeys(protractor.Key.ENTER).perform(); browser.wait(EC.visibilityOf(taggingcompliance_po.getFirstStatusRow()), timeOutHigh); const status_path = taggingcompliance_po.getFirstStatusRow().getText(); expect(status_path).toEqual('DataLake'); }); it('Verify help text window is opening', () => { browser.wait(EC.visibilityOf(taggingcompliance_po.openHelp()), timeOutHigh); browser.wait(EC.elementToBeClickable(taggingcompliance_po.openHelp()), timeOutHigh); taggingcompliance_po.openHelp().click(); const help_title = OverviewCompliance_po.getHelpTitle().getText(); expect(help_title).toEqual('Help'); browser.wait(EC.elementToBeClickable(taggingcompliance_po.getHelpClose()), timeOutHigh); taggingcompliance_po.getHelpClose().click(); }); it('Check if Untagged counts in Total Tag Compliance matches Asset List Table', () => { browser.wait(EC.visibilityOf(taggingcompliance_po.navigateToTaggingCompliance()), timeOutHigh); // browser.wait(EC.elementToBeClickable( taggingcompliance_po.getListTableFirstTotal()), timeOutHigh); taggingcompliance_po.getAllList().then(function(items) { for (let i = 1; i < items.length; i++) { browser.executeScript('arguments[0].scrollIntoView();', $('.list-table-inner-wrapper .list-table-each-list:nth-child(' + (i + 1) + ') .list-table-value .list-table-count-each:nth-child(1)').getWebElement()); $('.list-table-inner-wrapper .list-table-each-list:nth-child(' + (i + 1) + ') .list-table-value .list-table-count-each:nth-child(1)').getText().then(function (text) { $('.list-table-inner-wrapper .list-table-each-list:nth-child(' + (i + 1) + ') .list-table-value .list-table-count-each:nth-child(1)').click(); browser.wait(EC.visibilityOf(assetList_po.getAssetTotalRows()), timeOutHigh); asset_count1 = text; assetList_po.getAssetTotalRows().getText().then(function(subtext) { expect(asset_count1).toEqual(subtext); assetList_po.goBack().click(); }); } ); } }); }); it('Check if Tagged counts in Total Tag Compliance matches Asset List Table', () => { browser.wait(EC.visibilityOf(taggingcompliance_po.getApplicationtagHeader()), timeOutHigh); browser.wait(EC.elementToBeClickable( taggingcompliance_po.getListTableSecondTotal()), timeOutHigh); taggingcompliance_po.getAllList().then(function(items) { for (let i = 1; i < items.length; i++) { browser.executeScript('arguments[0].scrollIntoView();', $('.list-table-inner-wrapper .list-table-each-list:nth-child(' + (i + 1) + ') .list-table-value .list-table-count-each:nth-child(2)').getWebElement()); $('.list-table-inner-wrapper .list-table-each-list:nth-child(' + (i + 1) + ') .list-table-value .list-table-count-each:nth-child(2)').getText().then(function (text) { $('.list-table-inner-wrapper .list-table-each-list:nth-child(' + (i + 1) + ') .list-table-value .list-table-count-each:nth-child(2)').click(); browser.wait(EC.visibilityOf(assetList_po.getAssetTotalRows()), timeOutHigh); asset_count1 = text; assetList_po.getAssetTotalRows().getText().then(function(subtext) { expect(asset_count1).toEqual(subtext); assetList_po.goBack().click(); }); } ); } }); }); });
the_stack
import { EstimationMode } from '@emeraldpay/api'; import { BigAmount } from '@emeraldpay/bigamount'; import { Wei } from '@emeraldpay/bigamount-crypto'; import { UnsignedTx } from '@emeraldpay/emerald-vault-core'; import { EntryId, UnsignedBitcoinTx } from '@emeraldpay/emerald-vault-core/lib/types'; import { IEmeraldVault } from '@emeraldpay/emerald-vault-core/lib/vault'; import { BitcoinStoredTransaction, BlockchainCode, Blockchains, EthereumAddress, EthereumStoredTransaction, EthereumTx, isBitcoin, isEthereum, Logger, quantitiesToHex, } from '@emeraldwallet/core'; import BigNumber from 'bignumber.js'; import { Dispatch } from 'redux'; import * as screen from '../screen'; import { catchError, gotoScreen, showError } from '../screen/actions'; import * as history from '../txhistory'; import { DEFAULT_FEE, Dispatched, FEE_KEYS, GasPrices, GasPriceType, IExtraArgument, PriceSort } from '../types'; const log = Logger.forCategory('store.transaction'); function unwrap(value: string[] | string | null): Promise<string> { return new Promise((resolve, reject) => { const [data] = Array.isArray(value) ? value : [value]; if (typeof data === 'string') { return resolve(data); } reject(new Error(`Invalid value ${value}`)); }); } /** * Called after Tx sent */ function onEthereumTxSent( dispatch: Dispatch<any>, txHash: string, sourceTx: EthereumStoredTransaction, blockchain: BlockchainCode, ): void { // dispatch(loadAccountBalance(sourceTx.from)); const sentTx = { ...sourceTx, hash: txHash }; // TODO: dependency on wallet/history module! dispatch(history.actions.trackTxs([sentTx], blockchain)); dispatch(gotoScreen(screen.Pages.TX_DETAILS, sentTx)); } function onBitcoinTxSent( dispatch: Dispatch<any>, txHash: string, sourceTx: UnsignedBitcoinTx, blockchain: BlockchainCode, ): void { const sentTx: BitcoinStoredTransaction = { blockchain, since: new Date(), hash: txHash, entries: sourceTx.inputs .map((it) => it.entryId) .filter((it) => typeof it != 'undefined') .map((it) => it!) .reduce((all, it) => (all.indexOf(it) >= 0 ? all : all.concat(it)), [] as string[]), inputs: sourceTx.inputs.map((it) => { return { txid: it.txid, vout: it.vout, amount: it.amount, entryId: it.entryId, address: it.address, hdPath: it.hdPath, }; }), outputs: sourceTx.outputs, fee: sourceTx.fee, }; // TODO: dependency on wallet/history module! dispatch(history.actions.trackTxs([sentTx], blockchain)); dispatch(gotoScreen(screen.Pages.TX_DETAILS, sentTx)); } function withNonce(tx: EthereumStoredTransaction): (nonce: number) => Promise<EthereumStoredTransaction> { return (nonce) => new Promise((resolve) => resolve({ ...tx, nonce: quantitiesToHex(nonce) })); } function verifySender(expected: string): (a: string, c: BlockchainCode) => Promise<string> { return (raw: string, chain: BlockchainCode) => new Promise((resolve, reject) => { // Find chain id const chainId = Blockchains[chain].params.chainId; const tx = EthereumTx.fromRaw(raw, chainId); if (tx.verifySignature()) { log.debug('Tx signature verified'); if (!tx.getSenderAddress().equals(new EthereumAddress(expected))) { log.error(`WRONG SENDER: 0x${tx.getSenderAddress().toString()} != ${expected}`); reject(new Error('Emerald Vault returned signature from wrong Sender')); } else { resolve(raw); } } else { log.error(`Invalid signature: ${raw}`); reject(new Error('Emerald Vault returned invalid signature for the transaction')); } }); } function signTx( vault: IEmeraldVault, accountId: string, tx: EthereumStoredTransaction, passphrase: string, blockchain: BlockchainCode, ): Promise<string | string[]> { log.debug(`Calling emerald api to sign tx from ${tx.from} to ${tx.to} in ${blockchain} blockchain`); let gasPrices: Record<'gasPrice', string> | Record<'maxGasPrice' | 'priorityGasPrice', string>; if (tx.gasPrice == null) { const maxGasPrice = typeof tx.maxGasPrice === 'string' ? tx.maxGasPrice : tx.maxGasPrice?.toString() ?? '0'; const priorityGasPrice = typeof tx.priorityGasPrice === 'string' ? tx.priorityGasPrice : tx.priorityGasPrice?.toString() ?? '0'; gasPrices = { maxGasPrice, priorityGasPrice, }; } else { const gasPrice = typeof tx.gasPrice === 'string' ? tx.gasPrice : tx.gasPrice?.toString() ?? '0'; gasPrices = { gasPrice }; } const unsignedTx: UnsignedTx = { ...gasPrices, data: tx.data, from: tx.from, gas: typeof tx.gas === 'string' ? parseInt(tx.gas) : tx.gas, nonce: typeof tx.nonce === 'string' ? parseInt(tx.nonce) : tx.nonce, to: tx.to, value: typeof tx.value === 'string' ? tx.value : tx.value.toString(), }; return vault.signTx(accountId, unsignedTx, passphrase); } export function signTransaction( accountId: string, blockchain: BlockchainCode, from: string, passphrase: string, to: string, gas: number, value: Wei, data: string, gasPrice?: Wei, maxGasPrice?: Wei, priorityGasPrice?: Wei, nonce: number | string = '', ): Dispatched<any> { const originalTx: EthereumStoredTransaction = { blockchain, data, from, gas, nonce, to, gasPrice: gasPrice?.number, maxGasPrice: maxGasPrice?.number, priorityGasPrice: priorityGasPrice?.number, value: value.number, }; return (dispatch: any, getState, extra) => { const callSignTx = (tx: EthereumStoredTransaction): Promise<any> => { return signTx(extra.api.vault, accountId, tx, passphrase, blockchain) .then(unwrap) .then((rawTx) => verifySender(from)(rawTx, blockchain)) .then((signed) => ({ tx, signed })); }; if (nonce.toString().length > 0) { return callSignTx(originalTx); } return extra.backendApi .getNonce(blockchain, from) .then(withNonce(originalTx)) .then(callSignTx) .catch(catchError(dispatch)); }; } export function signBitcoinTransaction( entryId: EntryId, tx: UnsignedBitcoinTx, password: string, handler: (raw?: string, err?: string) => void, ): Dispatched<any> { return (dispatch: any, getState, extra) => { extra.api.vault .signTx(entryId, tx, password) .then((raw) => handler(raw)) .catch((err) => { handler(undefined, 'Internal error. ' + err?.message); dispatch(showError(err)); }); }; } export function broadcastTx( chain: BlockchainCode, tx: EthereumStoredTransaction | UnsignedBitcoinTx, signedTx: string, ): Dispatched<any> { return async (dispatch: any, getState: any, extra: IExtraArgument) => { try { const hash = await extra.backendApi.broadcastSignedTx(chain, signedTx); if (isBitcoin(chain)) { return onBitcoinTxSent(dispatch, hash, tx as BitcoinStoredTransaction, chain); } else if (isEthereum(chain)) { return onEthereumTxSent(dispatch, hash, tx as EthereumStoredTransaction, chain); } } catch (e) { dispatch(showError(e)); } }; } type Tx = { gas: BigNumber; to: string; data?: string; from?: string; value?: BigAmount; }; export function estimateGas(chain: BlockchainCode, tx: Tx): Dispatched<any> { const { data, from, gas, to, value } = tx; return (dispatch: any, getState: any, extra: IExtraArgument) => { return extra.backendApi.estimateTxCost(chain, { data, from, to, gas: gas.toNumber(), value: `0x${value?.number.toString(16) ?? 0}`, }); }; } export function estimateFee(blockchain: BlockchainCode, blocks: number, mode: EstimationMode) { return (dispatch: any, getState: any, extra: IExtraArgument) => { return extra.backendApi.estimateFee(blockchain, blocks, mode); }; } function sortBigNumber(first: BigNumber, second: BigNumber): number { if (first.eq(second)) { return 0; } return first.gt(second) ? 1 : -1; } export function getFee(blockchain: BlockchainCode): Dispatched<Record<typeof FEE_KEYS[number], GasPrices>> { return async (dispatch: any) => { let results = await Promise.allSettled( FEE_KEYS.map((key) => dispatch(estimateFee(blockchain, 128, key))), ); results = await Promise.allSettled( results.map((result, index) => result.status === 'fulfilled' ? Promise.resolve(result.value) : dispatch(estimateFee(blockchain, 256, FEE_KEYS[index])), ), ); let [avgLastNumber, avgTail5Number, avgMiddleNumber] = results.map((result) => { const value = result.status === 'fulfilled' ? result.value ?? DEFAULT_FEE : DEFAULT_FEE; let expect: GasPriceType; let max: GasPriceType; let priority: GasPriceType; if (typeof value === 'string') { ({ expect, max, priority } = { ...DEFAULT_FEE, expect: value }); } else { ({ expect, max, priority } = value); } return { expect: new BigNumber(expect), max: new BigNumber(max), priority: new BigNumber(priority), }; }); let { expects, highs, priorities } = [avgLastNumber, avgTail5Number, avgMiddleNumber].reduce<PriceSort>( (carry, item) => ({ expects: [...carry.expects, item.expect], highs: [...carry.highs, item.max], priorities: [...carry.priorities, item.priority], }), { expects: [], highs: [], priorities: [], }, ); expects = expects.sort(sortBigNumber); highs = highs.sort(sortBigNumber); priorities = priorities.sort(sortBigNumber); [avgLastNumber, avgTail5Number, avgMiddleNumber] = expects.reduce<Array<GasPrices<BigNumber>>>( (carry, item, index) => [ ...carry, { expect: item, max: highs[index], priority: priorities[index], }, ], [], ); if (avgTail5Number.expect.eq(0) && avgTail5Number.max.eq(0)) { // TODO Set default value from remote config avgTail5Number = { expect: new Wei(30, 'GWei').number, max: new Wei(30, 'GWei').number, priority: new Wei(1, 'GWei').number, }; } const avgLastExpect = avgLastNumber.expect.gt(0) ? avgLastNumber.expect.toNumber() : avgTail5Number.expect.minus(avgTail5Number.expect.multipliedBy(0.25)).toNumber(); const avgLastMax = avgLastNumber.max.gt(0) ? avgLastNumber.max.toNumber() : avgTail5Number.max.minus(avgTail5Number.max.multipliedBy(0.25)).toNumber(); const avgLastPriority = avgLastNumber.priority.gt(0) ? avgLastNumber.priority.toNumber() : avgTail5Number.priority.minus(avgTail5Number.priority.multipliedBy(0.25)).toNumber(); const avgMiddleExpect = avgMiddleNumber.expect.gt(0) ? avgMiddleNumber.expect.toNumber() : avgTail5Number.expect.plus(avgTail5Number.expect.multipliedBy(0.25)).toNumber(); const avgMiddleMax = avgMiddleNumber.max.gt(0) ? avgMiddleNumber.max.toNumber() : avgTail5Number.max.plus(avgTail5Number.max.multipliedBy(0.25)).toNumber(); const avgMiddlePriority = avgMiddleNumber.priority.gt(0) ? avgMiddleNumber.priority.toNumber() : avgTail5Number.priority.plus(avgTail5Number.priority.multipliedBy(0.25)).toNumber(); return { avgLast: { expect: avgLastExpect, max: avgLastMax, priority: avgLastPriority, }, avgMiddle: { expect: avgMiddleExpect, max: avgMiddleMax, priority: avgMiddlePriority, }, avgTail5: { expect: avgTail5Number.expect.toNumber(), max: avgTail5Number.max.toNumber(), priority: avgTail5Number.priority.toNumber(), }, }; }; }
the_stack
import { Form } from 'react-final-form' import * as web3 from 'src/logic/wallets/getWeb3' import { render, screen, fireEvent, waitFor } from 'src/utils/test-utils' import AddressInput from '.' const fieldName = 'test-field' const fieldTestId = 'test-field-id' const invalidNetworkPrefixErrorMessage = 'The chain prefix must match the current network' const invalidAddressErrorMessage = 'Must be a valid address, ENS or Unstoppable domain' const unsupportedPrefixError = 'Wrong chain prefix' const getENSAddressSpy = jest.spyOn(web3, 'getAddressFromDomain') describe('<AddressInput>', () => { it('Renders AddressInput Component', () => { renderAddressInputWithinForm() const inputNode = screen.getByTestId(fieldTestId) expect(inputNode).toBeInTheDocument() }) xit('Resolver ENS names', async () => { const address = '0x680cde08860141F9D223cE4E620B10Cd6741037E' const ensName = 'test.eth' // mock getAddress fn to return the Address getENSAddressSpy.mockImplementation(() => Promise.resolve(address)) renderAddressInputWithinForm() // we use a ENS name fireEvent.change(screen.getByTestId(fieldTestId), { target: { value: ensName } }) await waitFor(() => { // the loader is not present expect(screen.queryByRole('progressbar')).not.toBeInTheDocument() expect(screen.queryByDisplayValue(ensName)).not.toBeInTheDocument() const inputNode = screen.getByTestId(fieldTestId) as HTMLInputElement // ENS resolved with the valid address expect(inputNode.value).toBe(address) getENSAddressSpy.mockClear() }) }) it('Shows a loader while ENS resolution is loading', async () => { const address = '0x680cde08860141F9D223cE4E620B10Cd6741037E' const ensName = 'test.eth' // mock getAddress fn to return the Address getENSAddressSpy.mockImplementation(() => Promise.resolve(address)) renderAddressInputWithinForm() fireEvent.change(screen.getByTestId(fieldTestId), { target: { value: ensName } }) // get the loader by role=progressbar const loaderNode = screen.getByRole('progressbar') expect(loaderNode).toBeInTheDocument() await waitFor(() => { // the loader is not present expect(screen.queryByRole('progressbar')).not.toBeInTheDocument() const inputNode = screen.getByTestId(fieldTestId) as HTMLInputElement // ENS resolved with the valid address //expect(inputNode.value).toBe(address) getENSAddressSpy.mockClear() }) }) describe('Address validation', () => { it('validates address', () => { const invalidAddress = 'this-is-an-invalid-address' renderAddressInputWithinForm() const inputNode = screen.getByTestId(fieldTestId) as HTMLInputElement fireEvent.change(inputNode, { target: { value: invalidAddress } }) expect(inputNode.value).toBe(invalidAddress) expect(screen.queryByText(invalidAddressErrorMessage)).toBeInTheDocument() }) it('AddressInput is required to submit', () => { const onSubmit = jest.fn() renderAddressInputWithinForm(onSubmit) expect(onSubmit).not.toHaveBeenCalled() expect(screen.queryByText('Required')).not.toBeInTheDocument() // triggers validations on Submit the form fireEvent.click(screen.getByTestId('submit-test-form')) expect(screen.queryByText('Required')).toBeInTheDocument() expect(onSubmit).not.toHaveBeenCalled() }) }) describe('Network prefix validation', () => { it('Validates an ddress with an invalid prefix', () => { const customState = { appearance: { copyShortName: true, showShortName: true, }, } const onSubmit = jest.fn() const address = '0x680cde08860141F9D223cE4E620B10Cd6741037E' const invalidPrefixAddress = `eth:${address}` renderAddressInputWithinForm(onSubmit, customState) // populates the input with an invalid prefix network fireEvent.change(screen.getByTestId(fieldTestId), { target: { value: invalidPrefixAddress } }) // shows the error and the invalid prefix expect((screen.getByTestId(fieldTestId) as HTMLInputElement).value).toBe(invalidPrefixAddress) expect(screen.queryByText(invalidNetworkPrefixErrorMessage)).toBeInTheDocument() }) it('Validates an address with a valid prefix', () => { const customState = { appearance: { copyShortName: true, showShortName: true, }, } const onSubmit = jest.fn() const address = '0x680cde08860141F9D223cE4E620B10Cd6741037E' const validPrefixAddress = `rin:${address}` renderAddressInputWithinForm(onSubmit, customState) // now a valid value fireEvent.change(screen.getByTestId(fieldTestId), { target: { value: validPrefixAddress } }) expect(screen.queryByText(invalidNetworkPrefixErrorMessage)).not.toBeInTheDocument() expect((screen.getByTestId(fieldTestId) as HTMLInputElement).value).toBe(validPrefixAddress) }) it('Validates different Addresses with different prefix', () => { const validPrefixedAddress = 'rin:0x680cde08860141F9D223cE4E620B10Cd6741037E' const inValidPrefixedAddress = 'eth:0x2D42232C03C12f1dC1448f89dcE33d2d5A47Aa33' renderAddressInputWithinForm() // we update the field with the valid prefixed address fireEvent.change(screen.getByTestId(fieldTestId), { target: { value: validPrefixedAddress } }) expect(screen.queryByText(invalidNetworkPrefixErrorMessage)).not.toBeInTheDocument() expect((screen.getByTestId(fieldTestId) as HTMLInputElement).value).toBe(validPrefixedAddress) // no error is present expect(screen.queryByText(invalidNetworkPrefixErrorMessage)).not.toBeInTheDocument() // now invalid address network prefix fireEvent.change(screen.getByTestId(fieldTestId), { target: { value: inValidPrefixedAddress } }) // shows prefix error expect(screen.queryByText(invalidNetworkPrefixErrorMessage)).toBeInTheDocument() // Input value without network prefix expect((screen.getByTestId(fieldTestId) as HTMLInputElement).value).toBe(inValidPrefixedAddress) }) it('Network prefix is not mandatory', () => { const addressWithoutPrefix = '0x680cde08860141F9D223cE4E620B10Cd6741037E' renderAddressInputWithinForm() // address without prefix fireEvent.change(screen.getByTestId(fieldTestId), { target: { value: addressWithoutPrefix } }) // Input value with network prefix expect((screen.getByTestId(fieldTestId) as HTMLInputElement).value).toBe(addressWithoutPrefix) // no error is showed expect(screen.queryByText(invalidNetworkPrefixErrorMessage)).not.toBeInTheDocument() }) it('Prefix network is not added to the given address if its disabled in settings', () => { const customState = { appearance: { copyShortName: false, showShortName: false, }, } const onSubmit = jest.fn() const addressWithoutPrefix = '0x680cde08860141F9D223cE4E620B10Cd6741037E' renderAddressInputWithinForm(onSubmit, customState) // address without prefix fireEvent.change(screen.getByTestId(fieldTestId), { target: { value: addressWithoutPrefix } }) // Input value with network prefix expect((screen.getByTestId(fieldTestId) as HTMLInputElement).value).toBe(addressWithoutPrefix) // no error is showed expect(screen.queryByText(invalidNetworkPrefixErrorMessage)).not.toBeInTheDocument() }) it('Keeps the two dots (:) char in the input value if no prefix is present', () => { const addressWithoutTwoDots = ':0x680cde08860141F9D223cE4E620B10Cd6741037E' renderAddressInputWithinForm() fireEvent.change(screen.getByTestId(fieldTestId), { target: { value: addressWithoutTwoDots } }) // Input value without network prefix expect((screen.getByTestId(fieldTestId) as HTMLInputElement).value).toBe(addressWithoutTwoDots) // no error is showed expect(screen.queryByText(invalidNetworkPrefixErrorMessage)).not.toBeInTheDocument() }) it('Validates the network prefix even if its disabled in settings', () => { const customState = { appearance: { copyShortName: false, showShortName: false, }, } const inValidPrefixedAddress = 'eth:0x2D42232C03C12f1dC1448f89dcE33d2d5A47Aa33' const onSubmit = jest.fn() renderAddressInputWithinForm(onSubmit, customState) // invalid address network prefix fireEvent.change(screen.getByTestId(fieldTestId), { target: { value: inValidPrefixedAddress } }) // input value with the network prefix expect((screen.getByTestId(fieldTestId) as HTMLInputElement).value).toBe(inValidPrefixedAddress) // show prefix error expect(screen.queryByText(invalidNetworkPrefixErrorMessage)).toBeInTheDocument() }) xit('Resolve ENS names even if a network prefix error is present', async () => { const inValidPrefixedAddress = 'eth:0x2D42232C03C12f1dC1448f89dcE33d2d5A47Aa33' const addressFromENS = '0x680cde08860141F9D223cE4E620B10Cd6741037E' const ENSNameAddress = 'test.eth' // mock getAddress fn to return the Address getENSAddressSpy.mockImplementation(() => Promise.resolve(addressFromENS)) renderAddressInputWithinForm() // invalid address network prefix fireEvent.change(screen.getByTestId(fieldTestId), { target: { value: inValidPrefixedAddress } }) // show error expect(screen.queryByText(invalidNetworkPrefixErrorMessage)).toBeInTheDocument() // now we use a ENS name fireEvent.change(screen.getByTestId(fieldTestId), { target: { value: ENSNameAddress } }) await waitFor(() => { const inputNode = screen.getByTestId(fieldTestId) as HTMLInputElement // ENS resolved with the valid address and prefix expect(inputNode.value).toBe(addressFromENS) // no error is present expect(screen.queryByText(invalidNetworkPrefixErrorMessage)).not.toBeInTheDocument() getENSAddressSpy.mockClear() }) }) it('Validates unsupported shortNames', () => { const unsupportedPrefixedAddress = 'xxxx:0x2D42232C03C12f1dC1448f89dcE33d2d5A47Aa33' renderAddressInputWithinForm() // invalid address network prefix fireEvent.change(screen.getByTestId(fieldTestId), { target: { value: unsupportedPrefixedAddress } }) // input value with the network prefix expect((screen.getByTestId(fieldTestId) as HTMLInputElement).value).toBe(unsupportedPrefixedAddress) // show prefix error expect(screen.queryByText(unsupportedPrefixError)).toBeInTheDocument() }) xdescribe('Checksum address', () => { it('Checksum address', () => { const rawAddress = '0X9913B9180C20C6B0F21B6480C84422F6EBC4B808' const checksumAddress = '0x9913B9180C20C6b0F21B6480c84422F6ebc4B808' renderAddressInputWithinForm() fireEvent.change(screen.getByTestId(fieldTestId), { target: { value: rawAddress } }) // input value with checksum address expect((screen.getByTestId(fieldTestId) as HTMLInputElement).value).toBe(checksumAddress) }) it('Checksum valid address with prefix', () => { const rawAddressWithPrefix = 'rin:0X9913B9180C20C6B0F21B6480C84422F6EBC4B808' const checksumAddressWithPrefix = 'rin:0x9913B9180C20C6b0F21B6480c84422F6ebc4B808' renderAddressInputWithinForm() fireEvent.change(screen.getByTestId(fieldTestId), { target: { value: rawAddressWithPrefix } }) // input value with the network prefix and checksum address expect((screen.getByTestId(fieldTestId) as HTMLInputElement).value).toBe(checksumAddressWithPrefix) }) it('Checksum address only when a valid network prefix is present', () => { const rawAddressWithInvalidPrefix = 'eth:0X9913B9180C20C6B0F21B6480C84422F6EBC4B808' const rawAddressWithValidPrefix = 'rin:0X9913B9180C20C6B0F21B6480C84422F6EBC4B808' const checksumAddressWithPrefix = 'rin:0x9913B9180C20C6b0F21B6480c84422F6ebc4B808' renderAddressInputWithinForm() // invalid network prefix fireEvent.change(screen.getByTestId(fieldTestId), { target: { value: rawAddressWithInvalidPrefix } }) // checksum is not preformed expect((screen.getByTestId(fieldTestId) as HTMLInputElement).value).toBe(rawAddressWithInvalidPrefix) // prefix error is showed expect(screen.queryByText(invalidNetworkPrefixErrorMessage)).toBeInTheDocument() // valid network prefix fireEvent.change(screen.getByTestId(fieldTestId), { target: { value: rawAddressWithValidPrefix } }) // checksum address with the valid network prefix expect((screen.getByTestId(fieldTestId) as HTMLInputElement).value).toBe(checksumAddressWithPrefix) // no prefix error is showed expect(screen.queryByText(invalidNetworkPrefixErrorMessage)).not.toBeInTheDocument() }) }) }) }) // this is needed because AddressInput Component is implemented to be with a react final form function FormTestComponent({ children, onSubmit }) { return ( <Form onSubmit={onSubmit}> {({ handleSubmit }) => ( <form onSubmit={handleSubmit}> {children} <input type="submit" data-testid="submit-test-form" /> </form> )} </Form> ) } function renderAddressInputWithinForm(onSubmit = jest.fn, customState = {}) { return render( <FormTestComponent onSubmit={onSubmit}> <AddressInput name={fieldName} fieldMutator={(x) => x} testId={fieldTestId} /> </FormTestComponent>, customState, ) }
the_stack
import * as assert from "assert"; class RegexParser { readonly currentns: string; readonly restr: string; pos: number; constructor(currentns: string, restr: string) { this.currentns = currentns; this.restr = restr; this.pos = 0; } private done(): boolean { return this.restr.length <= this.pos; } private isToken(tk: string): boolean { return this.restr[this.pos] === tk; } private token(): string { return this.restr[this.pos]; } private advance(dist?: number) { this.pos = this.pos + (dist !== undefined ? dist : 1); } private parseBaseComponent(): RegexComponent | string { let res: RegexComponent | string; if(this.isToken("(")) { this.advance(); res = this.parseComponent(); if(!this.isToken(")")) { return "Un-matched paren"; } this.advance(); } else if(this.isToken("[")) { this.advance(); const compliment = this.isToken("^") if(compliment) { this.advance(); } let range: {lb: number, ub: number}[] = []; while(!this.isToken("]")) { const lb = this.token(); this.advance(); if (!this.isToken("-")) { range.push({ lb: lb.codePointAt(0) as number, ub: lb.codePointAt(0) as number }); } else { this.advance(); const ub = this.token(); this.advance(); range.push({ lb: lb.codePointAt(0) as number, ub: ub.codePointAt(0) as number }); } } if(!this.isToken("]")) { return "Invalid range"; } this.advance(); return new RegexCharRange(compliment, range); } else if(this.isToken("$")) { this.advance(); if(!this.isToken("{")) { return "Invalid regex const"; } this.advance(); let fname = ""; while(!this.isToken("}")) { fname += this.token(); this.advance(); } if(!this.isToken("}")) { return "Invalid regex const"; } this.advance(); let ccpos = fname.indexOf("::"); let ns = ccpos === -1 ? this.currentns : fname.slice(0, ccpos); let ccname = ccpos === -1 ? fname : fname.slice(ccpos + 3); return new RegexConstClass(ns, ccname); } else { res = new RegexLiteral(this.token(), this.token(), this.token()); this.advance(); } return res; } private parseCharClassOrEscapeComponent(): RegexComponent | string { if(this.isToken(".")) { return new RegexDotCharClass(); } else if(this.isToken("\\")) { this.advance(); if(this.isToken("\\") || this.isToken("/") || this.isToken(".") || this.isToken("*") || this.isToken("+") || this.isToken("?") || this.isToken("|") || this.isToken("(") || this.isToken(")") || this.isToken("[") || this.isToken("]") || this.isToken("{") || this.isToken("}") || this.isToken("$")) { const cc = this.token(); this.advance(); return new RegexLiteral(`\\${cc}`, cc, cc); } else { const cc = this.token(); this.advance(); let rc = ""; if(cc == "n") { rc = "\n"; } else if(cc == "r") { rc = "\r"; } else { rc = "\t"; } return new RegexLiteral(`\\${cc}`, `\\${cc}`, rc); } } else { return this.parseBaseComponent(); } } private parseRepeatComponent(): RegexComponent | string { let rcc = this.parseCharClassOrEscapeComponent(); if(typeof(rcc) === "string") { return rcc; } while(this.isToken("*") || this.isToken("+") || this.isToken("?") || this.isToken("{")) { if(this.isToken("*")) { rcc = new RegexStarRepeat(rcc); this.advance(); } else if(this.isToken("+")) { rcc = new RegexPlusRepeat(rcc); this.advance(); } else if(this.isToken("?")) { rcc = new RegexOptional(rcc); this.advance(); } else { this.advance(); let nre = new RegExp(/[0-9]+/, "y"); nre.lastIndex = this.pos; const nmin = nre.exec(this.restr); if(nmin === null) { return "Invalid number"; } this.advance(nmin[0].length); const min = Number.parseInt(nmin[0]); let max = min; if (this.isToken(",")) { this.advance(); nre.lastIndex = this.pos; const nmax = nre.exec(this.restr); if (nmax === null) { return "Invalid number"; } this.advance(nmax[0].length); max = Number.parseInt(nmax[0]); } if(!this.isToken("}")) { return "Un-matched paren"; } this.advance(); rcc = new RegexRangeRepeat(rcc, min, max); } } return rcc; } private parseSequenceComponent(): RegexComponent | string { let sre: RegexComponent[] = []; while(!this.done() && !this.isToken("|") && !this.isToken(")")) { const rpe = this.parseRepeatComponent(); if(typeof(rpe) === "string") { return rpe; } if(sre.length === 0) { sre.push(rpe); } else { const lcc = sre[sre.length - 1]; if(lcc instanceof RegexLiteral && rpe instanceof RegexLiteral) { sre[sre.length - 1] = RegexLiteral.mergeLiterals(lcc, rpe); } else { sre.push(rpe); } } } if(sre.length === 0) { return "Malformed regex"; } if (sre.length === 1) { return sre[0]; } else { return new RegexSequence(sre); } } private parseAlternationComponent(): RegexComponent | string { const rpei = this.parseSequenceComponent(); if (typeof (rpei) === "string") { return rpei; } let are: RegexComponent[] = [rpei]; while (!this.done() && this.isToken("|")) { this.advance(); const rpe = this.parseSequenceComponent(); if (typeof (rpe) === "string") { return rpe; } are.push(rpe); } if(are.length === 1) { return are[0]; } else { return new RegexAlternation(are); } } parseComponent(): RegexComponent | string { return this.parseAlternationComponent(); } } class BSQRegex { readonly restr: string; readonly re: RegexComponent; constructor(restr: string, re: RegexComponent) { this.restr = restr; this.re = re; } compileToJS(): string { // //TODO: we actually have NFA semantics for our regex -- JS matching is a subset so we need to replace this!!! // return "^" + this.re.compileToJS() + "$"; } compileToPatternToSMT(ascii: boolean): string { return this.re.compilePatternToSMT(ascii); } static parse(currentns: string, rstr: string): BSQRegex | string { const reparser = new RegexParser(currentns, rstr.substr(1, rstr.length - 2)); const rep = reparser.parseComponent(); if(typeof(rep) === "string") { return rep; } else { return new BSQRegex(rstr, rep); } } jemit(): any { return { restr: this.restr, re: this.re.jemit() }; } static jparse(obj: any): BSQRegex { return new BSQRegex(obj.restr, RegexComponent.jparse(obj.re)); } } abstract class RegexComponent { useParens(): boolean { return false; } abstract jemit(): any; abstract compileToJS(): string; abstract compilePatternToSMT(ascii: boolean): string; static jparse(obj: any): RegexComponent { const tag = obj.tag; switch (tag) { case "Literal": return RegexLiteral.jparse(obj); case "CharRange": return RegexCharRange.jparse(obj); case "DotCharClass": return RegexDotCharClass.jparse(obj); case "ConstRegexClass": return RegexConstClass.jparse(obj); case "StarRepeat": return RegexStarRepeat.jparse(obj); case "PlusRepeat": return RegexPlusRepeat.jparse(obj); case "RangeRepeat": return RegexRangeRepeat.jparse(obj); case "Optional": return RegexOptional.jparse(obj); case "Alternation": return RegexAlternation.jparse(obj); default: return RegexSequence.jparse(obj); } } } class RegexLiteral extends RegexComponent { readonly restr: string; readonly escstr: string; readonly litstr: string; constructor(restr: string, escstr: string, litstr: string) { super(); this.restr = restr; this.escstr = escstr; this.litstr = litstr; } jemit(): any { return {tag: "Literal", restr: this.restr, escstr: this.escstr, litstr: this.litstr}; } static jparse(obj: any): RegexComponent { return new RegexLiteral(obj.restr, obj.escstr, obj.litstr); } static mergeLiterals(l1: RegexLiteral, l2: RegexLiteral): RegexLiteral { return new RegexLiteral(l1.restr + l2.restr, l1.escstr + l2.escstr, l1.litstr + l2.litstr); } compileToJS(): string { return this.restr; } compilePatternToSMT(ascii: boolean): string { assert(ascii); return `(str.to.re "${this.escstr}")`; } } class RegexCharRange extends RegexComponent { readonly compliment: boolean; readonly range: {lb: number, ub: number}[]; constructor(compliment: boolean, range: {lb: number, ub: number}[]) { super(); assert(range.length !== 0); this.compliment = compliment; this.range = range; } jemit(): any { return { tag: "CharRange", compliment: this.compliment, range: this.range }; } static jparse(obj: any): RegexComponent { return new RegexCharRange(obj.compliment, obj.range); } private static valToSStr(cc: number): string { assert(cc >= 9); if(cc === 9) { return "\\t"; } else if (cc === 10) { return "\\n"; } else if (cc === 13) { return "\\r"; } else { return String.fromCodePoint(cc); } } compileToJS(): string { // //TODO: probably need to do some escaping here as well // const rng = this.range.map((rr) => (rr.lb == rr.ub) ? RegexCharRange.valToSStr(rr.lb) : `${RegexCharRange.valToSStr(rr.lb)}-${RegexCharRange.valToSStr(rr.ub)}`); return `[${this.compliment ? "^" : ""}${rng.join("")}]`; } compilePatternToSMT(ascii: boolean): string { assert(ascii); assert(!this.compliment); // //TODO: probably need to do some escaping here as well // const rng = this.range.map((rr) => (rr.lb == rr.ub) ? `(str.to.re "${RegexCharRange.valToSStr(rr.lb)}")` : `(re.range "${RegexCharRange.valToSStr(rr.lb)}" "${RegexCharRange.valToSStr(rr.ub)}")`); if(rng.length === 1) { return rng[0]; } else { return `(re.union ${rng.join(" ")})`; } } } class RegexDotCharClass extends RegexComponent { constructor() { super(); } jemit(): any { return { tag: "DotCharClass" }; } static jparse(obj: any): RegexComponent { return new RegexDotCharClass(); } compileToJS(): string { return "."; } compilePatternToSMT(ascii: boolean): string { return "re.allchar"; } } class RegexConstClass extends RegexComponent { readonly ns: string; readonly ccname: string; constructor(ns: string, ccname: string) { super(); this.ns = ns; this.ccname = ccname; } jemit(): any { return { tag: "ConstRegexClass", ns: this.ns, ccname: this.ccname }; } static jparse(obj: any): RegexComponent { return new RegexConstClass(obj.ns, obj.ccname); } compileToJS(): string { assert(false, `Should be replaced by const ${this.ns}::${this.ccname}`); return `${this.ns}::${this.ccname}`; } compilePatternToSMT(ascii: boolean): string { assert(false, `Should be replaced by const ${this.ns}::${this.ccname}`); return `${this.ns}::${this.ccname}`; } } class RegexStarRepeat extends RegexComponent { readonly repeat: RegexComponent; constructor(repeat: RegexComponent) { super(); this.repeat = repeat; } jemit(): any { return { tag: "StarRepeat", repeat: this.repeat.jemit() }; } static jparse(obj: any): RegexComponent { return new RegexStarRepeat(RegexComponent.jparse(obj.repeat)); } compileToJS(): string { return this.repeat.useParens() ? `(${this.repeat.compileToJS()})*` : `${this.repeat.compileToJS()}*`; } compilePatternToSMT(ascii: boolean): string { return `(re.* ${this.repeat.compilePatternToSMT(ascii)})`; } } class RegexPlusRepeat extends RegexComponent { readonly repeat: RegexComponent; constructor(repeat: RegexComponent) { super(); this.repeat = repeat; } jemit(): any { return { tag: "PlusRepeat", repeat: this.repeat.jemit() }; } static jparse(obj: any): RegexComponent { return new RegexPlusRepeat(RegexComponent.jparse(obj.repeat)); } compileToJS(): string { return this.repeat.useParens() ? `(${this.repeat.compileToJS()})+` : `${this.repeat.compileToJS()}+`; } compilePatternToSMT(ascii: boolean): string { return `(re.+ ${this.repeat.compilePatternToSMT(ascii)})`; } } class RegexRangeRepeat extends RegexComponent { readonly repeat: RegexComponent; readonly min: number; readonly max: number; constructor(repeat: RegexComponent, min: number, max: number) { super(); this.repeat = repeat; this.min = min; this.max = max; } jemit(): any { return { tag: "RangeRepeat", repeat: this.repeat.jemit(), min: this.min, max: this.max }; } static jparse(obj: any): RegexComponent { return new RegexRangeRepeat(RegexComponent.jparse(obj.repeat), obj.min, obj.max); } compileToJS(): string { return this.repeat.useParens() ? `(${this.repeat.compileToJS()}){${this.min},${this.max}}` : `${this.repeat.compileToJS()}{${this.min},${this.max}}`; } compilePatternToSMT(ascii: boolean): string { return `(re.loop ${this.repeat.compilePatternToSMT(ascii)} ${this.min} ${this.max})`; } } class RegexOptional extends RegexComponent { readonly opt: RegexComponent; constructor(opt: RegexComponent) { super(); this.opt = opt; } jemit(): any { return { tag: "Optional", opt: this.opt.jemit() }; } static jparse(obj: any): RegexComponent { return new RegexOptional(RegexComponent.jparse(obj.repeat)); } compileToJS(): string { return this.opt.useParens() ? `(${this.opt.compileToJS()})?` : `${this.opt.compileToJS()}?`; } compilePatternToSMT(ascii: boolean): string { return `(re.opt ${this.opt.compilePatternToSMT(ascii)})`; } } class RegexAlternation extends RegexComponent { readonly opts: RegexComponent[]; constructor(opts: RegexComponent[]) { super(); this.opts = opts; } useParens(): boolean { return true; } jemit(): any { return { tag: "Alternation", opts: this.opts.map((opt) => opt.jemit()) }; } static jparse(obj: any): RegexComponent { return new RegexAlternation(obj.opts.map((opt: any) => RegexComponent.jparse(opt))); } compileToJS(): string { return this.opts.map((opt) => opt.compileToJS()).join("|"); } compilePatternToSMT(ascii: boolean): string { return `(re.union ${this.opts.map((opt) => opt.compilePatternToSMT(ascii)).join(" ")})`; } } class RegexSequence extends RegexComponent { readonly elems: RegexComponent[]; constructor(elems: RegexComponent[]) { super(); this.elems = elems; } useParens(): boolean { return true; } jemit(): any { return { tag: "Sequence", elems: this.elems.map((elem) => elem.jemit()) }; } static jparse(obj: any): RegexComponent { return new RegexSequence(obj.elems.map((elem: any) => RegexComponent.jparse(elem))); } compileToJS(): string { return this.elems.map((elem) => elem.compileToJS()).join(""); } compilePatternToSMT(ascii: boolean): string { return `(re.++ ${this.elems.map((elem) => elem.compilePatternToSMT(ascii)).join(" ")})`; } } export { BSQRegex, RegexComponent, RegexLiteral, RegexCharRange, RegexDotCharClass, RegexConstClass, RegexStarRepeat, RegexPlusRepeat, RegexRangeRepeat, RegexOptional, RegexAlternation, RegexSequence };
the_stack
const chai = require('chai'); const expect = chai.expect; import { AllocationRegister } from '../source/allocationregister'; import { Buffer } from '../source/buffer'; import { Context } from '../source/context'; import { UnifiedBuffer } from '../source/unifiedbuffer'; /* spellchecker: enable */ /* tslint:disable:max-classes-per-file no-unused-expression */ interface SubDataCall { dstOffset: number; data: ArrayBuffer; } class ContextMock { allocationRegister = new AllocationRegister(); } class BufferMock extends Buffer { _bytes = 0; subDataCalls: Array<SubDataCall>; dataCalled: boolean; constructor(context: ContextMock) { super(context as Context); this.subDataCalls = new Array<SubDataCall>(); this.dataCalled = false; } create(target: GLenum): WebGLBuffer | undefined { this._valid = true; return undefined; } data(data: ArrayBufferView | ArrayBuffer | GLsizeiptr, usage: GLenum, bind: boolean = true, unbind: boolean = true): void { this.dataCalled = true; this._bytes = typeof data === 'number' ? data : data.byteLength; } subData(dstByteOffset: GLintptr, srcData: ArrayBufferView | ArrayBuffer, srcOffset: GLuint = 0, length: GLuint = 0, bind: boolean = true, unbind: boolean = true): void { let data: ArrayBuffer; if (srcData instanceof ArrayBuffer) { data = srcData; } else { data = srcData.buffer.slice(srcData.byteOffset, srcData.byteOffset + srcData.byteLength); } this.subDataCalls.push({ dstOffset: dstByteOffset, data }); } get bytes(): number { return this._bytes; } } class UnifiedBufferMock extends UnifiedBuffer { _gpuBuffer: BufferMock; constructor(context: ContextMock, size: number, mergeThreshold = 0) { super(context as Context, size, 0, mergeThreshold); this._gpuBuffer = new BufferMock(context); } get cpuBuffer(): ArrayBuffer { return this._cpuBuffer; } } describe('UnifiedBuffer', () => { it('should create buffer on gpu lazily', () => { const context = new ContextMock(); const buffer = new UnifiedBufferMock(context, 32); buffer.initialize(0); expect(buffer._gpuBuffer.dataCalled).to.be.false; buffer.update(); expect(buffer._gpuBuffer.dataCalled).to.be.true; }); it('should work with different TypedArrays', () => { const buffer = createUsableUnifiedBuffer(32); buffer.subData(0, new Float32Array(8).fill(3456)); buffer.update(); expect(buffer._gpuBuffer.subDataCalls.length).to.be.equal(1); const expectedFloats = new Float32Array(8).fill(3456); expect(new Float32Array(buffer._gpuBuffer.subDataCalls[0].data)).to.be.eql(expectedFloats); buffer._gpuBuffer.subDataCalls.length = 0; buffer.subData(0, new Int32Array(8).fill(-2134)); buffer.update(); expect(buffer._gpuBuffer.subDataCalls.length).to.be.equal(1); const expectedInts = new Int32Array(8).fill(-2134); expect(new Int32Array(buffer._gpuBuffer.subDataCalls[0].data)).to.be.eql(expectedInts); }); it('should keep content on resize', () => { const context = new ContextMock(); const buffer = new UnifiedBufferMock(context, 32); buffer.subData(0, new Float32Array(8).fill(17)); buffer.size = 16; expect(buffer.size).to.be.equal(16); const expectedSmall = new Float32Array(4).fill(17); expect(new Float32Array(buffer.cpuBuffer)).to.be.eql(expectedSmall); buffer.size = 32; expect(buffer.size).to.be.equal(32); const expectedLarge = new Float32Array(8).fill(17); expectedLarge.fill(0, 4, 8); expect(new Float32Array(buffer.cpuBuffer)).to.be.eql(expectedLarge); }); }); describe('UnifiedBuffer subData', () => { it('should throw on data exceeding size', () => { const context = new ContextMock(); const buffer = new UnifiedBufferMock(context, 32); expect(() => buffer.subData(0, new Uint8Array(64))).to.throw; expect(() => buffer.subData(8, new Uint8Array(32))).to.throw; }); it('should work with subarrays', () => { const context = new ContextMock(); const buffer = new UnifiedBufferMock(context, 32); const tooBigArray = new ArrayBuffer(64); const tooBigArrayView = new Uint8Array(tooBigArray); tooBigArrayView.fill(13, 0, 16); tooBigArrayView.fill(17, 16, 32); const subArray = tooBigArrayView.subarray(8, 24); expect(() => buffer.subData(0, subArray)).to.not.throw; buffer.subData(0, subArray); const expected = new Uint8Array(32); expected.fill(13, 0, 8); expected.fill(17, 8, 16); expect(new Uint8Array(buffer.cpuBuffer)).to.be.eql(expected); }); }); describe('UnifiedBuffer update', () => { it('should not make unnecessary subData calls', () => { const context = new ContextMock(); const buffer = new UnifiedBufferMock(context, 32); buffer.initialize(0); buffer.subData(0, new Uint8Array(32)); buffer.update(); expect(buffer._gpuBuffer.subDataCalls.length).to.be.equal(0); expect(buffer._gpuBuffer.dataCalled).to.be.true; buffer._gpuBuffer.dataCalled = false; buffer.subData(0, new Uint8Array(32)); buffer.update(); expect(buffer._gpuBuffer.subDataCalls.length).to.be.equal(1); expect(buffer._gpuBuffer.dataCalled).to.be.false; buffer._gpuBuffer.subDataCalls.length = 0; buffer.size = 16; buffer.subData(0, new Uint8Array(16)); buffer.update(); expect(buffer._gpuBuffer.subDataCalls.length).to.be.equal(0); expect(buffer._gpuBuffer.dataCalled).to.be.true; }); it('should discard old updates', () => { const buffer = createUsableUnifiedBuffer(32); buffer.subData(8, new Uint8Array(16).fill(1)); buffer.subData(8, new Uint8Array(16).fill(2)); buffer.update(); expect(buffer._gpuBuffer.subDataCalls.length).to.be.equal(1); }); it('should merge overlapping updates 1', () => { const buffer = createUsableUnifiedBuffer(32); /** * _______ * |______| old * ________ * |_______| new */ buffer.subData(0, new Uint8Array(16).fill(1)); buffer.subData(8, new Uint8Array(16).fill(2)); buffer.update(); const expectedData = new Uint8Array(24).fill(1, 0, 16).fill(2, 8, 24); const expectedSubDataCalls = new Array<SubDataCall>({ dstOffset: 0, data: expectedData, }); expect(mapSubDataCalls(buffer._gpuBuffer.subDataCalls)).to.be.eql(expectedSubDataCalls); }); it('should merge overlapping updates 2', () => { const buffer = createUsableUnifiedBuffer(32); /** * _______ * |______| old * ________ * |_______| new */ buffer.subData(8, new Uint8Array(16).fill(1)); buffer.subData(0, new Uint8Array(16).fill(2)); buffer.update(); const expectedData = new Uint8Array(24).fill(1, 8, 24).fill(2, 0, 16); const expectedSubDataCalls = new Array<SubDataCall>({ dstOffset: 0, data: expectedData, }); expect(mapSubDataCalls(buffer._gpuBuffer.subDataCalls)).to.be.eql(expectedSubDataCalls); }); it('should merge overlapping updates 3', () => { const buffer = createUsableUnifiedBuffer(32); /** * ______________ * |_____________| old * ________ * |_______| new */ buffer.subData(0, new Uint8Array(32).fill(1)); buffer.subData(8, new Uint8Array(16).fill(2)); buffer.update(); const expectedData = new Uint8Array(32).fill(1, 0, 32).fill(2, 8, 24); const expectedSubDataCalls = new Array<SubDataCall>({ dstOffset: 0, data: expectedData, }); expect(mapSubDataCalls(buffer._gpuBuffer.subDataCalls)).to.be.eql(expectedSubDataCalls); }); it('should merge overlapping updates 4', () => { const buffer = createUsableUnifiedBuffer(32); /** * _______ * |______| old * ______________ * |_____________| new */ buffer.subData(8, new Uint8Array(16).fill(1)); buffer.subData(0, new Uint8Array(32).fill(2)); buffer.update(); const expectedData = new Uint8Array(32).fill(2, 0, 32); const expectedSubDataCalls = new Array<SubDataCall>({ dstOffset: 0, data: expectedData, }); expect(mapSubDataCalls(buffer._gpuBuffer.subDataCalls)).to.be.eql(expectedSubDataCalls); }); it('should not merge separate updates', () => { const buffer = createUsableUnifiedBuffer(32); /** * _______ * |______| old * _______ * |______| new */ buffer.subData(0, new Uint8Array(8).fill(1)); buffer.subData(24, new Uint8Array(8).fill(2)); buffer.update(); const expectedSubDataCalls = new Array<SubDataCall>( { dstOffset: 0, data: new Uint8Array(8).fill(1) }, { dstOffset: 24, data: new Uint8Array(8).fill(2) }); expect(mapSubDataCalls(buffer._gpuBuffer.subDataCalls)).to.be.eql(expectedSubDataCalls); }); it('should respect the merge threshold on non-overlapping ranges 1', () => { const buffer = createUsableUnifiedBuffer(32, -1); buffer.subData(0, new Uint8Array(8).fill(1)); buffer.subData(24, new Uint8Array(8).fill(2)); buffer.update(); const expectedData = new Uint8Array(32).fill(1, 0, 8).fill(2, 24, 32); const expectedSubDataCalls = new Array<SubDataCall>( { dstOffset: 0, data: expectedData }); expect(mapSubDataCalls(buffer._gpuBuffer.subDataCalls)).to.be.eql(expectedSubDataCalls); }); it('should respect the merge threshold on non-overlapping ranges 2', () => { const buffer = createUsableUnifiedBuffer(32, 4); buffer.subData(0, new Uint8Array(8).fill(1)); buffer.subData(10, new Uint8Array(8).fill(2)); buffer.subData(24, new Uint8Array(8).fill(3)); buffer.update(); const expectedData = new Uint8Array(18).fill(1, 0, 8).fill(2, 10, 18); const expectedSubDataCalls = new Array<SubDataCall>( { dstOffset: 0, data: expectedData }, { dstOffset: 24, data: new Uint8Array(8).fill(3) }); expect(mapSubDataCalls(buffer._gpuBuffer.subDataCalls)).to.be.eql(expectedSubDataCalls); }); it('should respect the merge threshold on overlapping ranges', () => { const buffer = createUsableUnifiedBuffer(32, 4); buffer.subData(8, new Uint8Array(8).fill(1)); buffer.subData(12, new Uint8Array(8).fill(2)); buffer.update(); const expectedData = new Uint8Array(12).fill(1, 0, 4).fill(2, 4, 12); const expectedSubDataCalls = new Array<SubDataCall>( { dstOffset: 8, data: expectedData }); expect(mapSubDataCalls(buffer._gpuBuffer.subDataCalls)).to.be.eql(expectedSubDataCalls); }); }); describe('UnifiedBuffer mergeSubDataRanges', () => { it('should merge all ranges within threshold', () => { const buffer = createUsableUnifiedBuffer(32, 0); buffer.subData(0, new Uint8Array(8).fill(1)); buffer.subData(16, new Uint8Array(8).fill(2)); buffer.subData(30, new Uint8Array(2).fill(3)); buffer.mergeThreshold = 8; buffer.mergeSubDataRanges(); buffer.update(); expect(buffer._gpuBuffer.subDataCalls.length).to.be.equal(2); }); it('should merge all ranges if threshold == -1', () => { const buffer = createUsableUnifiedBuffer(32, 0); buffer.subData(0, new Uint8Array(8).fill(1)); buffer.subData(16, new Uint8Array(8).fill(2)); buffer.subData(30, new Uint8Array(2).fill(3)); buffer.mergeThreshold = -1; buffer.mergeSubDataRanges(); buffer.update(); expect(buffer._gpuBuffer.subDataCalls.length).to.be.equal(1); }); }); function createUsableUnifiedBuffer(size: number, mergeThreshold = 0): UnifiedBufferMock { const context = new ContextMock(); const buffer = new UnifiedBufferMock(context as Context, 32, mergeThreshold); buffer.initialize(0); buffer.update(); return buffer; } function mapSubDataCalls(subDataCalls: Array<SubDataCall>): Array<SubDataCall> { return subDataCalls.map((subDataCall: SubDataCall) => { return { dstOffset: subDataCall.dstOffset, data: new Uint8Array(subDataCall.data), }; }); }
the_stack
import { Component, QueryList } from '@angular/core'; import { ViewChildren, ViewChild } from '@angular/core'; import { OnInit } from '@angular/core'; import { MdInputDirective } from '@angular/material'; import { NgForm } from '@angular/forms'; import { FormControl } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { AutoComplete } from 'primeng/primeng'; import { Observable } from 'rxjs'; import { SlimLoadingBarService } from 'ng2-slim-loading-bar'; import * as moment from 'moment'; import * as humanizeDuration from 'humanize-duration'; import { AppState } from '../app.service'; import { Appointment } from '../api/model/appointment'; import { AppointmentService } from '../api/api/appointment.service'; import { Examination } from '../api/model/examination'; import { ExaminationService } from '../api/api/examination.service'; import { Patient } from '../api/model/patient'; import { PatientService } from '../api/api/patient.service'; import { Room } from '../api/model/room'; import { RoomService } from '../api/api/room.service'; import { NotificationService } from '../api/api/notification.service'; import { NotificationBuilder } from './notificationBuilder'; @Component({ templateUrl: './detail.component.html', styleUrls: [ './detail.component.scss' ] }) export class AppointmentDetailComponent implements OnInit { public editing: boolean = false; public rooms: Room[] = undefined; // Patient autocomplete field public patientControl = new FormControl(); // Duration input public durationControl = new FormControl(); // Examinations autocomplete/tag field private examinations: Examination[] = []; private patients: Patient[] = []; private filteredPatients: Observable<Patient[]>; private filteredExaminations: Examination[] = undefined; private proposedTimeSlots: any[] = []; private localeHumanizer: any; private isTwelveHours: boolean; @ViewChildren('examMultiChooser') private examsMultiInput: QueryList<AutoComplete>; @ViewChild('duration') private durationInput: MdInputDirective; private model: AppointmentViewModel = { id: undefined, title: undefined, description: undefined, date: undefined, time: undefined, duration: undefined, room: undefined, patient: undefined, examinations: undefined, reminders: undefined }; constructor( private _state: AppState, private route: ActivatedRoute, private router: Router, private slimLoadingBarService: SlimLoadingBarService, private appointmentService: AppointmentService, private examinationService: ExaminationService, private roomService: RoomService, private patientService: PatientService, private notificationService: NotificationService) {} public ngOnInit(): void { const param: string = this.route.snapshot.params['id']; // Mouseflow integration if ((window as any)._mfq) { (window as any)._mfq.push(['newPageView', '/appointment/' + param]); } // This is a sub-page this._state.isSubPage.next(true); this._state.title.next(); this._state.actions.next(); this._state.primaryAction.next(); // Set up localized humanizer for durations this.localeHumanizer = humanizeDuration.humanizer({ language: localStorage.getItem('locale').startsWith('de') ? 'de' : 'en' }); // Set up localization this.isTwelveHours = this.isCurrentLocaleUsingTwelveHours(); // Set up rooms control (retrieve all rooms) this.getAllRooms(); // Create new appointment if (param === 'add') { this.editing = true; // View or edit existing appointment } else if (!isNaN(Number(param))) { this.editing = false; console.log('displaying appointment with id: %d', Number(param)); this.getAppointmentById(Number(param)); } // Set up patient autocomplete control this.patientService.patientFind().subscribe( (patients) => { this.patients = patients; this.filteredPatients = this.patientControl.valueChanges .startWith(null) .map((val) => this.filterPatients(val)); }, (err) => console.log(err) ); // Set up examinations control this.examinationService.examinationFind().subscribe( (examinations) => this.examinations = examinations, (err) => console.log(err) ); // Set up duration control this.durationControl.valueChanges .debounceTime(500) .distinctUntilChanged() .map((val) => this.sanitizeDuration(val)) .subscribe( (x) => { this.model.duration = x; this.onFormChange(); }, (err) => console.log(err) ); } public onSubmit(): void { this.slimLoadingBarService.start(); const newAppointment: Appointment = { title: this.model.title, description: this.model.description, modified: new Date(), created: new Date(), modifiedBy: 0, createdBy: 0, patientId: this.model.patient.id, roomId: this.model.room.id }; const examinations: Examination[] = this.model.examinations; const startDate = moment(this.model.date, 'l'); const startTime = moment(this.model.time, 'LT'); const start = startDate.clone(); start.hour(startTime.hour()); start.minute(startTime.minute()); const end: moment.Moment = start.clone(); end.add(moment.duration('PT' + this.model.duration)); newAppointment.start = start.toDate(); newAppointment.end = end.toDate(); // Add... if (!this.model.id) { this.appointmentService .appointmentCreate(newAppointment) .subscribe( (x) => { // Link examinations if (examinations && examinations.length > 0) { for (const examination of examinations) { this.linkExaminationWithAppointment(x, examination); } } // Create reminders if (this.model.reminders) { this.notificationService.notificationCreate( NotificationBuilder.getNotification( x, this.model.emailReminder ? this.model.patient.email : undefined, this.model.smsReminder ? this.model.patient.phone : undefined )) .subscribe( null, (err) => console.log(err), () => console.log('Created notification.') ); } }, (e) => { console.log('onError: %o', e); }, () => { this.slimLoadingBarService.complete(); console.log('Completed insert.'); // Navigate back to schedule view this.router.navigateByUrl('appointment'); } ); // ...or update } else { this.appointmentService .appointmentPrototypePatchAttributes(this.model.id.toString(), newAppointment) .subscribe( (x) => { // Before linking examinations, we actually have to get rid of existing ones this.appointmentService.appointmentPrototypeDeleteExaminations(String(x.id)) .subscribe( null, null, () => { for (const examination of examinations) { this.linkExaminationWithAppointment(x, examination); } } ); // TODO Reminders currently being ignored on update }, (e) => { console.log('onError: %o', e); }, () => { this.slimLoadingBarService.complete(); console.log('Completed update.'); // Navigate back to schedule view this.router.navigateByUrl('appointment'); } ); } } /** * Used to display patients in the suggestions drop down. */ public patientDisplayFn(patient: Patient): string { return patient ? `${patient.givenName} ${patient.surname} ` + `(${moment(patient.dateOfBirth).format('l')})` : null; } /** * Used to display room names in the frontend. */ public getRoomNameById(roomId: number): string { return this.getRoomById(roomId).name; } private getRoomById(roomId: number): Room { return this.rooms.find( (room) => { return room.id === roomId; } ); } private linkExaminationWithAppointment(appointment: Appointment, examination: Examination) { this.appointmentService.appointmentPrototypeLinkExaminations( appointment.id.toString(), examination.id.toString()) .subscribe( (x) => console.log( `Linked examination ${x.examinationId} with appointment ${x.appointmentId}` ), (e) => console.log(e), () => console.log('Completed linking examination with appointment.') ); } private getAllRooms(): void { this.roomService .roomFind() .subscribe( (x) => this.rooms = x, (e) => console.log(e), () => console.log('Get all rooms complete.') ); } private filterPatients(val: string): Patient[] { return val ? this.patients.filter( (patient) => new RegExp(val, 'gi').test(`${patient.surname} ${patient.givenName}`) ) : this.patients; } private findExaminations(event) { this.examinationService .examinationFind(`{"where": {"name": {"regexp": "${event.query}/i"}}}`) .subscribe( (x) => this.filteredExaminations = x, (e) => console.log(e), () => console.log('Completed querying for examinations.') ); } /** * Queries the appointment service for a possible time slot for the given * duration and room, from the given start date onwards. * * @param examinationId Will be ignored. */ private findTime( duration?: string, examinationId?: number, roomId?: number, startDate?: moment.Moment ) { console.log('Querying for the next free time slot.'); this.appointmentService .appointmentFindTime( duration ? 'PT' + duration : 'PT40M', // TODO move to server and replace by config-default examinationId, roomId, startDate ? startDate.toDate() : undefined) .subscribe( (x) => { this.proposedTimeSlots.push(x); this.proposedTimeSlots.sort(this.compareSuggestedTimeSlots); }, (e) => console.log(e), () => console.log('Completed querying for the next free time slot.') ); } /** * Helper method used to sort the suggested time slots array after inserting * new elements. */ private compareSuggestedTimeSlots(slotA, slotB): number { if (!slotA.scheduledTasks.NewAppointment.schedule[0].start || !slotB.scheduledTasks.NewAppointment.schedule[0].start) { return 1; } const a = moment(slotA.scheduledTasks.NewAppointment.schedule[0].start); const b = moment(slotB.scheduledTasks.NewAppointment.schedule[0].start); if (a.isAfter(b)) { return 1; } if (a.isBefore(b)) { return -1; } return 0; } /** * Will be called everytime the form changes, and query the backend for new * time slot suggestions. */ private onFormChange() { // When editing an existing appointment, don't display suggestions if (this.model.id) { return; } // Every time the form changes, use latest information to find a suitable date if (this.model.duration) { // Check if duration is valid const duration = moment.duration('PT' + this.model.duration); if (moment.isDuration(duration) && duration.asMinutes() > 1) { this.proposedTimeSlots = []; // Query for time slots from now on this.findTime( this.model.duration, this.model.examinations && this.model.examinations.length > 0 ? this.model.examinations[0].id : undefined, this.model.room ? this.model.room.id : undefined, moment() ); // The next day on this.findTime( this.model.duration, this.model.examinations && this.model.examinations.length > 0 ? this.model.examinations[0].id : undefined, this.model.room ? this.model.room.id : undefined, moment().add(1, 'day') ); // From next week on this.findTime( this.model.duration, this.model.examinations && this.model.examinations.length > 0 ? this.model.examinations[0].id : undefined, this.model.room ? this.model.room.id : undefined, moment().add(1, 'week') ); // From one month on this.findTime( this.model.duration, this.model.examinations && this.model.examinations.length > 0 ? this.model.examinations[0].id : undefined, this.model.room ? this.model.room.id : undefined, moment().add(1, 'month') ); } } } private getAppointmentById(id: number) { this.appointmentService.appointmentFindById(id.toString()) .subscribe( (x) => { const startDate = moment(x.start); const endDate = moment(x.end); const duration = moment.duration(endDate.diff(startDate)); this.model.id = x.id; this.model.date = startDate.format('l'); this.model.time = startDate.format('LT'); this.model.duration = duration.toJSON().substring(2); this.model.title = x.title; this.model.description = x.description; if (x.patientId) { this.patientService.patientFindById(x.patientId.toString()) .subscribe( (y) => this.model.patient = y, (e) => console.log(e), () => console.log('Completed querying for patient by id') ); } this.model.room = this.getRoomById(x.roomId); this.appointmentService.appointmentPrototypeGetExaminations(x.id.toString()) .subscribe( (z) => this.model.examinations = z, (e) => console.log(e), () => console.log('Completed querying for examinations by appointment id') ); }, (e) => console.log(e), () => console.log('Completed querying for appointment data') ); } /** * Triggered on duration input changes. Seeks to sanitize the entered value. */ private sanitizeDuration(val: string) { if (val) { // Strip any whitespaces from anywhere val = val.replace(/\s/g, ''); // Check different types of input if (/^[0-9]$/.test(val)) { val = val + 'H'; } else if (/^[0-9]{2}$/.test(val)) { val = val + 'M'; } else { val = val.toUpperCase(); } // this.onFormChange(); // TODO } return val; } private applySuggestion(timeSlot: any) { if (timeSlot) { console.log(timeSlot); const startDate = moment(timeSlot.start); this.model.duration = `${moment.duration(timeSlot.duration, 'minutes').toJSON().substring(2)}`; this.model.date = startDate.format('l'); this.model.time = startDate.format('LT'); this.model.room = this.getRoomById(timeSlot.resources[0]); // Clear suggestions this.proposedTimeSlots = []; } } private handleEditClick() { this.editing = true; } private formatDuration(durationString: string): string { return this.localeHumanizer(moment.duration('PT' + durationString).asMilliseconds()); } private isCurrentLocaleUsingTwelveHours(): boolean { return moment().format('LT').endsWith('M'); } } interface AppointmentViewModel { id: number; title: string; description: string; date: string; time: string; duration: string; room: Room; patient: Patient; examinations: Examination[]; reminders: boolean; smsReminder?: boolean; emailReminder?: boolean; }
the_stack
import * as fs from "fs"; import * as path from "path"; import {Option, program} from "commander"; import { CassetteFile, CassetteSpeed, CmdLoadModuleHeaderChunk, CmdProgram, CmdProgramBuilder, CmdTransferAddressChunk, decodeBasicProgram, decodeSystemProgram, decodeTrs80CassetteFile, decodeTrs80File, decodeTrsdos, Density, encodeCmdProgram, encodeSystemProgram, getTrs80FileExtension, HexdumpGenerator, isFloppy, numberToSide, ProgramAnnotation, RawBinaryFile, Side, SystemProgram, SystemProgramBuilder, TrackGeometry, TRS80_SCREEN_BEGIN, Trs80File, Trsdos, TrsdosDirEntry, trsdosProtectionLevelToString } from "trs80-base"; import {concatByteArrays, withCommas} from "teamten-ts-utils"; import { binaryAsCasFile, BitType, casAsAudio, concatAudio, Decoder, DEFAULT_SAMPLE_RATE, Program, readWavFile, Tape, writeWavFile } from "trs80-cassette"; import {version} from "./version.js"; import {addModel3RomEntryPoints, disasmForTrs80, disasmForTrs80Program} from "trs80-disasm"; import {Disasm, instructionsToText} from "z80-disasm"; import chalk from "chalk"; import { BasicLevel, basicLevelFromString, CassettePlayer, CGChip, Config, Keyboard, ModelType, modelTypeFromString, SilentSoundPlayer, Trs80, Trs80Screen } from "trs80-emulator"; import http from "http"; import * as url from "url"; import * as ws from "ws"; import {Asm} from "z80-asm"; import {toHex, toHexWord} from "z80-base"; const HELP_TEXT = ` See this page for full documentation: https://github.com/lkesteloot/trs80/blob/master/packages/trs80-tool/README.md ` /** * Set the chalk color level based on its name. See the --color option. * @param levelName */ function setColorLevel(levelName: string): void { levelName = levelName.toLowerCase(); switch (levelName) { case "auto": default: // Don't touch the level, let chalk set it. break; case "off": chalk.level = 0; break; case "16": chalk.level = 1; break; case "256": chalk.level = 2; break; case "16m": chalk.level = 3; break; } } /** * Return the singular or plural version of a string depending on the count. */ function pluralize(count: number, singular: string, plural?: string): string { return count === 1 ? singular : plural ?? (singular + "s"); } /** * Return the count and the singular or plural version of a string depending on the count. */ function pluralizeWithCount(count: number, singular: string, plural?: string): string { return `${withCommas(count)} ${pluralize(count, singular, plural)}`; } /** * Return the input pathname with the extension replaced. * @param pathname input pathname * @param extension extension with period. */ function replaceExtension(pathname: string, extension: string): string { const { dir, name } = path.parse(pathname); return path.join(dir, name + extension); } /** * Super class for files that are nested in another file, such as a floppy or cassette. */ abstract class ArchiveFile { public readonly filename: string; public readonly date: Date | undefined; protected constructor(filename: string, date: Date | undefined) { this.filename = filename; this.date = date; } public abstract getDirString(): string; public abstract getBinary(): Uint8Array; } /** * Nested file that came from a cassette file. */ class WavFile extends ArchiveFile { public readonly program: Program; constructor(program: Program) { super(WavFile.getFilename(program), undefined); this.program = program; } private static getFilename(program: Program): string { let extension = ".BIN"; if (program.isEdtasmProgram()) { extension = ".ASM"; } else if (program.isBasicProgram()) { extension = ".BAS"; } else if (decodeSystemProgram(program.binary) !== undefined) { extension = ".3BN"; } return program.getPseudoFilename() + extension; } public getDirString(): string { return this.filename.padEnd(12) + " " + withCommas(this.program.binary.length).padStart(8) + " " + this.program.baud + " baud"; } public getBinary(): Uint8Array { return this.program.binary; } } /** * Nested file that came from a CAS file. */ class CasFile extends ArchiveFile { public readonly cassetteFile: CassetteFile; constructor(filename: string, cassetteFile: CassetteFile) { super(filename, undefined); this.cassetteFile = cassetteFile; } getBinary(): Uint8Array { return this.cassetteFile.file.binary; } getDirString(): string { return this.filename.padEnd(14) + " " + withCommas(this.cassetteFile.file.binary.length).padStart(8) + " " + (this.cassetteFile.speed === CassetteSpeed.HIGH_SPEED ? "1500" : "500") + " baud"; } } /** * Nested file that came from a TRSDOS floppy. */ class TrsdosFile extends ArchiveFile { public readonly trsdos: Trsdos; public readonly file: TrsdosDirEntry; constructor(trsdos: Trsdos, file: TrsdosDirEntry) { super(file.getFilename("."), file.getDate()); this.trsdos = trsdos; this.file = file; } public getDirString(): string { return this.file.getFilename(".").padEnd(12) + " " + withCommas(this.file.getSize()).padStart(8) + " " + this.file.getFullDateString() + " " + trsdosProtectionLevelToString(this.file.getProtectionLevel(), this.trsdos.version); } public getBinary(): Uint8Array { return this.trsdos.readFile(this.file); } } /** * List of nested files in an archive (floppy or cassette). * TODO: I think we can get rid of this and use an array of InputFile objects instead. */ class Archive { public readonly error: string | undefined; public readonly files: ArchiveFile[] = []; public readonly tape: Tape | undefined; constructor(filename: string) { // Read the file. let buffer; try { buffer = fs.readFileSync(filename); } catch (e) { this.error = "Can't open \"" + filename + "\": " + e.message; return; } if (filename.toLowerCase().endsWith(".wav")) { // Decode the cassette. const wavFile = readWavFile(buffer.buffer); this.tape = new Tape(filename, wavFile); const decoder = new Decoder(this.tape); decoder.decode(); for (const program of this.tape.programs) { this.files.push(new WavFile(program)); } } else { // Decode the floppy or cassette. const file = decodeTrs80File(buffer, filename); if (isFloppy(file)) { const trsdos = decodeTrsdos(file); if (trsdos !== undefined) { for (const dirEntry of trsdos.dirEntries) { this.files.push(new TrsdosFile(trsdos, dirEntry)); } } else { this.error = "Operating system of floppy is unrecognized."; } } else if (file.className === "Cassette") { let counter = 1; const name = path.parse(filename).name; for (const cassetteFile of file.files) { const cassetteFilename = name + "-T" + counter + getTrs80FileExtension(cassetteFile.file); this.files.push(new CasFile(cassetteFilename, cassetteFile)); counter += 1; } } else { this.error = "This file type (" + file.className + ") does not have nested files."; } } } /** * Get the file for the given filename, which should have a dot separator for the extension. */ public getFileByFilename(filename: string): ArchiveFile | undefined { filename = filename.toUpperCase(); for (const file of this.files) { if (file.filename === filename) { return file; } } return undefined; } } /** * Information about each input file. */ class InputFile { public readonly filename: string; public readonly trs80File: Trs80File; public readonly baud: number | undefined; public readonly date: Date | undefined; constructor(filename: string, trs80File: Trs80File, baud?: number, date?: Date) { this.filename = filename; this.trs80File = trs80File; this.baud = baud; this.date = date; } /** * Return a new InputFile but with the file replaced by the parameter. */ public withFile(trs80File: Trs80File): InputFile { return new InputFile(this.filename, trs80File, this.baud, this.date); } } /** * Print one-line string description of the input file, and more if verbose. */ function printInfoForFile(filename: string, verbose: boolean): void { const {base, ext} = path.parse(filename); let description: string; const verboseLines: string[] = []; let buffer; try { buffer = fs.readFileSync(filename); } catch (e) { console.log(filename + ": Can't open file: " + e.message); return; } if (ext.toLowerCase() == ".wav") { // Parse a cassette WAV file. const wavFile = readWavFile(buffer.buffer); const tape = new Tape(base, wavFile); const decoder = new Decoder(tape); decoder.decode(); description = "Audio file with " + pluralizeWithCount(tape.programs.length, "file"); } else { try { const trs80File = decodeTrs80File(buffer, filename); if (trs80File.error !== undefined) { description = trs80File.error; } else { description = trs80File.getDescription(); const GENERATE_BITCELLS_JS = false; if (GENERATE_BITCELLS_JS && trs80File.className === "ScpFloppyDisk") { const bitcells = trs80File.tracks[1].revs[0].bitcells; const parts: string[] = []; parts.push("const bitcells = [\n"); for (const bitcell of bitcells) { parts.push(" " + bitcell + ",\n"); } parts.push("];\n"); fs.writeFileSync("bitcells/bitcells.js", parts.join("")); } if (isFloppy(trs80File)) { const trsdos = decodeTrsdos(trs80File); if (trsdos !== undefined) { description += ", " + trsdos.getOperatingSystemName() + " " + trsdos.getVersion() + " with " + pluralizeWithCount(trsdos.dirEntries.length, "file"); } if (verbose) { function getTrackGeometryInfo(trackGeometry: TrackGeometry): string { return [`sectors ${trackGeometry.firstSector} to ${trackGeometry.lastSector}`, `sides ${trackGeometry.firstSide} to ${trackGeometry.lastSide}`, `${trackGeometry.density === Density.SINGLE ? "single" : "double"} density`, `${trackGeometry.sectorSize} bytes per sector`].join(", "); } const geometry = trs80File.getGeometry(); const firstTrack = geometry.firstTrack; const lastTrack = geometry.lastTrack; if (geometry.hasHomogenousGeometry()) { verboseLines.push(`Tracks ${firstTrack.trackNumber} to ${lastTrack.trackNumber}, ` + getTrackGeometryInfo(firstTrack)); } else { verboseLines.push( `Tracks ${firstTrack.trackNumber} to ${lastTrack.trackNumber}`, `On track ${firstTrack.trackNumber}, ` + getTrackGeometryInfo(firstTrack), `On remaining tracks, ` + getTrackGeometryInfo(lastTrack)); } if (trsdos !== undefined) { if (trsdos.gatInfo.name !== "") { verboseLines.push("Floppy name: " + trsdos.gatInfo.name); } if (trsdos.gatInfo.date !== "") { verboseLines.push("Floppy date: " + trsdos.gatInfo.date); } if (trsdos.gatInfo.autoCommand !== "") { verboseLines.push("Auto command: " + trsdos.gatInfo.autoCommand); } } } } } } catch (e: any) { if ("message" in e) { description = "Error (" + e.message + ")"; } else { description = "Unknown error during decoding"; } } } console.log(filename + ": " + description); for (const line of verboseLines) { console.log(" " + line); } } /** * Handle the "dir" command. */ function dir(infile: string): void { const archive = new Archive(infile); if (archive.error !== undefined) { console.log(archive.error); } else { if (archive.files.length === 0) { console.log("No files"); } else { for (const file of archive.files) { console.log(file.getDirString()); } } } } /** * Handle the "info" command. */ function info(infiles: string[], verbose: boolean): void { for (const infile of infiles) { printInfoForFile(infile, verbose); } } /** * Handle the "extract" command. */ function extract(infile: string, outfile: string): void { const archive = new Archive(infile); if (archive.error !== undefined) { console.log(archive.error); process.exit(1); } else { // See if outfile is an existing directory. if (fs.existsSync(outfile) && fs.statSync(outfile).isDirectory()) { // Extract all files to this directory. for (const file of archive.files) { const binary = file.getBinary(); const outPathname = path.join(outfile, file.filename); fs.writeFileSync(outPathname, binary); if (file.date !== undefined) { fs.utimesSync(outPathname, file.date, file.date); } console.log("Extracted " + file.filename + " to " + outPathname); } } else { // Break apart outfile. const { base, ext } = path.parse(outfile); // See if it's a JSON file. if (ext.toLowerCase() === ".json") { // Output metadata to JSON file. const fullData: any = { programs: [], version: 1, }; if (archive.tape !== undefined) { fullData.sampleRate = archive.tape.sampleRate; } for (let i = 0; i < archive.files.length; i++) { const file = archive.files[i]; const programData: any = { name: file.filename, }; fullData.programs.push(programData); if (file instanceof WavFile) { const program = file.program; programData.trackNumber = program.trackNumber; programData.copyNumber = program.copyNumber; programData.startFrame = program.startFrame; programData.endFrame = program.endFrame; programData.speed = program.baud; programData.length = program.binary.length; // Decode various formats. programData.type = "unknown"; // Analyze system program. const fileBinary = file.getBinary(); const systemProgram = decodeSystemProgram(fileBinary); if (systemProgram !== undefined) { programData.type = "systemProgram"; programData.filename = systemProgram.filename; programData.chunkCount = systemProgram.chunks.length; // Check for checksum errors. let checksumErrors = 0; for (const chunk of systemProgram.chunks) { if (!chunk.isChecksumValid()) { checksumErrors += 1; } } programData.checksumErrorCount = checksumErrors; } // Label Basic program. const basicProgram = decodeBasicProgram(fileBinary); if (basicProgram !== undefined) { programData.type = "basic"; } // Warn about bit errors. programData.errorCount = program.countBitErrors(); programData.errors = []; for (const bitData of program.bitData) { if (bitData.bitType === BitType.BAD) { programData.errors.push(Math.round((bitData.startFrame + bitData.endFrame) / 2)); } } // See if it's a duplicate. let isDuplicate = false; for (let j = 0; j < i; j++) { const otherProgram = (archive.files[j] as WavFile).program; if (program.sameBinaryAs(otherProgram)) { isDuplicate = true; break; } } programData.isDuplicate = isDuplicate; } if (file instanceof TrsdosFile) { programData.date = file.file.getFullDateString(); programData.timestamp = file.file.getDate().getTime(); programData.protectionLevel = trsdosProtectionLevelToString(file.file.getProtectionLevel(), file.trsdos.version); programData.size = file.file.getSize(); programData.isSystemFile = file.file.isSystemFile(); programData.isExtendedEntry = file.file.isExtendedEntry(); programData.isHidden = file.file.isHidden(); programData.isActive = file.file.isActive(); } } fs.writeFileSync(outfile, JSON.stringify(fullData, undefined, 2)); console.log("Generated " + outfile); } else { // Output file contents to file. const file = archive.getFileByFilename(base); if (file === undefined) { // TODO: Look by name and different extension. console.log("Can't find file " + base); } else { const binary = file.getBinary(); fs.writeFileSync(outfile, binary); if (file.date !== undefined) { fs.utimesSync(outfile, file.date, file.date); } console.log("Extracted " + file.filename + " to " + outfile); } } } } } /** * Disassemble a program. * * @param trs80File program to disassemble. * @param entryPoints additional entry points in binary. */ function disassemble(trs80File: CmdProgram | SystemProgram, entryPoints: number[]): [binary: Uint8Array, description: string] { const disasm = disasmForTrs80Program(trs80File); for (const entryPoint of entryPoints) { disasm.addEntryPoint(entryPoint); } const instructions = disasm.disassemble() const text = instructionsToText(instructions).join("\n") + "\n"; const outBinary = new TextEncoder().encode(text); const description = "Disassembled " + (trs80File.className === "CmdProgram" ? "CMD program" : "system program"); return [outBinary, description]; } /** * Handle the "convert" command. * * @param inFilenames list of input filenames. * @param outFilename single output filename or directory. * @param baud optional new baud rate. * @param start optional start address of system file. * @param entryPoints additional entry points in binary. */ function convert(inFilenames: string[], outFilename: string, baud: number | undefined, start: number | "auto" | undefined, entryPoints: number[]): void { const inFiles: InputFile[] = []; const outputIsDirectory = fs.existsSync(outFilename) && fs.statSync(outFilename).isDirectory(); // Read all input files into an internal data structure, expanding archives like cassettes and floppies. for (const inFilename of inFilenames) { const { base, name, ext } = path.parse(inFilename); let buffer; try { buffer = fs.readFileSync(inFilename); } catch (e) { console.log("Can't open \"" + inFilename + "\": " + e.message); process.exit(1); } if (ext.toLowerCase() == ".wav") { // Parse a cassette WAV file. const wavFile = readWavFile(buffer.buffer); const tape = new Tape(base, wavFile); const decoder = new Decoder(tape); decoder.decode(); for (const program of tape.programs) { const trs80File = decodeTrs80CassetteFile(program.binary); const filename = name + "-" + program.getPseudoFilename() + getTrs80FileExtension(trs80File); inFiles.push(new InputFile(filename, trs80File, program.baud)); } } else { const trs80File = decodeTrs80File(buffer, inFilename); if (trs80File.error !== undefined) { console.log("Can't open \"" + inFilename + "\": " + trs80File.error); process.exit(1); } if (isFloppy(trs80File)) { const trsdos = decodeTrsdos(trs80File); if (trsdos === undefined) { // Should probably fail here. Having the floppy disk itself is probably not // what the user wants. inFiles.push(new InputFile(base, trs80File)); } else { // Expand floppy. for (const dirEntry of trsdos.dirEntries) { const trsdosFilename = dirEntry.getFilename("."); const trsdosBinary = trsdos.readFile(dirEntry); // Don't decode if we're going to just write files to disk anyway. const trsdosTrs80File = outputIsDirectory ? new RawBinaryFile(trsdosBinary) : decodeTrs80File(trsdosBinary, trsdosFilename); inFiles.push(new InputFile(trsdosFilename, trsdosTrs80File, undefined, dirEntry.getDate())); } } } else if (trs80File.className === "Cassette") { // Expand .CAS file. let counter = 1; for (const cassetteFile of trs80File.files) { const filename = name + "-T" + counter + getTrs80FileExtension(cassetteFile.file); const baud = cassetteFile.speed === CassetteSpeed.LOW_SPEED ? 500 : 1500; inFiles.push(new InputFile(filename, cassetteFile.file, baud)); counter++; } } else { inFiles.push(new InputFile(base, trs80File)); } } } // Update start address if requested. if (start !== undefined) { for (let i = 0; i < inFiles.length; i++) { const trs80File = inFiles[i].trs80File; let newTrs80File: Trs80File | undefined; if (trs80File.className === "SystemProgram") { if (start === "auto") { if (trs80File.entryPointAddress === 0) { const guessAddress = trs80File.guessEntryAddress(); if (guessAddress !== undefined) { newTrs80File = trs80File.withEntryPointAddress(guessAddress); } } } else { newTrs80File = trs80File.withEntryPointAddress(start); } } if (newTrs80File !== undefined) { inFiles[i] = inFiles[i].withFile(newTrs80File); } } } // If output is existing directory, put all input files there. if (outputIsDirectory) { for (const infile of inFiles) { const outpath = path.join(outFilename, infile.filename); fs.writeFileSync(outpath, infile.trs80File.binary); if (infile.date !== undefined) { fs.utimesSync(outpath, infile.date, infile.date); } console.log("Wrote " + outpath + " (" + pluralizeWithCount(infile.trs80File.binary.length, "byte") + ")"); } } else { // Output is a file. Its extension will help us determine how to convert the input files. const outExt = path.parse(outFilename).ext.toLowerCase(); if (outExt === "") { console.log("No file extension on output file \"" + outFilename + "\", don't know how to convert"); process.exit(1); } // See if input is a single file. if (inFiles.length === 1) { // Convert individual file. const infile = inFiles[0]; const inName = path.parse(infile.filename).name; let outBinary: Uint8Array; let description: string; switch (infile.trs80File.className) { case "RawBinaryFile": console.log("Cannot convert unknown file type of " + infile.filename); process.exit(1); break; case "BasicProgram": switch (outExt) { case ".bas": // Write as-is. outBinary = infile.trs80File.binary; description = "Basic file (tokenized)"; break; case ".asc": // Convert to ASCII. outBinary = Buffer.from(infile.trs80File.asAscii()); description = "Basic file (plain text)"; break; case ".cas": { // Encode in CAS file. const outBaud = (baud ?? infile.baud) ?? 500; outBinary = binaryAsCasFile(infile.trs80File.asCassetteBinary(), outBaud); description = "Basic file in " + (outBaud >= 1500 ? "high" : "low") + " speed CAS file"; break; } case ".wav": { // Encode in WAV file. const outBaud = (baud ?? infile.baud) ?? 500; const cas = binaryAsCasFile(infile.trs80File.asCassetteBinary(), outBaud); const audio = casAsAudio(cas, outBaud, DEFAULT_SAMPLE_RATE); outBinary = writeWavFile(audio, DEFAULT_SAMPLE_RATE); description = "Basic file in " + baud + " baud WAV file"; break; } default: console.log("Can't convert a Basic program to " + outExt.toUpperCase()); process.exit(1); break; } break; case "Jv1FloppyDisk": case "Jv3FloppyDisk": case "DmkFloppyDisk": case "ScpFloppyDisk": case "Cassette": console.log("Files of type \"" + infile.trs80File.getDescription + "\" are not yet supported"); process.exit(1); break; case "SystemProgram": switch (outExt) { case ".3bn": // Write as-is. outBinary = infile.trs80File.binary; description = infile.trs80File.getDescription(); break; case ".cmd": { // Convert to CMD program. const cmdProgram = infile.trs80File.toCmdProgram(inName.toUpperCase()); outBinary = cmdProgram.binary; description = cmdProgram.getDescription(); break; } case ".cas": { // Encode in CAS file. const outBaud = (baud ?? infile.baud) ?? 500; outBinary = binaryAsCasFile(infile.trs80File.binary, outBaud); description = infile.trs80File.getDescription() + " in " + (outBaud >= 1500 ? "high" : "low") + " speed CAS file"; break; } case ".wav": { // Encode in WAV file. const outBaud = (baud ?? infile.baud) ?? 500; const cas = binaryAsCasFile(infile.trs80File.binary, outBaud); const audio = casAsAudio(cas, outBaud, DEFAULT_SAMPLE_RATE); outBinary = writeWavFile(audio, DEFAULT_SAMPLE_RATE); description = infile.trs80File.getDescription() + " in " + outBaud + " baud WAV file"; break; } case ".lst": [outBinary, description] = disassemble(infile.trs80File, entryPoints); break; default: console.log("Can't convert a system program program to " + outExt.toUpperCase()); process.exit(1); break; } break; case "CmdProgram": switch (outExt) { case ".cmd": // Write as-is. outBinary = infile.trs80File.binary; description = infile.trs80File.getDescription(); break; case ".3bn": { // Convert to system program. const systemProgram = infile.trs80File.toSystemProgram(inName.toUpperCase()); outBinary = systemProgram.binary; description = systemProgram.getDescription(); break; } case ".cas": { // Encode in CAS file. const outBaud = (baud ?? infile.baud) ?? 500; const systemProgram = infile.trs80File.toSystemProgram(inName.toUpperCase()); const sysBinary = systemProgram.binary; outBinary = binaryAsCasFile(sysBinary, outBaud); description = systemProgram.getDescription() + " in " + (outBaud >= 1500 ? "high" : "low") + " speed CAS file"; break; } case ".wav": { // Encode in WAV file. const outBaud = (baud ?? infile.baud) ?? 500; const systemProgram = infile.trs80File.toSystemProgram(inName.toUpperCase()); const sysBinary = systemProgram.binary; const cas = binaryAsCasFile(sysBinary, outBaud); const audio = casAsAudio(cas, outBaud, DEFAULT_SAMPLE_RATE); outBinary = writeWavFile(audio, DEFAULT_SAMPLE_RATE); description = systemProgram.getDescription() + " in " + outBaud + " baud WAV file"; break; } case ".lst": [outBinary, description] = disassemble(infile.trs80File, entryPoints); break; default: console.log("Can't convert a CMD program to " + outExt.toUpperCase()); process.exit(1); break; } break; } fs.writeFileSync(outFilename, outBinary); console.log("Wrote " + outFilename + ": " + description); } else { // Make archive. if (outExt === ".cas" || outExt === ".wav") { // Make the individual cas files and their baud rate. const outCasFiles: {cas: Uint8Array, baud: number}[] = []; for (const inFile of inFiles) { // Convert to cassette format if necessary. let outBinary: Uint8Array; let description: string; switch (inFile.trs80File.className) { case "RawBinaryFile": case "SystemProgram": // Keep as-is. outBinary = inFile.trs80File.binary; description = inFile.trs80File.getDescription(); break; case "BasicProgram": outBinary = inFile.trs80File.asCassetteBinary(); description = inFile.trs80File.getDescription(); break; case "Jv1FloppyDisk": case "Jv3FloppyDisk": case "DmkFloppyDisk": case "ScpFloppyDisk": case "Cassette": // Shouldn't happen, we split up archives. console.log(`Can't put ${inFile.trs80File.getDescription()} into a ${outExt.toUpperCase()} file`); process.exit(1); break; case "CmdProgram": { // Convert to system program first. const inName = path.parse(inFile.filename).name; const systemProgram = inFile.trs80File.toSystemProgram(inName.toUpperCase()); outBinary = systemProgram.binary; description = systemProgram.getDescription(); break; } } const outBaud = (baud ?? inFile.baud) ?? 500; outCasFiles.push({cas: binaryAsCasFile(outBinary, outBaud), baud: outBaud}); console.log("In output file: " + description); } if (outExt === ".cas") { fs.writeFileSync(outFilename, concatByteArrays(outCasFiles.map(outCas => outCas.cas))); console.log("Wrote " + outFilename + ": CAS file with " + pluralizeWithCount(outCasFiles.length, "file")); } else { // outExt == ".wav" const audioParts: Int16Array[] = []; for (const outCas of outCasFiles) { // One second of silence before each program. audioParts.push(new Int16Array(DEFAULT_SAMPLE_RATE)); // Convert program to audio. audioParts.push(casAsAudio(outCas.cas, outCas.baud, DEFAULT_SAMPLE_RATE)); // One second of silence after each program. audioParts.push(new Int16Array(DEFAULT_SAMPLE_RATE)); } const wavBinary = writeWavFile(concatAudio(audioParts), DEFAULT_SAMPLE_RATE); fs.writeFileSync(outFilename, wavBinary); console.log("Wrote " + outFilename + ": WAV file with " + pluralizeWithCount(outCasFiles.length, "file")); } } else { // TODO handle floppy. console.log("Can't put multiple files into " + outExt.toUpperCase()); } } } } /** * Handle the "sectors" command. */ function sectors(filename: string, showContents: boolean): void { // Read the file. let buffer; try { buffer = fs.readFileSync(filename); } catch (e) { console.log("Can't open \"" + filename + "\": " + e.message); return; } // Decode the floppy or cassette. const file = decodeTrs80File(buffer, filename); if (!isFloppy(file)) { console.log("Not a recognized floppy file: " + filename); return; } if (file.error !== undefined) { console.log(filename + ": " + file.error); return; } console.log(filename + ": " + file.getDescription()); const geometry = file.getGeometry(); const minSectorNumber = Math.min(geometry.firstTrack.firstSector, geometry.lastTrack.firstSector); const maxSectorNumber = Math.max(geometry.firstTrack.lastSector, geometry.lastTrack.lastSector); const usedLetters = new Set<string>(); const CHALK_FOR_LETTER: { [letter: string]: chalk.Chalk } = { "-": chalk.gray, "C": chalk.red, "X": chalk.yellow, "S": chalk.reset, "D": chalk.reset, }; const LEGEND_FOR_LETTER: { [letter: string]: string } = { "-": "Missing sector", "C": "CRC error", "X": "Deleted sector", "S": "Single density", "D": "Double density", } for (let sideNumber = 0; sideNumber < geometry.numSides(); sideNumber++) { const side = numberToSide(sideNumber); const sideName = side === Side.FRONT ? "Front" : "Back"; const lineParts: string[] = [sideName.padStart(6, " ") + " "]; for (let sectorNumber = minSectorNumber; sectorNumber <= maxSectorNumber; sectorNumber++) { lineParts.push(sectorNumber.toString().padStart(3, " ")); } console.log(lineParts.join("")); for (let trackNumber = geometry.firstTrack.trackNumber; trackNumber <= geometry.lastTrack.trackNumber; trackNumber++) { const lineParts: string[] = [trackNumber.toString().padStart(6, " ") + " "]; for (let sectorNumber = minSectorNumber; sectorNumber <= maxSectorNumber; sectorNumber++) { const sectorData = file.readSector(trackNumber, side, sectorNumber); let text: string; if (sectorData === undefined) { text = "-"; } else if (sectorData.crcError) { text = "C"; } else if (sectorData.deleted) { text = "X"; } else if (sectorData.density === Density.SINGLE) { text = "S"; } else { text = "D"; } usedLetters.add(text); const color = CHALK_FOR_LETTER[text] ?? chalk.reset; lineParts.push("".padEnd(3 - text.length, " ") + color(text)); } console.log(lineParts.join("")); } console.log(""); } if (usedLetters.size > 0) { const legendLetters = Array.from(usedLetters.values()); legendLetters.sort(); console.log("Legend:"); for (const legendLetter of legendLetters) { const explanation = LEGEND_FOR_LETTER[legendLetter] ?? "Unknown"; const color = CHALK_FOR_LETTER[legendLetter] ?? chalk.reset; console.log(" " + color(legendLetter) + ": " + explanation); } console.log(""); } if (showContents) { // Dump each sector. for (let trackNumber = geometry.firstTrack.trackNumber; trackNumber <= geometry.lastTrack.trackNumber; trackNumber++) { const trackGeometry = geometry.getTrackGeometry(trackNumber); for (const side of trackGeometry.sides()) { for (let sectorNumber = trackGeometry.firstSector; sectorNumber <= trackGeometry.lastSector; sectorNumber++) { let header = `Track ${trackNumber}, side ${side}, sector ${sectorNumber}: `; const sector = file.readSector(trackNumber, side, sectorNumber); if (sector === undefined) { header += "missing"; } else { header += (sector.density === Density.SINGLE ? "single" : "double") + " density" + (sector.deleted ? ", marked as deleted" : ""); } console.log(header); if (sector !== undefined) { hexdumpBinary(sector.data, false, []); } console.log(""); } } } } } /** * Represents a span of characters in the hexdump with a single set of classes. */ class HexdumpSpan { public text: string; public readonly classes: string[]; constructor(text: string, classes: string[]) { this.text = text; this.classes = classes; } } /** * Hexdump generator for console output. */ class ConsoleHexdumpGenerator extends HexdumpGenerator<HexdumpSpan[], HexdumpSpan> { constructor(binary: Uint8Array, collapse: boolean, annotations: ProgramAnnotation[]) { super(binary, collapse, annotations); } protected newLine(): HexdumpSpan[] { return []; } protected getLineText(line: HexdumpSpan[]): string { return line.map(span => span.text).join(""); } protected newSpan(line: HexdumpSpan[], text: string, ...cssClass: string[]): HexdumpSpan { const span = new HexdumpSpan(text, cssClass); line.push(span); return span; } protected addTextToSpan(span: HexdumpSpan, text: string): void { span.text += text; } } /** * Hex dump a binary array. */ function hexdumpBinary(binary: Uint8Array, collapse: boolean, annotations: ProgramAnnotation[]): void { const hexdump = new ConsoleHexdumpGenerator(binary, collapse, annotations); for (const line of hexdump.generate()) { console.log(line.map(span => { if (span.classes.indexOf("outside-annotation") >= 0) { if (chalk.level === 0) { // Hide altogether. return "".padEnd(span.text.length, " "); } else { return chalk.dim(span.text); } } else { if (span.classes.indexOf("ascii-unprintable") >= 0) { return chalk.dim(span.text); } return span.text; } }).join("")); } } /** * Handle the "hexdump" command. */ function hexdump(filename: string, collapse: boolean): void { // Read the file. let buffer; try { buffer = fs.readFileSync(filename); } catch (e) { console.log("Can't open \"" + filename + "\": " + e.message); return; } // Decode the floppy or cassette. const file = decodeTrs80File(buffer, filename); if (file.error !== undefined) { console.log(filename + ": " + file.error); return; } hexdumpBinary(file.binary, collapse, file.annotations); } /** * Handle the "disasm" command. */ function disasm(filename: string, org: number | undefined, entryPoints: number[]) { // Read the file. let buffer; try { buffer = fs.readFileSync(filename); } catch (e) { console.log("Can't open \"" + filename + "\": " + e.message); return; } // Create and configure the disassembler. let disasm: Disasm; const ext = path.extname(filename).toUpperCase(); if (ext === ".CMD" || ext === ".3BN") { const trs80File = decodeTrs80File(buffer, filename); if (trs80File.className !== "CmdProgram" && trs80File.className !== "SystemProgram") { console.log("Can't parse program in " + filename); return; } disasm = disasmForTrs80Program(trs80File); } else if (ext === ".ROM" || ext === ".BIN") { disasm = disasmForTrs80(); disasm.addChunk(buffer, org ?? 0); if (org !== undefined || entryPoints.length === 0) { disasm.addEntryPoint(org ?? 0); } addModel3RomEntryPoints(disasm); } else { console.log("Can't disassemble files of type " + ext); return; } // Add extra entry points, if any. for (const entryPoint of entryPoints) { disasm.addEntryPoint(entryPoint); } const instructions = disasm.disassemble() const text = instructionsToText(instructions).join("\n"); console.log(text); } function connectXray(trs80: Trs80, keyboard: Keyboard): void { const host = "0.0.0.0"; const port = 8080; function serveFile(res: http.ServerResponse, filename: string, mimetype: string): void { let contents; console.log("Serving " + filename); try { contents = fs.readFileSync("xray/" + filename); } catch (e) { console.log("Exception reading: " + e.message); res.writeHead(404); res.end("File not found"); return; } res.setHeader("Content-Type", mimetype); res.writeHead(200); res.end(contents); } function requestListener(req: http.IncomingMessage, res: http.ServerResponse) { console.log(req.url); if (req.url === undefined) { console.log("Got undefined URL"); return; } const { pathname } = url.parse(req.url); // TODO deprecated switch (pathname) { case "/": case "/index.html": serveFile(res, "index.html", "text/html"); break; case "/trs_xray.js": serveFile(res, "trs_xray.js", "text/javascript"); break; case "/trs_xray.css": serveFile(res, "trs_xray.css", "text/css"); break; case "/channel": console.log("/channel was fetched"); break; default: console.log("URL unknown: " + req.url); res.writeHead(404); res.end("File not found"); break; } } function sendUpdate(ws: ws.WebSocket) { const regs = trs80.z80.regs; const info = { context: { system_name: "trs80-tool", model: 3, // TODO get from config. running: trs80.started, alt_single_step_mode: false, }, breakpoints: [], registers: { pc: regs.pc, sp: regs.sp, af: regs.af, bc: regs.bc, de: regs.de, hl: regs.hl, af_prime: regs.afPrime, bc_prime: regs.bcPrime, de_prime: regs.dePrime, hl_prime: regs.hlPrime, ix: regs.ix, iy: regs.iy, i: regs.i, r_1: regs.r, r_2: regs.r7 & 0x7F, z80_t_state_counter: trs80.tStateCount, z80_clockspeed: trs80.clockHz, z80_iff1: regs.iff1, z80_iff2: regs.iff2, z80_interrupt_mode: regs.im, }, }; ws.send(JSON.stringify(info)); } function sendMemory(ws: ws.WebSocket): void { // TODO parse non-force version. const MEM_SIZE = 0x10000; // TODO auto-detect. const memory = Buffer.alloc(MEM_SIZE + 2); for (let i = 0; i < MEM_SIZE; i++) { memory[i + 2] = trs80.readMemory(i); } // TODO first two bytes are start address in big-endian. ws.send(memory, { binary: true, }); } const wss = new ws.WebSocketServer({ noServer: true }); wss.on("connection", ws => { console.log("wss connection"); ws.on("message", message => { const command = message.toString(); const parts = command.split("/"); if (parts[0] === "action") { switch (parts[1]) { case "refresh": sendUpdate(ws); break; case "step": trs80.step(); sendUpdate(ws); break; case "continue": trs80.start(); sendUpdate(ws); break; case "stop": trs80.stop(); sendUpdate(ws); break; case "soft_reset": case "hard_reset": trs80.reset(); // TODO handle soft/hard distinction. break; case "key_event": { const press = parts[2] === "1"; const what = parts[3] === "1"; const key = parts[4]; keyboard.keyEvent(key, press); break; } case "get_memory": sendMemory(ws); break; default: console.log("Unknown command " + command); break; } } else { console.log("Unknown command: " + command); } }); setInterval(() => { if (trs80.started) { sendUpdate(ws); sendMemory(ws); } }, 100); }); const server = http.createServer(requestListener); server.on("upgrade", (request, socket, head) => { if (request.url === undefined) { console.log("upgrade URL is undefined"); return; } const { pathname } = url.parse(request.url); // TODO deprecated console.log("upgrade", request.url, pathname, head.toString()); if (pathname === '/channel') { console.log("upgrade channel"); wss.handleUpgrade(request, socket, head, ws => { console.log("upgrade handled", head); wss.emit("connection", ws, request); }); } else { socket.destroy(); } }); server.listen(port, host, () => { console.log(`Server is running on http://${host}:${port}`); }); } /** * Handle the "run" command. */ function run(programFiles: string[], xray: boolean, config: Config) { // Size of screen. const WIDTH = 64; const HEIGHT = 16; /** * Class to update a VT-100 screen. */ class Vt100Control { // Cursor position, 1-based, relative to where it was when we started the program. private row: number = 1; private col: number = 1; private savedRow: number = 1; private savedCol: number = 1; /** * Save the current position, and think of it as being at the specified location. */ public saveCursorPositionAs(row: number, col: number): void { process.stdout.write("\x1b7"); this.savedRow = row; this.savedCol = col; } /** * Restore the position to where it was when {@link saveCursorPositionAs} was called. */ public restoreCursorPosition(): void { process.stdout.write("\x1b8"); this.row = this.savedRow; this.col = this.savedCol; } /** * Move cursor to specified location. * * @param row 1-based line number. * @param col 1-base column number. */ public moveTo(row: number, col: number): void { if (row < this.row) { process.stdout.write("\x1b[" + (this.row - row) + "A"); } else if (row > this.row) { process.stdout.write("\x1b[" + (row - this.row) + "B"); } if (col < this.col) { process.stdout.write("\x1b[" + (this.col - col) + "D"); } else if (col > this.col) { process.stdout.write("\x1b[" + (col - this.col) + "C"); } this.row = row; this.col = col; } /** * Inform us that the cursor has moved forward count character. */ public advancedCol(count: number = 1): void { this.col += count; } /** * Inform us that the cursor has moved down count rows and reset back to the left column. */ public advancedRow(count: number = 1): void { this.row += count; this.col = 1; } } /** * Screen implementation for an ANSI TTY. */ class TtyScreen extends Trs80Screen { // Cache of what we've drawn already. private readonly drawnScreen = new Uint8Array(WIDTH*HEIGHT); private readonly vt100Control = new Vt100Control(); private lastCursorIndex: number | undefined = undefined; private lastUnderscoreIndex = 0; constructor() { super(); this.drawFrame(); this.vt100Control.saveCursorPositionAs(HEIGHT + 3, 1); // Update cursor periodically. Have to do this on a timer since the memory location // can be updated anytime. setInterval(() => this.checkCursorPosition(false), 10); } public exit(): void { this.vt100Control.moveTo(HEIGHT + 3, 1); } /** * Draw the frame around the screen. */ private drawFrame(): void { // Draw frame. const color = chalk.green; process.stdout.write(color("+" + "-".repeat(WIDTH) + "+\n")); for (let row = 0; row < HEIGHT; row++) { process.stdout.write(color("|" + " ".repeat(WIDTH) + "|\n")); } process.stdout.write(color("+" + "-".repeat(WIDTH) + "+\n")); this.vt100Control.advancedRow(HEIGHT + 2); } setConfig(config: Config) { // Nothing. } writeChar(address: number, value: number) { const index = address - TRS80_SCREEN_BEGIN; if (index >= 0 && index < WIDTH * HEIGHT) { this.updateScreen(false); } } /** * Redraw any characters that have changed since the old screen. */ private updateScreen(force: boolean): void { let row = 1; let col = 1; for (let i = 0; i < WIDTH*HEIGHT; i++) { // Draw a space at the current cursor. let value = i === this.lastCursorIndex ? 32 : trs80.readMemory(i + TRS80_SCREEN_BEGIN); if (config.modelType === ModelType.MODEL1) { // Level 2 used the letters from values 0 to 31. if (value < 32) { value += 64; } else if (config.cgChip === CGChip.ORIGINAL && value >= 96 && value < 128) { value -= 64; } } if (force || value !== this.drawnScreen[i]) { // Keep track of where we saw our last underscore, for Level 1 support. if (value === 95) { this.lastUnderscoreIndex = i; } // Replace non-ASCII. const ch = value === 128 ? " " : value < 32 || value >= 127 ? chalk.gray("?") : String.fromCodePoint(value); // Draw at location. this.vt100Control.moveTo(row + 1, col + 1); process.stdout.write(ch); this.vt100Control.advancedCol(); this.drawnScreen[i] = value; } col += 1; if (col === WIDTH + 1) { col = 1; row += 1; } } } /** * Redraw from memory. */ public redraw(): void { this.vt100Control.restoreCursorPosition(); this.vt100Control.moveTo(1, 1); this.drawFrame(); this.updateScreen(true); } /** * Check RAM for the cursor position and update it. * * @param forceUpdate force the position update even if it hasn't changed in simulation. */ private checkCursorPosition(forceUpdate: boolean): void { // Figure out where the cursor is. let cursorIndex; if (config.basicLevel === BasicLevel.LEVEL1) { // We don't know where the cursor position is stored in Level 1. Guess based on the last // underscore we saw. cursorIndex = this.lastUnderscoreIndex; } else { // Get cursor position from RAM. const cursorAddress = trs80.readMemory(0x4020) | (trs80.readMemory(0x4021) << 8); cursorIndex = cursorAddress - TRS80_SCREEN_BEGIN; } // Ignore bad values. if (cursorIndex < 0 || cursorIndex >= WIDTH*HEIGHT) { return; } this.lastCursorIndex = cursorIndex; this.updateScreen(false); // 1-based. const row = Math.floor(cursorIndex / WIDTH) + 1; const col = cursorIndex % WIDTH + 1; // Adjust for frame. this.vt100Control.moveTo(row + 1, col + 1); } } /** * Screen that does nothing. */ class NopScreen extends Trs80Screen { setConfig(config: Config) { // Nothing. } writeChar(address: number, value: number) { // Nothing. } } /** * Keyboard implementation for a TTY. Puts the TTY into raw mode. */ class TtyKeyboard extends Keyboard { constructor(screen: TtyScreen) { super(); process.stdin.setRawMode(true); process.stdin.on("data", (buffer) => { if (buffer.length > 0) { const key = buffer[0]; if (key === 0x03) { // Ctrl-C. screen.exit(); process.exit(); } else if (key === 0x0C) { // Ctrl-L. screen.redraw(); } else { let keyName: string; switch (key) { case 8: case 127: keyName = "Backspace"; break; case 10: case 13: keyName = "Enter"; break; case 27: keyName = "Escape"; break; default: keyName = String.fromCodePoint(key); break; } this.keyEvent(keyName, true); this.keyEvent(keyName, false); } } }); } } // Load file if specified. const trs80Files: Trs80File[] = []; for (const programFile of programFiles) { let buffer; try { buffer = fs.readFileSync(programFile); } catch (e) { console.log(programFile + ": Can't open file: " + e.message); return; } const trs80File = decodeTrs80File(buffer, programFile); if (trs80File.error !== undefined) { console.log(programFile + ": " + trs80File.error); return; } trs80Files.push(trs80File); } let screen; let keyboard; if (xray) { screen = new NopScreen(); keyboard = new Keyboard(); } else { screen = new TtyScreen(); keyboard = new TtyKeyboard(screen); } const cassette = new CassettePlayer(); const soundPlayer = new SilentSoundPlayer(); const trs80 = new Trs80(config, screen, keyboard, cassette, soundPlayer); trs80.reset(); trs80.start(); if (trs80Files.length > 0) { trs80.runTrs80File(trs80Files[0]); } // Mount floppies. for (let i = 1; i < trs80Files.length; i++) { const trs80File = trs80Files[i]; if (!isFloppy(trs80File)) { console.log("Additional files must be floppies"); return; } trs80.loadFloppyDisk(trs80File, i); } if (xray) { connectXray(trs80, keyboard); } } /** * Handle the "asm" command. */ function asm(srcPathname: string, outPathname: string, baud: number, lstPathname: string | undefined): void { // Get the lines for a file. function loadFile(filename: string): string[] | undefined { try { return fs.readFileSync(filename, "utf-8").split(/\r?\n/); } catch (e) { // File not found. return undefined; } } const { name } = path.parse(srcPathname); // Assemble program. const asm = new Asm(loadFile); const sourceFile = asm.assembleFile(srcPathname); if (sourceFile === undefined) { console.log("Cannot read file " + srcPathname); return; } // Generate listing. if (lstPathname !== undefined) { const lstFd = fs.openSync(lstPathname, "w"); for (const line of sourceFile.assembledLines) { if (line.binary.length !== 0) { // Show four bytes at a time. let displayAddress = line.address; for (let i = 0; i < line.binary.length; i += 4) { let result = toHex(displayAddress, 4) + ":"; for (let j = 0; j < 4 && i + j < line.binary.length; j++) { result += " " + toHex(line.binary[i + j], 2); displayAddress++; } if (i === 0) { result = result.padEnd(24, " ") + line.line; } fs.writeSync(lstFd, result + "\n"); } } else { fs.writeSync(lstFd, " ".repeat(24) + line.line + "\n"); } if (line.error !== undefined) { fs.writeSync(lstFd, "error: " + line.error + "\n"); } } fs.closeSync(lstFd); } // Show errors. let errorCount = 0; for (const line of sourceFile.assembledLines) { if (line.error !== undefined) { console.log(chalk.gray(line.line)); console.log(chalk.red("error: " + line.error)); console.log(); errorCount += 1; } } // Don't generate output if we have errors. if (errorCount !== 0) { console.log(errorCount + " errors"); process.exit(1); } // Guess the entry point if necessary. let entryPoint: number | undefined = asm.entryPoint; if (entryPoint === undefined) { for (const line of sourceFile.assembledLines) { if (line.binary.length > 0) { entryPoint = line.address; break; } } if (entryPoint === undefined) { console.log("No entry point specified"); process.exit(1); } console.log("Warning: No entry point specified, guessing 0x" + toHexWord(entryPoint)); } // Generate output. const binaryParts: Uint8Array[] = []; const extension = path.parse(outPathname).ext.toUpperCase(); switch (extension) { case ".CMD": { // Convert to CMD file. const builder = new CmdProgramBuilder(); for (const line of sourceFile.assembledLines) { builder.addBytes(line.address, line.binary); } const chunks = [ CmdLoadModuleHeaderChunk.fromFilename(name), ... builder.getChunks(), CmdTransferAddressChunk.fromEntryPointAddress(entryPoint), ] let binary = encodeCmdProgram(chunks); binaryParts.push(binary); break; } case ".3BN": case ".CAS": case ".WAV": { // Convert to 3BN file. const builder = new SystemProgramBuilder(); for (const line of sourceFile.assembledLines) { builder.addBytes(line.address, line.binary); } const chunks = builder.getChunks(); let binary = encodeSystemProgram(name, chunks, entryPoint); if (extension === ".CAS" || extension === ".WAV") { // Convert to CAS. binary = binaryAsCasFile(binary, baud); if (extension === ".WAV") { // Convert to WAV. const audio = casAsAudio(binary, baud, DEFAULT_SAMPLE_RATE); binary = writeWavFile(audio, DEFAULT_SAMPLE_RATE); } } binaryParts.push(binary); break; } default: console.log("Unknown output type: " + outPathname); return; } // Write output. const binFd = fs.openSync(outPathname, "w"); for (const part of binaryParts) { fs.writeSync(binFd, part); } fs.closeSync(binFd); } function main() { program .storeOptionsAsProperties(false) .name("trs80-tool") .addHelpText("after", HELP_TEXT) .version(version) .addOption(new Option("--color <color>", "color output") .choices(["off", "16", "256", "16m", "auto"]) .default("auto")); program .command("dir <infile>") .description("list files in the infile", { infile: "WAV, CAS, JV1, JV3, or DMK file (TRSDOS floppies only)", }) .action(infile => { dir(infile); }); program .command("info <infiles...>") .description("show information about each file", { infile: "any TRS-80 file", }) .option("--verbose", "output more information about each file") .action((infiles, options) => { info(infiles, options.verbose); }); program .command("convert <files...>") .description("convert one or more infiles to one outfile", { infile: "WAV, CAS, CMD, 3BN, or BAS file", outfile: "WAV, CAS, CMD, 3BN, BAS, or LST file", }) .option("--baud <baud>", "output baud rate (250, 500, 1000, or 1500)") .option("--start <address>", "new start address of system program, or \"auto\" to guess") .option("--entry <addresses>", "add entry points of binary (comma-separated), for LST output") .action((files, options) => { const baud = options.baud !== undefined ? parseInt(options.baud) : undefined; const start = options.start !== undefined ? options.start === "auto" ? "auto" : parseInt(options.start) : undefined; const entryPoints = options.entry !== undefined ? (options.entry as string).split(",").map(x => parseInt(x)) : []; if (files.length < 2) { console.log("Must specify at least one infile and exactly one outfile"); process.exit(1); } const infiles = files.slice(0, files.length - 1); const outfile = files[files.length - 1]; convert(infiles, outfile, baud, start, entryPoints); }); program .command("sectors <infiles...>") .description("show a sector map for each floppy file", { infile: "any TRS-80 floppy file", }) .option("--contents", "show the contents of the sectors") .action((infiles, options) => { setColorLevel(program.opts().color); for (const infile of infiles) { sectors(infile, options.contents); } }); program .command("hexdump <infile>") .description("display an annotated hexdump of infile", { infile: "WAV, CAS, CMD, 3BN, BAS, JV1, JV3, or DMK", }) .option("--no-collapse", "collapse consecutive identical lines") .action((infile, options) => { setColorLevel(program.opts().color); hexdump(infile, options.collapse); }); program .command("asm <infile> <outfile>") .description("assemble a program", { infile: "ASM file", outfile: "CMD, 3BN, CAS, or WAV file", }) .option("--baud <baud>", "baud rate for CAS and WAV file (250, 500, 1000, 1500), defaults to 500") .option("--listing <filename>", "generate listing file") .action((infile, outfile, options) => { setColorLevel(program.opts().color); const baud = options.baud === undefined ? 500 : parseInt(options.baud); if (baud !== 250 && baud !== 500 && baud !== 1000 && baud !== 1500) { console.log("Invalid baud rate: " + options.baud); process.exit(1); } asm(infile, outfile, baud, options.listing); }); program .command("disasm <infile>") .description("disassemble a program", { infile: "CMD, 3BN, ROM, or BIN", }) .option('--org <address>', "where to assume the binary is loaded") .option("--entry <addresses>", "add entry points of binary (comma-separated)") .action((infile, options) => { setColorLevel(program.opts().color); const org = options.org === undefined ? undefined : parseInt(options.org); const entryPoints = options.entry !== undefined ? (options.entry as string).split(",").map(x => parseInt(x)) : []; disasm(infile, org, entryPoints); }); program .command("run [program...]") .description("run a TRS-80 emulator", { program: "optional program file to run" }) .option("--xray", "run an xray debug server") .option("--model <model>", "which model (1, 3, 4), defaults to 3") .option("--level <level>", "which level (1 or 2), defaults to 2") .action((programs, options) => { const modelName = options.model ?? "3"; const levelName = options.level ?? "2"; const modelType = modelTypeFromString(modelName); if (modelType === undefined) { console.log("Invalid model: " + modelName); process.exit(1); } const basicLevel = basicLevelFromString(levelName); if (basicLevel === undefined) { console.log("Invalid Basic level: " + levelName); process.exit(1); } if (basicLevel === BasicLevel.LEVEL1 && modelType !== ModelType.MODEL1) { console.log("Can only run Level 1 Basic with Model I"); process.exit(1); } const config = Config.makeDefault() .withModelType(modelType) .withBasicLevel(basicLevel); if (!config.isValid()) { // Kinda generic! console.log("Invalid model and Basic level configuration"); process.exit(1); } run(programs, options.xray, config); }); program .parse(); } main();
the_stack
import {OnInit} from '@angular/core'; import {Component} from '@angular/core'; import {Ajax} from '../../../../shared/ajax/ajax.service'; import * as yaml from 'js-yaml'; declare let toastr: any; declare let swal: any; declare let $: any; declare let mApp: any; @Component({ templateUrl: './config-manage.component.html', }) export class ConfigManageComponent implements OnInit { productList: any[] = []; selectProductId: any = null; selectProductInfo: any = null; envs: any[] = []; labels: any[] = []; selectEnvId: any = null; selectEnvInfo: any = null; selectLabelId: any = null; selectLabelInfo: any = null; envParamsTemList: any[] = []; encryptKeyList: any[] = []; persistentList: any[] = []; persistent: any[] = []; configFromConfigServerList: any[] = []; editorOptions = {theme: 'vs-dark', language: 'yaml', automaticLayout: true}; editorOptionsProperties = { theme: 'vs-dark', language: 'ini', automaticLayout: true, }; code_properties: String = ``; code: string = ``; configType: number = 1; constructor(private ajax: Ajax) {} ngOnInit(): void { this.initProductList(); } ngAfterViewInit(): void { this.initFormValidation(); this.initYmlEditor(); } initFormValidation() { /* * Translated default messages for the jQuery validation plugin. * Locale: ZH (Chinese, 中文 (Zhōngwén), 汉语, 漢語) */ $.extend($.validator.messages, { required: '这是必填字段', remote: '请修正此字段', email: '请输入有效的电子邮件地址', url: '请输入有效的网址', date: '请输入有效的日期', dateISO: '请输入有效的日期 (YYYY-MM-DD)', number: '请输入有效的数字', digits: '只能输入数字', creditcard: '请输入有效的信用卡号码', equalTo: '你的输入不相同', extension: '请输入有效的后缀', maxlength: $.validator.format('最多可以输入 {0} 个字符'), minlength: $.validator.format('最少要输入 {0} 个字符'), rangelength: $.validator.format( '请输入长度在 {0} 到 {1} 之间的字符串' ), range: $.validator.format('请输入范围在 {0} 到 {1} 之间的数值'), max: $.validator.format('请输入不大于 {0} 的数值'), min: $.validator.format('请输入不小于 {0} 的数值'), }); $('#id-config-manage-form').validate({ //display error alert on form submit invalidHandler: function(event, validator) { console.log(event); }, submitHandler: form => { this.save(); }, }); } initYmlEditor() { // monaco.editor.create(document.getElementById('id-yml-editor'), { // value: '', // language: 'yaml', // }); } async configTypeChange(configType) { this.configType = configType; await this.getPersistentList(); } async initProductList() { let result = await this.ajax.get('/xhr/project'); this.productList = result; if (this.selectProductId == null) { this.selectProductId = this.productList.length > 0 ? this.productList[0].id : null; } this.selectProduct(this.selectProductId); } async selectProduct(id) { this.selectProductId = id; this.selectProductInfo = this.productList.filter(item => { if (this.selectProductId == item.id) { return true; } })[0]; this.envs = this.selectProductInfo.envs; if (this.envs.length > 0) { this.selectEnvId = this.envs[0].id; this.selectEnvInfo = this.envs[0]; } this.labels = this.selectProductInfo.labels; if (this.labels.length > 0) { this.selectLabelId = this.labels[0].id; this.selectLabelInfo = this.labels[0]; } await this.getEnvParamsTemplate(); await this.getEncrptKeyList(); await this.getPersistentList(); } /** * 根据环境参数获取当前环境中的一些模板信息 * @author stone-jin, https://www.520stone.com */ async getEnvParamsTemplate() { let result = await this.ajax.get('/xhr/envParam', { envId: this.selectEnvId, }); this.envParamsTemList = result; } /** * 加密Key清单 * @author stone-jin, https://www.520stone.com */ async getEncrptKeyList() { let result = await this.ajax.get('/xhr/encryptKey', {}); this.encryptKeyList = result; } /** * 选中对应的版本 * @param id 版本的id * @author stone-jin, https://www.520stone.com */ async selectLabel(id) { this.selectLabelId = id; this.selectLabelInfo = this.selectProductInfo.labels.filter(item => { if (item.id === this.selectLabelId) { return true; } })[0]; await this.getEnvParamsTemplate(); await this.getEncrptKeyList(); await this.getPersistentList(); } /** * 选中对应的环境 * @param id 环境的id * @author stone-jin, https://www.520stone.com */ async selectEnv(id) { this.selectEnvId = id; this.selectEnvInfo = this.selectProductInfo.envs.filter(item => { if (item.id === this.selectEnvId) { return true; } })[0]; await this.getEnvParamsTemplate(); await this.getEncrptKeyList(); await this.getPersistentList(); } /** * 根据当前项目名称,环境名称,版本名称获取当前的存储配置信息 * @author stone-jin, https://www.520stone.com */ async getPersistentList() { let params = { project: this.selectProductInfo.name, profile: this.selectEnvInfo.name, label: this.selectLabelInfo.name, }; let result = await this.ajax.get('/xhr/property/persistent', params); this.persistentList = result; this.persistent = []; let keys = Object.keys(this.persistentList); for (let i = 0; i < keys.length; i++) { this.persistent.push({ key: keys[i], value: this.persistentList[keys[i]], }); } this.code = yaml.safeDump(this.translateToYaml(result)); this.code_properties = ``; keys.map(item => { this.code_properties += item + '=' + this.persistentList[item] + '\n'; }); } mergeJSON(minor, main) { for (var key in minor) { if (main[key] === undefined) { // 不冲突的,直接赋值 main[key] = minor[key]; continue; } // 冲突了,如果是Object,看看有么有不冲突的属性 // 不是Object 则以(minor)为准为主, if (this.isJSON(minor[key]) || this.isArray(minor[key])) { // arguments.callee 递归调用,并且与函数名解耦 //arguments.callee(minor[key], main[key]); this.mergeJSON(minor[key], main[key]); } else { main[key] = minor[key]; } } } isJSON(target) { return typeof target == 'object' && target.constructor == Object; } isArray(o) { return Object.prototype.toString.call(o) == '[object Array]'; } /** * 由于后端存储是key value的格式,并不是yaml转成json即可,或者json转成yaml,需要把key通过.进行split分割 * @param json */ translateToYaml(json) { let yamlJson = {}; let keys = Object.keys(json); for (let i = 0; i < keys.length; i++) { let tmps = keys[i].split('.'); let result = {}; for (let j = tmps.length - 1; j >= 0; j--) { if (j === tmps.length - 1) { if (parseInt(json[keys[i]]) + '' == json[keys[i]]) { result[tmps[j]] = parseInt(json[keys[i]]); } else if ( json[keys[i]].indexOf('[') == 0 && json[keys[i]].lastIndexOf(']') == json[keys[i]].length - 1 ) { result[tmps[j]] = JSON.parse(json[keys[i]]); } else { result[tmps[j]] = json[keys[i]]; } } else { let tmp = {}; tmp[tmps[j]] = result; result = tmp; } } let resultTmp = JSON.parse(JSON.stringify(result)); this.mergeJSON(resultTmp, yamlJson); } return yamlJson; } /** * 判断是否是JSON对象 * @param obj */ isJson(obj) { var isjson = typeof obj == 'object' && Object.prototype.toString.call(obj).toLowerCase() == '[object object]' && !obj.length; return isjson; } /** * 从yaml格式的json转成后端需要的json * @param ymlJson */ YamlToJSON(ymlJson) { let keys = Object.keys(ymlJson); let result = {}; let bEnd = true; for (let i = 0; i < keys.length; i++) { if (ymlJson[keys[i]] instanceof Array) { result[keys[i]] = JSON.stringify(ymlJson[keys[i]]); } else if (!this.isJson(ymlJson[keys[i]])) { result[keys[i]] = ymlJson[keys[i]]; } else { console.log(ymlJson[keys[i]]); let tmp_keys = Object.keys(ymlJson[keys[i]]); for (let j = 0; j < tmp_keys.length; j++) { result[keys[i] + '.' + tmp_keys[j]] = ymlJson[keys[i]][tmp_keys[j]]; } bEnd = false; } } return {bEnd, result}; } /** * 配置中心获取存储配置 * @author stone-jin, https://www.520stone.com */ async getFromConfigServer() { try { let result = await this.ajax.get('/xhr/property/configServer', { project: this.selectProductInfo.name, profile: this.selectEnvInfo.name, label: this.selectLabelInfo.name, }); $('#m_modal_1').modal('show'); let tmp = result.filter(item => { if ( item.name.substring(item.name.lastIndexOf('-') + 1) === this.selectEnvInfo.name && item.name.substring(0, item.name.lastIndexOf('-')) === this.selectProductInfo.name ) { return true; } else { return false; } })[0].source; let keys = Object.keys(tmp); this.configFromConfigServerList = []; keys.map(item => { this.configFromConfigServerList.push({ name: item, value: tmp[item], }); }); } catch (e) { console.log(e); toastr.error('配置中心获取存储配置失败'); } } /** * 保存存储配置信息 */ async save() { try { let params = {}; if (this.configType == 1) { for (let i = 0; i < this.persistent.length; i++) { params[this.persistent[i].key] = this.persistent[i].value; if ( this.persistent[i].key === '' || this.persistent[i].value === '' ) { toastr.error('当前存储配置不能为空,请进行补全!'); return; } } } else if (this.configType == 2) { let tmp = yaml.safeLoad(this.code); let result = false; while (!result) { let tmpResult = this.YamlToJSON(tmp); result = tmpResult.bEnd; tmp = tmpResult.result; } params = tmp; } else if (this.configType == 3) { let result = this.code_properties.split('\n'); for (let i = 0; i < result.length; i++) { let item = result[i].replace(/\s+/g, ''); if (item.length === 0) { continue; } let tmps = item.split('='); if (tmps.length !== 2) { toastr.error('properties请都按照对应的键值对配置!'); return; } if (tmps[0].indexOf('#') == 0) { continue; } params[tmps[0]] = tmps[1]; } } let url = `?project=${this.selectProductInfo.name}&profile=${ this.selectEnvInfo.name }&label=${this.selectLabelInfo.name}`; let result = await this.ajax.post( '/xhr/property/persistent' + url, params ); toastr.success('保存存储配置信息成功!'); } catch (e) { toastr.error('保存存储配置信息失败!'); } } getEncrpytStatus(item) { if (item.value.indexOf('{cipher}') >= 0) { return '1'; } else { return '0'; } } /** * 加密 * @param item 配置项 */ async lock(item) { mApp.block('#persistentList', {}); mApp.block('#envParamsList', {}); try { let result = await this.ajax.post( '/xhr/property/encrypt?envId=' + this.selectEnvId, item.value ); item.value = '{cipher}' + result; toastr.success('加密成功!'); } catch (e) { toastr.error('加密失败!'); } mApp.unblock('#persistentList'); mApp.unblock('#envParamsList'); } /** * 解密 * @param item 配置项 */ async unlock(item) { mApp.block('#persistentList', {}); mApp.block('#envParamsList', {}); try { let result = await this.ajax.post( '/xhr/property/decrypt?envId=' + this.selectEnvId, item.value.substring('{cipher}'.length) ); item.value = result; toastr.success('解密成功!'); } catch (e) { toastr.error('解密失败!'); } mApp.unblock('#persistentList'); mApp.unblock('#envParamsList'); } /** * 删除配置项 * @param index */ deleteItem(index) { swal({ title: 'Are you sure?', text: '你确定删除这个配置参数吗?', type: 'warning', showCancelButton: !0, confirmButtonText: '确定', cancelButtonText: '取消', }).then(async e => { if (e.value) { this.persistent.splice(index, 1); } }); } /** * 替换 * @param item */ replaceItem(item) { for (let i = 0; i < this.persistent.length; i++) { if (this.persistent[i].key === item.pKey) { this.persistent[i].value = item.pValue; this.save(); return; } } } /** * 一键替换 */ allReplace() { for (let i = 0; i < this.envParamsTemList.length; i++) { for (let j = 0; j < this.persistent.length; j++) { if (this.persistent[j].key === this.envParamsTemList[i].pKey) { this.persistent[j].value = this.envParamsTemList[i].pValue; } } } this.save(); } /** * 一键加密 */ allLock() { mApp.block('#persistentList', {}); for (let j = 0; j < this.encryptKeyList.length; j++) { for (let i = 0; i < this.persistent.length; i++) { if (this.encryptKeyList[j].eKey === this.persistent[i].key) { if (this.persistent[i].value.indexOf('{cipher}') < 0) { this.lock(this.persistent[i]); break; } } } } mApp.unblock('#persistentList'); } /** *是否能被替换 * @param {*} item * @returns * @memberof ConfigManageComponent */ fCanReplace(item) { let result = this.persistent.filter(item => { if (item.key == item.key) { return true; } else { return false; } }); if (result.length > 0) { return true; } else { return false; } } /** * 新增配置 */ addConfig() { this.persistent.push({ key: '', value: '', }); } }
the_stack
import { Order } from 'ccxt' import { EventBusEmitter, EventBusNode } from '@magic8bot/event-bus' import { ExchangeProvider, OrderOpts } from '../exchange' import { StrategyConfig, Wallet, Adjustment, eventBus, EVENT } from '../lib' import { OrderEngine, QuoteEngine } from '../engine' import { WalletStore } from '../store' import { SIGNAL } from '../types' import { logger, sleep } from '../util' interface OnEventType { savedOrder: Order update: Order } enum POSITION_STATE { NEW = 'NEW', OPENING = 'OPENING', OPEN = 'OPEN', CLOSING = 'CLOSING', CLOSED = 'CLOSED', } export class Position { private state: POSITION_STATE = POSITION_STATE.NEW private emitWalletAdjustment: EventBusEmitter<Adjustment> private orderEngine: OrderEngine private quoteEngine: QuoteEngine private wallet: Wallet private handleOnClose: () => void = null private eventBusNodes: { partial: EventBusNode complete: EventBusNode cancel: EventBusNode } = { partial: null, complete: null, cancel: null, } private eventListeners: { partial: () => void complete: () => void cancel: () => void } = { partial: null, complete: null, cancel: null, } private order: string = null private takeProfitFactor = 1.5 private limitOrderPriceOffset: number = null private lastSignal: SIGNAL = null private lastQuote: number = null private slPrice: number = null private tpPrice: number = null constructor(private readonly exchangeProvider: ExchangeProvider, private readonly strategyConfig: StrategyConfig) { const { exchange, symbol, strategy } = this.strategyConfig this.emitWalletAdjustment = eventBus.get(EVENT.WALLET_ADJUST)(exchange)(symbol)(strategy).emit this.eventBusNodes.partial = eventBus.get(EVENT.ORDER_PARTIAL)(exchange)(symbol)(strategy) this.eventBusNodes.complete = eventBus.get(EVENT.ORDER_COMPLETE)(exchange)(symbol)(strategy) this.eventBusNodes.cancel = eventBus.get(EVENT.ORDER_CANCEL)(exchange)(symbol)(strategy) this.orderEngine = new OrderEngine(this.exchangeProvider, this.strategyConfig) this.quoteEngine = new QuoteEngine(this.exchangeProvider, this.strategyConfig) this.wallet = WalletStore.instance.getWallet(strategyConfig) } processSignal(signal: SIGNAL, data?: Record<string, any>) { this.lastSignal = signal const { limitOrderPriceOffset } = data if (this.limitOrderPriceOffset === null) this.limitOrderPriceOffset = limitOrderPriceOffset switch (signal) { case SIGNAL.OPEN_LONG: if (this.state === POSITION_STATE.OPENING) return this.adjustOrder() if (this.state !== POSITION_STATE.NEW) break this.openLong() break case SIGNAL.OPEN_SHORT: if (this.state !== POSITION_STATE.NEW) break this.openShort() break case SIGNAL.CLOSE_LONG: if (this.state === POSITION_STATE.CLOSING) return this.adjustOrder() if (this.state !== POSITION_STATE.OPEN) break this.closeLong() break case SIGNAL.CLOSE_SHORT: if (this.state !== POSITION_STATE.OPEN) break this.closeShort() break } } onClose(fn: () => void) { this.handleOnClose = () => { this.order = null this.state = POSITION_STATE.CLOSED this.stopListen() this.handleOnClose = null fn() } } private async openLong() { const { exchange, symbol, strategy } = this.strategyConfig logger.info(`${exchange}.${symbol}.${strategy} opening new long position`) const quote = await this.quoteEngine.getBuyPrice() const price = this.exchangeProvider.priceToPrecision(exchange, symbol, quote) if (this.limitOrderPriceOffset) this.setEntryExitPrices(quote) const amount = this.getPurchasePower(price) const orderOpts: OrderOpts = { symbol, price, amount, type: 'limit', side: 'buy' } const order = await this.orderEngine.placeOrder(orderOpts) if (!order) return this.handleOnClose && this.handleOnClose() this.newOrderWalletAdjustment(order) this.state = POSITION_STATE.OPENING this.order = order.id logger.info(`${exchange}.${symbol}.${strategy}.${order.id} opened`) this.emitWalletAdjustment({ asset: 0, currency: -(amount * price), type: 'openLong' }) this.watchOrder(order) } private async closeLong(preQuote?: number) { const { exchange, symbol, strategy } = this.strategyConfig logger.info(`${exchange}.${symbol}.${strategy} closing long position`) const quote = preQuote ? preQuote : await this.quoteEngine.getSellPrice() const price = this.exchangeProvider.priceToPrecision(exchange, symbol, quote) const amount = this.exchangeProvider.amountToPrecision(this.wallet.asset) const orderOpts: OrderOpts = { symbol, price, amount, type: 'limit', side: 'sell' } const order = await this.orderEngine.placeOrder(orderOpts) if (!order) { await sleep(10) return this.closeLong() } this.order = order.id this.newOrderWalletAdjustment(order) this.state = POSITION_STATE.CLOSING this.emitWalletAdjustment({ asset: -this.wallet.asset, currency: 0, type: 'closeLong' }) this.watchOrder(order) } private openShort() { if (!this.strategyConfig.allowShorts) return // @todo(notVitaliy): Implement short selling } private closeShort() { // Do nothing } private async adjustOrder() { logger.debug(`Adjusting order`) await this.orderEngine.cancelOrder(this.order) if (this.state === POSITION_STATE.OPENING) return this.openLong() return this.closeLong() } private watchOrder(order: Order) { this.eventListeners.partial = this.eventBusNodes.partial(order.id).listen(this.onParial) this.eventListeners.complete = this.eventBusNodes.complete(order.id).listen(this.onComplete) this.eventListeners.cancel = this.eventBusNodes.cancel(order.id).listen(this.onCancel) this.orderEngine.checkOrder(order.id) } private newOrderWalletAdjustment(order: Order) { const adjustment = { asset: 0, currency: 0 } const type = order.side === 'buy' ? 'openLongFill' : 'closeLongFill' if (order.side === 'buy') adjustment.asset = order.filled else adjustment.currency = order.cost if (adjustment.asset || adjustment.currency) this.emitWalletAdjustment({ ...adjustment, type }) } private onParial = ({ savedOrder, update }: OnEventType) => { const adjustment = { asset: 0, currency: 0 } const type = update.side === 'buy' ? 'openLongFill' : 'closeLongFill' if (update.side === 'buy') adjustment.asset = update.filled - savedOrder.filled else adjustment.currency = update.cost - savedOrder.cost if (adjustment.asset || adjustment.currency) this.emitWalletAdjustment({ ...adjustment, type }) } private onComplete = async ({ savedOrder, update }: OnEventType) => { this.order = null this.onParial({ savedOrder, update }) this.stopListen() const { exchange, symbol, strategy } = this.strategyConfig logger.info(`${exchange}.${symbol}.${strategy}.${savedOrder.id} completed`) await this.getFees(update) if (savedOrder.side === 'sell') return this.handleOnClose() this.state = POSITION_STATE.OPEN this.checkPrice() // @todo(notVitaliy): Implement stop-loss / take-profits here } private onCancel = ({ savedOrder }: OnEventType) => { this.stopListen() const { exchange, symbol, strategy } = this.strategyConfig logger.info(`${exchange}.${symbol}.${strategy}.${savedOrder.id} canceled`) const { side, price, remaining } = savedOrder const currency = side === 'buy' ? price * remaining : 0 const asset = side === 'buy' ? 0 : remaining const adjustment = { asset, currency } this.emitWalletAdjustment({ ...adjustment, type: 'cancelOrder' }) if (!this.wallet.asset && this.handleOnClose) { this.handleOnClose() this.state = POSITION_STATE.CLOSED } } private stopListen() { Object.keys(this.eventListeners).forEach((key) => { if (!this.eventListeners[key]) return this.eventListeners[key]() this.eventListeners[key] = null }) } private getPurchasePower(price: number) { const { exchange, symbol } = this.strategyConfig const size = this.wallet.currency * ((Number(this.strategyConfig.sizePercent) || 5) / 100) const currency = this.exchangeProvider.priceToPrecision(exchange, symbol, size) return this.exchangeProvider.amountToPrecision(currency / price) } private setEntryExitPrices(quote: number) { this.lastQuote = quote this.slPrice = quote - this.limitOrderPriceOffset this.tpPrice = quote + this.limitOrderPriceOffset * this.takeProfitFactor console.log(this.tpPrice, this.slPrice, this.tpPrice - this.slPrice) } private async checkPrice() { if (this.state === POSITION_STATE.CLOSED) return const quote = await this.quoteEngine.getSellPrice() // Take profit hit but still in a buy signal trend. if (quote >= this.tpPrice && this.lastSignal !== SIGNAL.OPEN_LONG) return this.closeLong(quote) if (quote <= this.slPrice) return this.closeLong(quote) // // trailing stop-loss? // if (quote > this.lastQuote && this.lastSignal !== SIGNAL.OPEN_LONG && this.takeProfitFactor > 1) this.takeProfitFactor -= 0.01 // if (quote > this.lastQuote && this.lastSignal === SIGNAL.OPEN_LONG && this.takeProfitFactor > 1) this.setEntryExitPrices(quote) await sleep(5000) this.checkPrice() } private async getFees(order: Order) { const { exchange, symbol } = this.strategyConfig const trades = await this.exchangeProvider.getMyTrades(exchange, symbol) const orderTrades = trades.filter((trade) => trade.order === order.id) const totalFees = orderTrades.reduce( (acc, curr) => { if (!acc.cost) return { ...curr.fee } acc.cost += curr.fee.cost return acc }, { cost: null, currency: null } ) const [a] = symbol.split('/') const adjustment = { asset: 0, currency: 0 } if (totalFees.currency === a) adjustment.asset -= totalFees.cost else adjustment.currency -= totalFees.cost this.emitWalletAdjustment({ ...adjustment, type: 'fee' }) } }
the_stack
import { window } from "vscode"; import * as vscode from "vscode"; import { glo, IEditorInfo, IInLineInDepthDecorsRefs, infosOfControlledEditors, TyInLineInDepthInQueueInfo, TyOneFileEditorDecInfo, updateAllControlledEditors, } from "./extension"; import { getFullFileStats, renderLevels, tabsIntoSpaces } from "./utils"; import { doubleWidthCharsReg } from "./helpers/regex-main"; export const calculateColumnFromCharIndex = ( lineText: string, charIndex: number, tabSize: number, ): number => { let spacing = 0; for (let index = 0; index < charIndex; index++) { if (lineText.charAt(index) === "\t") { spacing += tabSize - (spacing % tabSize); } else { spacing++; } } return spacing; }; export const calculateCharIndexFromColumn = ( lineText: string, column: number, tabSize: number, ): number => { let spacing = 0; for (let index = 0; index <= column; index++) { if (spacing >= column) { return index; } if (lineText.charAt(index) === "\t") { spacing += tabSize - (spacing % tabSize); } else { spacing++; } } return spacing; }; export interface INotYetDisposedDec { dRef: vscode.TextEditorDecorationType; lineZero: number; // doc: vscode.TextDocument; } export interface INotYetDisposed { decs: INotYetDisposedDec[]; sameFirstElementCounter: number; firstDRef: vscode.TextEditorDecorationType | undefined; } export const notYetDisposedDecsObject: INotYetDisposed = { decs: [], sameFirstElementCounter: 0, firstDRef: undefined, }; export const nukeAllDecs = () => { // console.log("all nuke eeeeeeeeeeeeeeeeeeeeeeeee"); notYetDisposedDecsObject.decs.map((dec) => { dec.dRef.dispose(); }); notYetDisposedDecsObject.decs.length = 0; notYetDisposedDecsObject.decs = []; notYetDisposedDecsObject.sameFirstElementCounter = 0; notYetDisposedDecsObject.firstDRef = undefined; }; export let junkDecors3dArr: TyOneFileEditorDecInfo[] = []; // structure for optimization, not for decor history export const nukeJunkDecorations = () => { junkDecors3dArr.forEach((fileDecors) => { if (fileDecors) { fileDecors.forEach((lineDecors) => { if (lineDecors) { lineDecors.forEach((depthDecors) => { if (depthDecors) { depthDecors.forEach((inLineInDepthInQueueInfo) => { if (inLineInDepthInQueueInfo) { for (const key in inLineInDepthInQueueInfo.decorsRefs) { const decorRef = inLineInDepthInQueueInfo.decorsRefs[ key as keyof IInLineInDepthDecorsRefs ]; if (decorRef && decorRef !== "f") { decorRef.dispose(); // for memory leak prevention notYetDisposedDecsObject.decs = notYetDisposedDecsObject.decs.filter( (dec) => dec.dRef !== decorRef, ); } } } }); } }); } }); } }); junkDecors3dArr.length = 0; junkDecors3dArr = []; // OPTIMIZATION took very seriously: if (notYetDisposedDecsObject.decs.length >= 1) { if ( notYetDisposedDecsObject.firstDRef === notYetDisposedDecsObject.decs[0].dRef ) { notYetDisposedDecsObject.sameFirstElementCounter += 1; } else { notYetDisposedDecsObject.sameFirstElementCounter = 0; notYetDisposedDecsObject.firstDRef = notYetDisposedDecsObject.decs[0].dRef; } if (notYetDisposedDecsObject.sameFirstElementCounter > 100) { nukeAllDecs(); updateAllControlledEditors({ alsoStillVisibleAndHist: true }); } } }; interface IColorDecoratorItem { range: { start: { line: number; character: number; }; }; } export const colorDecorsToSpacesForFile = ( txt: string, editorInfo: IEditorInfo, ) => { const cDArr = editorInfo.colorDecoratorsArr; if (cDArr.length === 0) { return txt; } let textWithColorDecorSpaces = ""; let currSplitterIndex = 0; // const cDAlt = glo.trySupportDoubleWidthChars ? " " : " "; const cDAlt = " "; for (let i = 0; i < cDArr.length; i += 1) { const currSP = cDArr[i]; const g = currSP.cDGlobalIndexZeroInMonoText; textWithColorDecorSpaces += txt.slice(currSplitterIndex, g) + cDAlt; currSplitterIndex = g; } textWithColorDecorSpaces += txt.slice(currSplitterIndex, txt.length); return textWithColorDecorSpaces; }; export const getLastColIndexForLineWithColorDecSpaces = ( lineTxt: string, editorInfo: IEditorInfo, lineIndex: number, currLastColIndex: number, ) => { // return lineTxt; let withPlusOne = currLastColIndex + 1; const cDArr = editorInfo.colorDecoratorsArr; const filteredArr = cDArr.filter((x) => x.cDLineZero === lineIndex); if (filteredArr.length === 0) { return currLastColIndex; } const sortedArr = filteredArr.sort( (a, b) => a.cDGlobalIndexZeroInMonoText - b.cDGlobalIndexZeroInMonoText, ); const myCount = sortedArr.filter( (x) => x.cDCharZeroInMonoText <= withPlusOne, ).length; // for (let i = 0; i < sortedArr.length; i += 1) { // const currSP = sortedArr[i]; // const col = currSP.cDCharZeroInMonoText; // } return withPlusOne + myCount * 2 - 1; }; export const selectFocusedBlock = () => { const thisEditor = window.activeTextEditor; if (thisEditor) { const thisEditorInfo = infosOfControlledEditors.find( (x) => x.editorRef === thisEditor, ); if (thisEditorInfo) { const focus = thisEditorInfo.focusDuo.curr; if (focus) { const fDepth = focus.depth; const fIndexInDepth = focus.indexInTheDepth; const renderingInfoForFullFile = thisEditorInfo.renderingInfoForFullFile; if (fDepth >= 1 && renderingInfoForFullFile) { const masterLevels = renderingInfoForFullFile.masterLevels; const allit = renderingInfoForFullFile.allit; const theBlock = masterLevels[fDepth - 1][fIndexInDepth]; const rangeStart = allit[theBlock.s]; const rangeEnd = allit[theBlock.e]; const monoLineOfStart = thisEditorInfo.monoText.slice( thisEditorInfo.textLinesMap[rangeStart.lineZero], thisEditorInfo.textLinesMap[rangeStart.lineZero + 1], ); const monoLineOfEnd = thisEditorInfo.monoText.slice( thisEditorInfo.textLinesMap[rangeEnd.lineZero], thisEditorInfo.textLinesMap[rangeEnd.lineZero + 1], ); vscode.commands .executeCommand( "vscode.executeDocumentColorProvider", thisEditorInfo.editorRef.document.uri, ) .then((dataArr) => { // item.range.start.line, // item.range.start.character, let colorPosArr: IColorDecoratorItem[] = []; const arr = dataArr as | IColorDecoratorItem[] | undefined; if (arr && arr.length >= 1) { colorPosArr = arr.filter((x) => { return [ rangeStart.lineZero, rangeEnd.lineZero, ].includes(x.range.start.line); }); colorPosArr.sort( (a, b) => a.range.start.line - b.range.start.line, ); } const sArray = colorPosArr.filter( (x) => x.range.start.line === rangeStart.lineZero, ); const eArray = colorPosArr.filter( (x) => x.range.start.line === rangeEnd.lineZero, ); let countS = 0; let countE = 0; sArray.map((x) => { if ( x.range.start.character < rangeStart.inLineIndexZero ) { countS += 1; } }); eArray.map((x) => { if ( x.range.start.character < rangeEnd.inLineIndexZero ) { countE += 1; } }); const monoInLineIndexZeroOfStart = rangeStart.inLineIndexZero + 1 - 2 * countS; const monoInLineIndexZeroOfEnd = rangeEnd.inLineIndexZero - 2 * countE; const currDoc = thisEditorInfo.editorRef.document; const docLineOfStart = currDoc.lineAt( rangeStart.lineZero, ).text; const docLineOfEnd = currDoc.lineAt( rangeEnd.lineZero, ).text; let tabSize = thisEditorInfo.editorRef.options.tabSize; if (typeof tabSize !== "number") { tabSize = 4; } const docInLineCharZeroOfStart = calculateCharIndexFromColumn( docLineOfStart, monoInLineIndexZeroOfStart, tabSize, ); const docInLineCharZeroOfEnd = calculateCharIndexFromColumn( docLineOfEnd, monoInLineIndexZeroOfEnd, tabSize, ); const rangeAsArray: [ number, number, number, number, ] = [ rangeStart.lineZero, docInLineCharZeroOfStart, rangeEnd.lineZero, docInLineCharZeroOfEnd, ]; thisEditor.selection = new vscode.Selection( ...rangeAsArray, ); }); } } } } }; const generateInDepthIndexesOfEachDepthFromFocus = ( editorInfo: IEditorInfo, ): (number[] | null)[] | null => { // return type is (number[] | null)[] because number is the indexInDepth for each depth // all "null"s from depth0 to focus (excluded) // and all "number[]"s from Focus to inside const currFocusBlock = editorInfo.focusDuo.curr; if (!currFocusBlock) { return null; } const levels = editorInfo.renderingInfoForFullFile?.masterLevels; let my2dPath: number[][] = [[currFocusBlock.indexInTheDepth]]; if (!levels) { return null; } const superLevels = [[], ...levels]; for (let i = currFocusBlock.depth + 1; i <= glo.maxDepth + 3; i += 1) { const last1dInMyPath: number[] = my2dPath[my2dPath.length - 1]; if (superLevels[i] && superLevels[i].length) { const nextInnerIndexes: number[] = superLevels[i] .map((x, i) => { return { currI: i, outerI: x.outerIndexInOuterLevel, }; }) .filter((y) => { const outer = y.outerI; if ( typeof outer === "number" && last1dInMyPath.includes(outer) ) { return true; } return false; }) .map((x) => x.currI); if (nextInnerIndexes.length) { my2dPath.push(nextInnerIndexes); } else { break; } } else { break; } } // if (currFocusBlock.depth + 1 !== my2dPath.length + 1) { // return null; // } const starter: null[] = new Array(currFocusBlock.depth).fill(null); // not +1 because focus level is excluded const finalThing: (number[] | null)[] = [...starter, ...my2dPath]; // return [0, ...myPath]; return finalThing; }; const generateFocusTreePath = (editorInfo: IEditorInfo): number[] | null => { // return type is number[] because number is the indexInDepth for each depth from depth0 to Focus const currFocusBlock = editorInfo.focusDuo.curr; if (!currFocusBlock) { return null; } const levels = editorInfo.renderingInfoForFullFile?.masterLevels; let myPath: number[] = [currFocusBlock.indexInTheDepth]; // reversed if (!levels) { return null; } const superLevels = [[], ...levels]; // console.log("exla iwyeba curr outer", levels, currFocusBlock); for (let i = currFocusBlock.depth; i >= -3; i -= 1) { const firstInMyPath = myPath[0]; if (superLevels[i] && superLevels[i][firstInMyPath]) { const nextOuterIndex = superLevels[i][firstInMyPath].outerIndexInOuterLevel; if (typeof nextOuterIndex === "number") { myPath.unshift(nextOuterIndex); } else { break; } } else { break; } } if (currFocusBlock.depth + 1 !== myPath.length + 1) { return null; } return [0, ...myPath]; }; export const updateFocusInfo = (editorInfo: IEditorInfo) => { if (editorInfo.focusDuo.currIsFreezed) { return; } const thisEditorInfo = editorInfo; const thisEditor = editorInfo.editorRef; const textLinesMap = thisEditorInfo.textLinesMap; const cursorPos = thisEditor.selection.active; const focusedLineZeroInDoc = cursorPos.line; const focusedColumnZeroInDoc = cursorPos.character - 1; // console.log("focusedLineZeroInDoc:", focusedLineZeroInDoc); // console.log("focusedColumnZeroInDoc:", focusedColumnZeroInDoc); // thisEditor.document.lineAt(cursorPos).range.end.character; let globalIndexZero = -1; // if (focusedColumnZeroInDoc === -1) { // if (false) { // globalIndexZero = textLinesMap[focusedLineZeroInDoc] - 1 + 1; // } else { const lineTextInDocBeforeColumn = thisEditor.document .lineAt(cursorPos) .text.slice(0, focusedColumnZeroInDoc + 1); let lineMonoTextBeforeColumn = tabsIntoSpaces( lineTextInDocBeforeColumn, (thisEditor.options.tabSize as number) || 4, ); if (glo.trySupportDoubleWidthChars) { lineMonoTextBeforeColumn = lineMonoTextBeforeColumn.replace( doubleWidthCharsReg, "Z_", ); } // let tabSize = 4; // default // const fetchedTabSize = editorInfo.editorRef.options.tabSize; // if (fetchedTabSize && typeof fetchedTabSize === "number") { // tabSize = fetchedTabSize; // } let lastColIndex = lineMonoTextBeforeColumn.length - 1; if ( glo.colorDecoratorsInStyles && editorInfo.colorDecoratorsArr.length >= 1 ) { lastColIndex = getLastColIndexForLineWithColorDecSpaces( lineMonoTextBeforeColumn, editorInfo, focusedLineZeroInDoc, lastColIndex, ); } globalIndexZero = textLinesMap[focusedLineZeroInDoc] + lastColIndex; // } // gvaqvs globalIndexZero let candidate: { globalLength: number; depthMOeee: number; blockInd: number; } = { globalLength: 9999999999, depthMOeee: -1, blockInd: 0 }; const depths = thisEditorInfo.renderingInfoForFullFile?.masterLevels; const allit = thisEditorInfo.renderingInfoForFullFile?.allit; if (depths && allit) { // let zz_sGlobal: number = -7; // let zz_eGlobal: number = -7; // depthMOeee -> depth Minus One ->> eee // let breakDepthloop = false; for (let depthMOeee = 0; depthMOeee < depths.length; depthMOeee += 1) { for ( let blockInd = 0; blockInd < depths[depthMOeee].length; blockInd += 1 ) { const thisBlock = depths[depthMOeee][blockInd]; const sGlobal = allit[thisBlock.s].globalIndexZero; const eGlobal = allit[thisBlock.e].globalIndexZero; if ( sGlobal <= globalIndexZero && eGlobal > globalIndexZero && eGlobal - sGlobal < candidate.globalLength ) { candidate = { blockInd, depthMOeee: depthMOeee, globalLength: eGlobal - sGlobal, }; // zz_sGlobal = sGlobal; // zz_eGlobal = eGlobal; } } } // thisEditorInfo.focusedBlock = { // depth: candidate.depthMOeee, // index: candidate.blockInd, // }; const fDuo = thisEditorInfo.focusDuo; if (fDuo.curr) { fDuo.prev = { depth: fDuo.curr.depth, indexInTheDepth: fDuo.curr.indexInTheDepth, }; } else { fDuo.prev = null; } fDuo.curr = { depth: candidate.depthMOeee + 1, indexInTheDepth: candidate.blockInd, }; editorInfo.focusTreePath = generateFocusTreePath(editorInfo); editorInfo.innersFromFocus = generateInDepthIndexesOfEachDepthFromFocus(editorInfo); // console.log("currrrrrrrr", editorInfo.innersFromFocus); // console.log(editorInfo.renderingInfoForFullFile?.masterLevels); // console.log(editorInfo.renderingInfoForFullFile?.allit); } }; export interface IUpdateRender { editorInfo: IEditorInfo; timer: number; // milliseconds supMode?: "reparse" | "scroll" | "focus"; } export const updateRender = ({ editorInfo, timer, supMode }: IUpdateRender) => { if ( !glo.isOn || glo.blackListOfFileFormats.includes( editorInfo.editorRef.document.languageId, ) ) { if (editorInfo.decors.length > 0) { editorInfo.upToDateLines.upEdge = -1; editorInfo.upToDateLines.lowEdge = -1; junkDecors3dArr.push(editorInfo.decors); nukeJunkDecorations(); editorInfo.decors = []; editorInfo.needToAnalyzeFile = true; } return; } clearTimeout(editorInfo.timerForDo); // if (editorInfo.needToAnalyzeFile) { // timer = glo.renderTimerForChange; // } editorInfo.timerForDo = setTimeout(async () => { // console.log("<new cycle>"); if (glo.maxDepth <= -2) { editorInfo.upToDateLines.upEdge = -1; editorInfo.upToDateLines.lowEdge = -1; junkDecors3dArr.push(editorInfo.decors); nukeJunkDecorations(); editorInfo.decors = []; editorInfo.needToAnalyzeFile = true; return; } const visRanges = editorInfo.editorRef.visibleRanges; const firstVisLine = visRanges[0].start.line; const lastVisLine = visRanges[visRanges.length - 1].end.line; const firstLineZeroOfRender = firstVisLine - glo.renderIncBeforeAfterVisRange; const lastLineZeroOfRender = lastVisLine + glo.renderIncBeforeAfterVisRange; // -------------- // console.log("easy"); editorInfo.upToDateLines.upEdge = -1; editorInfo.upToDateLines.lowEdge = -1; junkDecors3dArr.push(editorInfo.decors); editorInfo.decors = []; if (editorInfo.needToAnalyzeFile) { // console.time("getFF"); editorInfo.renderingInfoForFullFile = await getFullFileStats({ editorInfo, }); // console.timeEnd("getFF"); } if (editorInfo.renderingInfoForFullFile) { editorInfo.needToAnalyzeFile = false; updateFocusInfo(editorInfo); // console.time("renderLevelsEasy"); renderLevels( editorInfo, firstLineZeroOfRender, lastLineZeroOfRender, ); // console.timeEnd("renderLevelsEasy"); } nukeJunkDecorations(); }, timer); // ms };
the_stack
export * from '././account'; export * from '././accounts'; export * from '././address'; export * from '././bankAccount'; export * from '././benefit'; export * from '././benefitLine'; export * from '././benefitObject'; export * from '././benefits'; export * from '././courtOrderLine'; export * from '././deduction'; export * from '././deductionLine'; export * from '././deductionObject'; export * from '././deductions'; export * from '././earningsLine'; export * from '././earningsOrder'; export * from '././earningsOrderObject'; export * from '././earningsOrders'; export * from '././earningsRate'; export * from '././earningsRateObject'; export * from '././earningsRates'; export * from '././earningsTemplate'; export * from '././earningsTemplateObject'; export * from '././employee'; export * from '././employeeLeave'; export * from '././employeeLeaveBalance'; export * from '././employeeLeaveBalances'; export * from '././employeeLeaveObject'; export * from '././employeeLeaveType'; export * from '././employeeLeaveTypeObject'; export * from '././employeeLeaveTypes'; export * from '././employeeLeaves'; export * from '././employeeObject'; export * from '././employeeOpeningBalances'; export * from '././employeeOpeningBalancesObject'; export * from '././employeePayTemplate'; export * from '././employeePayTemplateObject'; export * from '././employeePayTemplates'; export * from '././employeeStatutoryLeaveBalance'; export * from '././employeeStatutoryLeaveBalanceObject'; export * from '././employeeStatutoryLeaveSummary'; export * from '././employeeStatutoryLeavesSummaries'; export * from '././employeeStatutorySickLeave'; export * from '././employeeStatutorySickLeaveObject'; export * from '././employeeStatutorySickLeaves'; export * from '././employeeTax'; export * from '././employeeTaxObject'; export * from '././employees'; export * from '././employment'; export * from '././employmentObject'; export * from '././invalidField'; export * from '././leaveAccrualLine'; export * from '././leaveEarningsLine'; export * from '././leavePeriod'; export * from '././leavePeriods'; export * from '././leaveType'; export * from '././leaveTypeObject'; export * from '././leaveTypes'; export * from '././pagination'; export * from '././payRun'; export * from '././payRunCalendar'; export * from '././payRunCalendarObject'; export * from '././payRunCalendars'; export * from '././payRunObject'; export * from '././payRuns'; export * from '././paymentLine'; export * from '././paymentMethod'; export * from '././paymentMethodObject'; export * from '././payslip'; export * from '././payslipObject'; export * from '././payslips'; export * from '././problem'; export * from '././reimbursement'; export * from '././reimbursementLine'; export * from '././reimbursementObject'; export * from '././reimbursements'; export * from '././salaryAndWage'; export * from '././salaryAndWageObject'; export * from '././salaryAndWages'; export * from '././settings'; export * from '././statutoryDeduction'; export * from '././statutoryDeductionCategory'; export * from '././taxLine'; export * from '././timesheet'; export * from '././timesheetEarningsLine'; export * from '././timesheetLine'; export * from '././timesheetLineObject'; export * from '././timesheetObject'; export * from '././timesheets'; export * from '././trackingCategories'; export * from '././trackingCategory'; import localVarRequest = require('request'); import { Account } from '././account'; import { Accounts } from '././accounts'; import { Address } from '././address'; import { BankAccount } from '././bankAccount'; import { Benefit } from '././benefit'; import { BenefitLine } from '././benefitLine'; import { BenefitObject } from '././benefitObject'; import { Benefits } from '././benefits'; import { CourtOrderLine } from '././courtOrderLine'; import { Deduction } from '././deduction'; import { DeductionLine } from '././deductionLine'; import { DeductionObject } from '././deductionObject'; import { Deductions } from '././deductions'; import { EarningsLine } from '././earningsLine'; import { EarningsOrder } from '././earningsOrder'; import { EarningsOrderObject } from '././earningsOrderObject'; import { EarningsOrders } from '././earningsOrders'; import { EarningsRate } from '././earningsRate'; import { EarningsRateObject } from '././earningsRateObject'; import { EarningsRates } from '././earningsRates'; import { EarningsTemplate } from '././earningsTemplate'; import { EarningsTemplateObject } from '././earningsTemplateObject'; import { Employee } from '././employee'; import { EmployeeLeave } from '././employeeLeave'; import { EmployeeLeaveBalance } from '././employeeLeaveBalance'; import { EmployeeLeaveBalances } from '././employeeLeaveBalances'; import { EmployeeLeaveObject } from '././employeeLeaveObject'; import { EmployeeLeaveType } from '././employeeLeaveType'; import { EmployeeLeaveTypeObject } from '././employeeLeaveTypeObject'; import { EmployeeLeaveTypes } from '././employeeLeaveTypes'; import { EmployeeLeaves } from '././employeeLeaves'; import { EmployeeObject } from '././employeeObject'; import { EmployeeOpeningBalances } from '././employeeOpeningBalances'; import { EmployeeOpeningBalancesObject } from '././employeeOpeningBalancesObject'; import { EmployeePayTemplate } from '././employeePayTemplate'; import { EmployeePayTemplateObject } from '././employeePayTemplateObject'; import { EmployeePayTemplates } from '././employeePayTemplates'; import { EmployeeStatutoryLeaveBalance } from '././employeeStatutoryLeaveBalance'; import { EmployeeStatutoryLeaveBalanceObject } from '././employeeStatutoryLeaveBalanceObject'; import { EmployeeStatutoryLeaveSummary } from '././employeeStatutoryLeaveSummary'; import { EmployeeStatutoryLeavesSummaries } from '././employeeStatutoryLeavesSummaries'; import { EmployeeStatutorySickLeave } from '././employeeStatutorySickLeave'; import { EmployeeStatutorySickLeaveObject } from '././employeeStatutorySickLeaveObject'; import { EmployeeStatutorySickLeaves } from '././employeeStatutorySickLeaves'; import { EmployeeTax } from '././employeeTax'; import { EmployeeTaxObject } from '././employeeTaxObject'; import { Employees } from '././employees'; import { Employment } from '././employment'; import { EmploymentObject } from '././employmentObject'; import { InvalidField } from '././invalidField'; import { LeaveAccrualLine } from '././leaveAccrualLine'; import { LeaveEarningsLine } from '././leaveEarningsLine'; import { LeavePeriod } from '././leavePeriod'; import { LeavePeriods } from '././leavePeriods'; import { LeaveType } from '././leaveType'; import { LeaveTypeObject } from '././leaveTypeObject'; import { LeaveTypes } from '././leaveTypes'; import { Pagination } from '././pagination'; import { PayRun } from '././payRun'; import { PayRunCalendar } from '././payRunCalendar'; import { PayRunCalendarObject } from '././payRunCalendarObject'; import { PayRunCalendars } from '././payRunCalendars'; import { PayRunObject } from '././payRunObject'; import { PayRuns } from '././payRuns'; import { PaymentLine } from '././paymentLine'; import { PaymentMethod } from '././paymentMethod'; import { PaymentMethodObject } from '././paymentMethodObject'; import { Payslip } from '././payslip'; import { PayslipObject } from '././payslipObject'; import { Payslips } from '././payslips'; import { Problem } from '././problem'; import { Reimbursement } from '././reimbursement'; import { ReimbursementLine } from '././reimbursementLine'; import { ReimbursementObject } from '././reimbursementObject'; import { Reimbursements } from '././reimbursements'; import { SalaryAndWage } from '././salaryAndWage'; import { SalaryAndWageObject } from '././salaryAndWageObject'; import { SalaryAndWages } from '././salaryAndWages'; import { Settings } from '././settings'; import { StatutoryDeduction } from '././statutoryDeduction'; import { StatutoryDeductionCategory } from '././statutoryDeductionCategory'; import { TaxLine } from '././taxLine'; import { Timesheet } from '././timesheet'; import { TimesheetEarningsLine } from '././timesheetEarningsLine'; import { TimesheetLine } from '././timesheetLine'; import { TimesheetLineObject } from '././timesheetLineObject'; import { TimesheetObject } from '././timesheetObject'; import { Timesheets } from '././timesheets'; import { TrackingCategories } from '././trackingCategories'; import { TrackingCategory } from '././trackingCategory'; /* tslint:disable:no-unused-variable */ let primitives = [ "string", "boolean", "double", "integer", "long", "float", "number", "any" ]; let enumsMap: {[index: string]: any} = { "Account.TypeEnum": Account.TypeEnum, "Benefit.CategoryEnum": Benefit.CategoryEnum, "Benefit.CalculationTypeEnum": Benefit.CalculationTypeEnum, "Deduction.DeductionCategoryEnum": Deduction.DeductionCategoryEnum, "Deduction.CalculationTypeEnum": Deduction.CalculationTypeEnum, "EarningsRate.EarningsTypeEnum": EarningsRate.EarningsTypeEnum, "EarningsRate.RateTypeEnum": EarningsRate.RateTypeEnum, "Employee.GenderEnum": Employee.GenderEnum, "EmployeeLeaveType.ScheduleOfAccrualEnum": EmployeeLeaveType.ScheduleOfAccrualEnum, "EmployeeStatutoryLeaveBalance.LeaveTypeEnum": EmployeeStatutoryLeaveBalance.LeaveTypeEnum, "EmployeeStatutoryLeaveBalance.UnitsEnum": EmployeeStatutoryLeaveBalance.UnitsEnum, "EmployeeStatutoryLeaveSummary.TypeEnum": EmployeeStatutoryLeaveSummary.TypeEnum, "EmployeeStatutoryLeaveSummary.StatusEnum": EmployeeStatutoryLeaveSummary.StatusEnum, "EmployeeStatutorySickLeave.EntitlementFailureReasonsEnum": EmployeeStatutorySickLeave.EntitlementFailureReasonsEnum, "Employment.NiCategoryEnum": Employment.NiCategoryEnum, "LeavePeriod.PeriodStatusEnum": LeavePeriod.PeriodStatusEnum, "PayRun.PayRunStatusEnum": PayRun.PayRunStatusEnum, "PayRun.PayRunTypeEnum": PayRun.PayRunTypeEnum, "PayRun.CalendarTypeEnum": PayRun.CalendarTypeEnum, "PayRunCalendar.CalendarTypeEnum": PayRunCalendar.CalendarTypeEnum, "PaymentMethod.PaymentMethodEnum": PaymentMethod.PaymentMethodEnum, "Payslip.PaymentMethodEnum": Payslip.PaymentMethodEnum, "SalaryAndWage.StatusEnum": SalaryAndWage.StatusEnum, "SalaryAndWage.PaymentTypeEnum": SalaryAndWage.PaymentTypeEnum, "StatutoryDeductionCategory": StatutoryDeductionCategory, "Timesheet.StatusEnum": Timesheet.StatusEnum, } let typeMap: {[index: string]: any} = { "Account": Account, "Accounts": Accounts, "Address": Address, "BankAccount": BankAccount, "Benefit": Benefit, "BenefitLine": BenefitLine, "BenefitObject": BenefitObject, "Benefits": Benefits, "CourtOrderLine": CourtOrderLine, "Deduction": Deduction, "DeductionLine": DeductionLine, "DeductionObject": DeductionObject, "Deductions": Deductions, "EarningsLine": EarningsLine, "EarningsOrder": EarningsOrder, "EarningsOrderObject": EarningsOrderObject, "EarningsOrders": EarningsOrders, "EarningsRate": EarningsRate, "EarningsRateObject": EarningsRateObject, "EarningsRates": EarningsRates, "EarningsTemplate": EarningsTemplate, "EarningsTemplateObject": EarningsTemplateObject, "Employee": Employee, "EmployeeLeave": EmployeeLeave, "EmployeeLeaveBalance": EmployeeLeaveBalance, "EmployeeLeaveBalances": EmployeeLeaveBalances, "EmployeeLeaveObject": EmployeeLeaveObject, "EmployeeLeaveType": EmployeeLeaveType, "EmployeeLeaveTypeObject": EmployeeLeaveTypeObject, "EmployeeLeaveTypes": EmployeeLeaveTypes, "EmployeeLeaves": EmployeeLeaves, "EmployeeObject": EmployeeObject, "EmployeeOpeningBalances": EmployeeOpeningBalances, "EmployeeOpeningBalancesObject": EmployeeOpeningBalancesObject, "EmployeePayTemplate": EmployeePayTemplate, "EmployeePayTemplateObject": EmployeePayTemplateObject, "EmployeePayTemplates": EmployeePayTemplates, "EmployeeStatutoryLeaveBalance": EmployeeStatutoryLeaveBalance, "EmployeeStatutoryLeaveBalanceObject": EmployeeStatutoryLeaveBalanceObject, "EmployeeStatutoryLeaveSummary": EmployeeStatutoryLeaveSummary, "EmployeeStatutoryLeavesSummaries": EmployeeStatutoryLeavesSummaries, "EmployeeStatutorySickLeave": EmployeeStatutorySickLeave, "EmployeeStatutorySickLeaveObject": EmployeeStatutorySickLeaveObject, "EmployeeStatutorySickLeaves": EmployeeStatutorySickLeaves, "EmployeeTax": EmployeeTax, "EmployeeTaxObject": EmployeeTaxObject, "Employees": Employees, "Employment": Employment, "EmploymentObject": EmploymentObject, "InvalidField": InvalidField, "LeaveAccrualLine": LeaveAccrualLine, "LeaveEarningsLine": LeaveEarningsLine, "LeavePeriod": LeavePeriod, "LeavePeriods": LeavePeriods, "LeaveType": LeaveType, "LeaveTypeObject": LeaveTypeObject, "LeaveTypes": LeaveTypes, "Pagination": Pagination, "PayRun": PayRun, "PayRunCalendar": PayRunCalendar, "PayRunCalendarObject": PayRunCalendarObject, "PayRunCalendars": PayRunCalendars, "PayRunObject": PayRunObject, "PayRuns": PayRuns, "PaymentLine": PaymentLine, "PaymentMethod": PaymentMethod, "PaymentMethodObject": PaymentMethodObject, "Payslip": Payslip, "PayslipObject": PayslipObject, "Payslips": Payslips, "Problem": Problem, "Reimbursement": Reimbursement, "ReimbursementLine": ReimbursementLine, "ReimbursementObject": ReimbursementObject, "Reimbursements": Reimbursements, "SalaryAndWage": SalaryAndWage, "SalaryAndWageObject": SalaryAndWageObject, "SalaryAndWages": SalaryAndWages, "Settings": Settings, "StatutoryDeduction": StatutoryDeduction, "TaxLine": TaxLine, "Timesheet": Timesheet, "TimesheetEarningsLine": TimesheetEarningsLine, "TimesheetLine": TimesheetLine, "TimesheetLineObject": TimesheetLineObject, "TimesheetObject": TimesheetObject, "Timesheets": Timesheets, "TrackingCategories": TrackingCategories, "TrackingCategory": TrackingCategory, } export class ObjectSerializer { public static findCorrectType(data: any, expectedType: string) { if (data == undefined) { return expectedType; } else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) { return expectedType; } else if (expectedType === "Date") { return expectedType; } else { if (enumsMap[expectedType]) { return expectedType; } if (!typeMap[expectedType]) { return expectedType; // w/e we don't know the type } // Check the discriminator let discriminatorProperty = typeMap[expectedType].discriminator; if (discriminatorProperty == null) { return expectedType; // the type does not have a discriminator. use it. } else { if (data[discriminatorProperty]) { var discriminatorType = data[discriminatorProperty]; if(typeMap[discriminatorType]){ return discriminatorType; // use the type given in the discriminator } else { return expectedType; // discriminator did not map to a type } } else { return expectedType; // discriminator was not present (or an empty string) } } } } public static serialize(data: any, type: string) { if (data == undefined) { return data; } else if (primitives.indexOf(type.toLowerCase()) !== -1) { return data; } else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6 let subType: string = type.replace("Array<", ""); // Array<Type> => Type> subType = subType.substring(0, subType.length - 1); // Type> => Type let transformedData: any[] = []; for (let index in data) { let date = data[index]; transformedData.push(ObjectSerializer.serialize(date, subType)); } if(subType === 'string') { return transformedData.join(',') } else { return transformedData } } else if (type === "Date") { return data.toISOString(); } else { if (enumsMap[type]) { return data; } if (!typeMap[type]) { // in case we dont know the type return data; } // Get the actual type of this object type = this.findCorrectType(data, type); // get the map for the correct type. let attributeTypes = typeMap[type].getAttributeTypeMap(); let instance: {[index: string]: any} = {}; for (let index in attributeTypes) { let attributeType = attributeTypes[index]; instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type); } return instance; } } public static deserializeDateFormats(type: string, data: any) { const isDate = new Date(data) if (isNaN(isDate.getTime())) { const re = /-?\d+/; const m = re.exec(data); return new Date(parseInt(m[0], 10)); } else { return isDate } } public static deserialize(data: any, type: string) { // polymorphism may change the actual type. type = ObjectSerializer.findCorrectType(data, type); if (data == undefined) { return data; } else if (primitives.indexOf(type.toLowerCase()) !== -1) { if (type === "string" && data.toString().substring(0, 6) === "/Date(") { return this.deserializeDateFormats(type, data) // For MS dates that are of type 'string' } else { return data; } } else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6 let subType: string = type.replace("Array<", ""); // Array<Type> => Type> subType = subType.substring(0, subType.length - 1); // Type> => Type let transformedData: any[] = []; // Asset API returns string even for Array<Model> const dataFormatted = typeof data == 'string' ? JSON.parse(data) : data for (let index in dataFormatted) { let currentData = dataFormatted[index]; transformedData.push(ObjectSerializer.deserialize(currentData, subType)); } return transformedData; } else if (type === "Date") { return this.deserializeDateFormats(type, data) } else { if (enumsMap[type]) {// is Enum return data; } if (!typeMap[type]) { // dont know the type return data; } let instance = new typeMap[type](); let attributeTypes = typeMap[type].getAttributeTypeMap(); for (let index in attributeTypes) { let attributeType = attributeTypes[index]; instance[attributeType.name] = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type); } return instance; } } } export interface Authentication { /** * Apply authentication settings to header and query params. */ applyToRequest(requestOptions: localVarRequest.Options): Promise<void> | void; } export class HttpBasicAuth implements Authentication { public username: string = ''; public password: string = ''; applyToRequest(requestOptions: localVarRequest.Options): void { requestOptions.auth = { username: this.username, password: this.password } } } export class ApiKeyAuth implements Authentication { public apiKey: string = ''; constructor(private location: string, private paramName: string) { } applyToRequest(requestOptions: localVarRequest.Options): void { if (this.location == "query") { (<any>requestOptions.qs)[this.paramName] = this.apiKey; } else if (this.location == "header" && requestOptions && requestOptions.headers) { requestOptions.headers[this.paramName] = this.apiKey; } } } export class OAuth implements Authentication { public accessToken: string = ''; applyToRequest(requestOptions: localVarRequest.Options): void { if (requestOptions && requestOptions.headers) { requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; } } } export class VoidAuth implements Authentication { public username: string = ''; public password: string = ''; applyToRequest(_: localVarRequest.Options): void { // Do nothing } }
the_stack
import { assert } from "chai"; import * as buffer from "buffer"; import * as fs from "fs"; import * as path from "path"; import { PassThrough, Readable } from "stream"; import { AbortController } from "@azure/abort-controller"; import { createRandomLocalFile, recorderEnvSetup, bodyToString, getBSU, createRandomLocalFileWithTotalSize } from "../utils"; import { RetriableReadableStreamOptions } from "../../src/utils/RetriableReadableStream"; import { record, Recorder } from "@azure-tools/test-recorder"; import { ContainerClient, BlobClient, BlockBlobClient, BlobServiceClient } from "../../src"; import { readStreamToLocalFileWithLogs } from "../utils/testutils.node"; import { BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES } from "../../src/utils/constants"; import { Test_CPK_INFO } from "../utils/fakeTestSecrets"; import { streamToBuffer2 } from "../../src/utils/utils.node"; import { delay } from "../../src/utils/utils.common"; import { Context } from "mocha"; describe("Highlevel", () => { let containerName: string; let containerClient: ContainerClient; let blobName: string; let blobClient: BlobClient; let blockBlobClient: BlockBlobClient; let tempFileSmall: string; let tempFileSmallLength: number; let tempFileLarge: string; let tempFileLargeLength: number; const tempFolderPath = "temp"; const timeoutForLargeFileUploadingTest = 20 * 60 * 1000; let recorder: Recorder; let blobServiceClient: BlobServiceClient; beforeEach(async function(this: Context) { recorder = record(this, recorderEnvSetup); blobServiceClient = getBSU({ keepAliveOptions: { enable: true } }); containerName = recorder.getUniqueName("container"); containerClient = blobServiceClient.getContainerClient(containerName); await containerClient.create(); blobName = recorder.getUniqueName("blob"); blobClient = containerClient.getBlobClient(blobName); blockBlobClient = blobClient.getBlockBlobClient(); }); afterEach(async function(this: Context) { if (!this.currentTest?.isPending()) { await containerClient.delete(); await recorder.stop(); } }); before(async function(this: Context) { recorder = record(this, recorderEnvSetup); if (!fs.existsSync(tempFolderPath)) { fs.mkdirSync(tempFolderPath); } const MB = 1024 * 1024; tempFileLargeLength = 256 * MB + 1; // First prime number after 256MB. tempFileLarge = await createRandomLocalFileWithTotalSize( tempFolderPath, tempFileLargeLength, MB ); tempFileSmallLength = 4 * MB + 37; // First prime number after 4MB. tempFileSmall = await createRandomLocalFileWithTotalSize( tempFolderPath, tempFileSmallLength, MB ); await recorder.stop(); }); after(async function(this: Context) { recorder = record(this, recorderEnvSetup); fs.unlinkSync(tempFileLarge); fs.unlinkSync(tempFileSmall); await recorder.stop(); }); it("put blob with maximum size", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); const MB = 1024 * 1024; const maxPutBlobSizeLimitInMB = 5000; const tempFile = await createRandomLocalFile(tempFolderPath, maxPutBlobSizeLimitInMB, MB); const inputStream = fs.createReadStream(tempFile); try { await blockBlobClient.upload(() => inputStream, maxPutBlobSizeLimitInMB * MB, { abortSignal: AbortController.timeout(20 * 1000) // takes too long to upload the file }); } catch (err) { assert.equal(err.name, "AbortError"); } fs.unlinkSync(tempFile); }).timeout(timeoutForLargeFileUploadingTest); it("uploadFile should success when blob >= BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); await blockBlobClient.uploadFile(tempFileLarge, { blockSize: 4 * 1024 * 1024, concurrency: 20 }); const downloadResponse = await blockBlobClient.download(0); const downloadedFile = path.join(tempFolderPath, recorder.getUniqueName("downloadfile.")); await readStreamToLocalFileWithLogs(downloadResponse.readableStreamBody!, downloadedFile); const downloadedData = await fs.readFileSync(downloadedFile); const uploadedData = await fs.readFileSync(tempFileLarge); fs.unlinkSync(downloadedFile); assert.ok(downloadedData.equals(uploadedData)); }).timeout(timeoutForLargeFileUploadingTest); it("uploadFile should work with tags", async function() { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); const tags = { tag1: "val1", tag2: "val2" }; await blockBlobClient.uploadFile(tempFileSmall, { blockSize: 4 * 1024 * 1024, concurrency: 20, tags }); const response = await blockBlobClient.getTags(); assert.deepStrictEqual(response.tags, tags); }); it("uploadFile should success when blob < BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); await blockBlobClient.uploadFile(tempFileSmall, { blockSize: 4 * 1024 * 1024, concurrency: 20 }); const downloadResponse = await blockBlobClient.download(0); const downloadedFile = path.join(tempFolderPath, recorder.getUniqueName("downloadfile.")); await readStreamToLocalFileWithLogs(downloadResponse.readableStreamBody!, downloadedFile); const downloadedData = await fs.readFileSync(downloadedFile); const uploadedData = await fs.readFileSync(tempFileSmall); fs.unlinkSync(downloadedFile); assert.ok(downloadedData.equals(uploadedData)); }); it("uploadFile should success when blob < BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES and configured maxSingleShotSize", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); await blockBlobClient.uploadFile(tempFileSmall, { maxSingleShotSize: 0 }); const downloadResponse = await blockBlobClient.download(0); const downloadedFile = path.join(tempFolderPath, recorder.getUniqueName("downloadfile.")); await readStreamToLocalFileWithLogs(downloadResponse.readableStreamBody!, downloadedFile); const downloadedData = await fs.readFileSync(downloadedFile); const uploadedData = await fs.readFileSync(tempFileSmall); fs.unlinkSync(downloadedFile); assert.ok(downloadedData.equals(uploadedData)); }); it("uploadFile should abort when blob >= BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES", async () => { const aborter = AbortController.timeout(1); try { await blockBlobClient.uploadFile(tempFileLarge, { abortSignal: aborter, blockSize: 4 * 1024 * 1024, concurrency: 20 }); assert.fail(); } catch (err) { assert.equal(err.name, "AbortError"); } }); it("uploadFile should abort when blob < BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES", async () => { const aborter = AbortController.timeout(1); try { await blockBlobClient.uploadFile(tempFileSmall, { abortSignal: aborter, blockSize: 4 * 1024 * 1024, concurrency: 20 }); assert.fail(); } catch (err) { assert.equal(err.name, "AbortError"); } }); it("uploadFile should update progress when blob >= BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES", async () => { recorder.skip( "node", "Abort - Recorder does not record a request if it's aborted in a 'progress' callback" ); let eventTriggered = false; const aborter = new AbortController(); /* eslint no-empty: ["error", { "allowEmptyCatch": true }] */ try { await blockBlobClient.uploadFile(tempFileLarge, { abortSignal: aborter.signal, blockSize: 4 * 1024 * 1024, concurrency: 20, onProgress: (ev) => { assert.ok(ev.loadedBytes); eventTriggered = true; aborter.abort(); } }); } catch (err) {} assert.ok(eventTriggered); }); it("uploadFile should update progress when blob < BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES", async () => { recorder.skip( "node", "Abort - Recorder does not record a request if it's aborted in a 'progress' callback" ); let eventTriggered = false; const aborter = new AbortController(); /* eslint no-empty: ["error", { "allowEmptyCatch": true }] */ try { await blockBlobClient.uploadFile(tempFileSmall, { abortSignal: aborter.signal, blockSize: 4 * 1024 * 1024, concurrency: 20, onProgress: (ev) => { assert.ok(ev.loadedBytes); eventTriggered = true; aborter.abort(); } }); } catch (err) {} assert.ok(eventTriggered); }); it("uploadFile should succeed with blockSize = BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); const tempFile = await createRandomLocalFile( tempFolderPath, BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES / (1024 * 1024) + 1, 1024 * 1024 ); try { await blockBlobClient.uploadFile(tempFile, { blockSize: BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES, abortSignal: AbortController.timeout(20 * 1000) // takes too long to upload the file }); } catch (err) { assert.equal(err.name, "AbortError"); } fs.unlinkSync(tempFile); }).timeout(timeoutForLargeFileUploadingTest); it("uploadStream should success", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); const rs = fs.createReadStream(tempFileLarge); await blockBlobClient.uploadStream(rs, 4 * 1024 * 1024, 20); const downloadResponse = await blockBlobClient.download(0); const downloadFilePath = path.join(tempFolderPath, recorder.getUniqueName("downloadFile")); await readStreamToLocalFileWithLogs(downloadResponse.readableStreamBody!, downloadFilePath); const downloadedBuffer = fs.readFileSync(downloadFilePath); const uploadedBuffer = fs.readFileSync(tempFileLarge); assert.ok(uploadedBuffer.equals(downloadedBuffer)); fs.unlinkSync(downloadFilePath); }).timeout(timeoutForLargeFileUploadingTest); it("uploadStream should success for tiny buffers", async () => { recorder.skip( undefined, "UUID is randomly generated within the SDK and used in the HTTP request and cannot be preserved." ); const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); const bufferStream = new PassThrough(); bufferStream.end(buf); await blockBlobClient.uploadStream(bufferStream, 4 * 1024 * 1024, 20); const downloadResponse = await blockBlobClient.download(0); const downloadBuffer = Buffer.allocUnsafe(buf.byteLength); await streamToBuffer2(downloadResponse.readableStreamBody!, downloadBuffer); assert.ok(buf.equals(downloadBuffer)); }); it("uploadStream should work with tags", async function() { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); const bufferStream = new PassThrough(); bufferStream.end(buf); const tags = { tag1: "val1", tag2: "val2" }; await blockBlobClient.uploadStream(bufferStream, 4 * 1024 * 1024, 20, { tags }); const response = await blockBlobClient.getTags(); assert.deepStrictEqual(response.tags, tags); }); it("uploadStream should abort", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); const rs = fs.createReadStream(tempFileLarge); const aborter = AbortController.timeout(1); try { await blockBlobClient.uploadStream(rs, 4 * 1024 * 1024, 20, { abortSignal: aborter }); assert.fail(); } catch (err) { assert.equal(err.name, "AbortError"); } }); it("uploadStream should update progress event", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); const rs = fs.createReadStream(tempFileLarge); let eventTriggered = false; await blockBlobClient.uploadStream(rs, 4 * 1024 * 1024, 20, { onProgress: (ev) => { assert.ok(ev.loadedBytes); eventTriggered = true; } }); assert.ok(eventTriggered); }).timeout(timeoutForLargeFileUploadingTest); it("uploadStream should work with empty data", async () => { const emptyReadable = new Readable(); emptyReadable.push(null); await blockBlobClient.uploadStream(emptyReadable, 1024, 10); const downloadResponse = await blockBlobClient.download(0); const data = await bodyToString(downloadResponse); assert.deepStrictEqual(data, ""); }); // Skipped due to memory limitation of the testing VM. This was failing in the "Windows Node 10" testing environment. it.skip( "uploadStream should work when blockSize = BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); const tempFile = await createRandomLocalFile( tempFolderPath, BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES / (1024 * 1024) + 1, 1024 * 1024 ); const rs = fs.createReadStream(tempFile); try { // abort as it may take too long, will cover the data integrity validation with manual large scale tests await blockBlobClient.uploadStream(rs, BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES, undefined, { abortSignal: AbortController.timeout(timeoutForLargeFileUploadingTest / 10) }); } catch (err) { assert.equal(err.name, "AbortError"); } fs.unlinkSync(tempFile); } ).timeout(timeoutForLargeFileUploadingTest); it("downloadToBuffer should success - without passing the buffer", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); const rs = fs.createReadStream(tempFileLarge); await blockBlobClient.uploadStream(rs, 4 * 1024 * 1024, 20); const buf = await blockBlobClient.downloadToBuffer(0, undefined, { blockSize: 4 * 1024 * 1024, maxRetryRequestsPerBlock: 5, concurrency: 20 }); const localFileContent = fs.readFileSync(tempFileLarge); assert.ok(localFileContent.equals(buf)); }).timeout(timeoutForLargeFileUploadingTest); it("downloadToBuffer should throw error if the count(size provided in bytes) is too large", async () => { let error; try { // casting to "any" is required since @types/node@8 doesn't have `constants` though it is present on the `buffer`, // "as any" can be removed once we move from @types/node v8 to v10 await blockBlobClient.downloadToBuffer(undefined, (buffer as any).constants.MAX_LENGTH + 1); } catch (err) { error = err; } assert.ok( error.message.includes("Unable to allocate the buffer of size:"), "Error is not thrown when the count(size provided in bytes) is too large." ); }); it("downloadToBuffer should success", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); const rs = fs.createReadStream(tempFileLarge); await blockBlobClient.uploadStream(rs, 4 * 1024 * 1024, 20); const buf = Buffer.alloc(tempFileLargeLength); await blockBlobClient.downloadToBuffer(buf, 0, undefined, { blockSize: 4 * 1024 * 1024, maxRetryRequestsPerBlock: 5, concurrency: 20 }); const localFileContent = fs.readFileSync(tempFileLarge); assert.ok(localFileContent.equals(buf)); }).timeout(timeoutForLargeFileUploadingTest); it("downloadBlobToBuffer should success when downloading a range inside blob", async () => { await blockBlobClient.upload("aaaabbbb", 8); const buf = Buffer.alloc(4); await blockBlobClient.downloadToBuffer(buf, 4, 4, { blockSize: 4, maxRetryRequestsPerBlock: 5, concurrency: 1 }); assert.deepStrictEqual(buf.toString(), "bbbb"); await blockBlobClient.downloadToBuffer(buf, 3, 4, { blockSize: 4, maxRetryRequestsPerBlock: 5, concurrency: 1 }); assert.deepStrictEqual(buf.toString(), "abbb"); await blockBlobClient.downloadToBuffer(buf, 2, 4, { blockSize: 4, maxRetryRequestsPerBlock: 5, concurrency: 1 }); assert.deepStrictEqual(buf.toString(), "aabb"); await blockBlobClient.downloadToBuffer(buf, 1, 4, { blockSize: 4, maxRetryRequestsPerBlock: 5, concurrency: 1 }); assert.deepStrictEqual(buf.toString(), "aaab"); }); it("downloadToBuffer should abort", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); const rs = fs.createReadStream(tempFileLarge); await blockBlobClient.uploadStream(rs, 4 * 1024 * 1024, 20); try { const buf = Buffer.alloc(tempFileLargeLength); await blockBlobClient.downloadToBuffer(buf, 0, undefined, { abortSignal: AbortController.timeout(1), blockSize: 4 * 1024 * 1024, maxRetryRequestsPerBlock: 5, concurrency: 20 }); assert.fail(); } catch (err) { assert.equal(err.name, "AbortError"); } }).timeout(timeoutForLargeFileUploadingTest); it("downloadToBuffer should update progress event", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); const rs = fs.createReadStream(tempFileSmall); await blockBlobClient.uploadStream(rs, 4 * 1024 * 1024, 10); let eventTriggered = false; const buf = Buffer.alloc(tempFileSmallLength); const aborter = new AbortController(); /* eslint no-empty: ["error", { "allowEmptyCatch": true }] */ try { await blockBlobClient.downloadToBuffer(buf, 0, undefined, { abortSignal: aborter.signal, blockSize: 1 * 1024, maxRetryRequestsPerBlock: 5, concurrency: 1, onProgress: () => { eventTriggered = true; aborter.abort(); } }); } catch (err) {} assert.ok(eventTriggered); }); it("downloadToBuffer with CPK", async () => { const content = "Hello World"; const CPKblobName = recorder.getUniqueName("blobCPK"); const CPKblobClient = containerClient.getBlobClient(CPKblobName); const CPKblockBlobClient = CPKblobClient.getBlockBlobClient(); await CPKblockBlobClient.upload(content, content.length, { customerProvidedKey: Test_CPK_INFO }); const downloadToBufferRes = await CPKblockBlobClient.downloadToBuffer(undefined, undefined, { customerProvidedKey: Test_CPK_INFO }); assert.ok(downloadToBufferRes.equals(Buffer.from(content))); let exceptionCaught = false; try { await CPKblobClient.downloadToBuffer(); } catch (err) { assert.equal(err.details.errorCode, "BlobUsesCustomerSpecifiedEncryption"); exceptionCaught = true; } assert.ok(exceptionCaught); }); it("blobclient.download should success when internal stream unexpected ends at the stream end", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); const uploadResponse = await blockBlobClient.uploadFile(tempFileSmall, { blockSize: 4 * 1024 * 1024, concurrency: 20 }); /* eslint-disable prefer-const */ let retirableReadableStreamOptions: RetriableReadableStreamOptions; const downloadResponse = await blockBlobClient.download(0, undefined, { conditions: { ifMatch: uploadResponse.etag }, maxRetryRequests: 1, onProgress: (ev) => { if (ev.loadedBytes >= tempFileSmallLength) { retirableReadableStreamOptions.doInjectErrorOnce = true; } } }); retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any).options; /* eslint-enable prefer-const */ const downloadedFile = path.join(tempFolderPath, recorder.getUniqueName("downloadfile.")); await readStreamToLocalFileWithLogs(downloadResponse.readableStreamBody!, downloadedFile); const downloadedData = await fs.readFileSync(downloadedFile); const uploadedData = await fs.readFileSync(tempFileSmall); fs.unlinkSync(downloadedFile); assert.ok(downloadedData.equals(uploadedData)); }); it("blobclient.download should download full data successfully when internal stream unexpected ends", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); const uploadResponse = await blockBlobClient.uploadFile(tempFileSmall, { blockSize: 4 * 1024 * 1024, concurrency: 20 }); /* eslint-disable prefer-const */ let retirableReadableStreamOptions: RetriableReadableStreamOptions; let injectedErrors = 0; const downloadResponse = await blockBlobClient.download(0, undefined, { conditions: { ifMatch: uploadResponse.etag }, maxRetryRequests: 3, onProgress: () => { if (injectedErrors++ < 3) { retirableReadableStreamOptions.doInjectErrorOnce = true; } } }); retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any).options; /* eslint-enable prefer-const */ const downloadedFile = path.join(tempFolderPath, recorder.getUniqueName("downloadfile.")); await readStreamToLocalFileWithLogs(downloadResponse.readableStreamBody!, downloadedFile); const downloadedData = await fs.readFileSync(downloadedFile); const uploadedData = await fs.readFileSync(tempFileSmall); fs.unlinkSync(downloadedFile); assert.ok(downloadedData.equals(uploadedData)); }); it("blobclient.download should download partial data when internal stream unexpected ends", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); const uploadResponse = await blockBlobClient.uploadFile(tempFileSmall, { blockSize: 4 * 1024 * 1024, concurrency: 20 }); const partialSize = 500 * 1024; /* eslint-disable prefer-const */ let retirableReadableStreamOptions: RetriableReadableStreamOptions; let injectedErrors = 0; const downloadResponse = await blockBlobClient.download(0, partialSize, { conditions: { ifMatch: uploadResponse.etag }, maxRetryRequests: 3, onProgress: () => { if (injectedErrors++ < 3) { retirableReadableStreamOptions.doInjectErrorOnce = true; } } }); retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any).options; /* eslint-enable prefer-const */ const downloadedFile = path.join(tempFolderPath, recorder.getUniqueName("downloadfile.")); await readStreamToLocalFileWithLogs(downloadResponse.readableStreamBody!, downloadedFile); const downloadedData = await fs.readFileSync(downloadedFile); const uploadedData = await fs.readFileSync(tempFileSmall); fs.unlinkSync(downloadedFile); assert.ok(downloadedData.slice(0, partialSize).equals(uploadedData.slice(0, partialSize))); }); it("blobclient.download should download data failed when exceeding max stream retry requests", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); const uploadResponse = await blockBlobClient.uploadFile(tempFileSmall, { blockSize: 4 * 1024 * 1024, concurrency: 20 }); const downloadedFile = path.join(tempFolderPath, recorder.getUniqueName("downloadfile.")); let retirableReadableStreamOptions: RetriableReadableStreamOptions; let injectedErrors = 0; let expectedError = false; try { const downloadResponse = await blockBlobClient.download(0, undefined, { conditions: { ifMatch: uploadResponse.etag }, maxRetryRequests: 0, onProgress: () => { if (injectedErrors++ < 1) { retirableReadableStreamOptions.doInjectErrorOnce = true; } } }); retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any).options; await readStreamToLocalFileWithLogs(downloadResponse.readableStreamBody!, downloadedFile); } catch (error) { expectedError = true; } assert.ok(expectedError); fs.unlinkSync(downloadedFile); }); it("blobclient.download should abort after retries", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); const uploadResponse = await blockBlobClient.uploadFile(tempFileSmall, { blockSize: 4 * 1024 * 1024, concurrency: 20 }); const downloadedFile = path.join(tempFolderPath, recorder.getUniqueName("downloadfile.")); let retirableReadableStreamOptions: RetriableReadableStreamOptions; let injectedErrors = 0; let expectedError = false; try { const aborter = new AbortController(); const downloadResponse = await blockBlobClient.download(0, undefined, { abortSignal: aborter.signal, conditions: { ifMatch: uploadResponse.etag }, maxRetryRequests: 3, onProgress: () => { if (injectedErrors++ < 2) { // Trigger 2 times of retry retirableReadableStreamOptions.doInjectErrorOnce = true; } else { // Trigger aborter aborter.abort(); } } }); retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any).options; await readStreamToLocalFileWithLogs(downloadResponse.readableStreamBody!, downloadedFile); } catch (error) { expectedError = true; } assert.ok(expectedError); fs.unlinkSync(downloadedFile); }); it("download abort should work when still fetching body", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); await blockBlobClient.uploadFile(tempFileSmall, { blockSize: 4 * 1024 * 1024, concurrency: 20 }); const aborter = new AbortController(); const res = await blobClient.download(0, undefined, { abortSignal: aborter.signal }); let exceptionCaught = false; res.readableStreamBody!.on("error", (err) => { assert.equal(err.name, "AbortError"); exceptionCaught = true; }); aborter.abort(); await delay(10); assert.ok(exceptionCaught); }); it("downloadToFile should success", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); const downloadedFilePath = recorder.getUniqueName("downloadedtofile."); const rs = fs.createReadStream(tempFileSmall); await blockBlobClient.uploadStream(rs, 4 * 1024 * 1024, 20); const response = await blobClient.downloadToFile(downloadedFilePath, 0, undefined); assert.ok( response.contentLength === tempFileSmallLength, "response.contentLength doesn't match tempFileSmallLength" ); assert.equal( response.readableStreamBody, undefined, "Expecting response.readableStreamBody to be undefined." ); const localFileContent = fs.readFileSync(tempFileSmall); const downloadedFileContent = fs.readFileSync(downloadedFilePath); assert.ok(localFileContent.equals(downloadedFileContent)); fs.unlinkSync(downloadedFilePath); }); it("downloadToFile should fail when saving to directory", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); const rs = fs.createReadStream(tempFileSmall); await blockBlobClient.uploadStream(rs, 4 * 1024 * 1024, 20); try { await blobClient.downloadToFile(__dirname); throw new Error("Test failure."); } catch (err) { assert.notEqual(err.message, "Test failure."); } }); it("set tier while upload", async () => { recorder.skip("node", "Temp file - recorder doesn't support saving the file"); // single upload await blockBlobClient.uploadFile(tempFileSmall, { tier: "Hot", maxSingleShotSize: 256 * 1024 * 1024 }); assert.equal((await blockBlobClient.getProperties()).accessTier, "Hot"); await blockBlobClient.uploadFile(tempFileSmall, { tier: "Cool", maxSingleShotSize: 4 * 1024 * 1024 }); assert.equal((await blockBlobClient.getProperties()).accessTier, "Cool"); await blockBlobClient.uploadStream(fs.createReadStream(tempFileSmall), undefined, undefined, { tier: "Hot" }); assert.equal((await blockBlobClient.getProperties()).accessTier, "Hot"); }); it("uploadData should work with Buffer, ArrayBuffer and ArrayBufferView", async () => { const byteLength = 10; const arrayBuf = new ArrayBuffer(byteLength); const uint8Array = new Uint8Array(arrayBuf); for (let i = 0; i < byteLength; i++) { uint8Array[i] = i; } await blockBlobClient.uploadData(arrayBuf); const res = await blockBlobClient.downloadToBuffer(); assert.ok(res.equals(Buffer.from(arrayBuf))); const uint8ArrayPartial = new Uint8Array(arrayBuf, 1, 3); await blockBlobClient.uploadData(uint8ArrayPartial); const res1 = await blockBlobClient.downloadToBuffer(); assert.ok(res1.equals(Buffer.from(arrayBuf, 1, 3))); const uint16Array = new Uint16Array(arrayBuf, 4, 2); await blockBlobClient.uploadData(uint16Array); const res2 = await blockBlobClient.downloadToBuffer(); assert.ok(res2.equals(Buffer.from(arrayBuf, 4, 2 * 2))); const buf = Buffer.from(arrayBuf, 0, 5); await blockBlobClient.uploadData(buf); const res3 = await blockBlobClient.downloadToBuffer(); assert.ok(res3.equals(buf)); }); });
the_stack
import {BacklogClient, BacklogClientImpl, GoogleAppsScriptDateFormatter} from "./BacklogClient" import {Key, Project, Issue, BacklogDefinition, Locale, UserProperty, CustomFieldDefinition, IssueType, isSupportedCustomField} from "./datas" import {HttpClient} from "./Http" import {Option, Some, None} from "./Option" import {Either, Right, Left} from "./Either" import {createIssueConverter} from "./IssueConverter" import {List, isEmptyList, find} from "./List" import {Message} from "./resources" import {SpreadSheetService} from "./SpreadSheetService" const TEMPLATE_SHEET_NAME = "Template" const ROW_HEADER_INDEX = 1 const COLUMN_START_INDEX = 1 /** データ列の開始インデックス */ const ROW_START_INDEX = 2 /** データ行の開始インデックス */ const DEFAULT_COLUMN_LENGTH = 16 const MAX_LIST_ITEM_COUNT = 500 type Validation<A> = (a: A, onError: Error) => Either<Error, A> const isEmpty: Validation<string> = (str: string, onError: Error): Either<Error, string> => str !== "" ? Right(str) : Left(onError) const slice = <A>(items: A[]): A[] => items.slice(0, MAX_LIST_ITEM_COUNT - 1) const createBacklogClient = (space: string, domain: string, apiKey: string, locale: Locale): Either<Error, BacklogClient> => { const spaceResult = isEmpty(space, Error(Message.SPACE_URL_REQUIRED(locale))) const apiKeyResult = isEmpty(apiKey, Error(Message.API_KEY_REQUIRED(locale))) return Either.map2(spaceResult, apiKeyResult, (s, a) => { return Right(new BacklogClientImpl(new HttpClient, s, domain, a, new GoogleAppsScriptDateFormatter)) }) } export const getProject = (client: BacklogClient, key: Key<Project>, locale: Locale): Either<Error, Project> => { const validationResult = isEmpty(key, Error(Message.PROJECT_KEY_REQUIRED(locale))) const clientResult = client.getProjectV2(key).recover(error => { if (error.message.indexOf("returned code 404") !== -1) return Left(Error(Message.SPACE_OR_PROJECT_NOT_FOUND(locale))) if (error.message.indexOf("returned code 401") !== -1) return Left(Error(Message.AUTHENTICATE_FAILED(locale))) return Left(Error(Message.API_ACCESS_ERROR(error, locale))) }) return Either.map2(validationResult, clientResult, (_, project) => Right(project)) } const validate = (issues: List<any>, issueTypes: List<IssueType>, customFieldDefinitions: List<CustomFieldDefinition>, client: BacklogClient, locale: Locale): Either<Error, boolean> => { for (let i = 0; i < customFieldDefinitions.length; i++) { const definition = customFieldDefinitions[i] if (definition.required && !isSupportedCustomField(definition)) return Left(Error(Message.VALIDATE_CUSTOM_FIELD_VALUE_IS_REQUIRED_UNSUPPORTED(definition.name, locale))) } const definitions = customFieldDefinitions.filter(item => isSupportedCustomField(item)) for (let i = 0; i < issues.length; i++) { const issue = issues[i] const errorString = Message.VALIDATE_ERROR_LINE(i + 2, locale) const customFields = issue["customFields"] as List<any> if (!Option(issue.summary).isDefined) return Left(Error(errorString + Message.VALIDATE_SUMMARY_EMPTY(locale))) if (!Option(issue.issueTypeName).isDefined) return Left(Error(errorString + Message.VALIDATE_ISSUE_TYPE_EMPTY(locale))) if (issue.parentIssueKey !== undefined && issue.parentIssueKey !== "*") if (!client.getIssueV2(issue.parentIssueKey).isDefined) return Left(Error(errorString + Message.VALIDATE_PARENT_ISSUE_KEY_NOT_FOUND(issue.parentIssueKey, locale))) for (let j = 0; j < definitions.length; j++) { const definition = definitions[j] const customField = customFields[j] if (definition.required && isEmptyList(definition.applicableIssueTypes) && customField.value === undefined) return Left(Error(errorString + Message.VALIDATE_CUSTOM_FIELD_VALUE_IS_REQUIRED(definition.name, locale))) if (definition.required && customField.value === undefined) { for (let k = 0; k < definition.applicableIssueTypes.length; k++) { const issueTypeId = definition.applicableIssueTypes[k] const issueTypeDefinition = find( (issueType: IssueType) => issueType.name === issue.issueTypeName, issueTypes ).orError(Error(`Issue type name not found. Name: ${issue.issueTypeName}`)).getOrError() if (issueTypeDefinition.id === issueTypeId) return Left(Error(errorString + Message.VALIDATE_CUSTOM_FIELD_VALUE_IS_REQUIRED_ISSUE_TYPE(definition.name, issueTypeDefinition, locale))) } } if (customField.value === undefined) continue switch (definition.typeId) { case 3: if (typeof customField.value !== "number") return Left(Error(errorString + Message.VALIDATE_CUSTOM_FIELD_VALUE_IS_NUMBER(definition.name, customField.value, locale))) break case 4: if (!(customField.value instanceof Date)) return Left(Error(errorString + Message.VALIDATE_CUSTOM_FIELD_VALUE_IS_DATE(definition.name, customField.value, locale))) break } } } return Right(true) } const getMessage = (key: string, spreadSheetService: SpreadSheetService) => Message.findByKey(key, spreadSheetService.getUserLocale()) const getUserProperties = (spreadSheetService: SpreadSheetService): UserProperty => { const lastSpace = spreadSheetService.getUserProperty("space") ? spreadSheetService.getUserProperty("space") : "" const lastDomain = spreadSheetService.getUserProperty("domain") ? spreadSheetService.getUserProperty("domain") : ".com" const lastApiKey = spreadSheetService.getUserProperty("apiKey") ? spreadSheetService.getUserProperty("apiKey") : "" const lastProjectKey = spreadSheetService.getUserProperty("projectKey") ? spreadSheetService.getUserProperty("projectKey") : "" return UserProperty(lastSpace, lastDomain, lastApiKey, lastProjectKey) } const storeUserProperties = (property: UserProperty, spreadSheetService: SpreadSheetService): void => { spreadSheetService.setUserProperty("space", property.space) spreadSheetService.setUserProperty("domain", property.domain) spreadSheetService.setUserProperty("apiKey", property.apiKey) spreadSheetService.setUserProperty("projectKey", property.projectKey) } const showMessage = (message: string, spreadSheetService: SpreadSheetService): void => spreadSheetService.showMessage(getMessage("scriptName", spreadSheetService), message) const strLength = (text: string): number => { let count = 0 for (let i = 0; i < text.length; i++) { const n = escape(text.charAt(i)) if (n.length < 4) count += 1 else count += 2 } return count } const createIssue = (client: BacklogClient, issue: Issue, optParentIssueId: Option<string>): Either<Error, Issue> => client.createIssueV2( Issue( 0, "", issue.projectId, issue.summary, issue.description, issue.startDate, issue.dueDate, issue.estimatedHours, issue.actualHours, issue.issueType, issue.categories, issue.versions, issue.milestones, issue.priority, issue.assignee, optParentIssueId.map(id => id.toString()), issue.customFields ) ) const getTemplateIssuesFromSpreadSheet = (spreadSheetService: SpreadSheetService): Either<Error, any> => { let issues = [] const spreadSheet = SpreadsheetApp.getActiveSpreadsheet() const sheet = spreadSheet.getSheetByName(TEMPLATE_SHEET_NAME) const columnLength = sheet.getLastColumn() const rowLength = sheet.getLastRow() - 1 if (rowLength <= 0) return Left(Error(Message.INVALID_ROW_LENGTH(spreadSheetService.getUserLocale()))) const values = sheet.getSheetValues( ROW_START_INDEX, COLUMN_START_INDEX, rowLength, columnLength ) for (let i = 0; i < values.length; i++) { let customFields = [] let customFieldIndex = 0 for (let j = 13; j < columnLength; j++) { customFields[customFieldIndex] = { header: spreadSheetService.getRange(sheet, j + 1, ROW_HEADER_INDEX).getFormula(), value: values[i][j] === "" ? undefined : values[i][j] } customFieldIndex++ } const issue = { summary: values[i][0] === "" ? undefined : values[i][0], description: values[i][1] === "" ? undefined : values[i][1], startDate: values[i][2] === "" ? undefined : values[i][2], dueDate: values[i][3] === "" ? undefined : values[i][3], estimatedHours: values[i][4] === "" ? undefined : values[i][4], actualHours: values[i][5] === "" ? undefined : values[i][5], issueTypeName: values[i][6] === "" ? undefined : values[i][6], categoryNames: values[i][7], versionNames: values[i][8], milestoneNames: values[i][9], priorityName: values[i][10] === "" ? undefined : values[i][10], assigneeName: values[i][11] === "" ? undefined : values[i][11], parentIssueKey: values[i][12] === "" ? undefined : values[i][12], customFields: customFields } issues[i] = issue } return Right(issues) } const calcWidth = (length: number): number => { const DEFAULT_FONT_SIZE = 10 /** フォントのデフォルトサイズ */ const ADJUST_WIDTH_FACTOR = 0.75 /** 列幅調整時の係数 */ return length * DEFAULT_FONT_SIZE * ADJUST_WIDTH_FACTOR } interface BacklogService { getUserProperties: () => UserProperty run: (property: UserProperty) => void init: (property: UserProperty) => void getMessage: (key: string) => string } export const BacklogService = (spreadSheetService: SpreadSheetService): BacklogService => ({ getUserProperties: (): UserProperty => getUserProperties(spreadSheetService), run: (property: UserProperty): void => { const current = Utilities.formatDate(new Date(), "JST", "yyyy/MM/dd HH:mm:ss") const sheetName = getMessage("scriptName", spreadSheetService) + " : " + current const LOG_KEY_NUMBER = 1 const LOG_SUMMARY_NUMBER = 2 const locale = spreadSheetService.getUserLocale() showMessage(getMessage("progress_collect", spreadSheetService), spreadSheetService) // BacklogScript throws an exception on error const templateIssues = getTemplateIssuesFromSpreadSheet(spreadSheetService).getOrError() storeUserProperties(property, spreadSheetService) showMessage(Message.PROGRESS_RUN_BEGIN(locale), spreadSheetService) const client = createBacklogClient(property.space, property.domain, property.apiKey, locale).getOrError() const project = getProject(client, property.projectKey, locale).getOrError() const definitions = client.getCustomFieldsV2(project.id) const issueTypes = client.getIssueTypesV2(project.id) const _ = validate(templateIssues, issueTypes, definitions, client, locale).getOrError() const converter = createIssueConverter(client, project.id) const convertResults = templateIssues.map(issue => converter.convert(issue)) const issues = Either.sequence(convertResults).getOrError() // Post issues let previousIssue = Option<Issue>(null) let keyLength = DEFAULT_COLUMN_LENGTH let summaryLength = DEFAULT_COLUMN_LENGTH for ( let i = 0; i < issues.length; i++) { let isTakenOverParentIssueId = false let optParentIssueId = issues[i].parentIssueId optParentIssueId.map(function(parentIssueId) { if (parentIssueId === "*") { if (previousIssue.flatMap(issue => issue.parentIssueId).isDefined) { previousIssue.map(issue => showMessage(Message.ALREADY_BEEN_CHILD_ISSUE(issue.issueKey, locale), spreadSheetService)) optParentIssueId = None<string>() } else { optParentIssueId = previousIssue.map(issue => issue.id.toString()) isTakenOverParentIssueId = true } } else { optParentIssueId = client.getIssueV2(parentIssueId).map(issue => issue.id) } }) createIssue(client, issues[i], optParentIssueId.map(id => id)).map(issue => { if (!isTakenOverParentIssueId) { previousIssue = Some(issue) } let logSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName) const issueKey = issue.issueKey const summary = issue.summary const fomula = "=hyperlink(\"" + property.space + "." + property.domain + "/" + "view/" + issueKey + "\";\"" + issueKey + "\")" const currentRow = i + 1 if (logSheet == null) logSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet(sheetName, 1) keyLength = Math.max(keyLength, strLength(issueKey)) summaryLength = Math.max(summaryLength, strLength(summary)) const keyWidth = calcWidth(keyLength) const summaryWidth = calcWidth(summaryLength) const keyCell = spreadSheetService.getRange(logSheet, LOG_KEY_NUMBER, currentRow) const summaryCell = spreadSheetService.getRange(logSheet, LOG_SUMMARY_NUMBER, currentRow) keyCell.setFormula(fomula).setFontColor("blue").setFontLine("underline") summaryCell.setValue(summary) spreadSheetService.setColumnWidth(logSheet, LOG_KEY_NUMBER, keyWidth) spreadSheetService.setColumnWidth(logSheet, LOG_SUMMARY_NUMBER, summaryWidth) SpreadsheetApp.flush() }).getOrError() } client.importFinalize(property.projectKey) showMessage(getMessage("scriptName", spreadSheetService) + getMessage("progress_end", spreadSheetService), spreadSheetService) return }, init: (property: UserProperty): void => { storeUserProperties(property, spreadSheetService) const locale = spreadSheetService.getUserLocale() const templateSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(TEMPLATE_SHEET_NAME) const lastRowNumber = templateSheet.getLastRow() - 1 if (lastRowNumber <= 0) throw Error(Message.INVALID_ROW_LENGTH(locale)) showMessage(Message.PROGRESS_INIT_BEGIN(locale), spreadSheetService) return createBacklogClient(property.space, property.domain, property.apiKey, locale) .flatMap(client => getProject(client, property.projectKey, locale).map(project => { const issueTypes = client.getIssueTypesV2(project.id) const categories = client.getCategoriesV2(project.id) const versions = client.getVersionsV2(project.id) const priorities = client.getPrioritiesV2() const users = client.getUsersV2(project.id) const customFields = client.getCustomFieldsV2(project.id) return BacklogDefinition(slice(issueTypes), slice(categories), slice(versions), slice(priorities), slice(users), customFields) }) ) .map(definition => { const issueTypeRule = SpreadsheetApp.newDataValidation().requireValueInList(definition.issueTypeNames(), true).build() const categoryRule = SpreadsheetApp.newDataValidation().requireValueInList(definition.categoryNames(), true).build() const versionRule = SpreadsheetApp.newDataValidation().requireValueInList(definition.versionNames(), true).build() const priorityRule = SpreadsheetApp.newDataValidation().requireValueInList(definition.priorityNames(), true).build() const userRule = SpreadsheetApp.newDataValidation().requireValueInList(definition.userNames(), true).build() const customFieldStartColumnNumber = 14 // N ~ let currentColumnNumber = customFieldStartColumnNumber templateSheet.getRange(2, 7, lastRowNumber).setDataValidation(issueTypeRule) // 7 = G templateSheet.getRange(2, 8, lastRowNumber).setDataValidation(categoryRule) // 8 = H templateSheet.getRange(2, 9, lastRowNumber).setDataValidation(versionRule) // 9 = I templateSheet.getRange(2, 10, lastRowNumber).setDataValidation(versionRule) // 10 = J templateSheet.getRange(2, 11, lastRowNumber).setDataValidation(priorityRule) // 11 = K templateSheet.getRange(2, 12, lastRowNumber).setDataValidation(userRule) // 12 = L for (let i = 0; i < definition.customFields.length; i++) { const customField = definition.customFields[i] const headerCell = spreadSheetService.getRange(templateSheet, currentColumnNumber, ROW_HEADER_INDEX) const columnName = headerCell.getValue() /** * https://github.com/nulab/backlog4j/blob/master/src/main/java/com/nulabinc/backlog4j/CustomField.java#L10 * Text(1), TextArea(2), Numeric(3), Date(4), SingleList(5), MultipleList(6), CheckBox(7), Radio(8) * We don't support the types MultipleList(6) and CheckBox(7), Radio(8) */ let customFieldName = "" if (!isSupportedCustomField(customField)) continue switch (customField.typeId) { case 1: customFieldName = "文字列" break case 2: customFieldName = "文章" break case 3: customFieldName = "数値" break case 4: customFieldName = "日付" break case 5: customFieldName = "選択リスト" break } const headerName = customField.name + "(" + customFieldName + ")" if (columnName === "") { const headerStrLength = strLength(headerName) const headerWidth = calcWidth(headerStrLength) templateSheet.insertColumnAfter(currentColumnNumber - 1) templateSheet .getRange(1, currentColumnNumber, templateSheet.getLastRow(), 1) .setBackground("#F8FFFF") .setFontColor("black") spreadSheetService.setColumnWidth(templateSheet, currentColumnNumber, headerWidth) } headerCell.setFormula( "=hyperlink(\"" + property.space + ".backlog" + property.domain + "/EditAttribute.action?attribute.id=" + customField.id + "\";\"" + headerName + "\")" ) currentColumnNumber++ } // Data validation must be added after all column insert let validationRuleIndex = 0 for (let i = 0; i < definition.customFields.length; i++) { const customField = definition.customFields[i] if (!isSupportedCustomField(customField)) continue if (customField.typeId === 5) { definition.customFieldItemNames(customField).map(itemNames => { if (itemNames.length > 0) { const itemRule = SpreadsheetApp.newDataValidation().requireValueInList(itemNames, true).build() templateSheet.getRange(2, validationRuleIndex + customFieldStartColumnNumber, lastRowNumber).setDataValidation(itemRule) } }) } validationRuleIndex++ } showMessage(getMessage("complete_init", spreadSheetService), spreadSheetService) return }) .getOrError() }, getMessage: (key: string): string => getMessage(key, spreadSheetService) })
the_stack
import {fakeAsync, TestBed, tick} from "@angular/core/testing"; import {HttpClientTestingModule, HttpTestingController} from "@angular/common/http/testing"; import * as Immutable from "immutable"; import {ConfigService} from "../../../../services/settings/config.service"; import {LoggerService} from "../../../../services/utils/logger.service"; import {Config} from "../../../../services/settings/config"; import {MockStreamServiceRegistry} from "../../../mocks/mock-stream-service.registry"; import {ConnectedService} from "../../../../services/utils/connected.service"; import {RestService} from "../../../../services/utils/rest.service"; import {StreamServiceRegistry} from "../../../../services/base/stream-service.registry"; // noinspection JSUnusedLocalSymbols const DoNothing = {next: reaction => {}}; describe("Testing config service", () => { let mockRegistry: MockStreamServiceRegistry; let httpMock: HttpTestingController; let configService: ConfigService; beforeEach(() => { TestBed.configureTestingModule({ imports: [ HttpClientTestingModule ], providers: [ ConfigService, LoggerService, RestService, ConnectedService, {provide: StreamServiceRegistry, useClass: MockStreamServiceRegistry} ] }); mockRegistry = TestBed.get(StreamServiceRegistry); httpMock = TestBed.get(HttpTestingController); configService = TestBed.get(ConfigService); // Connect the services mockRegistry.connect(); // Finish test config init configService.onInit(); }); it("should create an instance", () => { expect(configService).toBeDefined(); }); it("should parse config json correctly", () => { const configJson = { general: { debug: true }, lftp: { remote_address: "remote.server.com", remote_username: "some.user", remote_password: "my.password", remote_path: "/some/remote/path", local_path: "/some/local/path", remote_path_to_scan_script: "/another/remote/path", use_ssh_key: true, num_max_parallel_downloads: 2, num_max_parallel_files_per_download: 8, num_max_connections_per_root_file: 32, num_max_connections_per_dir_file: 4, num_max_total_connections: 32, use_temp_file: true, }, controller: { interval_ms_remote_scan: 30000, interval_ms_local_scan: 10000, interval_ms_downloading_scan: 1000 }, web: { port: 8800 }, autoqueue: { enabled: true, patterns_only: false } }; httpMock.expectOne("/server/config/get").flush(configJson); configService.config.subscribe({ next: config => { expect(config.general.debug).toBe(true); expect(config.lftp.remote_address).toBe("remote.server.com"); expect(config.lftp.remote_username).toBe("some.user"); expect(config.lftp.remote_password).toBe("my.password"); expect(config.lftp.remote_path).toBe("/some/remote/path"); expect(config.lftp.local_path).toBe("/some/local/path"); expect(config.lftp.remote_path_to_scan_script).toBe("/another/remote/path"); expect(config.lftp.use_ssh_key).toBe(true); expect(config.lftp.num_max_parallel_downloads).toBe(2); expect(config.lftp.num_max_parallel_files_per_download).toBe(8); expect(config.lftp.num_max_connections_per_root_file).toBe(32); expect(config.lftp.num_max_connections_per_dir_file).toBe(4); expect(config.lftp.num_max_total_connections).toBe(32); expect(config.lftp.use_temp_file).toBe(true); expect(config.controller.interval_ms_remote_scan).toBe(30000); expect(config.controller.interval_ms_local_scan).toBe(10000); expect(config.controller.interval_ms_downloading_scan).toBe(1000); expect(config.web.port).toBe(8800); expect(config.autoqueue.enabled).toBe(true); expect(config.autoqueue.patterns_only).toBe(false); } }); httpMock.verify(); }); it("should get null on get error 404", () => { httpMock.expectOne("/server/config/get").flush( "Not found", {status: 404, statusText: "Bad Request"} ); configService.config.subscribe({ next: config => { expect(config).toBe(null); } }); httpMock.verify(); }); it("should get null on get network error", () => { httpMock.expectOne("/server/config/get").error(new ErrorEvent("mock error")); configService.config.subscribe({ next: config => { expect(config).toBe(null); } }); httpMock.verify(); }); it("should get null on disconnect", fakeAsync(() => { const configExpected = [ new Config({lftp: {remote_address: "first"}}), null ]; httpMock.expectOne("/server/config/get").flush({lftp: {remote_address: "first"}}); let configSubscriberIndex = 0; configService.config.subscribe({ next: config => { expect(Immutable.is(config, configExpected[configSubscriberIndex++])).toBe(true); } }); // status disconnect mockRegistry.disconnect(); tick(); httpMock.verify(); expect(configSubscriberIndex).toBe(2); })); it("should retry GET on disconnect", fakeAsync(() => { // first connect httpMock.expectOne("/server/config/get").flush("{}"); // status disconnect mockRegistry.disconnect(); tick(); // status reconnect mockRegistry.connect(); tick(); httpMock.expectOne("/server/config/get").flush("{}"); httpMock.verify(); })); it("should send a GET on a set config option", () => { // first connect httpMock.expectOne("/server/config/get").flush("{}"); let configSubscriberIndex = 0; configService.set("general", "debug", true).subscribe({ next: reaction => { configSubscriberIndex++; expect(reaction.success).toBe(true); } }); // set request httpMock.expectOne("/server/config/set/general/debug/true").flush("{}"); expect(configSubscriberIndex).toBe(1); httpMock.verify(); }); it("should send correct GET requests on setting config options", () => { // first connect httpMock.expectOne("/server/config/get").flush("{}"); // boolean configService.set("general", "debug", true).subscribe(DoNothing); httpMock.expectOne("/server/config/set/general/debug/true").flush("{}"); configService.set("general", "debug", false).subscribe(DoNothing); httpMock.expectOne("/server/config/set/general/debug/false").flush("{}"); // integer configService.set("general", "debug", 0).subscribe(DoNothing); httpMock.expectOne("/server/config/set/general/debug/0").flush("{}"); configService.set("general", "debug", 1000).subscribe(DoNothing); httpMock.expectOne("/server/config/set/general/debug/1000").flush("{}"); configService.set("general", "debug", -1000).subscribe(DoNothing); httpMock.expectOne("/server/config/set/general/debug/-1000").flush("{}"); // string configService.set("general", "debug", "test").subscribe(DoNothing); httpMock.expectOne("/server/config/set/general/debug/test").flush("{}"); configService.set("general", "debug", "test space").subscribe(DoNothing); httpMock.expectOne("/server/config/set/general/debug/test%2520space").flush("{}"); configService.set("general", "debug", "test/slash").subscribe(DoNothing); httpMock.expectOne("/server/config/set/general/debug/test%252Fslash").flush("{}"); configService.set("general", "debug", "test\"doublequote").subscribe( DoNothing ); httpMock.expectOne("/server/config/set/general/debug/test%2522doublequote").flush("{}"); configService.set("general", "debug", "/test/leadingslash").subscribe(DoNothing); httpMock.expectOne("/server/config/set/general/debug/%252Ftest%252Fleadingslash").flush("{}"); httpMock.verify(); }); it("should return error on setting non-existing section", () => { // first connect httpMock.expectOne("/server/config/get").flush("{}"); let configSubscriberIndex = 0; configService.set("bad_section", "debug", true).subscribe({ next: reaction => { configSubscriberIndex++; expect(reaction.success).toBe(false); expect(reaction.errorMessage).toBe("Config has no option named bad_section.debug"); } }); expect(configSubscriberIndex).toBe(1); httpMock.verify(); }); it("should return error on setting non-existing option", () => { // first connect httpMock.expectOne("/server/config/get").flush("{}"); let configSubscriberIndex = 0; configService.set("general", "bad_option", true).subscribe({ next: reaction => { configSubscriberIndex++; expect(reaction.success).toBe(false); expect(reaction.errorMessage).toBe("Config has no option named general.bad_option"); } }); expect(configSubscriberIndex).toBe(1); httpMock.verify(); }); it("should return error on empty value", () => { // first connect httpMock.expectOne("/server/config/get").flush("{}"); let configSubscriberIndex = 0; configService.set("general", "debug", "").subscribe({ next: reaction => { configSubscriberIndex++; expect(reaction.success).toBe(false); expect(reaction.errorMessage).toBe("Setting general.debug cannot be blank."); } }); expect(configSubscriberIndex).toBe(1); httpMock.verify(); }); it("should send updated config on a successful set", () => { const configJson = {general: {debug: false}}; // first connect httpMock.expectOne("/server/config/get").flush(configJson); const configExpected = [ new Config({general: {debug: false}}), new Config({general: {debug: true}}) ]; let configSubscriberIndex = 0; configService.config.subscribe({ next: config => { expect(Immutable.is(config, configExpected[configSubscriberIndex++])).toBe(true); } }); // issue the set configService.set("general", "debug", true).subscribe(DoNothing); // set request httpMock.expectOne("/server/config/set/general/debug/true").flush(""); expect(configSubscriberIndex).toBe(2); httpMock.verify(); }); it("should NOT send updated config on a failed set", () => { const configJson = {general: {debug: false}}; // first connect httpMock.expectOne("/server/config/get").flush(configJson); const configExpected = [ new Config({general: {debug: false}}) ]; let configSubscriberIndex = 0; configService.config.subscribe({ next: config => { expect(Immutable.is(config, configExpected[configSubscriberIndex++])).toBe(true); } }); // issue the set configService.set("general", "debug", true).subscribe(DoNothing); // set request httpMock.expectOne("/server/config/set/general/debug/true").flush( "Not found", {status: 404, statusText: "Bad Request"} ); expect(configSubscriberIndex).toBe(1); httpMock.verify(); }); });
the_stack
import { Cluster } from './Cluster' import { MarkerExtended, ClustererOptions, ClusterIconStyle, TCalculator, ClusterIconInfo, } from './types' /** * Supports up to 9007199254740991 (Number.MAX_SAFE_INTEGER) markers * which is not a problem as max array length is 4294967296 (2**32) */ const CALCULATOR = function CALCULATOR( markers: MarkerExtended[], numStyles: number ): ClusterIconInfo { const count = markers.length const numberOfDigits = count.toString().length const index = Math.min(numberOfDigits, numStyles) return { text: count.toString(), index: index, title: '', } } const BATCH_SIZE = 2000 const BATCH_SIZE_IE = 500 const IMAGE_PATH = 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' const IMAGE_EXTENSION = 'png' const IMAGE_SIZES = [53, 56, 66, 78, 90] const CLUSTERER_CLASS = 'cluster' export class Clusterer { markers: MarkerExtended[] clusters: Cluster[] listeners: google.maps.MapsEventListener[] activeMap: google.maps.Map | google.maps.StreetViewPanorama | null ready: boolean gridSize: number minClusterSize: number maxZoom: number | null styles: ClusterIconStyle[] title: string zoomOnClick: boolean averageCenter: boolean ignoreHidden: boolean enableRetinaIcons: boolean imagePath: string imageExtension: string imageSizes: number[] calculator: TCalculator batchSize: number batchSizeIE: number clusterClass: string timerRefStatic: number | null constructor( map: google.maps.Map, optMarkers: MarkerExtended[] = [], optOptions: ClustererOptions = {} ) { this.extend(Clusterer, google.maps.OverlayView) this.markers = [] this.clusters = [] this.listeners = [] this.activeMap = null this.ready = false this.gridSize = optOptions.gridSize || 60 this.minClusterSize = optOptions.minimumClusterSize || 2 this.maxZoom = optOptions.maxZoom || null this.styles = optOptions.styles || [] this.title = optOptions.title || '' this.zoomOnClick = true if (optOptions.zoomOnClick !== undefined) { this.zoomOnClick = optOptions.zoomOnClick } this.averageCenter = false if (optOptions.averageCenter !== undefined) { this.averageCenter = optOptions.averageCenter } this.ignoreHidden = false if (optOptions.ignoreHidden !== undefined) { this.ignoreHidden = optOptions.ignoreHidden } this.enableRetinaIcons = false if (optOptions.enableRetinaIcons !== undefined) { this.enableRetinaIcons = optOptions.enableRetinaIcons } this.imagePath = optOptions.imagePath || IMAGE_PATH this.imageExtension = optOptions.imageExtension || IMAGE_EXTENSION this.imageSizes = optOptions.imageSizes || IMAGE_SIZES this.calculator = optOptions.calculator || CALCULATOR this.batchSize = optOptions.batchSize || BATCH_SIZE this.batchSizeIE = optOptions.batchSizeIE || BATCH_SIZE_IE this.clusterClass = optOptions.clusterClass || CLUSTERER_CLASS if (navigator.userAgent.toLowerCase().indexOf('msie') !== -1) { // Try to avoid IE timeout when processing a huge number of markers: this.batchSize = this.batchSizeIE } this.timerRefStatic = null this.setupStyles() this.addMarkers(optMarkers, true) // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore this.setMap(map) // Note: this causes onAdd to be called } onAdd() { // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore this.activeMap = this.getMap() this.ready = true this.repaint() // Add the map event listeners this.listeners = [ google.maps.event.addListener( // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore this.getMap(), 'zoom_changed', // eslint-disable-next-line @getify/proper-arrows/this, @getify/proper-arrows/name () => { this.resetViewport(false) // Workaround for this Google bug: when map is at level 0 and "-" of // zoom slider is clicked, a "zoom_changed" event is fired even though // the map doesn't zoom out any further. In this situation, no "idle" // event is triggered so the cluster markers that have been removed // do not get redrawn. Same goes for a zoom in at maxZoom. if ( // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore this.getMap().getZoom() === (this.get('minZoom') || 0) || // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore this.getMap().getZoom() === this.get('maxZoom') ) { google.maps.event.trigger(this, 'idle') } } ), google.maps.event.addListener( // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore this.getMap(), 'idle', // eslint-disable-next-line @getify/proper-arrows/this, @getify/proper-arrows/name () => { this.redraw() } ), ] } // eslint-disable-next-line @getify/proper-arrows/this onRemove() { // Put all the managed markers back on the map: for (let i = 0; i < this.markers.length; i++) { if (this.markers[i].getMap() !== this.activeMap) { this.markers[i].setMap(this.activeMap) } } // Remove all clusters: for (let i = 0; i < this.clusters.length; i++) { this.clusters[i].remove() } this.clusters = [] // Remove map event listeners: for (let i = 0; i < this.listeners.length; i++) { google.maps.event.removeListener(this.listeners[i]) } this.listeners = [] this.activeMap = null this.ready = false } // eslint-disable-next-line @typescript-eslint/no-empty-function draw() {} setupStyles() { if (this.styles.length > 0) { return } for (let i = 0; i < this.imageSizes.length; i++) { this.styles.push({ url: this.imagePath + (i + 1) + '.' + this.imageExtension, height: this.imageSizes[i], width: this.imageSizes[i], }) } } fitMapToMarkers() { const markers = this.getMarkers() const bounds = new google.maps.LatLngBounds() for (let i = 0; i < markers.length; i++) { const position = markers[i].getPosition() if (position) { bounds.extend(position) } } // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore this.getMap().fitBounds(bounds) } getGridSize(): number { return this.gridSize } setGridSize(gridSize: number) { this.gridSize = gridSize } getMinimumClusterSize(): number { return this.minClusterSize } setMinimumClusterSize(minimumClusterSize: number) { this.minClusterSize = minimumClusterSize } getMaxZoom(): number | null { return this.maxZoom } setMaxZoom(maxZoom: number) { this.maxZoom = maxZoom } getStyles(): ClusterIconStyle[] { return this.styles } setStyles(styles: ClusterIconStyle[]) { this.styles = styles } getTitle(): string { return this.title } setTitle(title: string) { this.title = title } getZoomOnClick(): boolean { return this.zoomOnClick } setZoomOnClick(zoomOnClick: boolean) { this.zoomOnClick = zoomOnClick } getAverageCenter(): boolean { return this.averageCenter } setAverageCenter(averageCenter: boolean) { this.averageCenter = averageCenter } getIgnoreHidden(): boolean { return this.ignoreHidden } setIgnoreHidden(ignoreHidden: boolean) { this.ignoreHidden = ignoreHidden } getEnableRetinaIcons(): boolean { return this.enableRetinaIcons } setEnableRetinaIcons(enableRetinaIcons: boolean) { this.enableRetinaIcons = enableRetinaIcons } getImageExtension(): string { return this.imageExtension } setImageExtension(imageExtension: string) { this.imageExtension = imageExtension } getImagePath(): string { return this.imagePath } setImagePath(imagePath: string) { this.imagePath = imagePath } getImageSizes(): number[] { return this.imageSizes } setImageSizes(imageSizes: number[]) { this.imageSizes = imageSizes } getCalculator(): TCalculator { return this.calculator } setCalculator(calculator: TCalculator) { this.calculator = calculator } getBatchSizeIE(): number { return this.batchSizeIE } setBatchSizeIE(batchSizeIE: number) { this.batchSizeIE = batchSizeIE } getClusterClass(): string { return this.clusterClass } setClusterClass(clusterClass: string) { this.clusterClass = clusterClass } getMarkers(): MarkerExtended[] { return this.markers } getTotalMarkers(): number { return this.markers.length } getClusters(): Cluster[] { return this.clusters } getTotalClusters(): number { return this.clusters.length } addMarker(marker: MarkerExtended, optNoDraw: boolean) { this.pushMarkerTo(marker) if (!optNoDraw) { this.redraw() } } addMarkers(markers: MarkerExtended[], optNoDraw: boolean) { for (const key in markers) { if (markers.hasOwnProperty(key)) { this.pushMarkerTo(markers[key]) } } if (!optNoDraw) { this.redraw() } } pushMarkerTo(marker: MarkerExtended) { // If the marker is draggable add a listener so we can update the clusters on the dragend: if (marker.getDraggable()) { // eslint-disable-next-line @getify/proper-arrows/name, @getify/proper-arrows/this google.maps.event.addListener(marker, 'dragend', () => { if (this.ready) { marker.isAdded = false this.repaint() } }) } marker.isAdded = false this.markers.push(marker) } removeMarker_(marker: MarkerExtended): boolean { let index = -1 if (this.markers.indexOf) { index = this.markers.indexOf(marker) } else { for (let i = 0; i < this.markers.length; i++) { if (marker === this.markers[i]) { index = i break } } } if (index === -1) { // Marker is not in our list of markers, so do nothing: return false } marker.setMap(null) this.markers.splice(index, 1) // Remove the marker from the list of managed markers return true } removeMarker(marker: MarkerExtended, optNoDraw: boolean): boolean { const removed = this.removeMarker_(marker) if (!optNoDraw && removed) { this.repaint() } return removed } removeMarkers(markers: MarkerExtended[], optNoDraw: boolean): boolean { let removed = false for (let i = 0; i < markers.length; i++) { removed = removed || this.removeMarker_(markers[i]) } if (!optNoDraw && removed) { this.repaint() } return removed } clearMarkers() { this.resetViewport(true) this.markers = [] } repaint() { const oldClusters = this.clusters.slice() this.clusters = [] this.resetViewport(false) this.redraw() // Remove the old clusters. // Do it in a timeout to prevent blinking effect. setTimeout(function timeout() { for (let i = 0; i < oldClusters.length; i++) { oldClusters[i].remove() } }, 0) } getExtendedBounds(bounds: google.maps.LatLngBounds): google.maps.LatLngBounds { // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore const projection = this.getProjection() // Convert the points to pixels and the extend out by the grid size. const trPix = projection.fromLatLngToDivPixel( // Turn the bounds into latlng. new google.maps.LatLng(bounds.getNorthEast().lat(), bounds.getNorthEast().lng()) ) trPix.x += this.gridSize trPix.y -= this.gridSize const blPix = projection.fromLatLngToDivPixel( // Turn the bounds into latlng. new google.maps.LatLng(bounds.getSouthWest().lat(), bounds.getSouthWest().lng()) ) blPix.x -= this.gridSize blPix.y += this.gridSize // Extend the bounds to contain the new bounds. bounds.extend( // Convert the pixel points back to LatLng nw projection.fromDivPixelToLatLng(trPix) ) bounds.extend( // Convert the pixel points back to LatLng sw projection.fromDivPixelToLatLng(blPix) ) return bounds } redraw() { // Redraws all the clusters. this.createClusters(0) } resetViewport(optHide: boolean) { // Remove all the clusters for (let i = 0; i < this.clusters.length; i++) { this.clusters[i].remove() } this.clusters = [] // Reset the markers to not be added and to be removed from the map. for (let i = 0; i < this.markers.length; i++) { const marker = this.markers[i] marker.isAdded = false if (optHide) { marker.setMap(null) } } } distanceBetweenPoints(p1: google.maps.LatLng, p2: google.maps.LatLng): number { const R = 6371 // Radius of the Earth in km const dLat = ((p2.lat() - p1.lat()) * Math.PI) / 180 const dLon = ((p2.lng() - p1.lng()) * Math.PI) / 180 const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos((p1.lat() * Math.PI) / 180) * Math.cos((p2.lat() * Math.PI) / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2) return R * (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))) } isMarkerInBounds(marker: MarkerExtended, bounds: google.maps.LatLngBounds): boolean { const position = marker.getPosition() if (position) { return bounds.contains(position) } return false } addToClosestCluster(marker: MarkerExtended) { let cluster let distance = 40000 // Some large number let clusterToAddTo = null for (let i = 0; i < this.clusters.length; i++) { cluster = this.clusters[i] const center = cluster.getCenter() const position = marker.getPosition() if (center && position) { const d = this.distanceBetweenPoints(center, position) if (d < distance) { distance = d clusterToAddTo = cluster } } } if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) { clusterToAddTo.addMarker(marker) } else { cluster = new Cluster(this) cluster.addMarker(marker) this.clusters.push(cluster) } } createClusters(iFirst: number) { if (!this.ready) { return } // Cancel previous batch processing if we're working on the first batch: if (iFirst === 0) { /** * This event is fired when the <code>Clusterer</code> begins * clustering markers. * @name Clusterer#clusteringbegin * @param {Clusterer} mc The Clusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, 'clusteringbegin', this) if (this.timerRefStatic !== null) { window.clearTimeout(this.timerRefStatic) // @ts-ignore delete this.timerRefStatic } } // Get our current map view bounds. // Create a new bounds object so we don't affect the map. // // See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug: const mapBounds = // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore this.getMap().getZoom() > 3 ? new google.maps.LatLngBounds( // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore this.getMap() .getBounds() .getSouthWest(), // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore this.getMap() .getBounds() .getNorthEast() ) : new google.maps.LatLngBounds( new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625) ) const bounds = this.getExtendedBounds(mapBounds) const iLast = Math.min(iFirst + this.batchSize, this.markers.length) for (let i = iFirst; i < iLast; i++) { const marker = this.markers[i] if (!marker.isAdded && this.isMarkerInBounds(marker, bounds)) { if (!this.ignoreHidden || (this.ignoreHidden && marker.getVisible())) { this.addToClosestCluster(marker) } } } if (iLast < this.markers.length) { this.timerRefStatic = window.setTimeout( // eslint-disable-next-line @getify/proper-arrows/this, @getify/proper-arrows/name () => { this.createClusters(iLast) }, 0 ) } else { this.timerRefStatic = null /** * This event is fired when the <code>Clusterer</code> stops * clustering markers. * @name Clusterer#clusteringend * @param {Clusterer} mc The Clusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, 'clusteringend', this) for (let i = 0; i < this.clusters.length; i++) { this.clusters[i].updateIcon() } } } extend(obj1: any, obj2: any): any { return function applyExtend(object: any) { // eslint-disable-next-line guard-for-in for (const property in object.prototype) { // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore this.prototype[property] = object.prototype[property] } // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore return this }.apply(obj1, [obj2]) } }
the_stack
import assert from "assert"; import { readFileSync } from "fs"; import fs from "fs/promises"; import path from "path"; import { setImmediate } from "timers/promises"; import { CachePlugin } from "@miniflare/cache"; import { BindingsPlugin, Fetcher, MiniflareCoreError, Response, _CoreMount, } from "@miniflare/core"; import { Compatibility, NoOpLog, PluginContext, getRequestContext, viewToBuffer, } from "@miniflare/shared"; import { getObjectProperties, logPluginOptions, parsePluginArgv, parsePluginWranglerConfig, useMiniflare, useServer, useTmp, } from "@miniflare/shared-test"; import test from "ava"; const log = new NoOpLog(); const compat = new Compatibility(); const rootPath = process.cwd(); const ctx: PluginContext = { log, compat, rootPath }; const fixturesPath = path.join(__dirname, "..", "..", "..", "test", "fixtures"); // add.wasm is a WebAssembly module with a single export "add" that adds // its 2 integer parameters together and returns the result, it is from: // https://webassembly.github.io/wabt/demo/wat2wasm/ const addModulePath = path.join(fixturesPath, "add.wasm"); // lorem-ipsum.txt is five paragraphs of lorem ipsum nonsense text const loremIpsumPath = path.join(fixturesPath, "lorem-ipsum.txt"); const loremIpsum = readFileSync(loremIpsumPath, "utf-8"); // we also make a data version of it to verify aganst data blobs const loremIpsumData = viewToBuffer(readFileSync(loremIpsumPath)); test("BindingsPlugin: parses options from argv", (t) => { let options = parsePluginArgv(BindingsPlugin, [ "--env", ".env.test", "--binding", "KEY1=value1", "--binding", "KEY2=value2", "--global", "KEY3=value3", "--global", "KEY4=value4", "--wasm", "MODULE1=module1.wasm", "--wasm", "MODULE2=module2.wasm", "--text-blob", "TEXT1=text-blob-1.txt", "--text-blob", "TEXT2=text-blob-2.txt", "--data-blob", "DATA1=data-blob-1.bin", "--data-blob", "DATA2=data-blob-2.bin", "--service", "SERVICE1=service1", "--service", "SERVICE2=service2@development", ]); t.deepEqual(options, { envPath: ".env.test", bindings: { KEY1: "value1", KEY2: "value2" }, globals: { KEY3: "value3", KEY4: "value4" }, wasmBindings: { MODULE1: "module1.wasm", MODULE2: "module2.wasm" }, textBlobBindings: { TEXT1: "text-blob-1.txt", TEXT2: "text-blob-2.txt" }, dataBlobBindings: { DATA1: "data-blob-1.bin", DATA2: "data-blob-2.bin" }, serviceBindings: { SERVICE1: "service1", SERVICE2: { service: "service2", environment: "development" }, }, }); options = parsePluginArgv(BindingsPlugin, [ "-e", ".env.test", "-b", "KEY1=value1", "-b", "KEY2=value2", "-S", "SERVICE1=service1", "-S", "SERVICE2=service2@development", ]); t.deepEqual(options, { envPath: ".env.test", bindings: { KEY1: "value1", KEY2: "value2" }, serviceBindings: { SERVICE1: "service1", SERVICE2: { service: "service2", environment: "development" }, }, }); }); test("BindingsPlugin: parses options from wrangler config", async (t) => { let options = parsePluginWranglerConfig(BindingsPlugin, { wasm_modules: { MODULE1: "module1.wasm", MODULE2: "module2.wasm", }, text_blobs: { TEXT1: "text-blob-1.txt", TEXT2: "text-blob-2.txt", }, data_blobs: { DATA1: "data-blob-1.bin", DATA2: "data-blob-2.bin", }, experimental_services: [ { name: "SERVICE1", service: "service1", environment: "development" }, { name: "SERVICE2", service: "service2", environment: "production" }, ], miniflare: { globals: { KEY5: "value5", KEY6: false, KEY7: 10 }, env_path: ".env.test", }, }); t.like(options, { envPath: ".env.test", globals: { KEY5: "value5", KEY6: false, KEY7: 10 }, wasmBindings: { MODULE1: "module1.wasm", MODULE2: "module2.wasm" }, textBlobBindings: { TEXT1: "text-blob-1.txt", TEXT2: "text-blob-2.txt" }, dataBlobBindings: { DATA1: "data-blob-1.bin", DATA2: "data-blob-2.bin" }, serviceBindings: { SERVICE1: { service: "service1", environment: "development" }, SERVICE2: { service: "service2", environment: "production" }, }, }); // Wrangler bindings are stored in the kWranglerBindings symbol, which isn't // exported, so setup the plugin and check they're included options = parsePluginWranglerConfig(BindingsPlugin, { vars: { KEY1: "value1", KEY2: "value2", KEY3: true, KEY4: 42 }, }); const plugin = new BindingsPlugin(ctx, options); const result = await plugin.setup(); // Wrangler bindings should be stringified t.deepEqual(result.bindings, { KEY1: "value1", KEY2: "value2", KEY3: "true", KEY4: "42", }); }); test("BindingsPlugin: logs options", (t) => { // wranglerOptions should contain [kWranglerBindings] const wranglerOptions = parsePluginWranglerConfig(BindingsPlugin, { vars: { KEY1: "value1", KEY2: "value2" }, }); let logs = logPluginOptions(BindingsPlugin, { ...wranglerOptions, envPath: ".env.custom", bindings: { KEY3: "value3", KEY4: "value4" }, globals: { KEY5: "value5", KEY6: "value6" }, wasmBindings: { MODULE1: "module1.wasm", MODULE2: "module2.wasm" }, textBlobBindings: { TEXT1: "text-blob-1.txt", TEXT2: "text-blob-2.txt" }, dataBlobBindings: { DATA1: "data-blob-1.bin", DATA2: "data-blob-2.bin" }, serviceBindings: { SERVICE1: "service1", SERVICE2: { service: "service2", environment: "development" }, }, }); t.deepEqual(logs, [ "Env Path: .env.custom", "Wrangler Variables: KEY1, KEY2", "Custom Bindings: KEY3, KEY4", "Custom Globals: KEY5, KEY6", "WASM Bindings: MODULE1, MODULE2", "Text Blob Bindings: TEXT1, TEXT2", "Data Blob Bindings: DATA1, DATA2", "Service Bindings: SERVICE1, SERVICE2", ]); logs = logPluginOptions(BindingsPlugin, { envPath: true }); t.deepEqual(logs, ["Env Path: .env"]); logs = logPluginOptions(BindingsPlugin, { envPath: false }); t.deepEqual(logs, []); }); test("BindingsPlugin: uses default .env path if envPathDefaultFallback set and envPath is undefined", (t) => { let plugin = new BindingsPlugin(ctx, { envPathDefaultFallback: true }); t.true(plugin.envPath); // Check leaves envPath alone if defined plugin = new BindingsPlugin(ctx, { envPathDefaultFallback: true, envPath: false, }); t.false(plugin.envPath); plugin = new BindingsPlugin(ctx, { envPathDefaultFallback: true, envPath: ".env.custom", }); t.is(plugin.envPath, ".env.custom"); }); test("BindingsPlugin: setup: loads .env bindings from default location", async (t) => { const tmp = await useTmp(t); const defaultEnvPath = path.join(tmp, ".env"); let plugin = new BindingsPlugin( { log, compat, rootPath: tmp }, { envPath: true } ); // Shouldn't throw if file doesn't exist... let result = await plugin.setup(); // ...but should still watch file t.deepEqual(result, { globals: undefined, bindings: {}, watch: [defaultEnvPath], }); // Create file and try setup again await fs.writeFile(defaultEnvPath, "KEY=value"); result = await plugin.setup(); t.deepEqual(result, { globals: undefined, bindings: { KEY: "value" }, watch: [defaultEnvPath], }); // Check default .env only loaded when envPath set to true plugin = new BindingsPlugin({ log, compat, rootPath: tmp }, {}); result = await plugin.setup(); t.deepEqual(result, { globals: undefined, bindings: {}, watch: [] }); }); test("BindingsPlugin: setup: loads .env bindings from custom location", async (t) => { const tmp = await useTmp(t); const defaultEnvPath = path.join(tmp, ".env"); const customEnvPath = path.join(tmp, ".env.custom"); await fs.writeFile(defaultEnvPath, "KEY=default"); const plugin = new BindingsPlugin( { log, compat, rootPath: tmp }, // Should resolve envPath relative to rootPath { envPath: ".env.custom" } ); // Should throw if file doesn't exist await t.throwsAsync(plugin.setup(), { code: "ENOENT", message: /\.env\.custom/, }); // Create file and try setup again await fs.writeFile(customEnvPath, "KEY=custom"); const result = await plugin.setup(); t.deepEqual(result, { globals: undefined, bindings: { KEY: "custom" }, watch: [customEnvPath], }); }); test("BindingsPlugin: setup: includes custom bindings", async (t) => { const obj = { a: 1 }; const plugin = new BindingsPlugin(ctx, { bindings: { obj } }); const result = await plugin.setup(); t.is(result.bindings?.obj, obj); t.deepEqual(result.watch, []); }); test("BindingsPlugin: setup: loads WebAssembly bindings", async (t) => { let plugin = new BindingsPlugin(ctx, { wasmBindings: { ADD: addModulePath }, }); let result = await plugin.setup(); t.not(result.bindings?.ADD, undefined); assert(result.bindings?.ADD); const instance = new WebAssembly.Instance(result.bindings.ADD); assert(typeof instance.exports.add === "function"); t.is(instance.exports.add(1, 2), 3); // Check resolves wasmBindings path relative to rootPath plugin = new BindingsPlugin( { log, compat, rootPath: path.dirname(addModulePath) }, { wasmBindings: { ADD: path.basename(addModulePath) } } ); result = await plugin.setup(); t.not(result.bindings?.ADD, undefined); }); test("BindingsPlugin: setup: loads text blob bindings", async (t) => { let plugin = new BindingsPlugin(ctx, { textBlobBindings: { LOREM_IPSUM: loremIpsumPath }, }); let result = await plugin.setup(); t.is(result.bindings?.LOREM_IPSUM, loremIpsum); // Check resolves text blob bindings path relative to rootPath plugin = new BindingsPlugin( { log, compat, rootPath: path.dirname(loremIpsumPath) }, { textBlobBindings: { LOREM_IPSUM: "lorem-ipsum.txt" } } ); result = await plugin.setup(); t.is(result.bindings?.LOREM_IPSUM, loremIpsum); }); test("BindingsPlugin: setup: loads data blob bindings", async (t) => { let plugin = new BindingsPlugin(ctx, { dataBlobBindings: { BINARY_DATA: loremIpsumPath }, }); let result = await plugin.setup(); t.deepEqual(result.bindings?.BINARY_DATA, loremIpsumData); // Check resolves data blob bindings path relative to rootPath plugin = new BindingsPlugin( { log, compat, rootPath: path.dirname(loremIpsumPath) }, { dataBlobBindings: { BINARY_DATA: "lorem-ipsum.txt" } } ); result = await plugin.setup(); t.deepEqual(result.bindings?.BINARY_DATA, loremIpsumData); }); test("BindingsPlugin: setup: loads bindings from all sources", async (t) => { // Bindings should be loaded in this order, from lowest to highest priority: // 1) Wrangler [vars] // 2) .env Variables // 3) WASM Module Bindings // 4) Text Blob Bindings // 5) Data Blob Bindings // 6) Service Bindings // 7) Custom Bindings // wranglerOptions should contain [kWranglerBindings] const wranglerOptions = parsePluginWranglerConfig(BindingsPlugin, { vars: { A: "w", B: "w", C: "w", D: "w", E: "w", F: "w", G: "w" }, }); const tmp = await useTmp(t); const envPath = path.join(tmp, ".env"); await fs.writeFile(envPath, "A=env\nB=env\nC=env\nD=env\nE=env\nF=env"); const obj = { ping: "pong" }; const throws = () => { throw new Error("Should not be called"); }; const plugin = new BindingsPlugin(ctx, { ...wranglerOptions, wasmBindings: { A: addModulePath, B: addModulePath, C: addModulePath, D: addModulePath, E: addModulePath, }, textBlobBindings: { A: loremIpsumPath, B: loremIpsumPath, C: loremIpsumPath, D: loremIpsumPath, }, dataBlobBindings: { A: loremIpsumPath, B: loremIpsumPath, C: loremIpsumPath, }, serviceBindings: { A: throws, B: throws }, bindings: { A: obj }, envPath, }); const result = await plugin.setup(); assert(result.bindings); t.is(result.bindings.G, "w"); t.is(result.bindings.F, "env"); t.true(result.bindings.E instanceof WebAssembly.Module); t.is(result.bindings.D, loremIpsum); t.deepEqual(result.bindings.C, loremIpsumData); t.true(result.bindings.B instanceof Fetcher); t.is(result.bindings.A, obj); }); // Service bindings tests test("Fetcher: hides implementation details", (t) => { const throws = () => { throw new Error("Should not be called"); }; const fetcher = new Fetcher(throws, throws); t.deepEqual(getObjectProperties(fetcher), ["fetch"]); }); test("BindingsPlugin: dispatches fetch to mounted service", async (t) => { const mf = useMiniflare( { BindingsPlugin }, { name: "a", modules: true, script: `export default { fetch(request, env) { const { pathname } = new URL(request.url); if (pathname === "/ping") { return new Response("pong"); } return env.SERVICE_B.fetch("http://localhost/test", { method: "POST" }); } }`, serviceBindings: { SERVICE_B: { service: "b", environment: "production" }, }, mounts: { b: { name: "b", modules: true, script: `export default { async fetch(request, env) { const res = await env.SERVICE_A.fetch("http://localhost/ping"); const text = await res.text(); return new Response(request.method + " " + request.url + ":" + text); } }`, // Implicitly testing service binding shorthand serviceBindings: { SERVICE_A: "a" }, }, }, } ); const res = await mf.dispatchFetch("http://localhost/"); t.is(await res.text(), "POST http://localhost/test:pong"); }); test("BindingsPlugin: dispatches fetch to custom service", async (t) => { const plugin = new BindingsPlugin(ctx, { serviceBindings: { async SERVICE(request) { return new Response(`${request.method} ${request.url}`); }, }, }); const { bindings } = await plugin.setup(); let res = await bindings!.SERVICE.fetch("http://localhost/", { method: "POST", }); t.is(await res.text(), "POST http://localhost/"); // No need to run beforeReload()/reload() hooks here, but just check that // running them doesn't break anything plugin.beforeReload(); plugin.reload({}, {}, new Map()); res = await bindings!.SERVICE.fetch("http://localhost/test"); t.is(await res.text(), "GET http://localhost/test"); }); test("BindingsPlugin: waits for services before dispatching", async (t) => { const plugin = new BindingsPlugin(ctx, { // Implicitly testing service binding without environment serviceBindings: { SERVICE: { service: "a" } }, }); const { bindings } = await plugin.setup(); plugin.beforeReload(); // Simulate fetching before reload complete const res = bindings!.SERVICE.fetch("http://localhost/"); await setImmediate(); const mount: _CoreMount = { dispatchFetch: async () => new Response("a service"), }; plugin.reload({}, {}, new Map([["a", mount]])); t.is(await (await res).text(), "a service"); }); test("BindingsPlugin: reload: throws if service isn't mounted", async (t) => { let plugin = new BindingsPlugin(ctx, { serviceBindings: { SERVICE: "a" }, }); await plugin.setup(); plugin.beforeReload(); t.throws(() => plugin.reload({}, {}, new Map()), { instanceOf: MiniflareCoreError, code: "ERR_SERVICE_NOT_MOUNTED", message: 'Service "a" for binding "SERVICE" not found.\nMake sure "a" is mounted so Miniflare knows where to find it.', }); // Check doesn't throw if using custom fetch function plugin = new BindingsPlugin(ctx, { serviceBindings: { SERVICE: () => new Response() }, }); await plugin.setup(); plugin.beforeReload(); plugin.reload({}, {}, new Map()); t.pass(); }); test("BindingsPlugin: reloads service bindings used by mount when another mounted worker reloads", async (t) => { const mf = useMiniflare( { BindingsPlugin }, { mounts: { a: { modules: true, routes: ["*"], script: `export default { async fetch(request, env) { const res = await env.SERVICE_B.fetch("http://localhost/"); return new Response("a" + await res.text()); } }`, serviceBindings: { SERVICE_B: "b" }, }, b: { modules: true, script: `export default { fetch: () => new Response("b1") }`, }, }, } ); let res = await mf.dispatchFetch("http://localhost/"); t.is(await res.text(), "ab1"); // Update "b" and check new response const b = await mf.getMount("b"); await b.setOptions({ script: `export default { fetch: () => new Response("b2") }`, }); res = await mf.dispatchFetch("http://localhost/"); t.is(await res.text(), "ab2"); }); test("BindingsPlugin: passes through when service doesn't respond", async (t) => { const upstream = (await useServer(t, (req, res) => res.end("upstream"))).http; const mf = useMiniflare( { BindingsPlugin }, { name: "parent", script: 'addEventListener("fetch", () => {})', mounts: { a: { script: 'addEventListener("fetch", () => {})' }, b: { modules: true, script: `export default { fetch(request, env, ctx) { ctx.passThroughOnException(); throw new Error("oops"); } }`, }, c: { modules: true, routes: ["*/*"], script: `export default { async fetch(request, env) { const { pathname } = new URL(request.url); const name = pathname === "/a" ? "SERVICE_A" : pathname === "/b" ? "SERVICE_B" : "SERVICE_PARENT"; const service = env[name]; const res = await service.fetch(${JSON.stringify(upstream)}); return new Response(name + ":" + await res.text()); } }`, serviceBindings: { SERVICE_A: "a", SERVICE_B: "b", SERVICE_PARENT: "parent", }, }, }, } ); // Check with both another mounted service and the parent and when // passThroughOnException() is called let res = await mf.dispatchFetch("http://localhost/a"); t.is(await res.text(), "SERVICE_A:upstream"); res = await mf.dispatchFetch("http://localhost/b"); t.is(await res.text(), "SERVICE_B:upstream"); res = await mf.dispatchFetch("http://localhost/parent"); t.is(await res.text(), "SERVICE_PARENT:upstream"); }); test("BindingsPlugin: propagates error if service throws", async (t) => { const mf = useMiniflare( { BindingsPlugin }, { modules: true, script: `export default { async fetch(request, env) { await env.SERVICE.fetch(request); return new Response("body"); } , }`, serviceBindings: { SERVICE: "a" }, mounts: { a: { modules: true, script: `export default { fetch: () => { throw new Error("oops"); }, }`, }, }, } ); await t.throwsAsync(mf.dispatchFetch("http://localhost/"), { message: "oops", }); }); test("BindingsPlugin: service fetch creates new request context", async (t) => { // noinspection JSUnusedGlobalSymbols const bindings = { assertSubrequests(expected: number) { t.is(getRequestContext()?.subrequests, expected); }, }; const mf = useMiniflare( { BindingsPlugin, CachePlugin }, { bindings, serviceBindings: { SERVICE: "a" }, modules: true, script: `export default { async fetch(request, env) { env.assertSubrequests(0); await caches.default.match("http://localhost/"); env.assertSubrequests(1); return await env.SERVICE.fetch(request); }, }`, mounts: { a: { bindings, modules: true, script: `export default { async fetch(request, env) { env.assertSubrequests(0); await caches.default.match("http://localhost/"); env.assertSubrequests(1); const n = parseInt(new URL(request.url).searchParams.get("n")); await Promise.all( Array.from(Array(n)).map(() => caches.default.match("http://localhost/")) ); return new Response("body"); }, }`, }, }, } ); await t.throwsAsync(mf.dispatchFetch("http://localhost/?n=50"), { instanceOf: Error, message: /^Too many subrequests/, }); const res = await mf.dispatchFetch("http://localhost/?n=1"); t.is(await res.text(), "body"); }); test("BindingsPlugin: service fetch increases pipeline depth", async (t) => { const depths: [request: number, pipeline: number][] = []; const mf = useMiniflare( { BindingsPlugin }, { bindings: { recordDepth() { const ctx = getRequestContext()!; depths.push([ctx.requestDepth, ctx.pipelineDepth]); }, }, modules: true, name: "service", serviceBindings: { SERVICE: "service" }, script: `export default { async fetch(request, env) { env.recordDepth(); const url = new URL(request.url); const n = parseInt(url.searchParams.get("n") ?? "0"); if (n === 0) return new Response("end"); url.searchParams.set("n", n - 1); const res = await env.SERVICE.fetch(url); return new Response(\`\${n},\${await res.text()}\`); } }`, } ); const res = await mf.dispatchFetch("http://localhost/?n=3"); t.is(await res.text(), "3,2,1,end"); t.deepEqual(depths, [ [1, 1], [1, 2], [1, 3], [1, 4], ]); await mf.dispatchFetch("http://localhost/?n=31"); // Shouldn't throw await t.throwsAsync(mf.dispatchFetch("http://localhost/?n=32"), { instanceOf: Error, message: /^Subrequest depth limit exceeded.+\nService bindings can recurse up to 32 times\./, }); });
the_stack
export interface paths { "/pet": { put: operations["updatePet"]; post: operations["addPet"]; }; "/pet/findByStatus": { /** Multiple status values can be provided with comma separated strings */ get: operations["findPetsByStatus"]; }; "/pet/findByTags": { /** Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ get: operations["findPetsByTags"]; }; "/pet/{petId}": { /** Returns a single pet */ get: operations["getPetById"]; post: operations["updatePetWithForm"]; delete: operations["deletePet"]; }; "/pet/{petId}/uploadImage": { post: operations["uploadFile"]; }; "/store/inventory": { /** Returns a map of status codes to quantities */ get: operations["getInventory"]; }; "/store/order": { post: operations["placeOrder"]; }; "/store/order/{orderId}": { /** For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions */ get: operations["getOrderById"]; /** For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors */ delete: operations["deleteOrder"]; }; "/user": { /** This can only be done by the logged in user. */ post: operations["createUser"]; }; "/user/createWithArray": { post: operations["createUsersWithArrayInput"]; }; "/user/createWithList": { post: operations["createUsersWithListInput"]; }; "/user/login": { get: operations["loginUser"]; }; "/user/logout": { get: operations["logoutUser"]; }; "/user/{username}": { get: operations["getUserByName"]; /** This can only be done by the logged in user. */ put: operations["updateUser"]; /** This can only be done by the logged in user. */ delete: operations["deleteUser"]; }; } export interface components { schemas: { /** * Pet Order * @description An order for a pets from the pet store */ Order: { /** Format: int64 */ id?: number; /** Format: int64 */ petId?: number; /** Format: int32 */ quantity?: number; /** Format: date-time */ shipDate?: string; /** @description Order Status */ status?: "placed" | "approved" | "delivered"; complete?: boolean; }; /** * Pet category * @description A category for a pet */ Category: { /** Format: int64 */ id?: number; name?: string; }; /** * a User * @description A User who is purchasing from the pet store */ User: { /** Format: int64 */ id?: number; username?: string; firstName?: string; lastName?: string; email?: string; password?: string; phone?: string; /** * Format: int32 * @description User Status */ userStatus?: number; }; /** * Pet Tag * @description A tag for a pet */ Tag: { /** Format: int64 */ id?: number; name?: string; }; /** * a Pet * @description A pet for sale in the pet store */ Pet: { /** Format: int64 */ id?: number; category?: components["schemas"]["Category"]; /** @example doggie */ name: string; photoUrls: string[]; tags?: components["schemas"]["Tag"][]; /** @description pet status in the store */ status?: "available" | "pending" | "sold"; }; /** * An uploaded response * @description Describes the result of uploading an image resource */ ApiResponse: { /** Format: int32 */ code?: number; type?: string; message?: string; }; }; requestBodies: { /** List of user object */ UserArray: { content: { "application/json": components["schemas"]["User"][]; }; }; /** Pet object that needs to be added to the store */ Pet: { content: { "application/json": components["schemas"]["Pet"]; "application/xml": components["schemas"]["Pet"]; }; }; }; } export interface operations { updatePet: { responses: { /** successful operation */ 200: { content: { "application/xml": components["schemas"]["Pet"]; "application/json": components["schemas"]["Pet"]; }; }; /** Invalid ID supplied */ 400: unknown; /** Pet not found */ 404: unknown; /** Validation exception */ 405: unknown; }; requestBody: components["requestBodies"]["Pet"]; }; addPet: { responses: { /** successful operation */ 200: { content: { "application/xml": components["schemas"]["Pet"]; "application/json": components["schemas"]["Pet"]; }; }; /** Invalid input */ 405: unknown; }; requestBody: components["requestBodies"]["Pet"]; }; /** Multiple status values can be provided with comma separated strings */ findPetsByStatus: { parameters: { query: { /** Status values that need to be considered for filter */ status: ("available" | "pending" | "sold")[]; }; }; responses: { /** successful operation */ 200: { content: { "application/xml": components["schemas"]["Pet"][]; "application/json": components["schemas"]["Pet"][]; }; }; /** Invalid status value */ 400: unknown; }; }; /** Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ findPetsByTags: { parameters: { query: { /** Tags to filter by */ tags: string[]; }; }; responses: { /** successful operation */ 200: { content: { "application/xml": components["schemas"]["Pet"][]; "application/json": components["schemas"]["Pet"][]; }; }; /** Invalid tag value */ 400: unknown; }; }; /** Returns a single pet */ getPetById: { parameters: { path: { /** ID of pet to return */ petId: number; }; }; responses: { /** successful operation */ 200: { content: { "application/xml": components["schemas"]["Pet"]; "application/json": components["schemas"]["Pet"]; }; }; /** Invalid ID supplied */ 400: unknown; /** Pet not found */ 404: unknown; }; }; updatePetWithForm: { parameters: { path: { /** ID of pet that needs to be updated */ petId: number; }; }; responses: { /** Invalid input */ 405: unknown; }; requestBody: { content: { "application/x-www-form-urlencoded": { /** @description Updated name of the pet */ name?: string; /** @description Updated status of the pet */ status?: string; }; }; }; }; deletePet: { parameters: { header: { api_key?: string; }; path: { /** Pet id to delete */ petId: number; }; }; responses: { /** Invalid pet value */ 400: unknown; }; }; uploadFile: { parameters: { path: { /** ID of pet to update */ petId: number; }; }; responses: { /** successful operation */ 200: { content: { "application/json": components["schemas"]["ApiResponse"]; }; }; }; requestBody: { content: { "multipart/form-data": { /** @description Additional data to pass to server */ additionalMetadata?: string; /** * Format: binary * @description file to upload */ file?: string; }; }; }; }; /** Returns a map of status codes to quantities */ getInventory: { responses: { /** successful operation */ 200: { content: { "application/json": { [key: string]: number }; }; }; }; }; placeOrder: { responses: { /** successful operation */ 200: { content: { "application/xml": components["schemas"]["Order"]; "application/json": components["schemas"]["Order"]; }; }; /** Invalid Order */ 400: unknown; }; /** order placed for purchasing the pet */ requestBody: { content: { "application/json": components["schemas"]["Order"]; }; }; }; /** For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions */ getOrderById: { parameters: { path: { /** ID of pet that needs to be fetched */ orderId: number; }; }; responses: { /** successful operation */ 200: { content: { "application/xml": components["schemas"]["Order"]; "application/json": components["schemas"]["Order"]; }; }; /** Invalid ID supplied */ 400: unknown; /** Order not found */ 404: unknown; }; }; /** For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors */ deleteOrder: { parameters: { path: { /** ID of the order that needs to be deleted */ orderId: string; }; }; responses: { /** Invalid ID supplied */ 400: unknown; /** Order not found */ 404: unknown; }; }; /** This can only be done by the logged in user. */ createUser: { responses: { /** successful operation */ default: unknown; }; /** Created user object */ requestBody: { content: { "application/json": components["schemas"]["User"]; }; }; }; createUsersWithArrayInput: { responses: { /** successful operation */ default: unknown; }; requestBody: components["requestBodies"]["UserArray"]; }; createUsersWithListInput: { responses: { /** successful operation */ default: unknown; }; requestBody: components["requestBodies"]["UserArray"]; }; loginUser: { parameters: { query: { /** The user name for login */ username: string; /** The password for login in clear text */ password: string; }; }; responses: { /** successful operation */ 200: { headers: { /** Cookie authentication key for use with the `api_key` apiKey authentication. */ "Set-Cookie"?: string; /** calls per hour allowed by the user */ "X-Rate-Limit"?: number; /** date in UTC when toekn expires */ "X-Expires-After"?: string; }; content: { "application/xml": string; "application/json": string; }; }; /** Invalid username/password supplied */ 400: unknown; }; }; logoutUser: { responses: { /** successful operation */ default: unknown; }; }; getUserByName: { parameters: { path: { /** The name that needs to be fetched. Use user1 for testing. */ username: string; }; }; responses: { /** successful operation */ 200: { content: { "application/xml": components["schemas"]["User"]; "application/json": components["schemas"]["User"]; }; }; /** Invalid username supplied */ 400: unknown; /** User not found */ 404: unknown; }; }; /** This can only be done by the logged in user. */ updateUser: { parameters: { path: { /** name that need to be deleted */ username: string; }; }; responses: { /** Invalid user supplied */ 400: unknown; /** User not found */ 404: unknown; }; /** Updated user object */ requestBody: { content: { "application/json": components["schemas"]["User"]; }; }; }; /** This can only be done by the logged in user. */ deleteUser: { parameters: { path: { /** The name that needs to be deleted */ username: string; }; }; responses: { /** Invalid username supplied */ 400: unknown; /** User not found */ 404: unknown; }; }; } export interface external {}
the_stack
import { API_DOMAIN, API_VER } from "./config"; import { Vector, FrameOffset } from "./ast-types"; import { GetFileResult, GetFileNodesResult, GetImageResult, GetImageFillsResult, GetCommentsResult, PostCommentResult, DeleteCommentsResult, GetUserMeResult, GetVersionsResult, GetTeamProjectsResult, GetProjectFilesResult, GetTeamComponentsResult, GetFileComponentsResult, GetComponentResult, GetTeamComponentSetsResult, GetFileComponentSetsResult, GetComponentSetResult, GetTeamStylesResult, GetFileStylesResult, GetStyleResult, StyleMetadata, ComponentMetadata, } from "./api-types"; import { ApiRequestMethod, toQueryParams } from "./utils"; type ApiClass = { request: ApiRequestMethod }; // FIGMA FILES // ----------------------------------------------------------------- export function getFileApi(this: ApiClass, /** * File to export JSON from * * Can be found in url to file, eg: * https://www.figma.com/file/FILE_KEY/FILE_NAME */ fileKey: string, opts?: { /** A specific version ID to get. Omitting this will get the current version of the file */ version?: string, /** If specified, only a subset of the document will be returned corresponding to the nodes listed, their children, and everything between the root node and the listed nodes */ ids?: string[], /** Positive integer representing how deep into the document tree to traverse. For example, setting this to 1 returns only Pages, setting it to 2 returns Pages and all top level objects on each page. Not setting this parameter returns all nodes */ depth?: number, /** Set to "paths" to export vector data */ geometry?: 'paths', /** A comma separated list of plugin IDs and/or the string "shared". Any data present in the document written by those plugins will be included in the result in the `pluginData` and `sharedPluginData` properties. */ plugin_data?: string, } ): Promise<GetFileResult> { const queryParams = toQueryParams({ ...opts, ids: opts && opts.ids && opts.ids.join(',') }); return this.request<GetFileResult>(`${API_DOMAIN}/${API_VER}/files/${fileKey}?${queryParams}`); } export function getFileNodesApi(this: ApiClass, /** * File to export JSON from * * Can be found in url to file, eg: * https://www.figma.com/file/FILE_KEY/FILE_NAME */ fileKey: string, /** list of node IDs to retrieve and convert */ ids: string[], opts?: { /** A specific version ID to get. Omitting this will get the current version of the file */ version?: string, /** Positive integer representing how deep into the document tree to traverse. For example, setting this to 1 returns only Pages, setting it to 2 returns Pages and all top level objects on each page. Not setting this parameter returns all nodes */ depth?: number, /** Set to "paths" to export vector data */ geometry?: 'paths', /** A comma separated list of plugin IDs and/or the string "shared". Any data present in the document written by those plugins will be included in the result in the `pluginData` and `sharedPluginData` properties. */ plugin_data?: string, } ): Promise<GetFileNodesResult> { const queryParams = toQueryParams({ ...opts, ids: ids.join(',') }); return this.request<GetFileNodesResult>(`${API_DOMAIN}/${API_VER}/files/${fileKey}/nodes?${queryParams}`); } export function getImageApi(this: ApiClass, fileKey: string, opts: { /** A comma separated list of node IDs to render */ ids: string, /** A number between 0.01 and 4, the image scaling factor */ scale: number, /** A string enum for the image output format */ format: 'jpg'|'png'|'svg'|'pdf', /** Whether to include id attributes for all SVG elements. `Default: false` */ svg_include_id?: boolean, /** Whether to simplify inside/outside strokes and use stroke attribute if possible instead of <mask>. `Default: true` */ svg_simplify_stroke?: boolean, /** Use the full dimensions of the node regardless of whether or not it is cropped or the space around it is empty. Use this to export text nodes without cropping. `Default: false` */ use_absolute_bounds?: boolean, /** A specific version ID to get. Omitting this will get the current version of the file */ version?: string, } ): Promise<GetImageResult> { const queryParams = toQueryParams(opts); return this.request<GetImageResult>(`${API_DOMAIN}/${API_VER}/images/${fileKey}?${queryParams}`); } export function getImageFillsApi(this: ApiClass, fileKey: string): Promise<GetImageFillsResult> { return this.request<GetImageFillsResult>(`${API_DOMAIN}/${API_VER}/files/${fileKey}/images`); } // COMMENTS // ----------------------------------------------------------------- export function getCommentsApi(this: ApiClass, fileKey: string): Promise<GetCommentsResult> { return this.request<GetCommentsResult>(`${API_DOMAIN}/${API_VER}/files/${fileKey}/comments`); } export function postCommentsApi( this: ApiClass, fileKey: string, /** The text contents of the comment to post */ message: string, /** The position of where to place the comment. This can either be an absolute canvas position or the relative position within a frame. */ client_meta: Vector|FrameOffset, /** (Optional) The comment to reply to, if any. This must be a root comment, that is, you cannot reply to a comment that is a reply itself (a reply has a parent_id). */ comment_id?: string, ): Promise<PostCommentResult> { const body: any = comment_id ? { message, client_meta, comment_id } : { message, client_meta }; /** Notice: we need to pass a custom 'Content-Type' header (as 'application-json') or the current implementation * (see `this.appendHeaders` in api-class.ts) will use the default 'application/x-www-form-urlencoded' content-type */ return this.request<PostCommentResult>(`${API_DOMAIN}/${API_VER}/files/${fileKey}/comments`, { method: 'POST', data: body, }); } export function deleteCommentsApi(this: ApiClass, fileKey: string, comment_id: string): Promise<DeleteCommentsResult> { return this.request(`${API_DOMAIN}/${API_VER}/files/${fileKey}/comments/${comment_id}`, { method: 'DELETE', data: '' }); } // USERS // ----------------------------------------------------------------- export function getUserMeApi(this: ApiClass): Promise<GetUserMeResult> { return this.request(`${API_DOMAIN}/${API_VER}/me`); } // VERSION HISTORY // ----------------------------------------------------------------- export function getVersionsApi(this: ApiClass, fileKey: string): Promise<GetVersionsResult> { return this.request(`${API_DOMAIN}/${API_VER}/files/${fileKey}/versions`); } // PROJECTS // ----------------------------------------------------------------- export function getTeamProjectsApi(this: ApiClass, team_id: string): Promise<GetTeamProjectsResult> { return this.request(`${API_DOMAIN}/${API_VER}/teams/${team_id}/projects`); } export function getProjectFilesApi(this: ApiClass, project_id: string): Promise<GetProjectFilesResult> { return this.request(`${API_DOMAIN}/${API_VER}/projects/${project_id}/files`); } // COMPONENTS AND STYLES // ----------------------------------------------------------------- /** Get a paginated list of published components within a team library */ export function getTeamComponentsApi( this: ApiClass, /** Id of the team to list components from */ team_id: string, opts: { /** Number of items in a paged list of results. Defaults to 30. */ page_size?: number, /** Cursor indicating which id after which to start retrieving components for. Exclusive with before. The cursor value is an internally tracked integer that doesn't correspond to any Ids */ after?: number, /** Cursor indicating which id before which to start retrieving components for. Exclusive with after. The cursor value is an internally tracked integer that doesn't correspond to any Ids */ before?: number, } = {} ): Promise<GetTeamComponentsResult> { const queryParams = toQueryParams(opts); return this.request(`${API_DOMAIN}/${API_VER}/teams/${team_id}/components?${queryParams}`); } export function getFileComponentsApi(this: ApiClass, fileKey: string): Promise<GetFileComponentsResult> { return this.request(`${API_DOMAIN}/${API_VER}/files/${fileKey}/components`); } /** Get metadata on a component by key. */ export function getComponentApi( this: ApiClass, /** The unique identifier of the component. */ key: string ): Promise<GetComponentResult> { return this.request(`${API_DOMAIN}/${API_VER}/components/${key}`); } export function getTeamComponentSetsApi( this: ApiClass, /** Id of the team to list component_sets from */ team_id: string, opts: { /** Number of items in a paged list of results. Defaults to 30. */ page_size?: number, /** Cursor indicating which id after which to start retrieving components for. Exclusive with before. The cursor value is an internally tracked integer that doesn't correspond to any Ids */ after?: number, /** Cursor indicating which id before which to start retrieving components for. Exclusive with after. The cursor value is an internally tracked integer that doesn't correspond to any Ids */ before?: number, } = {} ): Promise<GetTeamComponentSetsResult> { const queryParams = toQueryParams(opts); return this.request(`${API_DOMAIN}/${API_VER}/teams/${team_id}/component_sets?${queryParams}`); } export function getFileComponentSetsApi(this: ApiClass, file_key: string): Promise<GetFileComponentSetsResult> { return this.request(`${API_DOMAIN}/${API_VER}/files/${file_key}/component_sets`); } export function getComponentSetApi( this: ApiClass, /** The unique identifier of the component_set */ key: string, ): Promise<GetComponentSetResult> { return this.request(`${API_DOMAIN}/${API_VER}/component_sets/${key}`); } export function getTeamStylesApi( this: ApiClass, team_id: string, opts: { /** Number of items in a paged list of results. Defaults to 30. */ page_size?: number, /** Cursor indicating which id after which to start retrieving components for. Exclusive with before. The cursor value is an internally tracked integer that doesn't correspond to any Ids */ after?: number, /** Cursor indicating which id before which to start retrieving components for. Exclusive with after. The cursor value is an internally tracked integer that doesn't correspond to any Ids */ before?: number, } = {} ): Promise<GetTeamStylesResult> { const queryParams = toQueryParams(opts); return this.request(`${API_DOMAIN}/${API_VER}/teams/${team_id}/styles?${queryParams}`); } export function getFileStylesApi(this: ApiClass, file_key: string): Promise<GetFileStylesResult> { return this.request(`${API_DOMAIN}/${API_VER}/files/${file_key}/styles`); } export function getStyleApi( this: ApiClass, /** The unique identifier of the style */ key: string, ): Promise<GetStyleResult> { return this.request(`${API_DOMAIN}/${API_VER}/styles/${key}`); }
the_stack
import { AndroidDeviceDiscovery } from "../../../mobile/mobile-core/android-device-discovery"; import { AndroidDebugBridge } from "../../../mobile/android/android-debug-bridge"; import { AndroidDebugBridgeResultHandler } from "../../../mobile/android/android-debug-bridge-result-handler"; import { Yok } from "../../../yok"; import * as _ from "lodash"; import { DeviceDiscoveryEventNames } from "../../../constants"; import { EventEmitter } from "events"; import { EOL } from "os"; import { assert } from "chai"; import { IInjector } from "../../../definitions/yok"; import { IDictionary } from "../../../declarations"; class AndroidDeviceMock { public deviceInfo: any = {}; constructor(public identifier: string, public status: string) { this.deviceInfo.identifier = identifier; this.deviceInfo.status = status; } public async init() { /* intentionally empty body */ } } interface IChildProcessMock { stdout: MockEventEmitter; stderr: MockEventEmitter; } class MockEventEmitter extends EventEmitter implements IChildProcessMock { public stdout: MockEventEmitter; public stderr: MockEventEmitter; } let mockStdoutEmitter: MockEventEmitter; let mockStderrEmitter: MockEventEmitter; let mockChildProcess: any; function createTestInjector(): IInjector { const injector = new Yok(); injector.register("injector", injector); injector.register("adb", AndroidDebugBridge); injector.register("errors", {}); injector.register("logger", {}); injector.register( "androidDebugBridgeResultHandler", AndroidDebugBridgeResultHandler ); injector.register("mobileHelper", { isAndroidPlatform: () => { return true; }, }); injector.register("childProcess", { spawn: (command: string, args?: string[], options?: any) => { mockChildProcess = new MockEventEmitter(); mockChildProcess.stdout = mockStdoutEmitter; mockChildProcess.stderr = mockStderrEmitter; return mockChildProcess; }, spawnFromEvent: ( command: string, args: string[], event: string, options?: any, spawnFromEventOptions?: any ) => { return Promise.resolve(args); }, }); injector.register("staticConfig", { getAdbFilePath: () => { return Promise.resolve("adbPath"); }, }); injector.register("androidDeviceDiscovery", AndroidDeviceDiscovery); const originalResolve = injector.resolve; // replace resolve as we do not want to create real AndroidDevice const resolve = (param: any, ctorArguments?: IDictionary<any>) => { if ( ctorArguments && Object.prototype.hasOwnProperty.call(ctorArguments, "status") && Object.prototype.hasOwnProperty.call(ctorArguments, "identifier") ) { return new AndroidDeviceMock( ctorArguments["identifier"], ctorArguments["status"] ); } else { return originalResolve.apply(injector, [param, ctorArguments]); } }; injector.resolve = resolve; return injector; } describe("androidDeviceDiscovery", () => { let androidDeviceDiscovery: Mobile.IAndroidDeviceDiscovery; let injector: IInjector; const androidDeviceIdentifier = "androidDevice"; const androidDeviceStatus = "device"; let devicesFound: any[]; beforeEach(() => { mockChildProcess = null; injector = createTestInjector(); mockStdoutEmitter = new MockEventEmitter(); mockStderrEmitter = new MockEventEmitter(); androidDeviceDiscovery = injector.resolve("androidDeviceDiscovery"); devicesFound = []; }); describe("startLookingForDevices", () => { it("finds correctly one device", async () => { androidDeviceDiscovery.on( DeviceDiscoveryEventNames.DEVICE_FOUND, (device: Mobile.IDevice) => { devicesFound.push(device); } ); // As startLookingForDevices is blocking, we should emit data on the next tick, so the future will be resolved and we'll receive the data. setTimeout(() => { const output = `List of devices attached ${EOL}${androidDeviceIdentifier} ${androidDeviceStatus}${EOL}${EOL}`; mockStdoutEmitter.emit("data", output); mockChildProcess.emit("close", 0); }, 1); await androidDeviceDiscovery.startLookingForDevices(); assert.isTrue( devicesFound.length === 1, "We should have found ONE device." ); assert.deepStrictEqual( devicesFound[0].deviceInfo.identifier, androidDeviceIdentifier ); assert.deepStrictEqual(devicesFound[0].status, androidDeviceStatus); }); }); describe("ensureAdbServerStarted", () => { it("should spawn adb with start-server parameter", async () => { const ensureAdbServerStartedOutput = await androidDeviceDiscovery.ensureAdbServerStarted(); assert.isTrue( _.includes(ensureAdbServerStartedOutput, "start-server"), "start-server should be passed to adb." ); }); }); describe("startLookingForDevices", () => { it("finds correctly one device", async () => { let promise: Promise<void>; androidDeviceDiscovery.on( DeviceDiscoveryEventNames.DEVICE_FOUND, (device: Mobile.IDevice) => { promise = new Promise<void>((resolve, reject) => { devicesFound.push(device); resolve(); }); } ); setTimeout(() => { const output = `List of devices attached ${EOL}${androidDeviceIdentifier} ${androidDeviceStatus}${EOL}${EOL}`; mockStdoutEmitter.emit("data", output); mockChildProcess.emit("close", 0); }, 0); await androidDeviceDiscovery.startLookingForDevices(); await promise; assert.isTrue( devicesFound.length === 1, "We should have found ONE device." ); assert.deepStrictEqual( devicesFound[0].deviceInfo.identifier, androidDeviceIdentifier ); assert.deepStrictEqual(devicesFound[0].status, androidDeviceStatus); }); it("finds correctly more than one device", async () => { let promise: Promise<void>; androidDeviceDiscovery.on( DeviceDiscoveryEventNames.DEVICE_FOUND, (device: Mobile.IDevice) => { promise = new Promise<void>((resolve, reject) => { devicesFound.push(device); if (devicesFound.length === 2) { resolve(); } }); } ); setTimeout(() => { const output = `List of devices attached ${EOL}${androidDeviceIdentifier} ${androidDeviceStatus}${EOL}secondDevice ${androidDeviceStatus}${EOL}`; mockStdoutEmitter.emit("data", output); mockChildProcess.emit("close", 0); }, 0); await androidDeviceDiscovery.startLookingForDevices(); await promise; assert.isTrue( devicesFound.length === 2, "We should have found two devices." ); assert.deepStrictEqual( devicesFound[0].deviceInfo.identifier, androidDeviceIdentifier ); assert.deepStrictEqual(devicesFound[0].status, androidDeviceStatus); assert.deepStrictEqual( devicesFound[1].deviceInfo.identifier, "secondDevice" ); assert.deepStrictEqual(devicesFound[1].status, androidDeviceStatus); }); it("does not find any devices when there are no devices", async () => { androidDeviceDiscovery.on( DeviceDiscoveryEventNames.DEVICE_FOUND, (device: Mobile.IDevice) => { throw new Error("Devices should not be found."); } ); setTimeout(() => { const output = `List of devices attached${EOL}`; mockStdoutEmitter.emit("data", output); mockChildProcess.emit("close", 0); }, 0); await androidDeviceDiscovery.startLookingForDevices(); assert.isTrue( devicesFound.length === 0, "We should have NOT found devices." ); }); const validateDeviceFoundWhenAdbReportsAdditionalMessages = async ( adbMessage: string ) => { let promise: Promise<void>; androidDeviceDiscovery.on( DeviceDiscoveryEventNames.DEVICE_FOUND, (device: Mobile.IDevice) => { promise = new Promise<void>((resolve, reject) => { devicesFound.push(device); resolve(); }); } ); setTimeout(() => { const output = `List of devices attached ${EOL}${adbMessage}${EOL}${androidDeviceIdentifier} ${androidDeviceStatus}${EOL}${EOL}`; mockStdoutEmitter.emit("data", output); mockChildProcess.emit("close", 0); }, 0); await androidDeviceDiscovery.startLookingForDevices(); await promise; assert.isTrue( devicesFound.length === 1, "We should have found ONE device." ); assert.deepStrictEqual( devicesFound[0].deviceInfo.identifier, androidDeviceIdentifier ); assert.deepStrictEqual(devicesFound[0].status, androidDeviceStatus); }; describe("does not report adb messages as new devices", () => { const adbAdditionalMessages = [ `adb server is out of date. killing...${EOL}* daemon started successfully *`, `adb server version (31) doesn't match this client (36); killing...${EOL}* daemon started successfully *`, "* daemon started successfully *", `* daemon not running. starting it now on port 5037 *${EOL}* daemon started successfully *`, ]; for (let index = 0; index < adbAdditionalMessages.length; index++) { const msg = adbAdditionalMessages[index]; it(`msg: ${msg}`, async () => { await validateDeviceFoundWhenAdbReportsAdditionalMessages(msg); }); } }); describe("when device is already found", () => { const defaultAdbOutput = `List of devices attached ${EOL}${androidDeviceIdentifier} ${androidDeviceStatus}${EOL}${EOL}`; beforeEach(async () => { let promise: Promise<void>; androidDeviceDiscovery.on( DeviceDiscoveryEventNames.DEVICE_FOUND, (device: Mobile.IDevice) => { promise = new Promise<void>((resolve, reject) => { devicesFound.push(device); resolve(); }); } ); setTimeout(() => { mockStdoutEmitter.emit("data", defaultAdbOutput); mockChildProcess.emit("close", 0); }, 0); await androidDeviceDiscovery.startLookingForDevices(); await promise; androidDeviceDiscovery.removeAllListeners( DeviceDiscoveryEventNames.DEVICE_FOUND ); }); it("does not report it as found next time when startLookingForDevices is called and same device is still connected", async () => { androidDeviceDiscovery.on( DeviceDiscoveryEventNames.DEVICE_FOUND, (device: Mobile.IDevice) => { throw new Error("Should not report same device as found"); } ); setTimeout(() => { mockStdoutEmitter.emit("data", defaultAdbOutput); mockChildProcess.emit("close", 0); }, 0); await androidDeviceDiscovery.startLookingForDevices(); assert.isTrue( devicesFound.length === 1, "We should have found ONE device." ); assert.deepStrictEqual( devicesFound[0].deviceInfo.identifier, androidDeviceIdentifier ); assert.deepStrictEqual(devicesFound[0].status, androidDeviceStatus); }); it("reports it as removed next time when called and device is removed", async () => { let promise: Promise<Mobile.IDevice>; androidDeviceDiscovery.on( DeviceDiscoveryEventNames.DEVICE_LOST, (device: Mobile.IDevice) => { promise = Promise.resolve(device); } ); setTimeout(() => { const output = `List of devices attached${EOL}`; mockStdoutEmitter.emit("data", output); mockChildProcess.emit("close", 0); }, 0); await androidDeviceDiscovery.startLookingForDevices(); const lostDevice = await promise; assert.deepStrictEqual( lostDevice.deviceInfo.identifier, androidDeviceIdentifier ); assert.deepStrictEqual( lostDevice.deviceInfo.status, androidDeviceStatus ); }); it("does not report it as removed two times when called and device is removed", async () => { let promise: Promise<Mobile.IDevice>; androidDeviceDiscovery.on( DeviceDiscoveryEventNames.DEVICE_LOST, (device: Mobile.IDevice) => { promise = Promise.resolve(device); } ); const output = `List of devices attached${EOL}`; setTimeout(() => { mockStdoutEmitter.emit("data", output); mockChildProcess.emit("close", 0); }, 0); await androidDeviceDiscovery.startLookingForDevices(); const lostDevice = await promise; assert.deepStrictEqual( lostDevice.deviceInfo.identifier, androidDeviceIdentifier ); assert.deepStrictEqual( lostDevice.deviceInfo.status, androidDeviceStatus ); androidDeviceDiscovery.on( DeviceDiscoveryEventNames.DEVICE_LOST, (device: Mobile.IDevice) => { throw new Error( "Should not report device as removed next time after it has been already reported." ); } ); setTimeout(() => { mockStdoutEmitter.emit("data", output); mockChildProcess.emit("close", 0); }, 0); await androidDeviceDiscovery.startLookingForDevices(); }); it("reports it as removed and added after that next time when called and device's status is changed", async () => { let deviceLostPromise: Promise<Mobile.IDevice>; let deviceFoundPromise: Promise<Mobile.IDevice>; androidDeviceDiscovery.on( DeviceDiscoveryEventNames.DEVICE_LOST, (device: Mobile.IDevice) => { _.remove( devicesFound, (d) => d.deviceInfo.identifier === device.deviceInfo.identifier ); deviceLostPromise = Promise.resolve(device); } ); androidDeviceDiscovery.on( DeviceDiscoveryEventNames.DEVICE_FOUND, (device: Mobile.IDevice) => { devicesFound.push(device); deviceFoundPromise = Promise.resolve(device); } ); const output = `List of devices attached${EOL}${androidDeviceIdentifier} unauthorized${EOL}${EOL}`; setTimeout(() => { mockStdoutEmitter.emit("data", output); mockChildProcess.emit("close", 0); }, 0); await androidDeviceDiscovery.startLookingForDevices(); const lostDevice = await deviceLostPromise; assert.deepStrictEqual( lostDevice.deviceInfo.identifier, androidDeviceIdentifier ); assert.deepStrictEqual( lostDevice.deviceInfo.status, androidDeviceStatus ); await deviceFoundPromise; assert.isTrue( devicesFound.length === 1, "We should have found ONE device." ); assert.deepStrictEqual( devicesFound[0].deviceInfo.identifier, androidDeviceIdentifier ); assert.deepStrictEqual(devicesFound[0].status, "unauthorized"); // Verify the device will not be reported as found next time when adb returns the same output: // In case it is reported, an error will be raised - Future resolved more than once for deviceFoundFuture setTimeout(() => { mockStdoutEmitter.emit("data", output); mockChildProcess.emit("close", 0); }, 0); await androidDeviceDiscovery.startLookingForDevices(); assert.isTrue( devicesFound.length === 1, "We should have found ONE device." ); }); }); it("throws error when adb writes on stderr", async () => { androidDeviceDiscovery.on( DeviceDiscoveryEventNames.DEVICE_FOUND, (device: Mobile.IDevice) => { throw new Error("Devices should not be found."); } ); const error = new Error("ADB Error"); try { setTimeout(() => { mockStderrEmitter.emit("data", error); mockChildProcess.emit("close", 1); }, 0); await androidDeviceDiscovery.startLookingForDevices(); } catch (err) { assert.deepStrictEqual(err, error.toString()); } }); it("throws error when adb writes on stderr multiple times", async () => { const error1 = new Error("ADB Error"); const error2 = new Error("ADB Error 2"); try { setTimeout(() => { mockStderrEmitter.emit("data", error1); mockStderrEmitter.emit("data", error2); mockChildProcess.emit("close", 1); }, 0); await androidDeviceDiscovery.startLookingForDevices(); } catch (err) { assert.deepStrictEqual(err, error1.toString() + error2.toString()); } }); it("throws error when adb's child process throws error", async () => { androidDeviceDiscovery.on( DeviceDiscoveryEventNames.DEVICE_FOUND, (device: Mobile.IDevice) => { throw new Error("Devices should not be found."); } ); const error = new Error("ADB Error"); try { setTimeout(() => { mockChildProcess.emit("error", error); }, 0); await androidDeviceDiscovery.startLookingForDevices(); } catch (err) { assert.deepStrictEqual(err, error); } }); }); });
the_stack
import { Reader, util, configure, Writer } from 'protobufjs/minimal' import { Timestamp } from '../../google/protobuf/timestamp' import * as Long from 'long' import { Header } from '../../tendermint/types/types' import { ProofOps } from '../../tendermint/crypto/proof' import { EvidenceParams, ValidatorParams, VersionParams } from '../../tendermint/types/params' import { PublicKey } from '../../tendermint/crypto/keys' export const protobufPackage = 'tendermint.abci' export enum CheckTxType { NEW = 0, RECHECK = 1, UNRECOGNIZED = -1 } export function checkTxTypeFromJSON(object: any): CheckTxType { switch (object) { case 0: case 'NEW': return CheckTxType.NEW case 1: case 'RECHECK': return CheckTxType.RECHECK case -1: case 'UNRECOGNIZED': default: return CheckTxType.UNRECOGNIZED } } export function checkTxTypeToJSON(object: CheckTxType): string { switch (object) { case CheckTxType.NEW: return 'NEW' case CheckTxType.RECHECK: return 'RECHECK' default: return 'UNKNOWN' } } export enum EvidenceType { UNKNOWN = 0, DUPLICATE_VOTE = 1, LIGHT_CLIENT_ATTACK = 2, UNRECOGNIZED = -1 } export function evidenceTypeFromJSON(object: any): EvidenceType { switch (object) { case 0: case 'UNKNOWN': return EvidenceType.UNKNOWN case 1: case 'DUPLICATE_VOTE': return EvidenceType.DUPLICATE_VOTE case 2: case 'LIGHT_CLIENT_ATTACK': return EvidenceType.LIGHT_CLIENT_ATTACK case -1: case 'UNRECOGNIZED': default: return EvidenceType.UNRECOGNIZED } } export function evidenceTypeToJSON(object: EvidenceType): string { switch (object) { case EvidenceType.UNKNOWN: return 'UNKNOWN' case EvidenceType.DUPLICATE_VOTE: return 'DUPLICATE_VOTE' case EvidenceType.LIGHT_CLIENT_ATTACK: return 'LIGHT_CLIENT_ATTACK' default: return 'UNKNOWN' } } export interface Request { echo: RequestEcho | undefined flush: RequestFlush | undefined info: RequestInfo | undefined setOption: RequestSetOption | undefined initChain: RequestInitChain | undefined query: RequestQuery | undefined beginBlock: RequestBeginBlock | undefined checkTx: RequestCheckTx | undefined deliverTx: RequestDeliverTx | undefined endBlock: RequestEndBlock | undefined commit: RequestCommit | undefined listSnapshots: RequestListSnapshots | undefined offerSnapshot: RequestOfferSnapshot | undefined loadSnapshotChunk: RequestLoadSnapshotChunk | undefined applySnapshotChunk: RequestApplySnapshotChunk | undefined } export interface RequestEcho { message: string } export interface RequestFlush {} export interface RequestInfo { version: string blockVersion: number p2pVersion: number } /** nondeterministic */ export interface RequestSetOption { key: string value: string } export interface RequestInitChain { time: Date | undefined chainId: string consensusParams: ConsensusParams | undefined validators: ValidatorUpdate[] appStateBytes: Uint8Array initialHeight: number } export interface RequestQuery { data: Uint8Array path: string height: number prove: boolean } export interface RequestBeginBlock { hash: Uint8Array header: Header | undefined lastCommitInfo: LastCommitInfo | undefined byzantineValidators: Evidence[] } export interface RequestCheckTx { tx: Uint8Array type: CheckTxType } export interface RequestDeliverTx { tx: Uint8Array } export interface RequestEndBlock { height: number } export interface RequestCommit {} /** lists available snapshots */ export interface RequestListSnapshots {} /** offers a snapshot to the application */ export interface RequestOfferSnapshot { /** snapshot offered by peers */ snapshot: Snapshot | undefined /** light client-verified app hash for snapshot height */ appHash: Uint8Array } /** loads a snapshot chunk */ export interface RequestLoadSnapshotChunk { height: number format: number chunk: number } /** Applies a snapshot chunk */ export interface RequestApplySnapshotChunk { index: number chunk: Uint8Array sender: string } export interface Response { exception: ResponseException | undefined echo: ResponseEcho | undefined flush: ResponseFlush | undefined info: ResponseInfo | undefined setOption: ResponseSetOption | undefined initChain: ResponseInitChain | undefined query: ResponseQuery | undefined beginBlock: ResponseBeginBlock | undefined checkTx: ResponseCheckTx | undefined deliverTx: ResponseDeliverTx | undefined endBlock: ResponseEndBlock | undefined commit: ResponseCommit | undefined listSnapshots: ResponseListSnapshots | undefined offerSnapshot: ResponseOfferSnapshot | undefined loadSnapshotChunk: ResponseLoadSnapshotChunk | undefined applySnapshotChunk: ResponseApplySnapshotChunk | undefined } /** nondeterministic */ export interface ResponseException { error: string } export interface ResponseEcho { message: string } export interface ResponseFlush {} export interface ResponseInfo { data: string version: string appVersion: number lastBlockHeight: number lastBlockAppHash: Uint8Array } /** nondeterministic */ export interface ResponseSetOption { code: number /** bytes data = 2; */ log: string info: string } export interface ResponseInitChain { consensusParams: ConsensusParams | undefined validators: ValidatorUpdate[] appHash: Uint8Array } export interface ResponseQuery { code: number /** bytes data = 2; // use "value" instead. */ log: string /** nondeterministic */ info: string index: number key: Uint8Array value: Uint8Array proofOps: ProofOps | undefined height: number codespace: string } export interface ResponseBeginBlock { events: Event[] } export interface ResponseCheckTx { code: number data: Uint8Array /** nondeterministic */ log: string /** nondeterministic */ info: string gasWanted: number gasUsed: number events: Event[] codespace: string } export interface ResponseDeliverTx { code: number data: Uint8Array /** nondeterministic */ log: string /** nondeterministic */ info: string gasWanted: number gasUsed: number events: Event[] codespace: string } export interface ResponseEndBlock { validatorUpdates: ValidatorUpdate[] consensusParamUpdates: ConsensusParams | undefined events: Event[] } export interface ResponseCommit { /** reserve 1 */ data: Uint8Array retainHeight: number } export interface ResponseListSnapshots { snapshots: Snapshot[] } export interface ResponseOfferSnapshot { result: ResponseOfferSnapshot_Result } export enum ResponseOfferSnapshot_Result { /** UNKNOWN - Unknown result, abort all snapshot restoration */ UNKNOWN = 0, /** ACCEPT - Snapshot accepted, apply chunks */ ACCEPT = 1, /** ABORT - Abort all snapshot restoration */ ABORT = 2, /** REJECT - Reject this specific snapshot, try others */ REJECT = 3, /** REJECT_FORMAT - Reject all snapshots of this format, try others */ REJECT_FORMAT = 4, /** REJECT_SENDER - Reject all snapshots from the sender(s), try others */ REJECT_SENDER = 5, UNRECOGNIZED = -1 } export function responseOfferSnapshot_ResultFromJSON( object: any ): ResponseOfferSnapshot_Result { switch (object) { case 0: case 'UNKNOWN': return ResponseOfferSnapshot_Result.UNKNOWN case 1: case 'ACCEPT': return ResponseOfferSnapshot_Result.ACCEPT case 2: case 'ABORT': return ResponseOfferSnapshot_Result.ABORT case 3: case 'REJECT': return ResponseOfferSnapshot_Result.REJECT case 4: case 'REJECT_FORMAT': return ResponseOfferSnapshot_Result.REJECT_FORMAT case 5: case 'REJECT_SENDER': return ResponseOfferSnapshot_Result.REJECT_SENDER case -1: case 'UNRECOGNIZED': default: return ResponseOfferSnapshot_Result.UNRECOGNIZED } } export function responseOfferSnapshot_ResultToJSON( object: ResponseOfferSnapshot_Result ): string { switch (object) { case ResponseOfferSnapshot_Result.UNKNOWN: return 'UNKNOWN' case ResponseOfferSnapshot_Result.ACCEPT: return 'ACCEPT' case ResponseOfferSnapshot_Result.ABORT: return 'ABORT' case ResponseOfferSnapshot_Result.REJECT: return 'REJECT' case ResponseOfferSnapshot_Result.REJECT_FORMAT: return 'REJECT_FORMAT' case ResponseOfferSnapshot_Result.REJECT_SENDER: return 'REJECT_SENDER' default: return 'UNKNOWN' } } export interface ResponseLoadSnapshotChunk { chunk: Uint8Array } export interface ResponseApplySnapshotChunk { result: ResponseApplySnapshotChunk_Result /** Chunks to refetch and reapply */ refetchChunks: number[] /** Chunk senders to reject and ban */ rejectSenders: string[] } export enum ResponseApplySnapshotChunk_Result { /** UNKNOWN - Unknown result, abort all snapshot restoration */ UNKNOWN = 0, /** ACCEPT - Chunk successfully accepted */ ACCEPT = 1, /** ABORT - Abort all snapshot restoration */ ABORT = 2, /** RETRY - Retry chunk (combine with refetch and reject) */ RETRY = 3, /** RETRY_SNAPSHOT - Retry snapshot (combine with refetch and reject) */ RETRY_SNAPSHOT = 4, /** REJECT_SNAPSHOT - Reject this snapshot, try others */ REJECT_SNAPSHOT = 5, UNRECOGNIZED = -1 } export function responseApplySnapshotChunk_ResultFromJSON( object: any ): ResponseApplySnapshotChunk_Result { switch (object) { case 0: case 'UNKNOWN': return ResponseApplySnapshotChunk_Result.UNKNOWN case 1: case 'ACCEPT': return ResponseApplySnapshotChunk_Result.ACCEPT case 2: case 'ABORT': return ResponseApplySnapshotChunk_Result.ABORT case 3: case 'RETRY': return ResponseApplySnapshotChunk_Result.RETRY case 4: case 'RETRY_SNAPSHOT': return ResponseApplySnapshotChunk_Result.RETRY_SNAPSHOT case 5: case 'REJECT_SNAPSHOT': return ResponseApplySnapshotChunk_Result.REJECT_SNAPSHOT case -1: case 'UNRECOGNIZED': default: return ResponseApplySnapshotChunk_Result.UNRECOGNIZED } } export function responseApplySnapshotChunk_ResultToJSON( object: ResponseApplySnapshotChunk_Result ): string { switch (object) { case ResponseApplySnapshotChunk_Result.UNKNOWN: return 'UNKNOWN' case ResponseApplySnapshotChunk_Result.ACCEPT: return 'ACCEPT' case ResponseApplySnapshotChunk_Result.ABORT: return 'ABORT' case ResponseApplySnapshotChunk_Result.RETRY: return 'RETRY' case ResponseApplySnapshotChunk_Result.RETRY_SNAPSHOT: return 'RETRY_SNAPSHOT' case ResponseApplySnapshotChunk_Result.REJECT_SNAPSHOT: return 'REJECT_SNAPSHOT' default: return 'UNKNOWN' } } /** * ConsensusParams contains all consensus-relevant parameters * that can be adjusted by the abci app */ export interface ConsensusParams { block: BlockParams | undefined evidence: EvidenceParams | undefined validator: ValidatorParams | undefined version: VersionParams | undefined } /** BlockParams contains limits on the block size. */ export interface BlockParams { /** Note: must be greater than 0 */ maxBytes: number /** Note: must be greater or equal to -1 */ maxGas: number } export interface LastCommitInfo { round: number votes: VoteInfo[] } /** * Event allows application developers to attach additional information to * ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and ResponseDeliverTx. * Later, transactions may be queried using these events. */ export interface Event { type: string attributes: EventAttribute[] } /** EventAttribute is a single key-value pair, associated with an event. */ export interface EventAttribute { key: Uint8Array value: Uint8Array /** nondeterministic */ index: boolean } /** * TxResult contains results of executing the transaction. * * One usage is indexing transaction results. */ export interface TxResult { height: number index: number tx: Uint8Array result: ResponseDeliverTx | undefined } /** Validator */ export interface Validator { /** The first 20 bytes of SHA256(public key) */ address: Uint8Array /** PubKey pub_key = 2 [(gogoproto.nullable)=false]; */ power: number } /** ValidatorUpdate */ export interface ValidatorUpdate { pubKey: PublicKey | undefined power: number } /** VoteInfo */ export interface VoteInfo { validator: Validator | undefined signedLastBlock: boolean } export interface Evidence { type: EvidenceType /** The offending validator */ validator: Validator | undefined /** The height when the offense occurred */ height: number /** The corresponding time where the offense occurred */ time: Date | undefined /** * Total voting power of the validator set in case the ABCI application does * not store historical validators. * https://github.com/tendermint/tendermint/issues/4581 */ totalVotingPower: number } export interface Snapshot { /** The height at which the snapshot was taken */ height: number /** The application-specific snapshot format */ format: number /** Number of chunks in the snapshot */ chunks: number /** Arbitrary snapshot hash, equal only if identical */ hash: Uint8Array /** Arbitrary application metadata */ metadata: Uint8Array } const baseRequest: object = {} export const Request = { encode(message: Request, writer: Writer = Writer.create()): Writer { if (message.echo !== undefined) { RequestEcho.encode(message.echo, writer.uint32(10).fork()).ldelim() } if (message.flush !== undefined) { RequestFlush.encode(message.flush, writer.uint32(18).fork()).ldelim() } if (message.info !== undefined) { RequestInfo.encode(message.info, writer.uint32(26).fork()).ldelim() } if (message.setOption !== undefined) { RequestSetOption.encode( message.setOption, writer.uint32(34).fork() ).ldelim() } if (message.initChain !== undefined) { RequestInitChain.encode( message.initChain, writer.uint32(42).fork() ).ldelim() } if (message.query !== undefined) { RequestQuery.encode(message.query, writer.uint32(50).fork()).ldelim() } if (message.beginBlock !== undefined) { RequestBeginBlock.encode( message.beginBlock, writer.uint32(58).fork() ).ldelim() } if (message.checkTx !== undefined) { RequestCheckTx.encode(message.checkTx, writer.uint32(66).fork()).ldelim() } if (message.deliverTx !== undefined) { RequestDeliverTx.encode( message.deliverTx, writer.uint32(74).fork() ).ldelim() } if (message.endBlock !== undefined) { RequestEndBlock.encode( message.endBlock, writer.uint32(82).fork() ).ldelim() } if (message.commit !== undefined) { RequestCommit.encode(message.commit, writer.uint32(90).fork()).ldelim() } if (message.listSnapshots !== undefined) { RequestListSnapshots.encode( message.listSnapshots, writer.uint32(98).fork() ).ldelim() } if (message.offerSnapshot !== undefined) { RequestOfferSnapshot.encode( message.offerSnapshot, writer.uint32(106).fork() ).ldelim() } if (message.loadSnapshotChunk !== undefined) { RequestLoadSnapshotChunk.encode( message.loadSnapshotChunk, writer.uint32(114).fork() ).ldelim() } if (message.applySnapshotChunk !== undefined) { RequestApplySnapshotChunk.encode( message.applySnapshotChunk, writer.uint32(122).fork() ).ldelim() } return writer }, decode(input: Reader | Uint8Array, length?: number): Request { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseRequest } as Request while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.echo = RequestEcho.decode(reader, reader.uint32()) break case 2: message.flush = RequestFlush.decode(reader, reader.uint32()) break case 3: message.info = RequestInfo.decode(reader, reader.uint32()) break case 4: message.setOption = RequestSetOption.decode(reader, reader.uint32()) break case 5: message.initChain = RequestInitChain.decode(reader, reader.uint32()) break case 6: message.query = RequestQuery.decode(reader, reader.uint32()) break case 7: message.beginBlock = RequestBeginBlock.decode(reader, reader.uint32()) break case 8: message.checkTx = RequestCheckTx.decode(reader, reader.uint32()) break case 9: message.deliverTx = RequestDeliverTx.decode(reader, reader.uint32()) break case 10: message.endBlock = RequestEndBlock.decode(reader, reader.uint32()) break case 11: message.commit = RequestCommit.decode(reader, reader.uint32()) break case 12: message.listSnapshots = RequestListSnapshots.decode( reader, reader.uint32() ) break case 13: message.offerSnapshot = RequestOfferSnapshot.decode( reader, reader.uint32() ) break case 14: message.loadSnapshotChunk = RequestLoadSnapshotChunk.decode( reader, reader.uint32() ) break case 15: message.applySnapshotChunk = RequestApplySnapshotChunk.decode( reader, reader.uint32() ) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): Request { const message = { ...baseRequest } as Request if (object.echo !== undefined && object.echo !== null) { message.echo = RequestEcho.fromJSON(object.echo) } else { message.echo = undefined } if (object.flush !== undefined && object.flush !== null) { message.flush = RequestFlush.fromJSON(object.flush) } else { message.flush = undefined } if (object.info !== undefined && object.info !== null) { message.info = RequestInfo.fromJSON(object.info) } else { message.info = undefined } if (object.setOption !== undefined && object.setOption !== null) { message.setOption = RequestSetOption.fromJSON(object.setOption) } else { message.setOption = undefined } if (object.initChain !== undefined && object.initChain !== null) { message.initChain = RequestInitChain.fromJSON(object.initChain) } else { message.initChain = undefined } if (object.query !== undefined && object.query !== null) { message.query = RequestQuery.fromJSON(object.query) } else { message.query = undefined } if (object.beginBlock !== undefined && object.beginBlock !== null) { message.beginBlock = RequestBeginBlock.fromJSON(object.beginBlock) } else { message.beginBlock = undefined } if (object.checkTx !== undefined && object.checkTx !== null) { message.checkTx = RequestCheckTx.fromJSON(object.checkTx) } else { message.checkTx = undefined } if (object.deliverTx !== undefined && object.deliverTx !== null) { message.deliverTx = RequestDeliverTx.fromJSON(object.deliverTx) } else { message.deliverTx = undefined } if (object.endBlock !== undefined && object.endBlock !== null) { message.endBlock = RequestEndBlock.fromJSON(object.endBlock) } else { message.endBlock = undefined } if (object.commit !== undefined && object.commit !== null) { message.commit = RequestCommit.fromJSON(object.commit) } else { message.commit = undefined } if (object.listSnapshots !== undefined && object.listSnapshots !== null) { message.listSnapshots = RequestListSnapshots.fromJSON( object.listSnapshots ) } else { message.listSnapshots = undefined } if (object.offerSnapshot !== undefined && object.offerSnapshot !== null) { message.offerSnapshot = RequestOfferSnapshot.fromJSON( object.offerSnapshot ) } else { message.offerSnapshot = undefined } if ( object.loadSnapshotChunk !== undefined && object.loadSnapshotChunk !== null ) { message.loadSnapshotChunk = RequestLoadSnapshotChunk.fromJSON( object.loadSnapshotChunk ) } else { message.loadSnapshotChunk = undefined } if ( object.applySnapshotChunk !== undefined && object.applySnapshotChunk !== null ) { message.applySnapshotChunk = RequestApplySnapshotChunk.fromJSON( object.applySnapshotChunk ) } else { message.applySnapshotChunk = undefined } return message }, toJSON(message: Request): unknown { const obj: any = {} message.echo !== undefined && (obj.echo = message.echo ? RequestEcho.toJSON(message.echo) : undefined) message.flush !== undefined && (obj.flush = message.flush ? RequestFlush.toJSON(message.flush) : undefined) message.info !== undefined && (obj.info = message.info ? RequestInfo.toJSON(message.info) : undefined) message.setOption !== undefined && (obj.setOption = message.setOption ? RequestSetOption.toJSON(message.setOption) : undefined) message.initChain !== undefined && (obj.initChain = message.initChain ? RequestInitChain.toJSON(message.initChain) : undefined) message.query !== undefined && (obj.query = message.query ? RequestQuery.toJSON(message.query) : undefined) message.beginBlock !== undefined && (obj.beginBlock = message.beginBlock ? RequestBeginBlock.toJSON(message.beginBlock) : undefined) message.checkTx !== undefined && (obj.checkTx = message.checkTx ? RequestCheckTx.toJSON(message.checkTx) : undefined) message.deliverTx !== undefined && (obj.deliverTx = message.deliverTx ? RequestDeliverTx.toJSON(message.deliverTx) : undefined) message.endBlock !== undefined && (obj.endBlock = message.endBlock ? RequestEndBlock.toJSON(message.endBlock) : undefined) message.commit !== undefined && (obj.commit = message.commit ? RequestCommit.toJSON(message.commit) : undefined) message.listSnapshots !== undefined && (obj.listSnapshots = message.listSnapshots ? RequestListSnapshots.toJSON(message.listSnapshots) : undefined) message.offerSnapshot !== undefined && (obj.offerSnapshot = message.offerSnapshot ? RequestOfferSnapshot.toJSON(message.offerSnapshot) : undefined) message.loadSnapshotChunk !== undefined && (obj.loadSnapshotChunk = message.loadSnapshotChunk ? RequestLoadSnapshotChunk.toJSON(message.loadSnapshotChunk) : undefined) message.applySnapshotChunk !== undefined && (obj.applySnapshotChunk = message.applySnapshotChunk ? RequestApplySnapshotChunk.toJSON(message.applySnapshotChunk) : undefined) return obj }, fromPartial(object: DeepPartial<Request>): Request { const message = { ...baseRequest } as Request if (object.echo !== undefined && object.echo !== null) { message.echo = RequestEcho.fromPartial(object.echo) } else { message.echo = undefined } if (object.flush !== undefined && object.flush !== null) { message.flush = RequestFlush.fromPartial(object.flush) } else { message.flush = undefined } if (object.info !== undefined && object.info !== null) { message.info = RequestInfo.fromPartial(object.info) } else { message.info = undefined } if (object.setOption !== undefined && object.setOption !== null) { message.setOption = RequestSetOption.fromPartial(object.setOption) } else { message.setOption = undefined } if (object.initChain !== undefined && object.initChain !== null) { message.initChain = RequestInitChain.fromPartial(object.initChain) } else { message.initChain = undefined } if (object.query !== undefined && object.query !== null) { message.query = RequestQuery.fromPartial(object.query) } else { message.query = undefined } if (object.beginBlock !== undefined && object.beginBlock !== null) { message.beginBlock = RequestBeginBlock.fromPartial(object.beginBlock) } else { message.beginBlock = undefined } if (object.checkTx !== undefined && object.checkTx !== null) { message.checkTx = RequestCheckTx.fromPartial(object.checkTx) } else { message.checkTx = undefined } if (object.deliverTx !== undefined && object.deliverTx !== null) { message.deliverTx = RequestDeliverTx.fromPartial(object.deliverTx) } else { message.deliverTx = undefined } if (object.endBlock !== undefined && object.endBlock !== null) { message.endBlock = RequestEndBlock.fromPartial(object.endBlock) } else { message.endBlock = undefined } if (object.commit !== undefined && object.commit !== null) { message.commit = RequestCommit.fromPartial(object.commit) } else { message.commit = undefined } if (object.listSnapshots !== undefined && object.listSnapshots !== null) { message.listSnapshots = RequestListSnapshots.fromPartial( object.listSnapshots ) } else { message.listSnapshots = undefined } if (object.offerSnapshot !== undefined && object.offerSnapshot !== null) { message.offerSnapshot = RequestOfferSnapshot.fromPartial( object.offerSnapshot ) } else { message.offerSnapshot = undefined } if ( object.loadSnapshotChunk !== undefined && object.loadSnapshotChunk !== null ) { message.loadSnapshotChunk = RequestLoadSnapshotChunk.fromPartial( object.loadSnapshotChunk ) } else { message.loadSnapshotChunk = undefined } if ( object.applySnapshotChunk !== undefined && object.applySnapshotChunk !== null ) { message.applySnapshotChunk = RequestApplySnapshotChunk.fromPartial( object.applySnapshotChunk ) } else { message.applySnapshotChunk = undefined } return message } } const baseRequestEcho: object = { message: '' } export const RequestEcho = { encode(message: RequestEcho, writer: Writer = Writer.create()): Writer { if (message.message !== '') { writer.uint32(10).string(message.message) } return writer }, decode(input: Reader | Uint8Array, length?: number): RequestEcho { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseRequestEcho } as RequestEcho while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.message = reader.string() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): RequestEcho { const message = { ...baseRequestEcho } as RequestEcho if (object.message !== undefined && object.message !== null) { message.message = String(object.message) } else { message.message = '' } return message }, toJSON(message: RequestEcho): unknown { const obj: any = {} message.message !== undefined && (obj.message = message.message) return obj }, fromPartial(object: DeepPartial<RequestEcho>): RequestEcho { const message = { ...baseRequestEcho } as RequestEcho if (object.message !== undefined && object.message !== null) { message.message = object.message } else { message.message = '' } return message } } const baseRequestFlush: object = {} export const RequestFlush = { encode(_: RequestFlush, writer: Writer = Writer.create()): Writer { return writer }, decode(input: Reader | Uint8Array, length?: number): RequestFlush { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseRequestFlush } as RequestFlush while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { default: reader.skipType(tag & 7) break } } return message }, fromJSON(_: any): RequestFlush { const message = { ...baseRequestFlush } as RequestFlush return message }, toJSON(_: RequestFlush): unknown { const obj: any = {} return obj }, fromPartial(_: DeepPartial<RequestFlush>): RequestFlush { const message = { ...baseRequestFlush } as RequestFlush return message } } const baseRequestInfo: object = { version: '', blockVersion: 0, p2pVersion: 0 } export const RequestInfo = { encode(message: RequestInfo, writer: Writer = Writer.create()): Writer { if (message.version !== '') { writer.uint32(10).string(message.version) } if (message.blockVersion !== 0) { writer.uint32(16).uint64(message.blockVersion) } if (message.p2pVersion !== 0) { writer.uint32(24).uint64(message.p2pVersion) } return writer }, decode(input: Reader | Uint8Array, length?: number): RequestInfo { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseRequestInfo } as RequestInfo while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.version = reader.string() break case 2: message.blockVersion = longToNumber(reader.uint64() as Long) break case 3: message.p2pVersion = longToNumber(reader.uint64() as Long) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): RequestInfo { const message = { ...baseRequestInfo } as RequestInfo if (object.version !== undefined && object.version !== null) { message.version = String(object.version) } else { message.version = '' } if (object.blockVersion !== undefined && object.blockVersion !== null) { message.blockVersion = Number(object.blockVersion) } else { message.blockVersion = 0 } if (object.p2pVersion !== undefined && object.p2pVersion !== null) { message.p2pVersion = Number(object.p2pVersion) } else { message.p2pVersion = 0 } return message }, toJSON(message: RequestInfo): unknown { const obj: any = {} message.version !== undefined && (obj.version = message.version) message.blockVersion !== undefined && (obj.blockVersion = message.blockVersion) message.p2pVersion !== undefined && (obj.p2pVersion = message.p2pVersion) return obj }, fromPartial(object: DeepPartial<RequestInfo>): RequestInfo { const message = { ...baseRequestInfo } as RequestInfo if (object.version !== undefined && object.version !== null) { message.version = object.version } else { message.version = '' } if (object.blockVersion !== undefined && object.blockVersion !== null) { message.blockVersion = object.blockVersion } else { message.blockVersion = 0 } if (object.p2pVersion !== undefined && object.p2pVersion !== null) { message.p2pVersion = object.p2pVersion } else { message.p2pVersion = 0 } return message } } const baseRequestSetOption: object = { key: '', value: '' } export const RequestSetOption = { encode(message: RequestSetOption, writer: Writer = Writer.create()): Writer { if (message.key !== '') { writer.uint32(10).string(message.key) } if (message.value !== '') { writer.uint32(18).string(message.value) } return writer }, decode(input: Reader | Uint8Array, length?: number): RequestSetOption { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseRequestSetOption } as RequestSetOption while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.key = reader.string() break case 2: message.value = reader.string() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): RequestSetOption { const message = { ...baseRequestSetOption } as RequestSetOption if (object.key !== undefined && object.key !== null) { message.key = String(object.key) } else { message.key = '' } if (object.value !== undefined && object.value !== null) { message.value = String(object.value) } else { message.value = '' } return message }, toJSON(message: RequestSetOption): unknown { const obj: any = {} message.key !== undefined && (obj.key = message.key) message.value !== undefined && (obj.value = message.value) return obj }, fromPartial(object: DeepPartial<RequestSetOption>): RequestSetOption { const message = { ...baseRequestSetOption } as RequestSetOption if (object.key !== undefined && object.key !== null) { message.key = object.key } else { message.key = '' } if (object.value !== undefined && object.value !== null) { message.value = object.value } else { message.value = '' } return message } } const baseRequestInitChain: object = { chainId: '', initialHeight: 0 } export const RequestInitChain = { encode(message: RequestInitChain, writer: Writer = Writer.create()): Writer { if (message.time !== undefined) { Timestamp.encode( toTimestamp(message.time), writer.uint32(10).fork() ).ldelim() } if (message.chainId !== '') { writer.uint32(18).string(message.chainId) } if (message.consensusParams !== undefined) { ConsensusParams.encode( message.consensusParams, writer.uint32(26).fork() ).ldelim() } for (const v of message.validators) { ValidatorUpdate.encode(v!, writer.uint32(34).fork()).ldelim() } if (message.appStateBytes.length !== 0) { writer.uint32(42).bytes(message.appStateBytes) } if (message.initialHeight !== 0) { writer.uint32(48).int64(message.initialHeight) } return writer }, decode(input: Reader | Uint8Array, length?: number): RequestInitChain { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseRequestInitChain } as RequestInitChain message.validators = [] while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ) break case 2: message.chainId = reader.string() break case 3: message.consensusParams = ConsensusParams.decode( reader, reader.uint32() ) break case 4: message.validators.push( ValidatorUpdate.decode(reader, reader.uint32()) ) break case 5: message.appStateBytes = reader.bytes() break case 6: message.initialHeight = longToNumber(reader.int64() as Long) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): RequestInitChain { const message = { ...baseRequestInitChain } as RequestInitChain message.validators = [] if (object.time !== undefined && object.time !== null) { message.time = fromJsonTimestamp(object.time) } else { message.time = undefined } if (object.chainId !== undefined && object.chainId !== null) { message.chainId = String(object.chainId) } else { message.chainId = '' } if ( object.consensusParams !== undefined && object.consensusParams !== null ) { message.consensusParams = ConsensusParams.fromJSON(object.consensusParams) } else { message.consensusParams = undefined } if (object.validators !== undefined && object.validators !== null) { for (const e of object.validators) { message.validators.push(ValidatorUpdate.fromJSON(e)) } } if (object.appStateBytes !== undefined && object.appStateBytes !== null) { message.appStateBytes = bytesFromBase64(object.appStateBytes) } if (object.initialHeight !== undefined && object.initialHeight !== null) { message.initialHeight = Number(object.initialHeight) } else { message.initialHeight = 0 } return message }, toJSON(message: RequestInitChain): unknown { const obj: any = {} message.time !== undefined && (obj.time = message.time !== undefined ? message.time.toISOString() : null) message.chainId !== undefined && (obj.chainId = message.chainId) message.consensusParams !== undefined && (obj.consensusParams = message.consensusParams ? ConsensusParams.toJSON(message.consensusParams) : undefined) if (message.validators) { obj.validators = message.validators.map((e) => e ? ValidatorUpdate.toJSON(e) : undefined ) } else { obj.validators = [] } message.appStateBytes !== undefined && (obj.appStateBytes = base64FromBytes( message.appStateBytes !== undefined ? message.appStateBytes : new Uint8Array() )) message.initialHeight !== undefined && (obj.initialHeight = message.initialHeight) return obj }, fromPartial(object: DeepPartial<RequestInitChain>): RequestInitChain { const message = { ...baseRequestInitChain } as RequestInitChain message.validators = [] if (object.time !== undefined && object.time !== null) { message.time = object.time } else { message.time = undefined } if (object.chainId !== undefined && object.chainId !== null) { message.chainId = object.chainId } else { message.chainId = '' } if ( object.consensusParams !== undefined && object.consensusParams !== null ) { message.consensusParams = ConsensusParams.fromPartial( object.consensusParams ) } else { message.consensusParams = undefined } if (object.validators !== undefined && object.validators !== null) { for (const e of object.validators) { message.validators.push(ValidatorUpdate.fromPartial(e)) } } if (object.appStateBytes !== undefined && object.appStateBytes !== null) { message.appStateBytes = object.appStateBytes } else { message.appStateBytes = new Uint8Array() } if (object.initialHeight !== undefined && object.initialHeight !== null) { message.initialHeight = object.initialHeight } else { message.initialHeight = 0 } return message } } const baseRequestQuery: object = { path: '', height: 0, prove: false } export const RequestQuery = { encode(message: RequestQuery, writer: Writer = Writer.create()): Writer { if (message.data.length !== 0) { writer.uint32(10).bytes(message.data) } if (message.path !== '') { writer.uint32(18).string(message.path) } if (message.height !== 0) { writer.uint32(24).int64(message.height) } if (message.prove === true) { writer.uint32(32).bool(message.prove) } return writer }, decode(input: Reader | Uint8Array, length?: number): RequestQuery { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseRequestQuery } as RequestQuery while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.data = reader.bytes() break case 2: message.path = reader.string() break case 3: message.height = longToNumber(reader.int64() as Long) break case 4: message.prove = reader.bool() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): RequestQuery { const message = { ...baseRequestQuery } as RequestQuery if (object.data !== undefined && object.data !== null) { message.data = bytesFromBase64(object.data) } if (object.path !== undefined && object.path !== null) { message.path = String(object.path) } else { message.path = '' } if (object.height !== undefined && object.height !== null) { message.height = Number(object.height) } else { message.height = 0 } if (object.prove !== undefined && object.prove !== null) { message.prove = Boolean(object.prove) } else { message.prove = false } return message }, toJSON(message: RequestQuery): unknown { const obj: any = {} message.data !== undefined && (obj.data = base64FromBytes( message.data !== undefined ? message.data : new Uint8Array() )) message.path !== undefined && (obj.path = message.path) message.height !== undefined && (obj.height = message.height) message.prove !== undefined && (obj.prove = message.prove) return obj }, fromPartial(object: DeepPartial<RequestQuery>): RequestQuery { const message = { ...baseRequestQuery } as RequestQuery if (object.data !== undefined && object.data !== null) { message.data = object.data } else { message.data = new Uint8Array() } if (object.path !== undefined && object.path !== null) { message.path = object.path } else { message.path = '' } if (object.height !== undefined && object.height !== null) { message.height = object.height } else { message.height = 0 } if (object.prove !== undefined && object.prove !== null) { message.prove = object.prove } else { message.prove = false } return message } } const baseRequestBeginBlock: object = {} export const RequestBeginBlock = { encode(message: RequestBeginBlock, writer: Writer = Writer.create()): Writer { if (message.hash.length !== 0) { writer.uint32(10).bytes(message.hash) } if (message.header !== undefined) { Header.encode(message.header, writer.uint32(18).fork()).ldelim() } if (message.lastCommitInfo !== undefined) { LastCommitInfo.encode( message.lastCommitInfo, writer.uint32(26).fork() ).ldelim() } for (const v of message.byzantineValidators) { Evidence.encode(v!, writer.uint32(34).fork()).ldelim() } return writer }, decode(input: Reader | Uint8Array, length?: number): RequestBeginBlock { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseRequestBeginBlock } as RequestBeginBlock message.byzantineValidators = [] while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.hash = reader.bytes() break case 2: message.header = Header.decode(reader, reader.uint32()) break case 3: message.lastCommitInfo = LastCommitInfo.decode( reader, reader.uint32() ) break case 4: message.byzantineValidators.push( Evidence.decode(reader, reader.uint32()) ) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): RequestBeginBlock { const message = { ...baseRequestBeginBlock } as RequestBeginBlock message.byzantineValidators = [] if (object.hash !== undefined && object.hash !== null) { message.hash = bytesFromBase64(object.hash) } if (object.header !== undefined && object.header !== null) { message.header = Header.fromJSON(object.header) } else { message.header = undefined } if (object.lastCommitInfo !== undefined && object.lastCommitInfo !== null) { message.lastCommitInfo = LastCommitInfo.fromJSON(object.lastCommitInfo) } else { message.lastCommitInfo = undefined } if ( object.byzantineValidators !== undefined && object.byzantineValidators !== null ) { for (const e of object.byzantineValidators) { message.byzantineValidators.push(Evidence.fromJSON(e)) } } return message }, toJSON(message: RequestBeginBlock): unknown { const obj: any = {} message.hash !== undefined && (obj.hash = base64FromBytes( message.hash !== undefined ? message.hash : new Uint8Array() )) message.header !== undefined && (obj.header = message.header ? Header.toJSON(message.header) : undefined) message.lastCommitInfo !== undefined && (obj.lastCommitInfo = message.lastCommitInfo ? LastCommitInfo.toJSON(message.lastCommitInfo) : undefined) if (message.byzantineValidators) { obj.byzantineValidators = message.byzantineValidators.map((e) => e ? Evidence.toJSON(e) : undefined ) } else { obj.byzantineValidators = [] } return obj }, fromPartial(object: DeepPartial<RequestBeginBlock>): RequestBeginBlock { const message = { ...baseRequestBeginBlock } as RequestBeginBlock message.byzantineValidators = [] if (object.hash !== undefined && object.hash !== null) { message.hash = object.hash } else { message.hash = new Uint8Array() } if (object.header !== undefined && object.header !== null) { message.header = Header.fromPartial(object.header) } else { message.header = undefined } if (object.lastCommitInfo !== undefined && object.lastCommitInfo !== null) { message.lastCommitInfo = LastCommitInfo.fromPartial(object.lastCommitInfo) } else { message.lastCommitInfo = undefined } if ( object.byzantineValidators !== undefined && object.byzantineValidators !== null ) { for (const e of object.byzantineValidators) { message.byzantineValidators.push(Evidence.fromPartial(e)) } } return message } } const baseRequestCheckTx: object = { type: 0 } export const RequestCheckTx = { encode(message: RequestCheckTx, writer: Writer = Writer.create()): Writer { if (message.tx.length !== 0) { writer.uint32(10).bytes(message.tx) } if (message.type !== 0) { writer.uint32(16).int32(message.type) } return writer }, decode(input: Reader | Uint8Array, length?: number): RequestCheckTx { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseRequestCheckTx } as RequestCheckTx while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.tx = reader.bytes() break case 2: message.type = reader.int32() as any break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): RequestCheckTx { const message = { ...baseRequestCheckTx } as RequestCheckTx if (object.tx !== undefined && object.tx !== null) { message.tx = bytesFromBase64(object.tx) } if (object.type !== undefined && object.type !== null) { message.type = checkTxTypeFromJSON(object.type) } else { message.type = 0 } return message }, toJSON(message: RequestCheckTx): unknown { const obj: any = {} message.tx !== undefined && (obj.tx = base64FromBytes( message.tx !== undefined ? message.tx : new Uint8Array() )) message.type !== undefined && (obj.type = checkTxTypeToJSON(message.type)) return obj }, fromPartial(object: DeepPartial<RequestCheckTx>): RequestCheckTx { const message = { ...baseRequestCheckTx } as RequestCheckTx if (object.tx !== undefined && object.tx !== null) { message.tx = object.tx } else { message.tx = new Uint8Array() } if (object.type !== undefined && object.type !== null) { message.type = object.type } else { message.type = 0 } return message } } const baseRequestDeliverTx: object = {} export const RequestDeliverTx = { encode(message: RequestDeliverTx, writer: Writer = Writer.create()): Writer { if (message.tx.length !== 0) { writer.uint32(10).bytes(message.tx) } return writer }, decode(input: Reader | Uint8Array, length?: number): RequestDeliverTx { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseRequestDeliverTx } as RequestDeliverTx while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.tx = reader.bytes() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): RequestDeliverTx { const message = { ...baseRequestDeliverTx } as RequestDeliverTx if (object.tx !== undefined && object.tx !== null) { message.tx = bytesFromBase64(object.tx) } return message }, toJSON(message: RequestDeliverTx): unknown { const obj: any = {} message.tx !== undefined && (obj.tx = base64FromBytes( message.tx !== undefined ? message.tx : new Uint8Array() )) return obj }, fromPartial(object: DeepPartial<RequestDeliverTx>): RequestDeliverTx { const message = { ...baseRequestDeliverTx } as RequestDeliverTx if (object.tx !== undefined && object.tx !== null) { message.tx = object.tx } else { message.tx = new Uint8Array() } return message } } const baseRequestEndBlock: object = { height: 0 } export const RequestEndBlock = { encode(message: RequestEndBlock, writer: Writer = Writer.create()): Writer { if (message.height !== 0) { writer.uint32(8).int64(message.height) } return writer }, decode(input: Reader | Uint8Array, length?: number): RequestEndBlock { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseRequestEndBlock } as RequestEndBlock while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.height = longToNumber(reader.int64() as Long) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): RequestEndBlock { const message = { ...baseRequestEndBlock } as RequestEndBlock if (object.height !== undefined && object.height !== null) { message.height = Number(object.height) } else { message.height = 0 } return message }, toJSON(message: RequestEndBlock): unknown { const obj: any = {} message.height !== undefined && (obj.height = message.height) return obj }, fromPartial(object: DeepPartial<RequestEndBlock>): RequestEndBlock { const message = { ...baseRequestEndBlock } as RequestEndBlock if (object.height !== undefined && object.height !== null) { message.height = object.height } else { message.height = 0 } return message } } const baseRequestCommit: object = {} export const RequestCommit = { encode(_: RequestCommit, writer: Writer = Writer.create()): Writer { return writer }, decode(input: Reader | Uint8Array, length?: number): RequestCommit { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseRequestCommit } as RequestCommit while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { default: reader.skipType(tag & 7) break } } return message }, fromJSON(_: any): RequestCommit { const message = { ...baseRequestCommit } as RequestCommit return message }, toJSON(_: RequestCommit): unknown { const obj: any = {} return obj }, fromPartial(_: DeepPartial<RequestCommit>): RequestCommit { const message = { ...baseRequestCommit } as RequestCommit return message } } const baseRequestListSnapshots: object = {} export const RequestListSnapshots = { encode(_: RequestListSnapshots, writer: Writer = Writer.create()): Writer { return writer }, decode(input: Reader | Uint8Array, length?: number): RequestListSnapshots { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseRequestListSnapshots } as RequestListSnapshots while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { default: reader.skipType(tag & 7) break } } return message }, fromJSON(_: any): RequestListSnapshots { const message = { ...baseRequestListSnapshots } as RequestListSnapshots return message }, toJSON(_: RequestListSnapshots): unknown { const obj: any = {} return obj }, fromPartial(_: DeepPartial<RequestListSnapshots>): RequestListSnapshots { const message = { ...baseRequestListSnapshots } as RequestListSnapshots return message } } const baseRequestOfferSnapshot: object = {} export const RequestOfferSnapshot = { encode( message: RequestOfferSnapshot, writer: Writer = Writer.create() ): Writer { if (message.snapshot !== undefined) { Snapshot.encode(message.snapshot, writer.uint32(10).fork()).ldelim() } if (message.appHash.length !== 0) { writer.uint32(18).bytes(message.appHash) } return writer }, decode(input: Reader | Uint8Array, length?: number): RequestOfferSnapshot { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseRequestOfferSnapshot } as RequestOfferSnapshot while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.snapshot = Snapshot.decode(reader, reader.uint32()) break case 2: message.appHash = reader.bytes() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): RequestOfferSnapshot { const message = { ...baseRequestOfferSnapshot } as RequestOfferSnapshot if (object.snapshot !== undefined && object.snapshot !== null) { message.snapshot = Snapshot.fromJSON(object.snapshot) } else { message.snapshot = undefined } if (object.appHash !== undefined && object.appHash !== null) { message.appHash = bytesFromBase64(object.appHash) } return message }, toJSON(message: RequestOfferSnapshot): unknown { const obj: any = {} message.snapshot !== undefined && (obj.snapshot = message.snapshot ? Snapshot.toJSON(message.snapshot) : undefined) message.appHash !== undefined && (obj.appHash = base64FromBytes( message.appHash !== undefined ? message.appHash : new Uint8Array() )) return obj }, fromPartial(object: DeepPartial<RequestOfferSnapshot>): RequestOfferSnapshot { const message = { ...baseRequestOfferSnapshot } as RequestOfferSnapshot if (object.snapshot !== undefined && object.snapshot !== null) { message.snapshot = Snapshot.fromPartial(object.snapshot) } else { message.snapshot = undefined } if (object.appHash !== undefined && object.appHash !== null) { message.appHash = object.appHash } else { message.appHash = new Uint8Array() } return message } } const baseRequestLoadSnapshotChunk: object = { height: 0, format: 0, chunk: 0 } export const RequestLoadSnapshotChunk = { encode( message: RequestLoadSnapshotChunk, writer: Writer = Writer.create() ): Writer { if (message.height !== 0) { writer.uint32(8).uint64(message.height) } if (message.format !== 0) { writer.uint32(16).uint32(message.format) } if (message.chunk !== 0) { writer.uint32(24).uint32(message.chunk) } return writer }, decode( input: Reader | Uint8Array, length?: number ): RequestLoadSnapshotChunk { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseRequestLoadSnapshotChunk } as RequestLoadSnapshotChunk while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.height = longToNumber(reader.uint64() as Long) break case 2: message.format = reader.uint32() break case 3: message.chunk = reader.uint32() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): RequestLoadSnapshotChunk { const message = { ...baseRequestLoadSnapshotChunk } as RequestLoadSnapshotChunk if (object.height !== undefined && object.height !== null) { message.height = Number(object.height) } else { message.height = 0 } if (object.format !== undefined && object.format !== null) { message.format = Number(object.format) } else { message.format = 0 } if (object.chunk !== undefined && object.chunk !== null) { message.chunk = Number(object.chunk) } else { message.chunk = 0 } return message }, toJSON(message: RequestLoadSnapshotChunk): unknown { const obj: any = {} message.height !== undefined && (obj.height = message.height) message.format !== undefined && (obj.format = message.format) message.chunk !== undefined && (obj.chunk = message.chunk) return obj }, fromPartial( object: DeepPartial<RequestLoadSnapshotChunk> ): RequestLoadSnapshotChunk { const message = { ...baseRequestLoadSnapshotChunk } as RequestLoadSnapshotChunk if (object.height !== undefined && object.height !== null) { message.height = object.height } else { message.height = 0 } if (object.format !== undefined && object.format !== null) { message.format = object.format } else { message.format = 0 } if (object.chunk !== undefined && object.chunk !== null) { message.chunk = object.chunk } else { message.chunk = 0 } return message } } const baseRequestApplySnapshotChunk: object = { index: 0, sender: '' } export const RequestApplySnapshotChunk = { encode( message: RequestApplySnapshotChunk, writer: Writer = Writer.create() ): Writer { if (message.index !== 0) { writer.uint32(8).uint32(message.index) } if (message.chunk.length !== 0) { writer.uint32(18).bytes(message.chunk) } if (message.sender !== '') { writer.uint32(26).string(message.sender) } return writer }, decode( input: Reader | Uint8Array, length?: number ): RequestApplySnapshotChunk { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseRequestApplySnapshotChunk } as RequestApplySnapshotChunk while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.index = reader.uint32() break case 2: message.chunk = reader.bytes() break case 3: message.sender = reader.string() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): RequestApplySnapshotChunk { const message = { ...baseRequestApplySnapshotChunk } as RequestApplySnapshotChunk if (object.index !== undefined && object.index !== null) { message.index = Number(object.index) } else { message.index = 0 } if (object.chunk !== undefined && object.chunk !== null) { message.chunk = bytesFromBase64(object.chunk) } if (object.sender !== undefined && object.sender !== null) { message.sender = String(object.sender) } else { message.sender = '' } return message }, toJSON(message: RequestApplySnapshotChunk): unknown { const obj: any = {} message.index !== undefined && (obj.index = message.index) message.chunk !== undefined && (obj.chunk = base64FromBytes( message.chunk !== undefined ? message.chunk : new Uint8Array() )) message.sender !== undefined && (obj.sender = message.sender) return obj }, fromPartial( object: DeepPartial<RequestApplySnapshotChunk> ): RequestApplySnapshotChunk { const message = { ...baseRequestApplySnapshotChunk } as RequestApplySnapshotChunk if (object.index !== undefined && object.index !== null) { message.index = object.index } else { message.index = 0 } if (object.chunk !== undefined && object.chunk !== null) { message.chunk = object.chunk } else { message.chunk = new Uint8Array() } if (object.sender !== undefined && object.sender !== null) { message.sender = object.sender } else { message.sender = '' } return message } } const baseResponse: object = {} export const Response = { encode(message: Response, writer: Writer = Writer.create()): Writer { if (message.exception !== undefined) { ResponseException.encode( message.exception, writer.uint32(10).fork() ).ldelim() } if (message.echo !== undefined) { ResponseEcho.encode(message.echo, writer.uint32(18).fork()).ldelim() } if (message.flush !== undefined) { ResponseFlush.encode(message.flush, writer.uint32(26).fork()).ldelim() } if (message.info !== undefined) { ResponseInfo.encode(message.info, writer.uint32(34).fork()).ldelim() } if (message.setOption !== undefined) { ResponseSetOption.encode( message.setOption, writer.uint32(42).fork() ).ldelim() } if (message.initChain !== undefined) { ResponseInitChain.encode( message.initChain, writer.uint32(50).fork() ).ldelim() } if (message.query !== undefined) { ResponseQuery.encode(message.query, writer.uint32(58).fork()).ldelim() } if (message.beginBlock !== undefined) { ResponseBeginBlock.encode( message.beginBlock, writer.uint32(66).fork() ).ldelim() } if (message.checkTx !== undefined) { ResponseCheckTx.encode(message.checkTx, writer.uint32(74).fork()).ldelim() } if (message.deliverTx !== undefined) { ResponseDeliverTx.encode( message.deliverTx, writer.uint32(82).fork() ).ldelim() } if (message.endBlock !== undefined) { ResponseEndBlock.encode( message.endBlock, writer.uint32(90).fork() ).ldelim() } if (message.commit !== undefined) { ResponseCommit.encode(message.commit, writer.uint32(98).fork()).ldelim() } if (message.listSnapshots !== undefined) { ResponseListSnapshots.encode( message.listSnapshots, writer.uint32(106).fork() ).ldelim() } if (message.offerSnapshot !== undefined) { ResponseOfferSnapshot.encode( message.offerSnapshot, writer.uint32(114).fork() ).ldelim() } if (message.loadSnapshotChunk !== undefined) { ResponseLoadSnapshotChunk.encode( message.loadSnapshotChunk, writer.uint32(122).fork() ).ldelim() } if (message.applySnapshotChunk !== undefined) { ResponseApplySnapshotChunk.encode( message.applySnapshotChunk, writer.uint32(130).fork() ).ldelim() } return writer }, decode(input: Reader | Uint8Array, length?: number): Response { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseResponse } as Response while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.exception = ResponseException.decode(reader, reader.uint32()) break case 2: message.echo = ResponseEcho.decode(reader, reader.uint32()) break case 3: message.flush = ResponseFlush.decode(reader, reader.uint32()) break case 4: message.info = ResponseInfo.decode(reader, reader.uint32()) break case 5: message.setOption = ResponseSetOption.decode(reader, reader.uint32()) break case 6: message.initChain = ResponseInitChain.decode(reader, reader.uint32()) break case 7: message.query = ResponseQuery.decode(reader, reader.uint32()) break case 8: message.beginBlock = ResponseBeginBlock.decode( reader, reader.uint32() ) break case 9: message.checkTx = ResponseCheckTx.decode(reader, reader.uint32()) break case 10: message.deliverTx = ResponseDeliverTx.decode(reader, reader.uint32()) break case 11: message.endBlock = ResponseEndBlock.decode(reader, reader.uint32()) break case 12: message.commit = ResponseCommit.decode(reader, reader.uint32()) break case 13: message.listSnapshots = ResponseListSnapshots.decode( reader, reader.uint32() ) break case 14: message.offerSnapshot = ResponseOfferSnapshot.decode( reader, reader.uint32() ) break case 15: message.loadSnapshotChunk = ResponseLoadSnapshotChunk.decode( reader, reader.uint32() ) break case 16: message.applySnapshotChunk = ResponseApplySnapshotChunk.decode( reader, reader.uint32() ) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): Response { const message = { ...baseResponse } as Response if (object.exception !== undefined && object.exception !== null) { message.exception = ResponseException.fromJSON(object.exception) } else { message.exception = undefined } if (object.echo !== undefined && object.echo !== null) { message.echo = ResponseEcho.fromJSON(object.echo) } else { message.echo = undefined } if (object.flush !== undefined && object.flush !== null) { message.flush = ResponseFlush.fromJSON(object.flush) } else { message.flush = undefined } if (object.info !== undefined && object.info !== null) { message.info = ResponseInfo.fromJSON(object.info) } else { message.info = undefined } if (object.setOption !== undefined && object.setOption !== null) { message.setOption = ResponseSetOption.fromJSON(object.setOption) } else { message.setOption = undefined } if (object.initChain !== undefined && object.initChain !== null) { message.initChain = ResponseInitChain.fromJSON(object.initChain) } else { message.initChain = undefined } if (object.query !== undefined && object.query !== null) { message.query = ResponseQuery.fromJSON(object.query) } else { message.query = undefined } if (object.beginBlock !== undefined && object.beginBlock !== null) { message.beginBlock = ResponseBeginBlock.fromJSON(object.beginBlock) } else { message.beginBlock = undefined } if (object.checkTx !== undefined && object.checkTx !== null) { message.checkTx = ResponseCheckTx.fromJSON(object.checkTx) } else { message.checkTx = undefined } if (object.deliverTx !== undefined && object.deliverTx !== null) { message.deliverTx = ResponseDeliverTx.fromJSON(object.deliverTx) } else { message.deliverTx = undefined } if (object.endBlock !== undefined && object.endBlock !== null) { message.endBlock = ResponseEndBlock.fromJSON(object.endBlock) } else { message.endBlock = undefined } if (object.commit !== undefined && object.commit !== null) { message.commit = ResponseCommit.fromJSON(object.commit) } else { message.commit = undefined } if (object.listSnapshots !== undefined && object.listSnapshots !== null) { message.listSnapshots = ResponseListSnapshots.fromJSON( object.listSnapshots ) } else { message.listSnapshots = undefined } if (object.offerSnapshot !== undefined && object.offerSnapshot !== null) { message.offerSnapshot = ResponseOfferSnapshot.fromJSON( object.offerSnapshot ) } else { message.offerSnapshot = undefined } if ( object.loadSnapshotChunk !== undefined && object.loadSnapshotChunk !== null ) { message.loadSnapshotChunk = ResponseLoadSnapshotChunk.fromJSON( object.loadSnapshotChunk ) } else { message.loadSnapshotChunk = undefined } if ( object.applySnapshotChunk !== undefined && object.applySnapshotChunk !== null ) { message.applySnapshotChunk = ResponseApplySnapshotChunk.fromJSON( object.applySnapshotChunk ) } else { message.applySnapshotChunk = undefined } return message }, toJSON(message: Response): unknown { const obj: any = {} message.exception !== undefined && (obj.exception = message.exception ? ResponseException.toJSON(message.exception) : undefined) message.echo !== undefined && (obj.echo = message.echo ? ResponseEcho.toJSON(message.echo) : undefined) message.flush !== undefined && (obj.flush = message.flush ? ResponseFlush.toJSON(message.flush) : undefined) message.info !== undefined && (obj.info = message.info ? ResponseInfo.toJSON(message.info) : undefined) message.setOption !== undefined && (obj.setOption = message.setOption ? ResponseSetOption.toJSON(message.setOption) : undefined) message.initChain !== undefined && (obj.initChain = message.initChain ? ResponseInitChain.toJSON(message.initChain) : undefined) message.query !== undefined && (obj.query = message.query ? ResponseQuery.toJSON(message.query) : undefined) message.beginBlock !== undefined && (obj.beginBlock = message.beginBlock ? ResponseBeginBlock.toJSON(message.beginBlock) : undefined) message.checkTx !== undefined && (obj.checkTx = message.checkTx ? ResponseCheckTx.toJSON(message.checkTx) : undefined) message.deliverTx !== undefined && (obj.deliverTx = message.deliverTx ? ResponseDeliverTx.toJSON(message.deliverTx) : undefined) message.endBlock !== undefined && (obj.endBlock = message.endBlock ? ResponseEndBlock.toJSON(message.endBlock) : undefined) message.commit !== undefined && (obj.commit = message.commit ? ResponseCommit.toJSON(message.commit) : undefined) message.listSnapshots !== undefined && (obj.listSnapshots = message.listSnapshots ? ResponseListSnapshots.toJSON(message.listSnapshots) : undefined) message.offerSnapshot !== undefined && (obj.offerSnapshot = message.offerSnapshot ? ResponseOfferSnapshot.toJSON(message.offerSnapshot) : undefined) message.loadSnapshotChunk !== undefined && (obj.loadSnapshotChunk = message.loadSnapshotChunk ? ResponseLoadSnapshotChunk.toJSON(message.loadSnapshotChunk) : undefined) message.applySnapshotChunk !== undefined && (obj.applySnapshotChunk = message.applySnapshotChunk ? ResponseApplySnapshotChunk.toJSON(message.applySnapshotChunk) : undefined) return obj }, fromPartial(object: DeepPartial<Response>): Response { const message = { ...baseResponse } as Response if (object.exception !== undefined && object.exception !== null) { message.exception = ResponseException.fromPartial(object.exception) } else { message.exception = undefined } if (object.echo !== undefined && object.echo !== null) { message.echo = ResponseEcho.fromPartial(object.echo) } else { message.echo = undefined } if (object.flush !== undefined && object.flush !== null) { message.flush = ResponseFlush.fromPartial(object.flush) } else { message.flush = undefined } if (object.info !== undefined && object.info !== null) { message.info = ResponseInfo.fromPartial(object.info) } else { message.info = undefined } if (object.setOption !== undefined && object.setOption !== null) { message.setOption = ResponseSetOption.fromPartial(object.setOption) } else { message.setOption = undefined } if (object.initChain !== undefined && object.initChain !== null) { message.initChain = ResponseInitChain.fromPartial(object.initChain) } else { message.initChain = undefined } if (object.query !== undefined && object.query !== null) { message.query = ResponseQuery.fromPartial(object.query) } else { message.query = undefined } if (object.beginBlock !== undefined && object.beginBlock !== null) { message.beginBlock = ResponseBeginBlock.fromPartial(object.beginBlock) } else { message.beginBlock = undefined } if (object.checkTx !== undefined && object.checkTx !== null) { message.checkTx = ResponseCheckTx.fromPartial(object.checkTx) } else { message.checkTx = undefined } if (object.deliverTx !== undefined && object.deliverTx !== null) { message.deliverTx = ResponseDeliverTx.fromPartial(object.deliverTx) } else { message.deliverTx = undefined } if (object.endBlock !== undefined && object.endBlock !== null) { message.endBlock = ResponseEndBlock.fromPartial(object.endBlock) } else { message.endBlock = undefined } if (object.commit !== undefined && object.commit !== null) { message.commit = ResponseCommit.fromPartial(object.commit) } else { message.commit = undefined } if (object.listSnapshots !== undefined && object.listSnapshots !== null) { message.listSnapshots = ResponseListSnapshots.fromPartial( object.listSnapshots ) } else { message.listSnapshots = undefined } if (object.offerSnapshot !== undefined && object.offerSnapshot !== null) { message.offerSnapshot = ResponseOfferSnapshot.fromPartial( object.offerSnapshot ) } else { message.offerSnapshot = undefined } if ( object.loadSnapshotChunk !== undefined && object.loadSnapshotChunk !== null ) { message.loadSnapshotChunk = ResponseLoadSnapshotChunk.fromPartial( object.loadSnapshotChunk ) } else { message.loadSnapshotChunk = undefined } if ( object.applySnapshotChunk !== undefined && object.applySnapshotChunk !== null ) { message.applySnapshotChunk = ResponseApplySnapshotChunk.fromPartial( object.applySnapshotChunk ) } else { message.applySnapshotChunk = undefined } return message } } const baseResponseException: object = { error: '' } export const ResponseException = { encode(message: ResponseException, writer: Writer = Writer.create()): Writer { if (message.error !== '') { writer.uint32(10).string(message.error) } return writer }, decode(input: Reader | Uint8Array, length?: number): ResponseException { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseResponseException } as ResponseException while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.error = reader.string() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): ResponseException { const message = { ...baseResponseException } as ResponseException if (object.error !== undefined && object.error !== null) { message.error = String(object.error) } else { message.error = '' } return message }, toJSON(message: ResponseException): unknown { const obj: any = {} message.error !== undefined && (obj.error = message.error) return obj }, fromPartial(object: DeepPartial<ResponseException>): ResponseException { const message = { ...baseResponseException } as ResponseException if (object.error !== undefined && object.error !== null) { message.error = object.error } else { message.error = '' } return message } } const baseResponseEcho: object = { message: '' } export const ResponseEcho = { encode(message: ResponseEcho, writer: Writer = Writer.create()): Writer { if (message.message !== '') { writer.uint32(10).string(message.message) } return writer }, decode(input: Reader | Uint8Array, length?: number): ResponseEcho { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseResponseEcho } as ResponseEcho while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.message = reader.string() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): ResponseEcho { const message = { ...baseResponseEcho } as ResponseEcho if (object.message !== undefined && object.message !== null) { message.message = String(object.message) } else { message.message = '' } return message }, toJSON(message: ResponseEcho): unknown { const obj: any = {} message.message !== undefined && (obj.message = message.message) return obj }, fromPartial(object: DeepPartial<ResponseEcho>): ResponseEcho { const message = { ...baseResponseEcho } as ResponseEcho if (object.message !== undefined && object.message !== null) { message.message = object.message } else { message.message = '' } return message } } const baseResponseFlush: object = {} export const ResponseFlush = { encode(_: ResponseFlush, writer: Writer = Writer.create()): Writer { return writer }, decode(input: Reader | Uint8Array, length?: number): ResponseFlush { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseResponseFlush } as ResponseFlush while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { default: reader.skipType(tag & 7) break } } return message }, fromJSON(_: any): ResponseFlush { const message = { ...baseResponseFlush } as ResponseFlush return message }, toJSON(_: ResponseFlush): unknown { const obj: any = {} return obj }, fromPartial(_: DeepPartial<ResponseFlush>): ResponseFlush { const message = { ...baseResponseFlush } as ResponseFlush return message } } const baseResponseInfo: object = { data: '', version: '', appVersion: 0, lastBlockHeight: 0 } export const ResponseInfo = { encode(message: ResponseInfo, writer: Writer = Writer.create()): Writer { if (message.data !== '') { writer.uint32(10).string(message.data) } if (message.version !== '') { writer.uint32(18).string(message.version) } if (message.appVersion !== 0) { writer.uint32(24).uint64(message.appVersion) } if (message.lastBlockHeight !== 0) { writer.uint32(32).int64(message.lastBlockHeight) } if (message.lastBlockAppHash.length !== 0) { writer.uint32(42).bytes(message.lastBlockAppHash) } return writer }, decode(input: Reader | Uint8Array, length?: number): ResponseInfo { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseResponseInfo } as ResponseInfo while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.data = reader.string() break case 2: message.version = reader.string() break case 3: message.appVersion = longToNumber(reader.uint64() as Long) break case 4: message.lastBlockHeight = longToNumber(reader.int64() as Long) break case 5: message.lastBlockAppHash = reader.bytes() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): ResponseInfo { const message = { ...baseResponseInfo } as ResponseInfo if (object.data !== undefined && object.data !== null) { message.data = String(object.data) } else { message.data = '' } if (object.version !== undefined && object.version !== null) { message.version = String(object.version) } else { message.version = '' } if (object.appVersion !== undefined && object.appVersion !== null) { message.appVersion = Number(object.appVersion) } else { message.appVersion = 0 } if ( object.lastBlockHeight !== undefined && object.lastBlockHeight !== null ) { message.lastBlockHeight = Number(object.lastBlockHeight) } else { message.lastBlockHeight = 0 } if ( object.lastBlockAppHash !== undefined && object.lastBlockAppHash !== null ) { message.lastBlockAppHash = bytesFromBase64(object.lastBlockAppHash) } return message }, toJSON(message: ResponseInfo): unknown { const obj: any = {} message.data !== undefined && (obj.data = message.data) message.version !== undefined && (obj.version = message.version) message.appVersion !== undefined && (obj.appVersion = message.appVersion) message.lastBlockHeight !== undefined && (obj.lastBlockHeight = message.lastBlockHeight) message.lastBlockAppHash !== undefined && (obj.lastBlockAppHash = base64FromBytes( message.lastBlockAppHash !== undefined ? message.lastBlockAppHash : new Uint8Array() )) return obj }, fromPartial(object: DeepPartial<ResponseInfo>): ResponseInfo { const message = { ...baseResponseInfo } as ResponseInfo if (object.data !== undefined && object.data !== null) { message.data = object.data } else { message.data = '' } if (object.version !== undefined && object.version !== null) { message.version = object.version } else { message.version = '' } if (object.appVersion !== undefined && object.appVersion !== null) { message.appVersion = object.appVersion } else { message.appVersion = 0 } if ( object.lastBlockHeight !== undefined && object.lastBlockHeight !== null ) { message.lastBlockHeight = object.lastBlockHeight } else { message.lastBlockHeight = 0 } if ( object.lastBlockAppHash !== undefined && object.lastBlockAppHash !== null ) { message.lastBlockAppHash = object.lastBlockAppHash } else { message.lastBlockAppHash = new Uint8Array() } return message } } const baseResponseSetOption: object = { code: 0, log: '', info: '' } export const ResponseSetOption = { encode(message: ResponseSetOption, writer: Writer = Writer.create()): Writer { if (message.code !== 0) { writer.uint32(8).uint32(message.code) } if (message.log !== '') { writer.uint32(26).string(message.log) } if (message.info !== '') { writer.uint32(34).string(message.info) } return writer }, decode(input: Reader | Uint8Array, length?: number): ResponseSetOption { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseResponseSetOption } as ResponseSetOption while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.code = reader.uint32() break case 3: message.log = reader.string() break case 4: message.info = reader.string() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): ResponseSetOption { const message = { ...baseResponseSetOption } as ResponseSetOption if (object.code !== undefined && object.code !== null) { message.code = Number(object.code) } else { message.code = 0 } if (object.log !== undefined && object.log !== null) { message.log = String(object.log) } else { message.log = '' } if (object.info !== undefined && object.info !== null) { message.info = String(object.info) } else { message.info = '' } return message }, toJSON(message: ResponseSetOption): unknown { const obj: any = {} message.code !== undefined && (obj.code = message.code) message.log !== undefined && (obj.log = message.log) message.info !== undefined && (obj.info = message.info) return obj }, fromPartial(object: DeepPartial<ResponseSetOption>): ResponseSetOption { const message = { ...baseResponseSetOption } as ResponseSetOption if (object.code !== undefined && object.code !== null) { message.code = object.code } else { message.code = 0 } if (object.log !== undefined && object.log !== null) { message.log = object.log } else { message.log = '' } if (object.info !== undefined && object.info !== null) { message.info = object.info } else { message.info = '' } return message } } const baseResponseInitChain: object = {} export const ResponseInitChain = { encode(message: ResponseInitChain, writer: Writer = Writer.create()): Writer { if (message.consensusParams !== undefined) { ConsensusParams.encode( message.consensusParams, writer.uint32(10).fork() ).ldelim() } for (const v of message.validators) { ValidatorUpdate.encode(v!, writer.uint32(18).fork()).ldelim() } if (message.appHash.length !== 0) { writer.uint32(26).bytes(message.appHash) } return writer }, decode(input: Reader | Uint8Array, length?: number): ResponseInitChain { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseResponseInitChain } as ResponseInitChain message.validators = [] while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.consensusParams = ConsensusParams.decode( reader, reader.uint32() ) break case 2: message.validators.push( ValidatorUpdate.decode(reader, reader.uint32()) ) break case 3: message.appHash = reader.bytes() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): ResponseInitChain { const message = { ...baseResponseInitChain } as ResponseInitChain message.validators = [] if ( object.consensusParams !== undefined && object.consensusParams !== null ) { message.consensusParams = ConsensusParams.fromJSON(object.consensusParams) } else { message.consensusParams = undefined } if (object.validators !== undefined && object.validators !== null) { for (const e of object.validators) { message.validators.push(ValidatorUpdate.fromJSON(e)) } } if (object.appHash !== undefined && object.appHash !== null) { message.appHash = bytesFromBase64(object.appHash) } return message }, toJSON(message: ResponseInitChain): unknown { const obj: any = {} message.consensusParams !== undefined && (obj.consensusParams = message.consensusParams ? ConsensusParams.toJSON(message.consensusParams) : undefined) if (message.validators) { obj.validators = message.validators.map((e) => e ? ValidatorUpdate.toJSON(e) : undefined ) } else { obj.validators = [] } message.appHash !== undefined && (obj.appHash = base64FromBytes( message.appHash !== undefined ? message.appHash : new Uint8Array() )) return obj }, fromPartial(object: DeepPartial<ResponseInitChain>): ResponseInitChain { const message = { ...baseResponseInitChain } as ResponseInitChain message.validators = [] if ( object.consensusParams !== undefined && object.consensusParams !== null ) { message.consensusParams = ConsensusParams.fromPartial( object.consensusParams ) } else { message.consensusParams = undefined } if (object.validators !== undefined && object.validators !== null) { for (const e of object.validators) { message.validators.push(ValidatorUpdate.fromPartial(e)) } } if (object.appHash !== undefined && object.appHash !== null) { message.appHash = object.appHash } else { message.appHash = new Uint8Array() } return message } } const baseResponseQuery: object = { code: 0, log: '', info: '', index: 0, height: 0, codespace: '' } export const ResponseQuery = { encode(message: ResponseQuery, writer: Writer = Writer.create()): Writer { if (message.code !== 0) { writer.uint32(8).uint32(message.code) } if (message.log !== '') { writer.uint32(26).string(message.log) } if (message.info !== '') { writer.uint32(34).string(message.info) } if (message.index !== 0) { writer.uint32(40).int64(message.index) } if (message.key.length !== 0) { writer.uint32(50).bytes(message.key) } if (message.value.length !== 0) { writer.uint32(58).bytes(message.value) } if (message.proofOps !== undefined) { ProofOps.encode(message.proofOps, writer.uint32(66).fork()).ldelim() } if (message.height !== 0) { writer.uint32(72).int64(message.height) } if (message.codespace !== '') { writer.uint32(82).string(message.codespace) } return writer }, decode(input: Reader | Uint8Array, length?: number): ResponseQuery { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseResponseQuery } as ResponseQuery while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.code = reader.uint32() break case 3: message.log = reader.string() break case 4: message.info = reader.string() break case 5: message.index = longToNumber(reader.int64() as Long) break case 6: message.key = reader.bytes() break case 7: message.value = reader.bytes() break case 8: message.proofOps = ProofOps.decode(reader, reader.uint32()) break case 9: message.height = longToNumber(reader.int64() as Long) break case 10: message.codespace = reader.string() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): ResponseQuery { const message = { ...baseResponseQuery } as ResponseQuery if (object.code !== undefined && object.code !== null) { message.code = Number(object.code) } else { message.code = 0 } if (object.log !== undefined && object.log !== null) { message.log = String(object.log) } else { message.log = '' } if (object.info !== undefined && object.info !== null) { message.info = String(object.info) } else { message.info = '' } if (object.index !== undefined && object.index !== null) { message.index = Number(object.index) } else { message.index = 0 } if (object.key !== undefined && object.key !== null) { message.key = bytesFromBase64(object.key) } if (object.value !== undefined && object.value !== null) { message.value = bytesFromBase64(object.value) } if (object.proofOps !== undefined && object.proofOps !== null) { message.proofOps = ProofOps.fromJSON(object.proofOps) } else { message.proofOps = undefined } if (object.height !== undefined && object.height !== null) { message.height = Number(object.height) } else { message.height = 0 } if (object.codespace !== undefined && object.codespace !== null) { message.codespace = String(object.codespace) } else { message.codespace = '' } return message }, toJSON(message: ResponseQuery): unknown { const obj: any = {} message.code !== undefined && (obj.code = message.code) message.log !== undefined && (obj.log = message.log) message.info !== undefined && (obj.info = message.info) message.index !== undefined && (obj.index = message.index) message.key !== undefined && (obj.key = base64FromBytes( message.key !== undefined ? message.key : new Uint8Array() )) message.value !== undefined && (obj.value = base64FromBytes( message.value !== undefined ? message.value : new Uint8Array() )) message.proofOps !== undefined && (obj.proofOps = message.proofOps ? ProofOps.toJSON(message.proofOps) : undefined) message.height !== undefined && (obj.height = message.height) message.codespace !== undefined && (obj.codespace = message.codespace) return obj }, fromPartial(object: DeepPartial<ResponseQuery>): ResponseQuery { const message = { ...baseResponseQuery } as ResponseQuery if (object.code !== undefined && object.code !== null) { message.code = object.code } else { message.code = 0 } if (object.log !== undefined && object.log !== null) { message.log = object.log } else { message.log = '' } if (object.info !== undefined && object.info !== null) { message.info = object.info } else { message.info = '' } if (object.index !== undefined && object.index !== null) { message.index = object.index } else { message.index = 0 } if (object.key !== undefined && object.key !== null) { message.key = object.key } else { message.key = new Uint8Array() } if (object.value !== undefined && object.value !== null) { message.value = object.value } else { message.value = new Uint8Array() } if (object.proofOps !== undefined && object.proofOps !== null) { message.proofOps = ProofOps.fromPartial(object.proofOps) } else { message.proofOps = undefined } if (object.height !== undefined && object.height !== null) { message.height = object.height } else { message.height = 0 } if (object.codespace !== undefined && object.codespace !== null) { message.codespace = object.codespace } else { message.codespace = '' } return message } } const baseResponseBeginBlock: object = {} export const ResponseBeginBlock = { encode( message: ResponseBeginBlock, writer: Writer = Writer.create() ): Writer { for (const v of message.events) { Event.encode(v!, writer.uint32(10).fork()).ldelim() } return writer }, decode(input: Reader | Uint8Array, length?: number): ResponseBeginBlock { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseResponseBeginBlock } as ResponseBeginBlock message.events = [] while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.events.push(Event.decode(reader, reader.uint32())) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): ResponseBeginBlock { const message = { ...baseResponseBeginBlock } as ResponseBeginBlock message.events = [] if (object.events !== undefined && object.events !== null) { for (const e of object.events) { message.events.push(Event.fromJSON(e)) } } return message }, toJSON(message: ResponseBeginBlock): unknown { const obj: any = {} if (message.events) { obj.events = message.events.map((e) => (e ? Event.toJSON(e) : undefined)) } else { obj.events = [] } return obj }, fromPartial(object: DeepPartial<ResponseBeginBlock>): ResponseBeginBlock { const message = { ...baseResponseBeginBlock } as ResponseBeginBlock message.events = [] if (object.events !== undefined && object.events !== null) { for (const e of object.events) { message.events.push(Event.fromPartial(e)) } } return message } } const baseResponseCheckTx: object = { code: 0, log: '', info: '', gasWanted: 0, gasUsed: 0, codespace: '' } export const ResponseCheckTx = { encode(message: ResponseCheckTx, writer: Writer = Writer.create()): Writer { if (message.code !== 0) { writer.uint32(8).uint32(message.code) } if (message.data.length !== 0) { writer.uint32(18).bytes(message.data) } if (message.log !== '') { writer.uint32(26).string(message.log) } if (message.info !== '') { writer.uint32(34).string(message.info) } if (message.gasWanted !== 0) { writer.uint32(40).int64(message.gasWanted) } if (message.gasUsed !== 0) { writer.uint32(48).int64(message.gasUsed) } for (const v of message.events) { Event.encode(v!, writer.uint32(58).fork()).ldelim() } if (message.codespace !== '') { writer.uint32(66).string(message.codespace) } return writer }, decode(input: Reader | Uint8Array, length?: number): ResponseCheckTx { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseResponseCheckTx } as ResponseCheckTx message.events = [] while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.code = reader.uint32() break case 2: message.data = reader.bytes() break case 3: message.log = reader.string() break case 4: message.info = reader.string() break case 5: message.gasWanted = longToNumber(reader.int64() as Long) break case 6: message.gasUsed = longToNumber(reader.int64() as Long) break case 7: message.events.push(Event.decode(reader, reader.uint32())) break case 8: message.codespace = reader.string() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): ResponseCheckTx { const message = { ...baseResponseCheckTx } as ResponseCheckTx message.events = [] if (object.code !== undefined && object.code !== null) { message.code = Number(object.code) } else { message.code = 0 } if (object.data !== undefined && object.data !== null) { message.data = bytesFromBase64(object.data) } if (object.log !== undefined && object.log !== null) { message.log = String(object.log) } else { message.log = '' } if (object.info !== undefined && object.info !== null) { message.info = String(object.info) } else { message.info = '' } if (object.gasWanted !== undefined && object.gasWanted !== null) { message.gasWanted = Number(object.gasWanted) } else { message.gasWanted = 0 } if (object.gasUsed !== undefined && object.gasUsed !== null) { message.gasUsed = Number(object.gasUsed) } else { message.gasUsed = 0 } if (object.events !== undefined && object.events !== null) { for (const e of object.events) { message.events.push(Event.fromJSON(e)) } } if (object.codespace !== undefined && object.codespace !== null) { message.codespace = String(object.codespace) } else { message.codespace = '' } return message }, toJSON(message: ResponseCheckTx): unknown { const obj: any = {} message.code !== undefined && (obj.code = message.code) message.data !== undefined && (obj.data = base64FromBytes( message.data !== undefined ? message.data : new Uint8Array() )) message.log !== undefined && (obj.log = message.log) message.info !== undefined && (obj.info = message.info) message.gasWanted !== undefined && (obj.gasWanted = message.gasWanted) message.gasUsed !== undefined && (obj.gasUsed = message.gasUsed) if (message.events) { obj.events = message.events.map((e) => (e ? Event.toJSON(e) : undefined)) } else { obj.events = [] } message.codespace !== undefined && (obj.codespace = message.codespace) return obj }, fromPartial(object: DeepPartial<ResponseCheckTx>): ResponseCheckTx { const message = { ...baseResponseCheckTx } as ResponseCheckTx message.events = [] if (object.code !== undefined && object.code !== null) { message.code = object.code } else { message.code = 0 } if (object.data !== undefined && object.data !== null) { message.data = object.data } else { message.data = new Uint8Array() } if (object.log !== undefined && object.log !== null) { message.log = object.log } else { message.log = '' } if (object.info !== undefined && object.info !== null) { message.info = object.info } else { message.info = '' } if (object.gasWanted !== undefined && object.gasWanted !== null) { message.gasWanted = object.gasWanted } else { message.gasWanted = 0 } if (object.gasUsed !== undefined && object.gasUsed !== null) { message.gasUsed = object.gasUsed } else { message.gasUsed = 0 } if (object.events !== undefined && object.events !== null) { for (const e of object.events) { message.events.push(Event.fromPartial(e)) } } if (object.codespace !== undefined && object.codespace !== null) { message.codespace = object.codespace } else { message.codespace = '' } return message } } const baseResponseDeliverTx: object = { code: 0, log: '', info: '', gasWanted: 0, gasUsed: 0, codespace: '' } export const ResponseDeliverTx = { encode(message: ResponseDeliverTx, writer: Writer = Writer.create()): Writer { if (message.code !== 0) { writer.uint32(8).uint32(message.code) } if (message.data.length !== 0) { writer.uint32(18).bytes(message.data) } if (message.log !== '') { writer.uint32(26).string(message.log) } if (message.info !== '') { writer.uint32(34).string(message.info) } if (message.gasWanted !== 0) { writer.uint32(40).int64(message.gasWanted) } if (message.gasUsed !== 0) { writer.uint32(48).int64(message.gasUsed) } for (const v of message.events) { Event.encode(v!, writer.uint32(58).fork()).ldelim() } if (message.codespace !== '') { writer.uint32(66).string(message.codespace) } return writer }, decode(input: Reader | Uint8Array, length?: number): ResponseDeliverTx { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseResponseDeliverTx } as ResponseDeliverTx message.events = [] while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.code = reader.uint32() break case 2: message.data = reader.bytes() break case 3: message.log = reader.string() break case 4: message.info = reader.string() break case 5: message.gasWanted = longToNumber(reader.int64() as Long) break case 6: message.gasUsed = longToNumber(reader.int64() as Long) break case 7: message.events.push(Event.decode(reader, reader.uint32())) break case 8: message.codespace = reader.string() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): ResponseDeliverTx { const message = { ...baseResponseDeliverTx } as ResponseDeliverTx message.events = [] if (object.code !== undefined && object.code !== null) { message.code = Number(object.code) } else { message.code = 0 } if (object.data !== undefined && object.data !== null) { message.data = bytesFromBase64(object.data) } if (object.log !== undefined && object.log !== null) { message.log = String(object.log) } else { message.log = '' } if (object.info !== undefined && object.info !== null) { message.info = String(object.info) } else { message.info = '' } if (object.gasWanted !== undefined && object.gasWanted !== null) { message.gasWanted = Number(object.gasWanted) } else { message.gasWanted = 0 } if (object.gasUsed !== undefined && object.gasUsed !== null) { message.gasUsed = Number(object.gasUsed) } else { message.gasUsed = 0 } if (object.events !== undefined && object.events !== null) { for (const e of object.events) { message.events.push(Event.fromJSON(e)) } } if (object.codespace !== undefined && object.codespace !== null) { message.codespace = String(object.codespace) } else { message.codespace = '' } return message }, toJSON(message: ResponseDeliverTx): unknown { const obj: any = {} message.code !== undefined && (obj.code = message.code) message.data !== undefined && (obj.data = base64FromBytes( message.data !== undefined ? message.data : new Uint8Array() )) message.log !== undefined && (obj.log = message.log) message.info !== undefined && (obj.info = message.info) message.gasWanted !== undefined && (obj.gasWanted = message.gasWanted) message.gasUsed !== undefined && (obj.gasUsed = message.gasUsed) if (message.events) { obj.events = message.events.map((e) => (e ? Event.toJSON(e) : undefined)) } else { obj.events = [] } message.codespace !== undefined && (obj.codespace = message.codespace) return obj }, fromPartial(object: DeepPartial<ResponseDeliverTx>): ResponseDeliverTx { const message = { ...baseResponseDeliverTx } as ResponseDeliverTx message.events = [] if (object.code !== undefined && object.code !== null) { message.code = object.code } else { message.code = 0 } if (object.data !== undefined && object.data !== null) { message.data = object.data } else { message.data = new Uint8Array() } if (object.log !== undefined && object.log !== null) { message.log = object.log } else { message.log = '' } if (object.info !== undefined && object.info !== null) { message.info = object.info } else { message.info = '' } if (object.gasWanted !== undefined && object.gasWanted !== null) { message.gasWanted = object.gasWanted } else { message.gasWanted = 0 } if (object.gasUsed !== undefined && object.gasUsed !== null) { message.gasUsed = object.gasUsed } else { message.gasUsed = 0 } if (object.events !== undefined && object.events !== null) { for (const e of object.events) { message.events.push(Event.fromPartial(e)) } } if (object.codespace !== undefined && object.codespace !== null) { message.codespace = object.codespace } else { message.codespace = '' } return message } } const baseResponseEndBlock: object = {} export const ResponseEndBlock = { encode(message: ResponseEndBlock, writer: Writer = Writer.create()): Writer { for (const v of message.validatorUpdates) { ValidatorUpdate.encode(v!, writer.uint32(10).fork()).ldelim() } if (message.consensusParamUpdates !== undefined) { ConsensusParams.encode( message.consensusParamUpdates, writer.uint32(18).fork() ).ldelim() } for (const v of message.events) { Event.encode(v!, writer.uint32(26).fork()).ldelim() } return writer }, decode(input: Reader | Uint8Array, length?: number): ResponseEndBlock { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseResponseEndBlock } as ResponseEndBlock message.validatorUpdates = [] message.events = [] while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.validatorUpdates.push( ValidatorUpdate.decode(reader, reader.uint32()) ) break case 2: message.consensusParamUpdates = ConsensusParams.decode( reader, reader.uint32() ) break case 3: message.events.push(Event.decode(reader, reader.uint32())) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): ResponseEndBlock { const message = { ...baseResponseEndBlock } as ResponseEndBlock message.validatorUpdates = [] message.events = [] if ( object.validatorUpdates !== undefined && object.validatorUpdates !== null ) { for (const e of object.validatorUpdates) { message.validatorUpdates.push(ValidatorUpdate.fromJSON(e)) } } if ( object.consensusParamUpdates !== undefined && object.consensusParamUpdates !== null ) { message.consensusParamUpdates = ConsensusParams.fromJSON( object.consensusParamUpdates ) } else { message.consensusParamUpdates = undefined } if (object.events !== undefined && object.events !== null) { for (const e of object.events) { message.events.push(Event.fromJSON(e)) } } return message }, toJSON(message: ResponseEndBlock): unknown { const obj: any = {} if (message.validatorUpdates) { obj.validatorUpdates = message.validatorUpdates.map((e) => e ? ValidatorUpdate.toJSON(e) : undefined ) } else { obj.validatorUpdates = [] } message.consensusParamUpdates !== undefined && (obj.consensusParamUpdates = message.consensusParamUpdates ? ConsensusParams.toJSON(message.consensusParamUpdates) : undefined) if (message.events) { obj.events = message.events.map((e) => (e ? Event.toJSON(e) : undefined)) } else { obj.events = [] } return obj }, fromPartial(object: DeepPartial<ResponseEndBlock>): ResponseEndBlock { const message = { ...baseResponseEndBlock } as ResponseEndBlock message.validatorUpdates = [] message.events = [] if ( object.validatorUpdates !== undefined && object.validatorUpdates !== null ) { for (const e of object.validatorUpdates) { message.validatorUpdates.push(ValidatorUpdate.fromPartial(e)) } } if ( object.consensusParamUpdates !== undefined && object.consensusParamUpdates !== null ) { message.consensusParamUpdates = ConsensusParams.fromPartial( object.consensusParamUpdates ) } else { message.consensusParamUpdates = undefined } if (object.events !== undefined && object.events !== null) { for (const e of object.events) { message.events.push(Event.fromPartial(e)) } } return message } } const baseResponseCommit: object = { retainHeight: 0 } export const ResponseCommit = { encode(message: ResponseCommit, writer: Writer = Writer.create()): Writer { if (message.data.length !== 0) { writer.uint32(18).bytes(message.data) } if (message.retainHeight !== 0) { writer.uint32(24).int64(message.retainHeight) } return writer }, decode(input: Reader | Uint8Array, length?: number): ResponseCommit { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseResponseCommit } as ResponseCommit while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 2: message.data = reader.bytes() break case 3: message.retainHeight = longToNumber(reader.int64() as Long) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): ResponseCommit { const message = { ...baseResponseCommit } as ResponseCommit if (object.data !== undefined && object.data !== null) { message.data = bytesFromBase64(object.data) } if (object.retainHeight !== undefined && object.retainHeight !== null) { message.retainHeight = Number(object.retainHeight) } else { message.retainHeight = 0 } return message }, toJSON(message: ResponseCommit): unknown { const obj: any = {} message.data !== undefined && (obj.data = base64FromBytes( message.data !== undefined ? message.data : new Uint8Array() )) message.retainHeight !== undefined && (obj.retainHeight = message.retainHeight) return obj }, fromPartial(object: DeepPartial<ResponseCommit>): ResponseCommit { const message = { ...baseResponseCommit } as ResponseCommit if (object.data !== undefined && object.data !== null) { message.data = object.data } else { message.data = new Uint8Array() } if (object.retainHeight !== undefined && object.retainHeight !== null) { message.retainHeight = object.retainHeight } else { message.retainHeight = 0 } return message } } const baseResponseListSnapshots: object = {} export const ResponseListSnapshots = { encode( message: ResponseListSnapshots, writer: Writer = Writer.create() ): Writer { for (const v of message.snapshots) { Snapshot.encode(v!, writer.uint32(10).fork()).ldelim() } return writer }, decode(input: Reader | Uint8Array, length?: number): ResponseListSnapshots { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseResponseListSnapshots } as ResponseListSnapshots message.snapshots = [] while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.snapshots.push(Snapshot.decode(reader, reader.uint32())) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): ResponseListSnapshots { const message = { ...baseResponseListSnapshots } as ResponseListSnapshots message.snapshots = [] if (object.snapshots !== undefined && object.snapshots !== null) { for (const e of object.snapshots) { message.snapshots.push(Snapshot.fromJSON(e)) } } return message }, toJSON(message: ResponseListSnapshots): unknown { const obj: any = {} if (message.snapshots) { obj.snapshots = message.snapshots.map((e) => e ? Snapshot.toJSON(e) : undefined ) } else { obj.snapshots = [] } return obj }, fromPartial( object: DeepPartial<ResponseListSnapshots> ): ResponseListSnapshots { const message = { ...baseResponseListSnapshots } as ResponseListSnapshots message.snapshots = [] if (object.snapshots !== undefined && object.snapshots !== null) { for (const e of object.snapshots) { message.snapshots.push(Snapshot.fromPartial(e)) } } return message } } const baseResponseOfferSnapshot: object = { result: 0 } export const ResponseOfferSnapshot = { encode( message: ResponseOfferSnapshot, writer: Writer = Writer.create() ): Writer { if (message.result !== 0) { writer.uint32(8).int32(message.result) } return writer }, decode(input: Reader | Uint8Array, length?: number): ResponseOfferSnapshot { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseResponseOfferSnapshot } as ResponseOfferSnapshot while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.result = reader.int32() as any break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): ResponseOfferSnapshot { const message = { ...baseResponseOfferSnapshot } as ResponseOfferSnapshot if (object.result !== undefined && object.result !== null) { message.result = responseOfferSnapshot_ResultFromJSON(object.result) } else { message.result = 0 } return message }, toJSON(message: ResponseOfferSnapshot): unknown { const obj: any = {} message.result !== undefined && (obj.result = responseOfferSnapshot_ResultToJSON(message.result)) return obj }, fromPartial( object: DeepPartial<ResponseOfferSnapshot> ): ResponseOfferSnapshot { const message = { ...baseResponseOfferSnapshot } as ResponseOfferSnapshot if (object.result !== undefined && object.result !== null) { message.result = object.result } else { message.result = 0 } return message } } const baseResponseLoadSnapshotChunk: object = {} export const ResponseLoadSnapshotChunk = { encode( message: ResponseLoadSnapshotChunk, writer: Writer = Writer.create() ): Writer { if (message.chunk.length !== 0) { writer.uint32(10).bytes(message.chunk) } return writer }, decode( input: Reader | Uint8Array, length?: number ): ResponseLoadSnapshotChunk { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseResponseLoadSnapshotChunk } as ResponseLoadSnapshotChunk while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.chunk = reader.bytes() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): ResponseLoadSnapshotChunk { const message = { ...baseResponseLoadSnapshotChunk } as ResponseLoadSnapshotChunk if (object.chunk !== undefined && object.chunk !== null) { message.chunk = bytesFromBase64(object.chunk) } return message }, toJSON(message: ResponseLoadSnapshotChunk): unknown { const obj: any = {} message.chunk !== undefined && (obj.chunk = base64FromBytes( message.chunk !== undefined ? message.chunk : new Uint8Array() )) return obj }, fromPartial( object: DeepPartial<ResponseLoadSnapshotChunk> ): ResponseLoadSnapshotChunk { const message = { ...baseResponseLoadSnapshotChunk } as ResponseLoadSnapshotChunk if (object.chunk !== undefined && object.chunk !== null) { message.chunk = object.chunk } else { message.chunk = new Uint8Array() } return message } } const baseResponseApplySnapshotChunk: object = { result: 0, refetchChunks: 0, rejectSenders: '' } export const ResponseApplySnapshotChunk = { encode( message: ResponseApplySnapshotChunk, writer: Writer = Writer.create() ): Writer { if (message.result !== 0) { writer.uint32(8).int32(message.result) } writer.uint32(18).fork() for (const v of message.refetchChunks) { writer.uint32(v) } writer.ldelim() for (const v of message.rejectSenders) { writer.uint32(26).string(v!) } return writer }, decode( input: Reader | Uint8Array, length?: number ): ResponseApplySnapshotChunk { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseResponseApplySnapshotChunk } as ResponseApplySnapshotChunk message.refetchChunks = [] message.rejectSenders = [] while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.result = reader.int32() as any break case 2: if ((tag & 7) === 2) { const end2 = reader.uint32() + reader.pos while (reader.pos < end2) { message.refetchChunks.push(reader.uint32()) } } else { message.refetchChunks.push(reader.uint32()) } break case 3: message.rejectSenders.push(reader.string()) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): ResponseApplySnapshotChunk { const message = { ...baseResponseApplySnapshotChunk } as ResponseApplySnapshotChunk message.refetchChunks = [] message.rejectSenders = [] if (object.result !== undefined && object.result !== null) { message.result = responseApplySnapshotChunk_ResultFromJSON(object.result) } else { message.result = 0 } if (object.refetchChunks !== undefined && object.refetchChunks !== null) { for (const e of object.refetchChunks) { message.refetchChunks.push(Number(e)) } } if (object.rejectSenders !== undefined && object.rejectSenders !== null) { for (const e of object.rejectSenders) { message.rejectSenders.push(String(e)) } } return message }, toJSON(message: ResponseApplySnapshotChunk): unknown { const obj: any = {} message.result !== undefined && (obj.result = responseApplySnapshotChunk_ResultToJSON(message.result)) if (message.refetchChunks) { obj.refetchChunks = message.refetchChunks.map((e) => e) } else { obj.refetchChunks = [] } if (message.rejectSenders) { obj.rejectSenders = message.rejectSenders.map((e) => e) } else { obj.rejectSenders = [] } return obj }, fromPartial( object: DeepPartial<ResponseApplySnapshotChunk> ): ResponseApplySnapshotChunk { const message = { ...baseResponseApplySnapshotChunk } as ResponseApplySnapshotChunk message.refetchChunks = [] message.rejectSenders = [] if (object.result !== undefined && object.result !== null) { message.result = object.result } else { message.result = 0 } if (object.refetchChunks !== undefined && object.refetchChunks !== null) { for (const e of object.refetchChunks) { message.refetchChunks.push(e) } } if (object.rejectSenders !== undefined && object.rejectSenders !== null) { for (const e of object.rejectSenders) { message.rejectSenders.push(e) } } return message } } const baseConsensusParams: object = {} export const ConsensusParams = { encode(message: ConsensusParams, writer: Writer = Writer.create()): Writer { if (message.block !== undefined) { BlockParams.encode(message.block, writer.uint32(10).fork()).ldelim() } if (message.evidence !== undefined) { EvidenceParams.encode(message.evidence, writer.uint32(18).fork()).ldelim() } if (message.validator !== undefined) { ValidatorParams.encode( message.validator, writer.uint32(26).fork() ).ldelim() } if (message.version !== undefined) { VersionParams.encode(message.version, writer.uint32(34).fork()).ldelim() } return writer }, decode(input: Reader | Uint8Array, length?: number): ConsensusParams { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseConsensusParams } as ConsensusParams while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.block = BlockParams.decode(reader, reader.uint32()) break case 2: message.evidence = EvidenceParams.decode(reader, reader.uint32()) break case 3: message.validator = ValidatorParams.decode(reader, reader.uint32()) break case 4: message.version = VersionParams.decode(reader, reader.uint32()) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): ConsensusParams { const message = { ...baseConsensusParams } as ConsensusParams if (object.block !== undefined && object.block !== null) { message.block = BlockParams.fromJSON(object.block) } else { message.block = undefined } if (object.evidence !== undefined && object.evidence !== null) { message.evidence = EvidenceParams.fromJSON(object.evidence) } else { message.evidence = undefined } if (object.validator !== undefined && object.validator !== null) { message.validator = ValidatorParams.fromJSON(object.validator) } else { message.validator = undefined } if (object.version !== undefined && object.version !== null) { message.version = VersionParams.fromJSON(object.version) } else { message.version = undefined } return message }, toJSON(message: ConsensusParams): unknown { const obj: any = {} message.block !== undefined && (obj.block = message.block ? BlockParams.toJSON(message.block) : undefined) message.evidence !== undefined && (obj.evidence = message.evidence ? EvidenceParams.toJSON(message.evidence) : undefined) message.validator !== undefined && (obj.validator = message.validator ? ValidatorParams.toJSON(message.validator) : undefined) message.version !== undefined && (obj.version = message.version ? VersionParams.toJSON(message.version) : undefined) return obj }, fromPartial(object: DeepPartial<ConsensusParams>): ConsensusParams { const message = { ...baseConsensusParams } as ConsensusParams if (object.block !== undefined && object.block !== null) { message.block = BlockParams.fromPartial(object.block) } else { message.block = undefined } if (object.evidence !== undefined && object.evidence !== null) { message.evidence = EvidenceParams.fromPartial(object.evidence) } else { message.evidence = undefined } if (object.validator !== undefined && object.validator !== null) { message.validator = ValidatorParams.fromPartial(object.validator) } else { message.validator = undefined } if (object.version !== undefined && object.version !== null) { message.version = VersionParams.fromPartial(object.version) } else { message.version = undefined } return message } } const baseBlockParams: object = { maxBytes: 0, maxGas: 0 } export const BlockParams = { encode(message: BlockParams, writer: Writer = Writer.create()): Writer { if (message.maxBytes !== 0) { writer.uint32(8).int64(message.maxBytes) } if (message.maxGas !== 0) { writer.uint32(16).int64(message.maxGas) } return writer }, decode(input: Reader | Uint8Array, length?: number): BlockParams { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseBlockParams } as BlockParams while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.maxBytes = longToNumber(reader.int64() as Long) break case 2: message.maxGas = longToNumber(reader.int64() as Long) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): BlockParams { const message = { ...baseBlockParams } as BlockParams if (object.maxBytes !== undefined && object.maxBytes !== null) { message.maxBytes = Number(object.maxBytes) } else { message.maxBytes = 0 } if (object.maxGas !== undefined && object.maxGas !== null) { message.maxGas = Number(object.maxGas) } else { message.maxGas = 0 } return message }, toJSON(message: BlockParams): unknown { const obj: any = {} message.maxBytes !== undefined && (obj.maxBytes = message.maxBytes) message.maxGas !== undefined && (obj.maxGas = message.maxGas) return obj }, fromPartial(object: DeepPartial<BlockParams>): BlockParams { const message = { ...baseBlockParams } as BlockParams if (object.maxBytes !== undefined && object.maxBytes !== null) { message.maxBytes = object.maxBytes } else { message.maxBytes = 0 } if (object.maxGas !== undefined && object.maxGas !== null) { message.maxGas = object.maxGas } else { message.maxGas = 0 } return message } } const baseLastCommitInfo: object = { round: 0 } export const LastCommitInfo = { encode(message: LastCommitInfo, writer: Writer = Writer.create()): Writer { if (message.round !== 0) { writer.uint32(8).int32(message.round) } for (const v of message.votes) { VoteInfo.encode(v!, writer.uint32(18).fork()).ldelim() } return writer }, decode(input: Reader | Uint8Array, length?: number): LastCommitInfo { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseLastCommitInfo } as LastCommitInfo message.votes = [] while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.round = reader.int32() break case 2: message.votes.push(VoteInfo.decode(reader, reader.uint32())) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): LastCommitInfo { const message = { ...baseLastCommitInfo } as LastCommitInfo message.votes = [] if (object.round !== undefined && object.round !== null) { message.round = Number(object.round) } else { message.round = 0 } if (object.votes !== undefined && object.votes !== null) { for (const e of object.votes) { message.votes.push(VoteInfo.fromJSON(e)) } } return message }, toJSON(message: LastCommitInfo): unknown { const obj: any = {} message.round !== undefined && (obj.round = message.round) if (message.votes) { obj.votes = message.votes.map((e) => (e ? VoteInfo.toJSON(e) : undefined)) } else { obj.votes = [] } return obj }, fromPartial(object: DeepPartial<LastCommitInfo>): LastCommitInfo { const message = { ...baseLastCommitInfo } as LastCommitInfo message.votes = [] if (object.round !== undefined && object.round !== null) { message.round = object.round } else { message.round = 0 } if (object.votes !== undefined && object.votes !== null) { for (const e of object.votes) { message.votes.push(VoteInfo.fromPartial(e)) } } return message } } const baseEvent: object = { type: '' } export const Event = { encode(message: Event, writer: Writer = Writer.create()): Writer { if (message.type !== '') { writer.uint32(10).string(message.type) } for (const v of message.attributes) { EventAttribute.encode(v!, writer.uint32(18).fork()).ldelim() } return writer }, decode(input: Reader | Uint8Array, length?: number): Event { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseEvent } as Event message.attributes = [] while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.type = reader.string() break case 2: message.attributes.push( EventAttribute.decode(reader, reader.uint32()) ) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): Event { const message = { ...baseEvent } as Event message.attributes = [] if (object.type !== undefined && object.type !== null) { message.type = String(object.type) } else { message.type = '' } if (object.attributes !== undefined && object.attributes !== null) { for (const e of object.attributes) { message.attributes.push(EventAttribute.fromJSON(e)) } } return message }, toJSON(message: Event): unknown { const obj: any = {} message.type !== undefined && (obj.type = message.type) if (message.attributes) { obj.attributes = message.attributes.map((e) => e ? EventAttribute.toJSON(e) : undefined ) } else { obj.attributes = [] } return obj }, fromPartial(object: DeepPartial<Event>): Event { const message = { ...baseEvent } as Event message.attributes = [] if (object.type !== undefined && object.type !== null) { message.type = object.type } else { message.type = '' } if (object.attributes !== undefined && object.attributes !== null) { for (const e of object.attributes) { message.attributes.push(EventAttribute.fromPartial(e)) } } return message } } const baseEventAttribute: object = { index: false } export const EventAttribute = { encode(message: EventAttribute, writer: Writer = Writer.create()): Writer { if (message.key.length !== 0) { writer.uint32(10).bytes(message.key) } if (message.value.length !== 0) { writer.uint32(18).bytes(message.value) } if (message.index === true) { writer.uint32(24).bool(message.index) } return writer }, decode(input: Reader | Uint8Array, length?: number): EventAttribute { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseEventAttribute } as EventAttribute while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.key = reader.bytes() break case 2: message.value = reader.bytes() break case 3: message.index = reader.bool() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): EventAttribute { const message = { ...baseEventAttribute } as EventAttribute if (object.key !== undefined && object.key !== null) { message.key = bytesFromBase64(object.key) } if (object.value !== undefined && object.value !== null) { message.value = bytesFromBase64(object.value) } if (object.index !== undefined && object.index !== null) { message.index = Boolean(object.index) } else { message.index = false } return message }, toJSON(message: EventAttribute): unknown { const obj: any = {} message.key !== undefined && (obj.key = base64FromBytes( message.key !== undefined ? message.key : new Uint8Array() )) message.value !== undefined && (obj.value = base64FromBytes( message.value !== undefined ? message.value : new Uint8Array() )) message.index !== undefined && (obj.index = message.index) return obj }, fromPartial(object: DeepPartial<EventAttribute>): EventAttribute { const message = { ...baseEventAttribute } as EventAttribute if (object.key !== undefined && object.key !== null) { message.key = object.key } else { message.key = new Uint8Array() } if (object.value !== undefined && object.value !== null) { message.value = object.value } else { message.value = new Uint8Array() } if (object.index !== undefined && object.index !== null) { message.index = object.index } else { message.index = false } return message } } const baseTxResult: object = { height: 0, index: 0 } export const TxResult = { encode(message: TxResult, writer: Writer = Writer.create()): Writer { if (message.height !== 0) { writer.uint32(8).int64(message.height) } if (message.index !== 0) { writer.uint32(16).uint32(message.index) } if (message.tx.length !== 0) { writer.uint32(26).bytes(message.tx) } if (message.result !== undefined) { ResponseDeliverTx.encode( message.result, writer.uint32(34).fork() ).ldelim() } return writer }, decode(input: Reader | Uint8Array, length?: number): TxResult { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseTxResult } as TxResult while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.height = longToNumber(reader.int64() as Long) break case 2: message.index = reader.uint32() break case 3: message.tx = reader.bytes() break case 4: message.result = ResponseDeliverTx.decode(reader, reader.uint32()) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): TxResult { const message = { ...baseTxResult } as TxResult if (object.height !== undefined && object.height !== null) { message.height = Number(object.height) } else { message.height = 0 } if (object.index !== undefined && object.index !== null) { message.index = Number(object.index) } else { message.index = 0 } if (object.tx !== undefined && object.tx !== null) { message.tx = bytesFromBase64(object.tx) } if (object.result !== undefined && object.result !== null) { message.result = ResponseDeliverTx.fromJSON(object.result) } else { message.result = undefined } return message }, toJSON(message: TxResult): unknown { const obj: any = {} message.height !== undefined && (obj.height = message.height) message.index !== undefined && (obj.index = message.index) message.tx !== undefined && (obj.tx = base64FromBytes( message.tx !== undefined ? message.tx : new Uint8Array() )) message.result !== undefined && (obj.result = message.result ? ResponseDeliverTx.toJSON(message.result) : undefined) return obj }, fromPartial(object: DeepPartial<TxResult>): TxResult { const message = { ...baseTxResult } as TxResult if (object.height !== undefined && object.height !== null) { message.height = object.height } else { message.height = 0 } if (object.index !== undefined && object.index !== null) { message.index = object.index } else { message.index = 0 } if (object.tx !== undefined && object.tx !== null) { message.tx = object.tx } else { message.tx = new Uint8Array() } if (object.result !== undefined && object.result !== null) { message.result = ResponseDeliverTx.fromPartial(object.result) } else { message.result = undefined } return message } } const baseValidator: object = { power: 0 } export const Validator = { encode(message: Validator, writer: Writer = Writer.create()): Writer { if (message.address.length !== 0) { writer.uint32(10).bytes(message.address) } if (message.power !== 0) { writer.uint32(24).int64(message.power) } return writer }, decode(input: Reader | Uint8Array, length?: number): Validator { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseValidator } as Validator while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.address = reader.bytes() break case 3: message.power = longToNumber(reader.int64() as Long) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): Validator { const message = { ...baseValidator } as Validator if (object.address !== undefined && object.address !== null) { message.address = bytesFromBase64(object.address) } if (object.power !== undefined && object.power !== null) { message.power = Number(object.power) } else { message.power = 0 } return message }, toJSON(message: Validator): unknown { const obj: any = {} message.address !== undefined && (obj.address = base64FromBytes( message.address !== undefined ? message.address : new Uint8Array() )) message.power !== undefined && (obj.power = message.power) return obj }, fromPartial(object: DeepPartial<Validator>): Validator { const message = { ...baseValidator } as Validator if (object.address !== undefined && object.address !== null) { message.address = object.address } else { message.address = new Uint8Array() } if (object.power !== undefined && object.power !== null) { message.power = object.power } else { message.power = 0 } return message } } const baseValidatorUpdate: object = { power: 0 } export const ValidatorUpdate = { encode(message: ValidatorUpdate, writer: Writer = Writer.create()): Writer { if (message.pubKey !== undefined) { PublicKey.encode(message.pubKey, writer.uint32(10).fork()).ldelim() } if (message.power !== 0) { writer.uint32(16).int64(message.power) } return writer }, decode(input: Reader | Uint8Array, length?: number): ValidatorUpdate { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseValidatorUpdate } as ValidatorUpdate while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.pubKey = PublicKey.decode(reader, reader.uint32()) break case 2: message.power = longToNumber(reader.int64() as Long) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): ValidatorUpdate { const message = { ...baseValidatorUpdate } as ValidatorUpdate if (object.pubKey !== undefined && object.pubKey !== null) { message.pubKey = PublicKey.fromJSON(object.pubKey) } else { message.pubKey = undefined } if (object.power !== undefined && object.power !== null) { message.power = Number(object.power) } else { message.power = 0 } return message }, toJSON(message: ValidatorUpdate): unknown { const obj: any = {} message.pubKey !== undefined && (obj.pubKey = message.pubKey ? PublicKey.toJSON(message.pubKey) : undefined) message.power !== undefined && (obj.power = message.power) return obj }, fromPartial(object: DeepPartial<ValidatorUpdate>): ValidatorUpdate { const message = { ...baseValidatorUpdate } as ValidatorUpdate if (object.pubKey !== undefined && object.pubKey !== null) { message.pubKey = PublicKey.fromPartial(object.pubKey) } else { message.pubKey = undefined } if (object.power !== undefined && object.power !== null) { message.power = object.power } else { message.power = 0 } return message } } const baseVoteInfo: object = { signedLastBlock: false } export const VoteInfo = { encode(message: VoteInfo, writer: Writer = Writer.create()): Writer { if (message.validator !== undefined) { Validator.encode(message.validator, writer.uint32(10).fork()).ldelim() } if (message.signedLastBlock === true) { writer.uint32(16).bool(message.signedLastBlock) } return writer }, decode(input: Reader | Uint8Array, length?: number): VoteInfo { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseVoteInfo } as VoteInfo while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.validator = Validator.decode(reader, reader.uint32()) break case 2: message.signedLastBlock = reader.bool() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): VoteInfo { const message = { ...baseVoteInfo } as VoteInfo if (object.validator !== undefined && object.validator !== null) { message.validator = Validator.fromJSON(object.validator) } else { message.validator = undefined } if ( object.signedLastBlock !== undefined && object.signedLastBlock !== null ) { message.signedLastBlock = Boolean(object.signedLastBlock) } else { message.signedLastBlock = false } return message }, toJSON(message: VoteInfo): unknown { const obj: any = {} message.validator !== undefined && (obj.validator = message.validator ? Validator.toJSON(message.validator) : undefined) message.signedLastBlock !== undefined && (obj.signedLastBlock = message.signedLastBlock) return obj }, fromPartial(object: DeepPartial<VoteInfo>): VoteInfo { const message = { ...baseVoteInfo } as VoteInfo if (object.validator !== undefined && object.validator !== null) { message.validator = Validator.fromPartial(object.validator) } else { message.validator = undefined } if ( object.signedLastBlock !== undefined && object.signedLastBlock !== null ) { message.signedLastBlock = object.signedLastBlock } else { message.signedLastBlock = false } return message } } const baseEvidence: object = { type: 0, height: 0, totalVotingPower: 0 } export const Evidence = { encode(message: Evidence, writer: Writer = Writer.create()): Writer { if (message.type !== 0) { writer.uint32(8).int32(message.type) } if (message.validator !== undefined) { Validator.encode(message.validator, writer.uint32(18).fork()).ldelim() } if (message.height !== 0) { writer.uint32(24).int64(message.height) } if (message.time !== undefined) { Timestamp.encode( toTimestamp(message.time), writer.uint32(34).fork() ).ldelim() } if (message.totalVotingPower !== 0) { writer.uint32(40).int64(message.totalVotingPower) } return writer }, decode(input: Reader | Uint8Array, length?: number): Evidence { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseEvidence } as Evidence while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.type = reader.int32() as any break case 2: message.validator = Validator.decode(reader, reader.uint32()) break case 3: message.height = longToNumber(reader.int64() as Long) break case 4: message.time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ) break case 5: message.totalVotingPower = longToNumber(reader.int64() as Long) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): Evidence { const message = { ...baseEvidence } as Evidence if (object.type !== undefined && object.type !== null) { message.type = evidenceTypeFromJSON(object.type) } else { message.type = 0 } if (object.validator !== undefined && object.validator !== null) { message.validator = Validator.fromJSON(object.validator) } else { message.validator = undefined } if (object.height !== undefined && object.height !== null) { message.height = Number(object.height) } else { message.height = 0 } if (object.time !== undefined && object.time !== null) { message.time = fromJsonTimestamp(object.time) } else { message.time = undefined } if ( object.totalVotingPower !== undefined && object.totalVotingPower !== null ) { message.totalVotingPower = Number(object.totalVotingPower) } else { message.totalVotingPower = 0 } return message }, toJSON(message: Evidence): unknown { const obj: any = {} message.type !== undefined && (obj.type = evidenceTypeToJSON(message.type)) message.validator !== undefined && (obj.validator = message.validator ? Validator.toJSON(message.validator) : undefined) message.height !== undefined && (obj.height = message.height) message.time !== undefined && (obj.time = message.time !== undefined ? message.time.toISOString() : null) message.totalVotingPower !== undefined && (obj.totalVotingPower = message.totalVotingPower) return obj }, fromPartial(object: DeepPartial<Evidence>): Evidence { const message = { ...baseEvidence } as Evidence if (object.type !== undefined && object.type !== null) { message.type = object.type } else { message.type = 0 } if (object.validator !== undefined && object.validator !== null) { message.validator = Validator.fromPartial(object.validator) } else { message.validator = undefined } if (object.height !== undefined && object.height !== null) { message.height = object.height } else { message.height = 0 } if (object.time !== undefined && object.time !== null) { message.time = object.time } else { message.time = undefined } if ( object.totalVotingPower !== undefined && object.totalVotingPower !== null ) { message.totalVotingPower = object.totalVotingPower } else { message.totalVotingPower = 0 } return message } } const baseSnapshot: object = { height: 0, format: 0, chunks: 0 } export const Snapshot = { encode(message: Snapshot, writer: Writer = Writer.create()): Writer { if (message.height !== 0) { writer.uint32(8).uint64(message.height) } if (message.format !== 0) { writer.uint32(16).uint32(message.format) } if (message.chunks !== 0) { writer.uint32(24).uint32(message.chunks) } if (message.hash.length !== 0) { writer.uint32(34).bytes(message.hash) } if (message.metadata.length !== 0) { writer.uint32(42).bytes(message.metadata) } return writer }, decode(input: Reader | Uint8Array, length?: number): Snapshot { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseSnapshot } as Snapshot while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.height = longToNumber(reader.uint64() as Long) break case 2: message.format = reader.uint32() break case 3: message.chunks = reader.uint32() break case 4: message.hash = reader.bytes() break case 5: message.metadata = reader.bytes() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): Snapshot { const message = { ...baseSnapshot } as Snapshot if (object.height !== undefined && object.height !== null) { message.height = Number(object.height) } else { message.height = 0 } if (object.format !== undefined && object.format !== null) { message.format = Number(object.format) } else { message.format = 0 } if (object.chunks !== undefined && object.chunks !== null) { message.chunks = Number(object.chunks) } else { message.chunks = 0 } if (object.hash !== undefined && object.hash !== null) { message.hash = bytesFromBase64(object.hash) } if (object.metadata !== undefined && object.metadata !== null) { message.metadata = bytesFromBase64(object.metadata) } return message }, toJSON(message: Snapshot): unknown { const obj: any = {} message.height !== undefined && (obj.height = message.height) message.format !== undefined && (obj.format = message.format) message.chunks !== undefined && (obj.chunks = message.chunks) message.hash !== undefined && (obj.hash = base64FromBytes( message.hash !== undefined ? message.hash : new Uint8Array() )) message.metadata !== undefined && (obj.metadata = base64FromBytes( message.metadata !== undefined ? message.metadata : new Uint8Array() )) return obj }, fromPartial(object: DeepPartial<Snapshot>): Snapshot { const message = { ...baseSnapshot } as Snapshot if (object.height !== undefined && object.height !== null) { message.height = object.height } else { message.height = 0 } if (object.format !== undefined && object.format !== null) { message.format = object.format } else { message.format = 0 } if (object.chunks !== undefined && object.chunks !== null) { message.chunks = object.chunks } else { message.chunks = 0 } if (object.hash !== undefined && object.hash !== null) { message.hash = object.hash } else { message.hash = new Uint8Array() } if (object.metadata !== undefined && object.metadata !== null) { message.metadata = object.metadata } else { message.metadata = new Uint8Array() } return message } } export interface ABCIApplication { Echo(request: RequestEcho): Promise<ResponseEcho> Flush(request: RequestFlush): Promise<ResponseFlush> Info(request: RequestInfo): Promise<ResponseInfo> SetOption(request: RequestSetOption): Promise<ResponseSetOption> DeliverTx(request: RequestDeliverTx): Promise<ResponseDeliverTx> CheckTx(request: RequestCheckTx): Promise<ResponseCheckTx> Query(request: RequestQuery): Promise<ResponseQuery> Commit(request: RequestCommit): Promise<ResponseCommit> InitChain(request: RequestInitChain): Promise<ResponseInitChain> BeginBlock(request: RequestBeginBlock): Promise<ResponseBeginBlock> EndBlock(request: RequestEndBlock): Promise<ResponseEndBlock> ListSnapshots(request: RequestListSnapshots): Promise<ResponseListSnapshots> OfferSnapshot(request: RequestOfferSnapshot): Promise<ResponseOfferSnapshot> LoadSnapshotChunk( request: RequestLoadSnapshotChunk ): Promise<ResponseLoadSnapshotChunk> ApplySnapshotChunk( request: RequestApplySnapshotChunk ): Promise<ResponseApplySnapshotChunk> } export class ABCIApplicationClientImpl implements ABCIApplication { private readonly rpc: Rpc constructor(rpc: Rpc) { this.rpc = rpc } Echo(request: RequestEcho): Promise<ResponseEcho> { const data = RequestEcho.encode(request).finish() const promise = this.rpc.request( 'tendermint.abci.ABCIApplication', 'Echo', data ) return promise.then((data) => ResponseEcho.decode(new Reader(data))) } Flush(request: RequestFlush): Promise<ResponseFlush> { const data = RequestFlush.encode(request).finish() const promise = this.rpc.request( 'tendermint.abci.ABCIApplication', 'Flush', data ) return promise.then((data) => ResponseFlush.decode(new Reader(data))) } Info(request: RequestInfo): Promise<ResponseInfo> { const data = RequestInfo.encode(request).finish() const promise = this.rpc.request( 'tendermint.abci.ABCIApplication', 'Info', data ) return promise.then((data) => ResponseInfo.decode(new Reader(data))) } SetOption(request: RequestSetOption): Promise<ResponseSetOption> { const data = RequestSetOption.encode(request).finish() const promise = this.rpc.request( 'tendermint.abci.ABCIApplication', 'SetOption', data ) return promise.then((data) => ResponseSetOption.decode(new Reader(data))) } DeliverTx(request: RequestDeliverTx): Promise<ResponseDeliverTx> { const data = RequestDeliverTx.encode(request).finish() const promise = this.rpc.request( 'tendermint.abci.ABCIApplication', 'DeliverTx', data ) return promise.then((data) => ResponseDeliverTx.decode(new Reader(data))) } CheckTx(request: RequestCheckTx): Promise<ResponseCheckTx> { const data = RequestCheckTx.encode(request).finish() const promise = this.rpc.request( 'tendermint.abci.ABCIApplication', 'CheckTx', data ) return promise.then((data) => ResponseCheckTx.decode(new Reader(data))) } Query(request: RequestQuery): Promise<ResponseQuery> { const data = RequestQuery.encode(request).finish() const promise = this.rpc.request( 'tendermint.abci.ABCIApplication', 'Query', data ) return promise.then((data) => ResponseQuery.decode(new Reader(data))) } Commit(request: RequestCommit): Promise<ResponseCommit> { const data = RequestCommit.encode(request).finish() const promise = this.rpc.request( 'tendermint.abci.ABCIApplication', 'Commit', data ) return promise.then((data) => ResponseCommit.decode(new Reader(data))) } InitChain(request: RequestInitChain): Promise<ResponseInitChain> { const data = RequestInitChain.encode(request).finish() const promise = this.rpc.request( 'tendermint.abci.ABCIApplication', 'InitChain', data ) return promise.then((data) => ResponseInitChain.decode(new Reader(data))) } BeginBlock(request: RequestBeginBlock): Promise<ResponseBeginBlock> { const data = RequestBeginBlock.encode(request).finish() const promise = this.rpc.request( 'tendermint.abci.ABCIApplication', 'BeginBlock', data ) return promise.then((data) => ResponseBeginBlock.decode(new Reader(data))) } EndBlock(request: RequestEndBlock): Promise<ResponseEndBlock> { const data = RequestEndBlock.encode(request).finish() const promise = this.rpc.request( 'tendermint.abci.ABCIApplication', 'EndBlock', data ) return promise.then((data) => ResponseEndBlock.decode(new Reader(data))) } ListSnapshots(request: RequestListSnapshots): Promise<ResponseListSnapshots> { const data = RequestListSnapshots.encode(request).finish() const promise = this.rpc.request( 'tendermint.abci.ABCIApplication', 'ListSnapshots', data ) return promise.then((data) => ResponseListSnapshots.decode(new Reader(data)) ) } OfferSnapshot(request: RequestOfferSnapshot): Promise<ResponseOfferSnapshot> { const data = RequestOfferSnapshot.encode(request).finish() const promise = this.rpc.request( 'tendermint.abci.ABCIApplication', 'OfferSnapshot', data ) return promise.then((data) => ResponseOfferSnapshot.decode(new Reader(data)) ) } LoadSnapshotChunk( request: RequestLoadSnapshotChunk ): Promise<ResponseLoadSnapshotChunk> { const data = RequestLoadSnapshotChunk.encode(request).finish() const promise = this.rpc.request( 'tendermint.abci.ABCIApplication', 'LoadSnapshotChunk', data ) return promise.then((data) => ResponseLoadSnapshotChunk.decode(new Reader(data)) ) } ApplySnapshotChunk( request: RequestApplySnapshotChunk ): Promise<ResponseApplySnapshotChunk> { const data = RequestApplySnapshotChunk.encode(request).finish() const promise = this.rpc.request( 'tendermint.abci.ABCIApplication', 'ApplySnapshotChunk', data ) return promise.then((data) => ResponseApplySnapshotChunk.decode(new Reader(data)) ) } } interface Rpc { request( service: string, method: string, data: Uint8Array ): Promise<Uint8Array> } declare var self: any | undefined declare var window: any | undefined var globalThis: any = (() => { if (typeof globalThis !== 'undefined') return globalThis if (typeof self !== 'undefined') return self if (typeof window !== 'undefined') return window if (typeof global !== 'undefined') return global throw 'Unable to locate global object' })() const atob: (b64: string) => string = globalThis.atob || ((b64) => globalThis.Buffer.from(b64, 'base64').toString('binary')) function bytesFromBase64(b64: string): Uint8Array { const bin = atob(b64) const arr = new Uint8Array(bin.length) for (let i = 0; i < bin.length; ++i) { arr[i] = bin.charCodeAt(i) } return arr } const btoa: (bin: string) => string = globalThis.btoa || ((bin) => globalThis.Buffer.from(bin, 'binary').toString('base64')) function base64FromBytes(arr: Uint8Array): string { const bin: string[] = [] for (let i = 0; i < arr.byteLength; ++i) { bin.push(String.fromCharCode(arr[i])) } return btoa(bin.join('')) } type Builtin = Date | Function | Uint8Array | string | number | undefined export type DeepPartial<T> = T extends Builtin ? T : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> } : Partial<T> function toTimestamp(date: Date): Timestamp { const seconds = date.getTime() / 1_000 const nanos = (date.getTime() % 1_000) * 1_000_000 return { seconds, nanos } } function fromTimestamp(t: Timestamp): Date { let millis = t.seconds * 1_000 millis += t.nanos / 1_000_000 return new Date(millis) } function fromJsonTimestamp(o: any): Date { if (o instanceof Date) { return o } else if (typeof o === 'string') { return new Date(o) } else { return fromTimestamp(Timestamp.fromJSON(o)) } } function longToNumber(long: Long): number { if (long.gt(Number.MAX_SAFE_INTEGER)) { throw new globalThis.Error('Value is larger than Number.MAX_SAFE_INTEGER') } return long.toNumber() } if (util.Long !== Long) { util.Long = Long as any configure() }
the_stack
import { Utils } from "@arkecosystem/crypto"; import { StandardCriteriaOf, StandardCriteriaOfItem } from "../../contracts/search"; import { injectable } from "../../ioc"; import { InvalidCriteria, UnexpectedError, UnsupportedValue } from "./errors"; @injectable() export class StandardCriteriaService { public testStandardCriterias<T>(value: T, ...criterias: StandardCriteriaOf<T>[]): boolean { return criterias.every((criteria) => { // Criteria is either single criteria item or array of criteria items. if (Array.isArray(criteria)) { // Array of criteria items constitute OR expression. // // Example: // [ // { type: Enums.TransactionType.DelegateRegistration }, // { type: Enums.TransactionType.Vote } // ] // // Alternatively (behaves same as above): // { // type: [ // Enums.TransactionType.DelegateRegistration, // Enums.TransactionType.Vote // ] // } return criteria.some((criteriaItem, i) => { try { return this.testStandardCriteriaItem(value, criteriaItem); } catch (error) { this.rethrowError(error, String(i)); } }); } else { return this.testStandardCriteriaItem(value, criteria); } }); } private testStandardCriteriaItem<T>(value: T, criteriaItem: StandardCriteriaOfItem<T>): boolean { if (typeof value === "undefined" || value === null) { return false; } if (typeof value === "boolean") { // narrowing `value` to `boolean` doesn't narrow `criteriaItem` to `StandardCriteriaOfItem<boolean>` :-( return this.testBooleanValueCriteriaItem(value, criteriaItem as StandardCriteriaOfItem<boolean>); } if (typeof value === "string") { return this.testStringValueCriteriaItem(value, criteriaItem as StandardCriteriaOfItem<string>); } if (typeof value === "number") { return this.testNumberValueCriteriaItem(value, criteriaItem as StandardCriteriaOfItem<number>); } if (typeof value === "bigint" || value instanceof Utils.BigNumber) { return this.testBigNumberValueCriteriaItem( value, criteriaItem as StandardCriteriaOfItem<BigInt | Utils.BigNumber>, ); } if (typeof value === "object" && !Array.isArray(value)) { // doesn't narrow to `object`, nor excluding `symbol` does :-( return this.testObjectValueCriteriaItem(value as any, criteriaItem as StandardCriteriaOfItem<object>); } // The only two other types left are: // `symbol` which is obviously not supported // `array` which is unfortunately not supported. // // Syntax for OR (array of criteria items) creates a conflict when testing array properties. // // Consider hypothetical resource that has array property: // { owners: ["alice", "bob", "charlie"] } // // Criteria that is used: // { owners: ["alice", "charlie"] } // // If it's "alice AND charlie" then how to specify "alice OR charlie"? // If it's "alice OR charlie" then how to specify "alice AND charlie"? // // Peer is the only resource with array property. throw new UnsupportedValue(value, []); } private testBooleanValueCriteriaItem(value: boolean, criteriaItem: StandardCriteriaOfItem<boolean>): boolean { // In most cases criteria is cast to the same type as value during validation (by joi). // Wallet's attributes property is an exception. There is currently now way to know what types may be there. // To test properties within it string values are also checked. // For example boolean `true` value is checked against boolean `true` and string `"true"`. if ([true, false, "true", "false"].includes(criteriaItem) === false) { throw new InvalidCriteria(value, criteriaItem, []); } if (value) { return criteriaItem === true || criteriaItem === "true"; } else { return criteriaItem === false || criteriaItem === "false"; } } private testStringValueCriteriaItem(value: string, criteriaItem: StandardCriteriaOfItem<string>): boolean { if (typeof criteriaItem !== "string") { throw new InvalidCriteria(value, criteriaItem, []); } if (criteriaItem.indexOf("%") === -1) { return criteriaItem === value; } // TODO: handle escape sequences (\%, \\, etc) let nextIndexFrom = 0; for (const part of criteriaItem.split("%")) { const index = value.indexOf(part, nextIndexFrom); if (index === -1) { return false; } nextIndexFrom = index + part.length; } return true; } private testNumberValueCriteriaItem(value: number, criteriaItem: StandardCriteriaOfItem<number>): boolean { if (typeof criteriaItem === "string" || typeof criteriaItem === "number") { if (isNaN(Number(criteriaItem))) { throw new InvalidCriteria(value, criteriaItem, []); } return value === Number(criteriaItem); } if (typeof criteriaItem === "object" && criteriaItem !== null) { if ("from" in criteriaItem) { if (isNaN(Number(criteriaItem["from"]))) { throw new InvalidCriteria(value, criteriaItem.from, ["from"]); } } if ("to" in criteriaItem) { if (isNaN(Number(criteriaItem["to"]))) { throw new InvalidCriteria(value, criteriaItem.to, ["to"]); } } if ("from" in criteriaItem && "to" in criteriaItem) { return value >= Number(criteriaItem["from"]) && value <= Number(criteriaItem["to"]); } if ("from" in criteriaItem) { return value >= Number(criteriaItem["from"]); } if ("to" in criteriaItem) { return value <= Number(criteriaItem["to"]); } } throw new InvalidCriteria(value, criteriaItem, []); } private testBigNumberValueCriteriaItem( value: BigInt | Utils.BigNumber, criteriaItem: StandardCriteriaOfItem<BigInt | Utils.BigNumber>, ): boolean { // Utils.BigNumber.make doesn't perform instanceof check const bnValue = value instanceof Utils.BigNumber ? value : Utils.BigNumber.make(value); if ( typeof criteriaItem === "number" || typeof criteriaItem === "string" || typeof criteriaItem === "bigint" || criteriaItem instanceof Utils.BigNumber ) { try { return bnValue.isEqualTo(criteriaItem); } catch (error) { throw new InvalidCriteria(value, criteriaItem, []); } } /* istanbul ignore else */ if (typeof criteriaItem === "object" && criteriaItem !== null) { try { if ("from" in criteriaItem && "to" in criteriaItem) { return bnValue.isGreaterThanEqual(criteriaItem.from) && bnValue.isLessThanEqual(criteriaItem.to); } if ("from" in criteriaItem) { return bnValue.isGreaterThanEqual(criteriaItem.from); } if ("to" in criteriaItem) { return bnValue.isLessThanEqual(criteriaItem.to); } } catch (error) { if ("from" in criteriaItem) { try { Utils.BigNumber.make(criteriaItem.from); } catch (error) { throw new InvalidCriteria(value, criteriaItem.from, ["from"]); } } /* istanbul ignore else */ if ("to" in criteriaItem) { try { Utils.BigNumber.make(criteriaItem.to); } catch (error) { throw new InvalidCriteria(value, criteriaItem.to, ["to"]); } } // unreachable /* istanbul ignore next */ throw error; } } throw new InvalidCriteria(value, criteriaItem, []); } private testObjectValueCriteriaItem(value: object, criteriaItem: StandardCriteriaOfItem<object>): boolean { const criteriaKeys = Object.keys(criteriaItem); if (criteriaKeys.length === 1 && criteriaKeys[0] === "*") { // Wildcard criteria that checks if any property matches // // Example: // { // attributes: { // htlc: { // locks: { // ["*"]: { // secretHash: "03da05c1c1d4f9c6bda13695b2f29fbc65d9589edc070fc61fe97974be3e59c1" // } // } // } // } // } try { return Object.values(value).some((v) => { return this.testStandardCriterias(v, criteriaItem["*"]); }); } catch (error) { this.rethrowError(error, "*"); } } else { return criteriaKeys.every((key) => { try { return this.testStandardCriterias(value[key], criteriaItem[key]); } catch (error) { this.rethrowError(error, key); } }); } } private rethrowError(error: Error, key: string): never { if (error instanceof InvalidCriteria) { throw new InvalidCriteria(error.value, error.criteria, [key, ...error.path]); } if (error instanceof UnsupportedValue) { throw new UnsupportedValue(error.value, [key, ...error.path]); } if (error instanceof UnexpectedError) { throw new UnexpectedError(error.error, [key, ...error.path]); } throw new UnexpectedError(error, [key]); } }
the_stack
import { observer } from "mobx-react" import React from "react" import { HotTable } from "@handsontable/react" import { action, observable, computed } from "mobx" import { ExplorerProgram, EXPLORER_FILE_SUFFIX, makeFullPath, } from "../explorer/ExplorerProgram" import { GitCmsClient } from "../gitCms/GitCmsClient" import { Prompt } from "react-router-dom" import Handsontable from "handsontable" import { CoreMatrix } from "../coreTable/CoreTableConstants" import { exposeInstanceOnWindow, slugify } from "../clientUtils/Util" import { LoadingIndicator } from "../grapher/loadingIndicator/LoadingIndicator" import { DefaultNewExplorerSlug, ExplorerChoiceParams, EXPLORERS_PREVIEW_ROUTE, UNSAVED_EXPLORER_DRAFT, UNSAVED_EXPLORER_PREVIEW_QUERYPARAMS, } from "../explorer/ExplorerConstants" import { AutofillColDefCommand, InlineDataCommand, SelectAllHitsCommand, } from "./ExplorerCommands" import { isEmpty } from "../gridLang/GrammarUtils" import classNames from "classnames" import { GitCmsFile, GIT_CMS_BASE_ROUTE } from "../gitCms/GitCmsConstants" import { AdminManager } from "./AdminManager" const RESERVED_NAMES = [DefaultNewExplorerSlug, "index", "new", "create"] // don't allow authors to save explorers with these names, otherwise might create some annoying situations. @observer export class ExplorerCreatePage extends React.Component<{ slug: string gitCmsBranchName: string manager?: AdminManager doNotFetch?: boolean // for testing }> { @computed private get manager() { return this.props.manager ?? {} } @action.bound private loadingModalOff() { this.manager.loadingIndicatorSetting = "off" } @action.bound private loadingModalOn() { this.manager.loadingIndicatorSetting = "loading" } @action.bound private resetLoadingModal() { this.manager.loadingIndicatorSetting = "default" } @action componentDidMount() { this.loadingModalOff() exposeInstanceOnWindow(this, "explorerEditor") if (this.props.doNotFetch) return this.fetchExplorerProgramOnLoad() this.startPollingLocalStorageForPreviewChanges() } @action.bound private startPollingLocalStorageForPreviewChanges() { setInterval(() => { const savedQueryParamsJSON = localStorage.getItem( `${UNSAVED_EXPLORER_PREVIEW_QUERYPARAMS}${this.program.slug}` ) if (typeof savedQueryParamsJSON === "string") this.program.decisionMatrix.setValuesFromChoiceParams( JSON.parse(savedQueryParamsJSON) as ExplorerChoiceParams ) }, 1000) } @observable isReady = false @action componentWillUnmount() { this.resetLoadingModal() } private gitCmsClient = new GitCmsClient(GIT_CMS_BASE_ROUTE) @action.bound private async fetchExplorerProgramOnLoad() { const { slug } = this.props const response = await this.gitCmsClient.readRemoteFile({ filepath: makeFullPath(slug), }) this.programOnDisk = new ExplorerProgram("", response.content ?? "") this.setProgram(this.draftIfAny ?? this.programOnDisk.toString()) this.isReady = true if (this.isModified) alert( `Your browser has a changed draft of '${slug}'. If you want to clear your local changes, click the "Clear Changes" button in the top right.` ) } @action.bound private setProgram(code: string) { this.program = new ExplorerProgram(this.program.slug, code) this.saveDraft(code) } private saveDraft(code: string) { localStorage.setItem(UNSAVED_EXPLORER_DRAFT + this.program.slug, code) } get draftIfAny() { return localStorage.getItem(UNSAVED_EXPLORER_DRAFT + this.program.slug) } private clearDraft() { localStorage.removeItem(UNSAVED_EXPLORER_DRAFT + this.program.slug) } @observable.ref private programOnDisk = new ExplorerProgram("", "") @observable.ref private program = new ExplorerProgram(this.props.slug, "") @action.bound private async _save(slug: string, commitMessage: string) { this.loadingModalOn() this.program.slug = slug await this.gitCmsClient.writeRemoteFile({ filepath: this.program.fullPath, content: this.program.toString(), commitMessage, }) this.loadingModalOff() this.programOnDisk = new ExplorerProgram("", this.program.toString()) this.setProgram(this.programOnDisk.toString()) this.clearDraft() } @action.bound private async saveAs() { const userSlug = prompt( `Create a slug (URL friendly name) for this explorer. Your new file will be pushed to the '${this.props.gitCmsBranchName}' branch on GitHub.`, this.program.slug ) if (!userSlug) return const slug = slugify(userSlug) if (!slug) { alert(`'${slug}' is not a valid slug`) return } if (new Set(RESERVED_NAMES).has(slug.toLowerCase())) { alert( `Cannot save '${userSlug}' because that is one of the reserved names: ${RESERVED_NAMES.join( ", " )}` ) return } await this._save(slug, `Saving ${this.program.slug} as ${slug}`) window.location.href = slug } @action.bound private clearChanges() { if (!confirm("Are you sure you want to clear your local changes?")) return this.setProgram(this.programOnDisk.toString()) this.clearDraft() } @action.bound private async save() { const commitMessage = prompt( `Enter a message describing this change. Your change will be pushed to the '${this.props.gitCmsBranchName}' on GitHub.`, `Updated ${this.program.slug}` ) if (!commitMessage) return await this._save(this.program.slug, commitMessage) } @computed get isModified() { return this.programOnDisk.toString() !== this.program.toString() } @observable gitCmsBranchName = this.props.gitCmsBranchName @action.bound private onSave() { if (this.program.isNewFile) this.saveAs() else if (this.isModified) this.save() } render() { if (!this.isReady) return <LoadingIndicator /> const { program, isModified } = this const { isNewFile, slug } = program const previewLink = `/admin/${EXPLORERS_PREVIEW_ROUTE}/${slug}` const buttons = [] buttons.push( <button key="save" disabled={!isModified && !isNewFile} className={classNames("btn", "btn-primary")} onClick={this.onSave} title="Saves file to disk, commits and pushes to GitHub" > Save </button> ) buttons.push( <button key="saveAs" disabled={isNewFile} title={ isNewFile ? "You need to save this file first." : "Saves file to disk, commits and pushes to GitHub" } className={classNames("btn", "btn-secondary")} onClick={this.saveAs} > Save As </button> ) buttons.push( <button key="clear" disabled={!isModified} title={isModified ? "" : "No changes"} className={classNames("btn", "btn-secondary")} onClick={this.clearChanges} > Clear Changes </button> ) const modifiedMessage = isModified ? "Are you sure you want to leave? You have unsaved changes." : "" // todo: provide an explanation of how many cells are modified. return ( <> <Prompt when={isModified} message={modifiedMessage} /> <main style={{ padding: 0, position: "relative", }} > <div className="ExplorerCreatePageHeader"> <div> <TemplatesComponent onChange={this.setProgram} isNewFile={isNewFile} /> </div> <div style={{ textAlign: "right" }}>{buttons}</div> </div> <HotEditor onChange={this.setProgram} program={program} programOnDisk={this.programOnDisk} /> <PictureInPicture previewLink={previewLink} /> <a className="PreviewLink" href={previewLink}> Visit preview </a> </main> </> ) } } class HotEditor extends React.Component<{ onChange: (code: string) => void program: ExplorerProgram programOnDisk: ExplorerProgram }> { private hotTableComponent = React.createRef<HotTable>() @computed private get program() { return this.props.program } @computed private get programOnDisk() { return this.props.programOnDisk } @action.bound private updateProgramFromHot() { const newVersion = this.hotTableComponent.current?.hotInstance.getData() as CoreMatrix if (!newVersion) return const newProgram = ExplorerProgram.fromMatrix( this.program.slug, newVersion ) if (this.program.toString() === newProgram.toString()) return this.props.onChange(newProgram.toString()) } private get hotSettings() { const { program, programOnDisk } = this const data = program.asArrays const { currentlySelectedGrapherRow } = program const cells = function (row: number, column: number) { const { comment, cssClasses, optionKeywords, placeholder, contents, } = program.getCell({ row, column }) const cellContentsOnDisk = programOnDisk.getCellContents({ row, column, }) const cellProperties: Partial<Handsontable.CellProperties> = {} const allClasses = cssClasses?.slice() ?? [] if (cellContentsOnDisk !== contents) { if (contents === "" && cellContentsOnDisk === undefined) allClasses.push("cellCreated") else if (isEmpty(contents)) allClasses.push("cellDeleted") else if (isEmpty(cellContentsOnDisk)) allClasses.push("cellCreated") else allClasses.push("cellChanged") } if (currentlySelectedGrapherRow === row && column) allClasses.push(`currentlySelectedGrapherRow`) cellProperties.className = allClasses.join(" ") cellProperties.comment = comment ? { value: comment } : undefined cellProperties.placeholder = placeholder if (optionKeywords && optionKeywords.length) { cellProperties.type = "autocomplete" cellProperties.source = optionKeywords } return cellProperties } const hotSettings: Handsontable.GridSettings = { afterChange: () => this.updateProgramFromHot(), afterRemoveRow: () => this.updateProgramFromHot(), afterRemoveCol: () => this.updateProgramFromHot(), allowInsertColumn: false, allowInsertRow: true, autoRowSize: false, autoColumnSize: false, cells, colHeaders: true, comments: true, contextMenu: { items: { AutofillColDefCommand: new AutofillColDefCommand( program, (newProgram: string) => this.props.onChange(newProgram) ).toHotCommand(), InlineDataCommand: new InlineDataCommand( program, (newProgram: string) => this.props.onChange(newProgram) ).toHotCommand(), SelectAllHitsCommand: new SelectAllHitsCommand( program ).toHotCommand(), sp0: { name: "---------" }, row_above: {}, row_below: {}, sp1: { name: "---------" }, remove_row: {}, remove_col: {}, sp2: { name: "---------" }, undo: {}, redo: {}, sp3: { name: "---------" }, copy: {}, cut: {}, }, }, data, height: "100%", manualColumnResize: true, manualRowMove: true, minCols: program.width + 3, minSpareCols: 2, minRows: 40, minSpareRows: 20, rowHeaders: true, search: true, stretchH: "all", width: "100%", wordWrap: false, } return hotSettings } render() { return ( <HotTable settings={this.hotSettings} ref={this.hotTableComponent as any} licenseKey={"non-commercial-and-evaluation"} /> ) } } class PictureInPicture extends React.Component<{ previewLink: string }> { render() { return ( <iframe src={this.props.previewLink} className="ExplorerPipPreview" /> ) } } class TemplatesComponent extends React.Component<{ isNewFile: boolean onChange: (code: string) => void }> { @action.bound private loadTemplate(filename: string) { this.props.onChange( this.templates.find((template) => template.filename === filename)! .content ) } @observable.ref templates: GitCmsFile[] = [] componentDidMount() { if (this.props.isNewFile) this.fetchTemplatesOnLoad() } private gitCmsClient = new GitCmsClient(GIT_CMS_BASE_ROUTE) @action.bound private async fetchTemplatesOnLoad() { const response = await this.gitCmsClient.readRemoteFiles({ glob: "*template*", folder: "explorers", }) this.templates = response.files } render() { return this.templates.map((template) => ( <button className={classNames("btn", "btn-primary")} key={template.filename} onClick={() => this.loadTemplate(template.filename)} > {template.filename .replace(EXPLORER_FILE_SUFFIX, "") .replace("-", " ")} </button> )) } }
the_stack
import { generateId } from '@/common/js/util'; import popContainer from '@/components/popContainer'; import { Component, Emit, Prop, Ref, Vue, Watch } from 'vue-property-decorator'; import { VNode } from 'vue/types/umd'; @Component({ components: { popContainer, }, }) export default class ConditionSelector extends Vue { // 条件列表 get conditionList() { return this.constraintList.sort((next, prev) => next.groupType - prev.groupType); } get conditionMap() { const map: any = {}; for (const condition of this.constraintList) { map[condition.constraintId] = condition; if (condition.children) { for (const child of condition.children) { child.parentId = condition.constraintId; map[child.constraintId] = child; } } } return map; } @Prop({ default: () => ({}) }) public constraintContent!: object; @Prop({ default: () => [] }) public constraintList!: any[]; @Prop({ default: false }) public readonly!: boolean; @Prop({ default: 'click' }) public trigger!: string; @Ref() public readonly conditionSelectorForm!: VNode; @Ref() public readonly conditionSelectorInput!: VNode; public selectorBoundary: Element = document.body; public validatorMap = { number: { validator(val: string) { return !isNaN(Number(val)); }, message: this.$t('请输入数字'), trigger: 'blur', }, regex: { validator(val: string) { return /^\/.+\/[gimsuy]*$/.test(val); }, message: this.$t('请输入正确的正则'), trigger: 'blur', }, required: { required: true, message: this.$t('不能为空'), trigger: 'blur', }, }; public conditionData = {}; public sameGroupIds = []; @Emit('change') public handleContentChange(content: object | null) { return content; } @Watch('constraintContent') public handleChange() { this.handleShowCondition(); } public deepClone(obj: any, cache: any[] = []) { if (obj == null || typeof obj !== 'object') { return obj; } const hit = cache.filter(c => c.original === obj)[0]; if (hit) { return hit.copy; } const copy = Array.isArray(obj) ? [] : {}; cache.push({ original: obj, copy, }); Object.keys(obj).forEach(key => { copy[key] = this.deepClone(obj[key], cache); }); return copy; } public getDefaultGroupData() { return { uid: generateId('_group_'), isEmpty: true, op: 'AND', items: [this.getDefaultItemData()], }; } public getDefaultItemData() { return { uid: generateId('_item_'), constraintId: [], constraintContent: '', config: { editable: true, placeholder: '', rules: [], }, }; } public formatData(content: object) { const data = this.deepClone(content); const groups = data.groups || []; for (let index = 0, len = groups.length; index < len; index++) { const group = groups[index]; !group.uid && Object.assign(group, { uid: generateId('_group_') }); const items = []; const conditions = group.items || []; for (let childIndex = 0, childLen = conditions.length; childIndex < childLen; childIndex++) { const item = conditions[childIndex]; !item.uid && Object.assign(item, { uid: generateId('_item_') }); const formatItem = { ...item, constraintId: [item.constraintId], config: { editable: true, placeholder: '', rules: [], }, }; const conditionItem = this.conditionMap[item.constraintId]; if (formatItem && conditionItem) { conditionItem.parentId && formatItem.constraintId.unshift(conditionItem.parentId); const formatCondition = this.formatCondition(formatItem, conditionItem, index, childIndex, false); Object.assign(formatItem, formatCondition); } items.push(formatItem); } group.items = items; } return data; } public formatCondition(data: object, condition: object, index: number, childIndex: number, setValue = true) { data.config.placeholder = condition.constraintValue; data.config.editable = condition.editable; // 同组内条件是否相同判断 data.config.rules = [ { message: this.$t('条件重复'), validator: (value: string) => this.conditionRepeatedValidator(value, index, childIndex), trigger: 'blur', }, ]; if (!condition.editable && setValue) { data.constraintContent = condition.constraintValue; } else if (condition.editable) { data.config.rules.unshift(this.validatorMap.required); if (condition.validator.content && condition.validator.content.regex) { const regex = condition.validator.content.regex; data.config.rules.push({ regex: new RegExp(regex), message: `${this.$t('输入内容不符合正则要求')}: /${regex}/`, trigger: 'blur', }); } else if (condition.validator.type === 'number_validator') { data.config.rules.push(this.validatorMap.number); } else if (condition.validator.type === 'regex_validator') { // 目前根据前后斜杠校验是否为正则,python可不写前后斜杠,所以先不校验 // data.config.rules.push(this.validatorMap['regex']) } } return data; } public conditionRepeatedValidator(value: string, index: number, childIndex: number) { const group = this.conditionData.groups[index]; if (group?.items) { if (group.items.length <= 1) { return true; } const curItem = group.items[childIndex]; for (let i = 0, length = group.items.length; i < length; i++) { if (i === childIndex) { continue; } const item = group.items[i]; // 编辑状态不同则为不同条件 if (item.config.editable !== curItem.config.editable) { continue; } if ( curItem.constraintContent === item.constraintContent && curItem.constraintId.toString() === item.constraintId.toString() ) { return false; } } } return true; } // 校验不同组条件是否完全相同 public diffConditionGroupvalidator() { // 清空报错组 this.sameGroupIds = []; const groups = this.deepClone(this.conditionData.groups); if (groups.length <= 1) { return true; } const sameGroupIds = []; for (let i = 0; i < groups.length; i++) { const curGroup = groups[i]; const curItems = curGroup.items; const curConditionValue = curItems.map(item => `${item.constraintId.toString()}_${item.constraintContent}`); for (let j = groups.length - 1; j > i; j--) { const nextGroup = groups[j]; const nextItems = nextGroup.items; // 组内条件数不同则为不同条件组 if (curItems.length !== nextItems.length || j === i) { continue; } const nextValue = nextItems.map(item => `${item.constraintId.toString()}_${item.constraintContent}`); // 通过去重判断是否为相同条件组 const valuesSet = new Set(curConditionValue.concat(nextValue)); // 去重后的个数和原来个数相同则为相同条件组 if (valuesSet.size === curConditionValue.length) { sameGroupIds.push(...[curGroup.uid, nextGroup.uid]); groups.splice(j, 1); } } } this.sameGroupIds = Array.from(new Set(sameGroupIds)); return !this.sameGroupIds.length; } // 手动触发同组条件校验 public sameGroupConditionValidator(index: number, childIndex: number) { const validateItemPrefix = 'validate_content_' + index; const curItemKey = `validate_content_${index}_${childIndex}`; const validateKeys = Object.keys(this.$refs).filter(key => key.indexOf(validateItemPrefix) === 0); for (const key of validateKeys) { // 避免选择后立即校验为空报错 if (key === curItemKey) { continue; } const item = Array.isArray(this.$refs[key]) ? this.$refs[key][0] : this.$refs[key]; if (item) { item.clearError(); item.validate('blur'); } } } public handleAddGroup() { this.conditionData.groups.push(this.getDefaultGroupData()); } public handleDeleteGroup(index: number) { this.conditionData.groups.splice(index, 1); this.sameGroupIds = []; } public handleAddItem(index: number) { this.conditionData.groups[index].items.push(this.getDefaultItemData()); this.$nextTick(() => { this.sameGroupConditionValidator(index); }); this.sameGroupIds = []; } public handleDeleteItem(index: number, childIndex: number) { this.conditionData.groups[index].items.splice(childIndex, 1); this.$nextTick(() => { this.sameGroupConditionValidator(index); }); this.sameGroupIds = []; } public handleItemBlur(index: number) { this.sameGroupIds = []; this.$nextTick(() => { this.sameGroupConditionValidator(index); }); } public handleClearCurConditionError(index: number, childIndex: number) { const refIds = [`validate_id_${index}_${childIndex}`, `validate_content_${index}_${childIndex}`]; for (const key of refIds) { const item = Array.isArray(this.$refs[key]) ? this.$refs[key][0] : this.$refs[key]; item?.clearError(); } } public handleConditionChange( newValue: any[], oldValue: any[], selectList: any[], index: number, childIndex: number) { const depth = newValue.length; const value = depth > 1 ? newValue[1] : newValue[0]; const selectItem = depth > 1 ? selectList[1] : selectList[0]; const item = this.conditionData.groups[index].items[childIndex]; // 重置内容 item.config.editable = true; item.constraintContent = ''; item.config.placeholder = '请输入'; item.config.rules = []; // 清空当前条件报错 this.handleClearCurConditionError(index, childIndex); if (value && selectItem) { Object.assign(item, this.formatCondition(item, selectItem, index, childIndex)); } this.$nextTick(() => { this.sameGroupConditionValidator(index, childIndex); }); this.sameGroupIds = []; } public handleShowCondition() { // 初始化数据 this.conditionData = this.constraintContent ? this.formatData(this.constraintContent) : { op: 'AND', groups: [this.getDefaultGroupData()], }; } // public handleClear() { // this.conditionData = { // op: 'AND', // groups: [this.getDefaultGroupData()] // } // this.handleContentChange(null) // } public handleChangeItemOp(index: number, op: string) { const item = this.conditionData.groups[index]; if (item) { Object.assign(item, { op: op === 'AND' ? 'OR' : 'AND' }); } } public handleChangeGroupOp(op: string) { this.$set(this.conditionData, 'op', op === 'AND' ? 'OR' : 'AND'); } public handleSubmitCondition() { return this.conditionSelectorForm.validate().then(validate => { if (!this.diffConditionGroupvalidator()) { return Promise.reject(this.$t('条件组重复')); } const data = this.deepClone(this.conditionData); // 处理提交数据 for (const group of data.groups) { delete group.isEmpty; delete group.uid; for (const item of group.items) { delete item.config; delete item.uid; item.constraintId = item.constraintId[item.constraintId.length - 1]; } } this.handleContentChange(data); return data; }); } public mounted() { this.conditionData = this.constraintContent ? this.formatData(this.constraintContent) : { op: 'AND', groups: [this.getDefaultGroupData()], }; } }
the_stack
import React, { useContext } from 'react' import { NativeEventEmitter, DeviceEventEmitter, NativeModules, Platform, } from 'react-native' import { requestLocationPermission } from '../utils/Permission' import { beaconLookup } from './beacon-lookup' import { beaconScanner, bluetoothScanner } from './contact-scanner' const eventEmitter = new NativeEventEmitter(NativeModules.ContactTracerModule) interface ContactTracerProps { anonymousId: string isPassedOnboarding: boolean } interface ContactTracerState { isServiceEnabled: boolean isLocationPermissionGranted: boolean isBluetoothOn: boolean anonymousId: string statusText: string beaconLocationName: any enable: () => void disable: () => void } const Context = React.createContext<ContactTracerState>(null) export class ContactTracerProvider extends React.Component< ContactTracerProps, ContactTracerState > { private isInited = false private statusText = '' private beaconLocationName = {} private advertiserEventSubscription = null private nearbyDeviceFoundEventSubscription = null private nearbyBeaconFoundEventSubscription = null constructor(props) { super(props) this.state = { isServiceEnabled: false, isLocationPermissionGranted: false, isBluetoothOn: false, anonymousId: '', statusText: this.statusText, beaconLocationName: this.beaconLocationName, enable: this.enable.bind(this), disable: this.disable.bind(this), } } componentDidMount() { this.registerListeners() NativeModules.ContactTracerModule.stopTracerService() if (this.props.isPassedOnboarding) { // Check if Tracer Service has been enabled NativeModules.ContactTracerModule.isTracerServiceEnabled() .then((enabled) => { this.setState({ isServiceEnabled: enabled, }) // Refresh Tracer Service Status in case the service is down if (enabled) return this.enable() return '' }) .then(() => {}) } } componentWillUnmount() { this.unregisterListeneres() } /** * Initialize Contact Tracer instance */ async init() { this.isInited = true const anonymousId = this.props.anonymousId this.setState({ anonymousId: anonymousId }) NativeModules.ContactTracerModule.setUserId( anonymousId, ).then((anonymousId) => {}) // Check if Tracer Service has been enabled NativeModules.ContactTracerModule.isTracerServiceEnabled() .then((enabled) => { this.setState({ isServiceEnabled: enabled, }) // Refresh Tracer Service Status in case the service is down NativeModules.ContactTracerModule.refreshTracerServiceStatus() }) .then(() => {}) // Check if BLE is available await NativeModules.ContactTracerModule.initialize() .then((result) => { return NativeModules.ContactTracerModule.isBLEAvailable() }) // For NativeModules.ContactTracerModule.isBLEAvailable() .then((isBLEAvailable) => { if (isBLEAvailable) { this.appendStatusText('BLE is available') // BLE is available, continue requesting Location Permission return requestLocationPermission() } else { // BLE is not available, don't do anything furthur since BLE is required this.appendStatusText('BLE is NOT available') } }) // For requestLocationPermission() .then((locationPermissionGranted) => { this.setState({ isLocationPermissionGranted: locationPermissionGranted, }) if (locationPermissionGranted) { // Location permission is granted, try turning on Bluetooth now this.appendStatusText('Location permission is granted') return NativeModules.ContactTracerModule.tryToTurnBluetoothOn() } else { // Location permission is required, we cannot continue working without this permission this.appendStatusText('Location permission is NOT granted') } }) // For NativeModules.ContactTracerModule.tryToTurnBluetoothOn() .then((bluetoothOn) => { this.setState({ isBluetoothOn: bluetoothOn, }) if (bluetoothOn) { this.appendStatusText('Bluetooth is On') // See if Multiple Advertisement is supported // Refresh Tracer Service Status in case the service is down NativeModules.ContactTracerModule.refreshTracerServiceStatus() return NativeModules.ContactTracerModule.isMultipleAdvertisementSupported() } else { this.appendStatusText('Bluetooth is Off') } }) // For NativeModules.ContactTracerModule.isMultipleAdvertisementSupported() .then((supported) => { if (supported) this.appendStatusText('Multitple Advertisement is supported') else this.appendStatusText('Multitple Advertisement is NOT supported') }) console.log('init complete') } /** * Enable Contact Tracer service * * Could be call only once and it will remember its state in persistant storage */ async enable() { console.log('enable tracing') if (!this.isInited) { await this.init() } NativeModules.ContactTracerModule.enableTracerService().then(() => {}) this.setState({ isServiceEnabled: true, }) } /** * Disable Contact Tracer service * * Could be call only once and it will remember its state in persistant storage */ disable() { console.log('disable tracing') NativeModules.ContactTracerModule.disableTracerService() this.setState({ isServiceEnabled: false, }) } /** * Read Contact Tracer service latest state * * Read state, set isServiceEnabled and call enable() to init */ refreshTracerService() { NativeModules.ContactTracerModule.isTracerServiceEnabled() .then((enabled) => { this.setState({ isServiceEnabled: enabled, }) // Refresh Tracer Service Status in case the service is down if (enabled) return this.enable() else return '' }) .then(() => {}) } /** * Initialize Listeners */ registerListeners() { // Register Event Emitter if (Platform.OS == 'ios') { console.log('add listener') this.advertiserEventSubscription = eventEmitter.addListener( 'AdvertiserMessage', this.onAdvertiserMessageReceived, ) this.nearbyDeviceFoundEventSubscription = eventEmitter.addListener( 'NearbyDeviceFound', this.onNearbyDeviceFoundReceived, ) this.nearbyBeaconFoundEventSubscription = eventEmitter.addListener( 'NearbyBeaconFound', this.onNearbyBeaconFoundReceived, ) } else { console.log('add listener') this.advertiserEventSubscription = DeviceEventEmitter.addListener( 'AdvertiserMessage', this.onAdvertiserMessageReceived, ) this.nearbyDeviceFoundEventSubscription = DeviceEventEmitter.addListener( 'NearbyDeviceFound', this.onNearbyDeviceFoundReceived, ) this.nearbyBeaconFoundEventSubscription = DeviceEventEmitter.addListener( 'NearbyBeaconFound', this.onNearbyBeaconFoundReceived, ) } } /** * Destroy Listeners */ unregisterListeneres() { // Unregister Event Emitter if (this.advertiserEventSubscription != null) { this.advertiserEventSubscription.remove() this.advertiserEventSubscription = null } if (this.nearbyDeviceFoundEventSubscription != null) { this.nearbyDeviceFoundEventSubscription.remove() this.nearbyDeviceFoundEventSubscription = null } if (this.nearbyBeaconFoundEventSubscription != null) { this.nearbyBeaconFoundEventSubscription.remove() this.nearbyBeaconFoundEventSubscription = null } } /** * Append debug text * * @param text Message to be appended */ appendStatusText(text) { console.log('tracing status', text) this.statusText = text + '\n' + this.statusText this.setState({ statusText: this.statusText, }) } /** * Event Emitting Handler */ onAdvertiserMessageReceived = (e) => { this.appendStatusText(e['message']) } onNearbyDeviceFoundReceived = (e) => { this.appendStatusText('') this.appendStatusText('***** RSSI: ' + e['rssi']) this.appendStatusText('***** Found Nearby Device: ' + e['name']) this.appendStatusText('') /* broadcast */ console.log('broadcast:' + e['name']) bluetoothScanner.add(e['name']) if (Date.now() - bluetoothScanner.oldestItemTS > 30 * 60 * 1000) { bluetoothScanner.upload() } } onNearbyBeaconFoundReceived = async (e: any) => { this.appendStatusText('') this.appendStatusText('***** Found Beacon: ' + e['uuid']) this.appendStatusText('***** major: ' + e['major']) this.appendStatusText('***** minor: ' + e['minor']) this.appendStatusText('') let oldestBeaconFoundTS = beaconScanner.oldestBeaconFoundTS || 0; if ((Date.now() - oldestBeaconFoundTS) > (30 * 1000) || !oldestBeaconFoundTS) { const { anonymousId, name } = await beaconLookup.getBeaconInfo(e.uuid, e.major, e.minor) if (anonymousId) { this.appendStatusText('***** anonymousId: ' + anonymousId) this.appendStatusText('***** name: ' + name) this.setState({ beaconLocationName: { anonymousId, name, time: Date.now(), uuid: e.uuid } }) beaconScanner.maskBeaconFound() beaconScanner.add(anonymousId) } } let oldestItemTS = beaconScanner.oldestItemTS || 0; if (Date.now() - oldestItemTS > 30 * 60 * 1000) { beaconScanner.upload() } } render() { return ( <Context.Provider value={this.state}> {this.props.children} </Context.Provider> ) } } export const useContactTracer = (): ContactTracerState => { return useContext(Context) }
the_stack
import { SetParser } from '@/parsers/SetParser'; import { Objects } from '@/lib/Objects'; import { Arrays } from '@/lib/Arrays'; import { Value } from '@/lib/Value'; import { ArrayUIDescriptor } from '@/descriptors/ArrayUIDescriptor'; import { ArrayField, ParserOptions, FieldKind, ArrayItemField, UnknowParser, ArrayDescriptor } from '../../types'; import { JsonSchema } from '../../types/jsonschema'; import { Parser } from './Parser'; export class ArrayParser extends SetParser<any, ArrayField, ArrayDescriptor, ArrayUIDescriptor> { readonly items: JsonSchema[] = []; additionalItems?: JsonSchema; max = -1; count = 0; radioIndex = 0; childrenParsers: UnknowParser[] = []; constructor(options: ParserOptions<any, ArrayField, ArrayDescriptor>, parent?: UnknowParser) { super('array', options, parent); } get initialValue(): unknown[] { const value = this.options.model || this.schema.default; return value instanceof Array ? [ ...value ] : []; } get limit(): number { if (this.field.uniqueItems || this.items.length === 0) { return this.items.length; } if (this.count < this.field.minItems || !Array.isArray(this.schema.items)) { return this.count; } return this.count < this.items.length ? this.count : this.items.length; } get children(): ArrayItemField[] { const limit = this.limit; const fields = Array(...Array(limit)) .map((x, index) => this.getFieldIndex(index)) .filter((field) => field !== null) as ArrayItemField[]; if (limit < this.count && this.additionalItems) { let index = limit; do { const additionalField = this.getFieldItem(this.additionalItems, index); if (additionalField === null) { break; } fields.push(additionalField); } while (++index < this.count); } return fields; } setFieldValue(field: ArrayItemField, value: unknown): void { // since it's possible to order children fields, the // current field's index must be computed each time // TODO: an improvement can be done by using a caching index table const index = this.childrenParsers.findIndex((parser) => parser.field === field); this.setIndexValue(index, value); } setIndexValue(index: number, value: unknown): void { this.rawValue[index] = value; this.setValue(this.rawValue); } isEmpty(data: unknown = this.model): boolean { return data instanceof Array && data.length === 0; } clearModel(): void { for (let i = 0; i < this.rawValue.length; i++) { this.rawValue[i] = undefined; } this.model.splice(0); } setValue(value: unknown[]): void { this.rawValue = value as any; this.model.splice(0); this.model.push(...this.parseValue(this.rawValue) as any); } reset(): void { this.clearModel(); this.initialValue.forEach((value, index) => this.setIndexValue(index, value)); this.childrenParsers.forEach((parser) => parser.reset()); } clear(): void { this.clearModel(); this.childrenParsers.forEach((parser) => parser.clear()); } getFieldItemName(name: string, index: number): string { return this.root.options.bracketedObjectInputName ? `${name}[${index}]` : name; } getFieldItem(itemSchema: JsonSchema, index: number): ArrayItemField | null { const kind: FieldKind | undefined = this.field.uniqueItems ? 'boolean' : SetParser.kind(itemSchema); const itemModel = typeof this.model[index] === 'undefined' ? itemSchema.default : this.model[index]; const itemDescriptor = this.options.descriptor && this.options.descriptor.items ? this.options.descriptor.items instanceof Array ? this.options.descriptor.items[index] : this.options.descriptor.items : { kind }; const itemName = this.options.name || itemModel; const name = kind === 'enum' && this.radioIndex++ ? `${itemName}-${this.radioIndex}` : itemName; const itemParser = SetParser.get({ kind: kind, schema: itemSchema, model: itemModel, id: `${this.id}-${index}`, name: this.getFieldItemName(name, index), descriptor: itemDescriptor, components: this.root.options.components }, this); if (this.rawValue.length <= index) { this.rawValue.push(undefined); } if (itemParser) { this.childrenParsers.push(itemParser); if (kind === 'boolean') { this.parseCheckboxField(itemParser as Parser<any, any, any, any>, itemModel); } // update the index raw value this.rawValue[index] = itemParser.model; // set the onChange option after the parser initialization // to prevent first field value emit itemParser.options.onChange = this.field.sortable ? (value) => { this.setFieldValue(itemParser.field, value); this.commit(); } : (value) => { this.setIndexValue(index, value); this.commit(); }; return itemParser.field; } return null; } getFieldIndex(index: number): ArrayItemField | null { const itemSchema = this.schema.items instanceof Array || this.field.uniqueItems ? this.items[index] : this.items[0]; return this.getFieldItem(itemSchema, index); } move(from: number, to: number): ArrayItemField | undefined { const items = this.field.children; if (items[from] && items[to]) { const movedField = Arrays.swap<ArrayItemField>(items, from, to); Arrays.swap(this.rawValue, from, to); this.field.setValue(this.rawValue); this.parse(); return movedField; } return undefined; } isDisabled([ from, to ]: [ number, number ]): boolean { return !this.field.sortable || !this.field.children[from] || !this.field.children[to]; } upIndexes(itemField: ArrayItemField): [ number, number ] { const from = Arrays.index(this.field.children, itemField); const to = from - 1; return [ from, to ]; } downIndexes(itemField: ArrayItemField): [ number, number ] { const from = Arrays.index(this.field.children, itemField); const to = from + 1; return [ from, to ]; } setButtons(itemField: ArrayItemField): void { itemField.buttons = { moveUp: { disabled: this.isDisabled(this.upIndexes(itemField)), trigger: () => this.move(...this.upIndexes(itemField)) }, moveDown: { disabled: this.isDisabled(this.downIndexes(itemField)), trigger: () => this.move(...this.downIndexes(itemField)) }, delete: { disabled: !this.field.sortable, trigger: () => { const index = Arrays.index(this.field.children, itemField); const deletedField = this.field.children.splice(index, 1).pop(); if (deletedField) { this.rawValue.splice(index, 1); this.field.setValue(this.rawValue); this.count--; this.requestRender(); } return deletedField; } } }; } setCount(value: number): boolean { if (this.schema.maxItems && value > this.field.maxItems) { return false; } this.count = value; this.radioIndex = 0; this.childrenParsers.splice(0); this.field.fields = {}; this.field.children = this.children; this.field.children.forEach((item, i) => { this.field.fields[i] = item; }); // apply array's model this.setValue(this.rawValue); this.field.children.forEach((itemField) => this.setButtons(itemField)); return true; } parseField(): void { this.field.sortable = false; this.field.minItems = this.schema.minItems || (this.field.required ? 1 : 0); this.field.maxItems = typeof this.schema.maxItems === 'number' && this.schema.maxItems > 0 ? this.schema.maxItems : Number.MAX_SAFE_INTEGER; if (this.schema.items) { if (this.schema.items instanceof Array) { this.items.push(...this.schema.items); if (this.schema.additionalItems && !Objects.isEmpty(this.schema.additionalItems)) { this.additionalItems = this.schema.additionalItems; } } else { this.items.push(this.schema.items); this.field.sortable = true; } } const self = this; const resetField = this.field.reset; this.field.pushButton = { get disabled() { return self.count === self.max || self.items.length === 0; }, trigger: () => this.setCount(this.count + 1) && this.requestRender() }; this.count = this.field.minItems > this.model.length ? this.field.minItems : this.model.length; // force render update for ArrayField this.field.addItemValue = (itemValue: any) => { if (this.field.pushButton.disabled) { return false; } this.rawValue.push(itemValue); this.setValue(this.rawValue); this.field.pushButton.trigger(); return true; }; // force render update for ArrayField this.field.reset = () => { resetField.call(this.field); this.requestRender(); }; this.parseUniqueItems(); this.setCount(this.count); } parseCheckboxField(parser: Parser<any, any, any, any>, itemModel: unknown): void { const isChecked = this.initialValue.includes(itemModel); parser.field.attrs.type = 'checkbox'; parser.setValue = (checked: boolean) => { parser.rawValue = checked; parser.model = checked ? itemModel : undefined; }; parser.setValue(isChecked); } parseUniqueItems(): void { if (this.schema.uniqueItems === true && this.items.length === 1) { const itemSchema = this.items[0]; if (itemSchema.enum instanceof Array) { this.field.uniqueItems = true; this.field.maxItems = itemSchema.enum.length; this.count = this.field.maxItems; this.items.splice(0); itemSchema.enum.forEach((value) => this.items.push({ ...itemSchema, enum: undefined, default: value, title: `${value}` })); this.max = this.items.length; } else { this.max = this.schema.maxItems || this.items.length; } } else if (this.schema.maxItems) { this.max = this.field.maxItems; } else if (this.schema.items instanceof Array) { this.max = this.additionalItems ? -1 : this.items.length; } else { this.max = -2; } if (this.field.uniqueItems) { const values: unknown[] = []; this.items.forEach((itemSchema) => { if (this.model.includes(itemSchema.default)) { values.push(itemSchema.default); } else { values.push(undefined); } }); this.model.splice(0); this.model.push(...values); } } parseValue(data: unknown[]): unknown[] { return Value.array(data); } } SetParser.register('array', ArrayParser);
the_stack
import * as utils from '../util/utils' import { EVENT, RECORD_ACTION, RecordMessage, TOPIC, RecordData, RecordPathData, ListenMessage, Message } from '../constants' import { Services } from '../deepstream-client' import { Options } from '../client-options' import { RecordCore, WriteAckCallback } from './record-core' import { Record } from './record' import { AnonymousRecord } from './anonymous-record' import { List } from './list' import { Listener, ListenCallback } from '../util/listener' import { SingleNotifier } from './single-notifier' import { WriteAcknowledgementService } from './write-ack-service' import { DirtyService } from './dirty-service' import { MergeStrategyService } from './merge-strategy-service' import { MergeStrategy } from './merge-strategy' import {BulkSubscriptionService} from '../util/bulk-subscription-service' // type SubscribeActions = RECORD_ACTION.SUBSCRIBEANDHEAD | RECORD_ACTION.SUBSCRIBECREATEANDREAD export interface RecordServices { bulkSubscriptionService: { [index: number]: BulkSubscriptionService<RECORD_ACTION> } writeAckService: WriteAcknowledgementService readRegistry: SingleNotifier<RecordMessage>, headRegistry: SingleNotifier<RecordMessage>, dirtyService: DirtyService, mergeStrategy: MergeStrategyService } export class RecordHandler { private recordCores = new Map<string, RecordCore>() private notifyCallbacks = new Map<string, Function>() private recordServices: RecordServices private dirtyService: DirtyService constructor (private services: Services, private options: Options, recordServices?: RecordServices, private listener: Listener = new Listener(TOPIC.RECORD, services)) { this.recordServices = recordServices || { bulkSubscriptionService: { [RECORD_ACTION.SUBSCRIBECREATEANDREAD]: this.getBulkSubscriptionService(RECORD_ACTION.SUBSCRIBECREATEANDREAD), [RECORD_ACTION.SUBSCRIBEANDREAD]: this.getBulkSubscriptionService(RECORD_ACTION.SUBSCRIBEANDREAD), [RECORD_ACTION.SUBSCRIBEANDHEAD]: this.getBulkSubscriptionService(RECORD_ACTION.SUBSCRIBEANDHEAD) }, writeAckService: new WriteAcknowledgementService(services), readRegistry: new SingleNotifier(services, RECORD_ACTION.READ, options.recordReadTimeout), headRegistry: new SingleNotifier(services, RECORD_ACTION.HEAD, options.recordReadTimeout), dirtyService: new DirtyService(services.storage, options.dirtyStorageName), mergeStrategy: new MergeStrategyService(services, options.mergeStrategy) } as RecordServices this.dirtyService = this.recordServices.dirtyService this.sendUpdatedData = this.sendUpdatedData.bind(this) this.onMergeCompleted = this.onMergeCompleted.bind(this) this.getRecordCore = this.getRecordCore.bind(this) this.removeRecord = this.removeRecord.bind(this) this.onBulkSubscriptionSent = this.onBulkSubscriptionSent.bind(this) this.services.connection.registerHandler(TOPIC.RECORD, this.handle.bind(this)) this.services.connection.onReestablished(this.syncDirtyRecords.bind(this)) if (this.services.connection.isConnected) { this.syncDirtyRecords() } } /** * Returns all the available data-sync names. * * Please note: Lists, AnonymousRecords and Records are all essentially * the same thing within the SDK, so this array will contain a list of * everything. * * Due to how records work as well even after a discard this list will * take a while to update. This is intentional as their is an option for * how long a record will survive before being discarded! You can change that * via the `recordDiscardTimeout: milliseconds` option. */ public names (): string[] { return [...this.recordCores.keys()] } public setMergeStrategy (recordName: string, mergeStrategy: MergeStrategy): void { if (typeof mergeStrategy === 'function') { this.recordServices.mergeStrategy.setMergeStrategyByName(recordName, mergeStrategy) } else { throw new Error('Invalid merge strategy: Must be a Function') } } public setMergeStrategyRegExp (regexp: RegExp, mergeStrategy: MergeStrategy): void { if (typeof mergeStrategy === 'function') { this.recordServices.mergeStrategy.setMergeStrategyByPattern(regexp, mergeStrategy) } else { throw new Error('Invalid merge strategy: Must be a Function') } } /** * Returns an existing record or creates a new one. * * @param {String} name the unique name of the record */ public getRecord (name: string): Record { return new Record(this.getRecordCore(name)) } /** * Returns an existing List or creates a new one. A list is a specialised * type of record that holds an array of recordNames. * * @param {String} name the unique name of the list */ public getList (name: string): List { return new List(this.getRecordCore(name)) } /** * Returns an anonymous record. A anonymous record is effectively * a wrapper that mimicks the API of a record, but allows for the * underlying record to be swapped without loosing subscriptions etc. * * This is particularly useful when selecting from a number of similarly * structured records. E.g. a list of users that can be choosen from a list * * The only API difference to a normal record is an additional setName( name ) method. */ public getAnonymousRecord (): AnonymousRecord { return new AnonymousRecord(this.getRecordCore) } /** * Allows to listen for record subscriptions made by this or other clients. This * is useful to create "active" data providers, e.g. providers that only provide * data for a particular record if a user is actually interested in it * * @param {String} pattern A combination of alpha numeric characters and wildcards( * ) * @param {Function} callback */ public listen (pattern: string, callback: ListenCallback): void { this.listener.listen(pattern, callback) } /** * Removes a listener that was previously registered with listenForSubscriptions * * @param {String} pattern A combination of alpha numeric characters and wildcards( * ) */ public unlisten (pattern: string): void { this.listener.unlisten(pattern) } /** * Retrieve the current record data without subscribing to changes * * @param {String} name the unique name of the record * @param {Function} callback */ public snapshot (name: string): Promise<RecordData> public snapshot (name: string, callback: (error: string | null, data: RecordData) => void): void public snapshot (name: string, callback?: (error: string | null, data: RecordData) => void): void | Promise<RecordData> { if (typeof name !== 'string' || name.length === 0) { throw new Error('invalid argument: name') } if (callback !== undefined && typeof callback !== 'function') { throw new Error('invalid argument: callback') } const recordCore = this.recordCores.get(name) if (recordCore) { if (callback) { recordCore.whenReady(null, () => { callback(null, recordCore.get()) }) } else { return new Promise((resolve, reject) => { recordCore.whenReady(null, () => { resolve(recordCore.get()) }) }) } return } if (callback) { this.recordServices.readRegistry.request(name, callback) } else { return new Promise((resolve, reject) => { this.recordServices.readRegistry.request(name, (error, data) => error ? reject(error) : resolve(data)) }) } } /** * Allows the user to query to see whether or not the record exists. * * @param {String} name the unique name of the record * @param {Function} callback */ public has (name: string): Promise<boolean> public has (name: string, callback: (error: string | null, has: boolean | null) => void): void public has (name: string, callback?: (error: string | null, has: boolean | null) => void): Promise<boolean> | void { if (typeof name !== 'string' || name.length === 0) { throw new Error('invalid argument: name') } if (callback !== undefined && typeof callback !== 'function') { throw new Error('invalid argument: callback') } let cb if (!callback) { return new Promise ((resolve, reject) => { cb = (error: string | null, version: number) => error ? reject(error) : resolve(version !== -1) this.head(name, cb) }) } cb = (error: string | null, version: number) => error ? callback(error, null) : callback(null, version !== -1) this.head(name, cb) } /** * Allows the user to query for the version number of a record. * * @param {String} name the unique name of the record * @param {Function} callback */ public head (name: string): Promise<number> public head (name: string, callback: (error: string | null, version: number) => void): void public head (name: string, callback?: (error: string | null, version: number) => void): void | Promise<number> { if (typeof name !== 'string' || name.length === 0) { throw new Error('invalid argument: name') } if (callback !== undefined && typeof callback !== 'function') { throw new Error('invalid argument: callback') } const recordCore = this.recordCores.get(name) if (recordCore) { if (callback) { recordCore.whenReady(null, () => { callback(null, recordCore.version as number) }) } else { return new Promise((resolve, reject) => { recordCore.whenReady(null, () => { resolve(recordCore.version as number) }) }) } return } if (callback) { this.recordServices.headRegistry.request(name, callback) } else { return new Promise((resolve, reject) => { this.recordServices.headRegistry.request(name, (error, data) => error ? reject(error) : resolve(data)) }) } } /** * A wrapper function around setData. The function works exactly * the same however when a callback is omitted a Promise will be * returned. * * @param {String} recordName the name of the record to set * @param {String|Object} pathOrData the path to set or the data to write * @param {Object|Function} dataOrCallback the data to write or the write acknowledgement * callback * @param {Function} callback the callback that will be called with the result * of the write * @returns {Promise} if a callback is omitted a Promise will be returned that resolves * with the result of the write */ public setDataWithAck (recordName: string, data: RecordData | undefined, callback?: WriteAckCallback): Promise<string | void> | void public setDataWithAck (recordName: string, path: string, data: RecordData | undefined, callback?: WriteAckCallback): Promise<string | void> | void public setDataWithAck (recordName: string, ...rest: any[]): Promise<string | void> | void { const args = utils.normalizeSetArguments(arguments, 1) if (!args.callback) { return new Promise((resolve, reject) => { args.callback = error => error === null ? resolve() : reject(error) this.sendSetData(recordName, -1, args) }) } this.sendSetData(recordName, -1, args) } /** * Allows setting the data for a record without being subscribed to it. If * the client is subscribed to the record locally, the update will be proxied * through the record object like a normal call to Record.set. Otherwise a force * write will be performed that overwrites any remote data. * * @param {String} recordName the name of the record to write to * @param {String|Object} pathOrData either the path to write data to or the data to * set the record to * @param {Object|Primitive|Function} dataOrCallback either the data to write to the * record or a callback function * indicating write success * @param {Function} callback if provided this will be called with the result of the * write */ public setData (recordName: string, data: RecordData): void public setData (recordName: string, path: string, data: RecordPathData | undefined, callback: WriteAckCallback): void public setData (recordName: string, pathOrData: string | RecordData, dataOrCallback: RecordPathData | WriteAckCallback | undefined, callback?: WriteAckCallback): void public setData (recordName: string): void { const args = utils.normalizeSetArguments(arguments, 1) this.sendSetData(recordName, -1, args) } public delete (recordName: string, callback?: (error: string | null) => void): void | Promise<void> { // TODO: Use a delete service to make the logic in record core and here common throw Error('Delete is not yet supported without use of a Record') } public notify (recordNames: string[], callback?: (error: string) => void): void | Promise<void> { if (!this.services.connection.isConnected) { if (callback) { callback(EVENT.CLIENT_OFFLINE) return } return new Promise((resolve, reject) => reject(EVENT.CLIENT_OFFLINE)) } const correlationId = utils.getUid() this.services.connection.sendMessage({ topic: TOPIC.RECORD, action: RECORD_ACTION.NOTIFY, names: recordNames, correlationId }) if (callback) { this.notifyCallbacks.set(correlationId, callback) } else { return new Promise((resolve, reject) => { this.notifyCallbacks.set(correlationId, (error: string) => error ? reject(error) : resolve()) }) } } private sendSetData (recordName: string, version: number, args: utils.RecordSetArguments): void { const { path, data, callback } = args if (!recordName || typeof recordName !== 'string' || recordName.length === 0) { throw new Error('invalid argument: recordName must be an non empty string') } if (!path && (data === null || typeof data !== 'object')) { throw new Error('invalid argument: data must be an object when no path is provided') } const recordCores = this.recordCores.get(recordName) if (recordCores) { recordCores.set({ path, data, callback }) return } let action if (path) { if (data === undefined) { action = RECORD_ACTION.ERASE } else { action = RECORD_ACTION.CREATEANDPATCH } } else { action = RECORD_ACTION.CREATEANDUPDATE } const message = { topic: TOPIC.RECORD, action, name: recordName, path, version, parsedData: data } if (callback) { this.recordServices.writeAckService.send(message, callback) } else { this.services.connection.sendMessage(message) } } public saveToOfflineStorage () { this.recordCores.forEach(recordCore => recordCore.saveRecordToOffline()) } public clearOfflineStorage (): Promise<void> public clearOfflineStorage (callback: (error: string | null) => void): void public clearOfflineStorage (callback?: (error: string | null) => void): Promise<void> | void { if (callback) { this.services.storage.reset(callback) } else { return new Promise((resolve, reject) => { this.services.storage.reset(error => error ? reject(error) : resolve()) }) } } /** * Will be called by the client for incoming messages on the RECORD topic * * @param {Object} message parsed and validated deepstream message */ private handle (message: RecordMessage) { if ( (message.action === RECORD_ACTION.NOTIFY && message.isAck) || (message.isError && message.action === RECORD_ACTION.RECORD_NOTIFY_ERROR) ) { const callback = this.notifyCallbacks.get(message.correlationId!) if (callback) { callback(message.data || null) this.notifyCallbacks.delete(message.correlationId!) } else { this.services.logger.error(message, RECORD_ACTION.NOTIFY) } return } if (message.isAck) { this.services.timeoutRegistry.remove(message) return } if ( message.action === RECORD_ACTION.SUBSCRIPTION_FOR_PATTERN_FOUND || message.action === RECORD_ACTION.SUBSCRIPTION_FOR_PATTERN_REMOVED || message.action === RECORD_ACTION.LISTEN || message.action === RECORD_ACTION.UNLISTEN ) { this.listener.handle(message as ListenMessage) return } if (message.isWriteAck && message.action !== RECORD_ACTION.VERSION_EXISTS) { this.recordServices.writeAckService.recieve(message) return } if (message.action === RECORD_ACTION.READ_RESPONSE || message.originalAction === RECORD_ACTION.READ) { if (message.isError) { this.recordServices.readRegistry.recieve(message, RECORD_ACTION[message.action]) } else { this.recordServices.readRegistry.recieve(message, null, message.parsedData) } return } if ( message.action === RECORD_ACTION.HEAD_RESPONSE_BULK ) { Object.keys(message.versions!).forEach(name => { this.recordServices.headRegistry.recieve({ topic: TOPIC.RECORD, action: RECORD_ACTION.HEAD_RESPONSE, originalAction: RECORD_ACTION.HEAD, name, version: message.versions![name] }, null, message.versions![name]) }) } if ( message.action === RECORD_ACTION.HEAD_RESPONSE || message.originalAction === RECORD_ACTION.HEAD ) { if (message.isError) { this.recordServices.headRegistry.recieve(message, RECORD_ACTION[message.action]) } else { this.recordServices.headRegistry.recieve(message, null, message.version) } } const recordCore = this.recordCores.get(message.name) if (recordCore) { recordCore.handle(message) return } if ( message.action === RECORD_ACTION.VERSION_EXISTS ) { return } if ( message.action === RECORD_ACTION.SUBSCRIPTION_HAS_PROVIDER || message.action === RECORD_ACTION.SUBSCRIPTION_HAS_NO_PROVIDER ) { // record can receive a HAS_PROVIDER after discarding the record return } if (message.isError) { this.services.logger.error(message) return } this.services.logger.error(message, EVENT.UNSOLICITED_MESSAGE) } /** * Callback for 'deleted' and 'discard' events from a record. Removes the record from * the registry */ private removeRecord (recordName: string) { this.recordCores.delete(recordName) } private getRecordCore (recordName: string): RecordCore<any> { let recordCore = this.recordCores.get(recordName) if (!recordCore) { recordCore = new RecordCore(recordName, this.services, this.options, this.recordServices, this.removeRecord) this.recordCores.set(recordName, recordCore) } return recordCore } private syncDirtyRecords () { this.dirtyService.whenLoaded(this, this._syncDirtyRecords) } // TODO: Expose issues here, as there isn't a reason why a record core needs to exist in // order to sync up private _syncDirtyRecords () { const dirtyRecords = this.dirtyService.getAll() for (const [recordName] of dirtyRecords) { const recordCore = this.recordCores.get(recordName) if (recordCore && recordCore.references.size > 0) { // if it isn't zero the record core takes care of it continue } this.services.storage.get(recordName, this.sendUpdatedData) } } private sendUpdatedData (recordName: string, version: number, data: RecordData) { if (version === -1) { // deleted locally, how to merge? this.services.logger.warn({ topic: TOPIC.RECORD }, RECORD_ACTION.DELETE, "Deleted record while offline, can't resolve") return } const callback = (error: string | null, name: string) => { if (!error) { this.dirtyService.setDirty(name, false) } else { this.recordServices.readRegistry.register(name, this, message => { this.recordServices.mergeStrategy.merge( message, version, data, this.onMergeCompleted, this ) }) } } this.sendSetData(recordName, version, { data, callback }) } private onMergeCompleted (error: string | null, { name, version }: RecordMessage, mergeData: RecordData) { this.sendSetData(name, version! + 1, { data: mergeData }) } private getBulkSubscriptionService (bulkSubscribe: RECORD_ACTION) { return new BulkSubscriptionService<RECORD_ACTION>( this.services, this.options.subscriptionInterval, TOPIC.RECORD, bulkSubscribe, RECORD_ACTION.UNSUBSCRIBE, this.onBulkSubscriptionSent ) } private onBulkSubscriptionSent (message: Message) { if (!message.names) { this.services.timeoutRegistry.add({ message }) } } }
the_stack
export const CoNET_version = '3.2.0' import * as Fs from 'fs' import * as Path from 'path' import * as Os from 'os' import * as Async from 'async' import * as Crypto from 'crypto' import * as OpenPgp from 'openpgp' import * as Util from 'util' import * as Http from 'http' import * as Https from 'https' import * as Net from 'net' import * as Nodemailer from 'nodemailer' import * as Url from 'url' import { StringDecoder } from 'string_decoder' import { DH_CHECK_P_NOT_SAFE_PRIME } from 'constants'; /** * define */ const InitKeyPair = () => { const keyPair: keypair = { publicKey: null, privateKey: null, keyLength: null, nikeName: null, createDate: null, email: null, passwordOK: false, verified: false, publicKeyID: null, _password: null } return keyPair } export const checkUrl = ( url ) => { const urlCheck = Url.parse ( url ) const ret = /^http:|^https:$/.test ( urlCheck.protocol ) && ! /^localhost|^127.0.0.1/. test ( urlCheck.hostname ) if ( ret ) { return true } return false } export const QTGateFolder = Path.join ( !/^android$/i.test ( process.platform ) ? Os.homedir() : Path.join( __dirname, "../../../../.." ), '.CoNET' ) export const QTGateLatest = Path.join ( QTGateFolder, 'latest' ) export const QTGateTemp = Path.join ( QTGateFolder, 'tempfile' ) export const QTGateVideo = Path.join ( QTGateTemp, 'videoTemp') export const ErrorLogFile = Path.join ( QTGateFolder, 'systemError.log' ) export const CoNETConnectLog = Path.join ( QTGateFolder, 'CoNETConnect.log' ) export const imapDataFileName1 = Path.join ( QTGateFolder, 'imapData.pem' ) export const CoNET_Home = Path.join ( __dirname ) export const CoNET_PublicKey = Path.join ( CoNET_Home, '1231B119.pem') export const LocalServerPortNumber = 3000 export const configPath = Path.join ( QTGateFolder, 'config.json' ) //const packageFilePath = Path.join ( __dirname,'package.json') //export const packageFile = require ( packageFilePath ) export const QTGateSignKeyID = /3acbe3cbd3c1caa9|864662851231B119/i export const twitterDataFileName = Path.join ( QTGateFolder, 'twitterData.pem' ) export const checkFolder = ( folder: string, CallBack: ( err?: Error ) => void ) => { Fs.access ( folder, err => { if ( err ) { return Fs.mkdir ( folder, err1 => { if ( err1 ) { return CallBack ( err1 ) } return CallBack () }) } return CallBack () }) } export const convertByte = ( byte: number ) => { if ( byte < 1000 ) { return `${ byte } B` } const kbyte = Math.round ( byte / 10.24 ) / 100 if ( kbyte < 1000 ) { return `${ kbyte } KB` } const mbyte = Math.round ( kbyte / 10 ) / 100 if ( mbyte < 1000 ) { return `${ mbyte } MB` } const gbyte = Math.round ( mbyte / 10 ) / 100 if ( gbyte < 1000 ) { return `${ gbyte } GB` } const tbyte = Math.round ( mbyte / 10 ) / 100 return `${ tbyte } TB` } export const checkSystemFolder = CallBack => { const callback = ( err, kkk ) => { if ( err ) { console.log ( `checkSystemFolder return error`, err ) return CallBack ( err ) } console.log (`checkSystemFolder QTGateFolder = [${ QTGateFolder }]`) return CallBack () } return Async.series ([ next => checkFolder ( QTGateFolder, next ), next => checkFolder ( QTGateLatest, next ), next => checkFolder ( QTGateTemp, next ), next => checkFolder ( QTGateVideo, next ) ], callback ) } export const getLocalInterface = () => { const ifaces = Os.networkInterfaces() const ret = [] Object.keys ( ifaces ).forEach ( n => { ifaces[ n ].forEach ( iface => { if ( 'IPv4' !== iface.family || iface.internal !== false ) { // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses return } ret.push ( iface.address ) }) }) return ret } export const InitConfig = () => { const ret: install_config = { firstRun: true, alreadyInit: false, multiLogin: false, version: CoNET_version, newVersion: null, newVerReady: false, keypair: InitKeyPair (), salt: Crypto.randomBytes ( 64 ), iterations: 2000 + Math.round ( Math.random () * 2000 ), keylen: Math.round ( 16 + Math.random() * 30 ), digest: 'sha512', freeUser: true, account: null, serverGlobalIpAddress: null, serverPort: LocalServerPortNumber, connectedQTGateServer: false, localIpAddress: getLocalInterface (), lastConnectType: 1, connectedImapDataUuid: null } return ret } export const getNickName = ( str: string ) => { const uu = str.split ('<') return uu[0] } export const getEmailAddress = ( str: string ) => { const uu = str.split ('<') return uu[1].substr( 0, uu[1].length -1 ) } export const getQTGateSign = ( user: OpenPgp.key.users ) => { if ( !user.otherCertifications || !user.otherCertifications.length ) { return null } let Certification = false user.otherCertifications.forEach ( n => { console.log (`user.otherCertifications\n${ n.issuerKeyId.toHex ().toLowerCase() }`) if ( QTGateSignKeyID.test ( n.issuerKeyId.toHex ().toLowerCase())) { return Certification = true } }) return Certification } export async function getKeyPairInfo ( publicKey: string, privateKey: string, password: string, CallBack: ( err?: Error, keyPair?: keypair ) => void ) { if ( ! publicKey || ! privateKey ) { return CallBack ( new Error ('publicKey or privateKey empty!')) } const _privateKey = await OpenPgp.key.readArmored ( privateKey ) const _publicKey = await OpenPgp.key.readArmored ( publicKey ) if ( _privateKey.err || _publicKey.err ) { console.log (`_privateKey.err = [${ _privateKey.err }], _publicKey.err [${ _publicKey.err }]`) console.log ( publicKey ) return CallBack ( new Error ('no key')) } //console.log (`getKeyPairInfo success!\nprivateKey\npublicKey`) const privateKey1 = _privateKey.keys[0] const publicKey1 = _publicKey.keys const user = publicKey1[0].users[0] const ret = InitKeyPair() let didCallback = false ret.publicKey = publicKey ret.privateKey = privateKey ret.nikeName = getNickName ( user.userId.userid ) ret.createDate = privateKey1.primaryKey.created.toDateString () ret.email = getEmailAddress ( user.userId.userid ) ret.verified = getQTGateSign ( user ) ret.publicKeyID = publicKey1[0].primaryKey.getFingerprint().toUpperCase() ret.passwordOK = false if ( !password ) { return CallBack ( null, ret ) } //console.log (`getKeyPairInfo test password!`) return privateKey1.decrypt ( password ).then ( keyOK => { //console.log (`privateKey1.decrypt then keyOK [${ keyOK }] didCallback [${ didCallback }]`) ret.passwordOK = keyOK ret._password = password didCallback = true return CallBack ( null, ret ) }).catch ( err => { console.log (`privateKey1.decrypt catch ERROR didCallback = [${ didCallback }]`, err ) if ( !didCallback ) { return CallBack ( null, ret ) } }) } export const emitConfig = ( config: install_config, passwordOK: boolean ) => { if ( !config ) { return null } const ret: install_config = { keypair: config.keypair, firstRun: config.firstRun, alreadyInit: config.alreadyInit, newVerReady: config.newVerReady, version: CoNET_version, multiLogin: config.multiLogin, freeUser: config.freeUser, account: config.keypair && config.keypair.email ? config.keypair.email : null, serverGlobalIpAddress: config.serverGlobalIpAddress, serverPort: config.serverPort, connectedQTGateServer: config.connectedQTGateServer, localIpAddress: getLocalInterface(), lastConnectType: config.lastConnectType, iterations: config.iterations, connectedImapDataUuid: config.connectedImapDataUuid } ret.keypair.passwordOK = false return ret } export const saveConfig = ( config: install_config, CallBack ) => { return Fs.writeFile ( configPath, JSON.stringify ( config ), CallBack ) } export const checkConfig = CallBack => { Fs.access ( configPath, err => { if ( err ) { return CallBack ( null, InitConfig ()) } let config: install_config = null try { config = require ( configPath ) } catch ( e ) { return CallBack ( null, InitConfig ()) } config.salt = Buffer.from ( config.salt['data'] ) // update? config.version = CoNET_version config.newVerReady = false config.newVersion = null config.serverPort = LocalServerPortNumber config.localIpAddress = getLocalInterface () config.firstRun = false if ( !config.keypair || ! config.keypair.publicKey ) { return CallBack ( null, config ) } return getKeyPairInfo ( config.keypair.publicKey, config.keypair.privateKey, null, ( err, key: keypair ) => { if ( err ) { CallBack ( err ) return console.log (`checkConfig getKeyPairInfo error`, err ) } config.keypair = key return CallBack ( null, config ) }) }) } export const newKeyPair = ( emailAddress: string, nickname: string, password: string, CallBack ) => { const userId = { name: nickname, email: emailAddress } const option: OpenPgp.KeyOptions = { passphrase: password, userIds: [ userId ], curve: "ed25519", aead_protect: true, aead_protect_version: 4 } return OpenPgp.generateKey ( option ).then (( keypair: { publicKeyArmored: string, privateKeyArmored: string }) => { const ret: keyPair = { publicKey: keypair.publicKeyArmored, privateKey: keypair.privateKeyArmored } return CallBack ( null, ret ) }).catch ( err => { // ERROR return CallBack ( err ) }) } export const getImapSmtpHost = function ( _email: string ) { const email = _email.toLowerCase() const yahoo = ( domain: string ) => { if ( /yahoo.co.jp$/i.test ( domain )) return 'yahoo.co.jp'; if ( /((.*\.){0,1}yahoo|yahoogroups|yahooxtra|yahoogruppi|yahoogrupper)(\..{2,3}){1,2}$/.test ( domain )) return 'yahoo.com'; if ( /(^hotmail|^outlook|^live|^msn)(\..{2,3}){1,2}$/.test ( domain )) return 'hotmail.com'; if ( /^(me|^icould|^mac)\.com/.test ( domain )) return 'me.com' return domain } const emailSplit = email.split ( '@' ) if ( emailSplit.length !== 2 ) return null const domain = yahoo ( emailSplit [1] ) const ret = { imap: 'imap.' + domain, smtp: 'smtp.' + domain, SmtpPort: [465,587,994], ImapPort: 993, imapSsl: true, smtpSsl: true, haveAppPassword: false, ApplicationPasswordInformationUrl: [''] } switch ( domain ) { // yahoo domain have two different // the yahoo.co.jp is different other yahoo.* case 'yahoo.co.jp': { ret.imap = 'imap.mail.yahoo.co.jp'; ret.smtp = 'smtp.mail.yahoo.co.jp' } break; // gmail case 'google.com': case 'googlemail.com': case 'gmail': { ret.haveAppPassword = true; ret.ApplicationPasswordInformationUrl = [ 'https://support.google.com/accounts/answer/185833?hl=zh-Hans', 'https://support.google.com/accounts/answer/185833?hl=ja', 'https://support.google.com/accounts/answer/185833?hl=en' ] } break; case 'gandi.net': ret.imap = ret.smtp = 'mail.gandi.net' break // yahoo.com case 'rocketmail.com': case 'y7mail.com': case 'ymail.com': case 'yahoo.com': { ret.imap = 'imap.mail.yahoo.com' ret.smtp = (/^bizmail.yahoo.com$/.test(emailSplit[1])) ? 'smtp.bizmail.yahoo.com' : 'smtp.mail.yahoo.com' ret.haveAppPassword = true; ret.ApplicationPasswordInformationUrl = [ 'https://help.yahoo.com/kb/SLN15241.html', 'https://help.yahoo.com/kb/SLN15241.html', 'https://help.yahoo.com/kb/SLN15241.html' ] } break; case 'mail.ee': ret.smtp = 'mail.ee' ret.imap = 'mail.inbox.ee' break // gmx.com case 'gmx.co.uk': case 'gmx.de': case 'gmx.us': case 'gmx.com' : { ret.smtp = 'mail.gmx.com' ret.imap = 'imap.gmx.com' } break; // aim.com case 'aim.com': { ret.imap = 'imap.aol.com' } break; // outlook.com case 'windowslive.com': case 'hotmail.com': case 'outlook.com': { ret.imap = 'imap-mail.outlook.com' ret.smtp = 'smtp-mail.outlook.com' } break; // apple mail case 'icloud.com': case 'mac.com': case 'me.com': { ret.imap = 'imap.mail.me.com' ret.smtp = 'smtp.mail.me.com' } break; // 163.com case '126.com': case '163.com': { ret.imap = 'appleimap.' + domain ret.smtp = 'applesmtp.' + domain } break; case 'sina.com': case 'yeah.net': { ret.smtpSsl = false } break; } return ret } export const availableImapServer = /imap\-mail\.outlook\.com$|imap\.mail\.yahoo\.(com|co\.jp|co\.uk|au)$|imap\.mail\.me\.com$|imap\.gmail\.com$|gmx\.(com|us|net)$|imap\.zoho\.com$/i const doUrl = ( url: string, CallBack) => { let ret = '' const res = res => { res.on( 'data', (data: Buffer) => { ret += data.toString('utf8') }) res.once ( 'end', () => { return CallBack( null, ret ) }) } if ( /^https/.test( url )) return Https.get ( url, res ) .once ( 'error', err => { console.log( 'on err ', err ) return CallBack ( err ) }) return Http.get ( url, res ) .once ( 'error', err => { console.log( 'on err ', err ) return CallBack ( err ) }) } const _smtpVerify = ( imapData: IinputData, CallBack: ( err?: Error, success?: any ) => void ) => { const option = { host: Net.isIP ( imapData.smtpServer ) ? null : imapData.smtpServer, hostname: Net.isIP ( imapData.smtpServer ) ? imapData.smtpServer : null, port: imapData.smtpPortNumber, secure: imapData.smtpSsl, auth: { user: imapData.smtpUserName, pass: imapData.smtpUserPassword }, connectionTimeout: ( 1000 * 15 ).toString (), tls: { rejectUnauthorized: imapData.smtpIgnoreCertificate, ciphers: imapData.ciphers }, debug: true } const transporter = Nodemailer.createTransport ( option ) return transporter.verify ( CallBack ) //DEBUG ? saveLog ( `transporter.verify callback [${ JSON.stringify ( err )}] success[${ success }]` ) : null /* if ( err ) { const _err = JSON.stringify ( err ) if ( /Invalid login|AUTH/i.test ( _err )) return CallBack ( 8 ) if ( /certificate/i.test ( _err )) return CallBack ( 9 ) return CallBack ( 10 ) } return CallBack() */ } export const smtpVerify = ( imapData: IinputData, CallBack: ( err? ) => void ) => { console.log (`doing smtpVerify!`) let testArray: IinputData[] = null let _ret = false let err1 = null if ( typeof imapData.smtpPortNumber === 'object' ) { testArray = imapData.smtpPortNumber.map ( n => { const ret: IinputData = JSON.parse ( JSON.stringify ( imapData )) ret.smtpPortNumber = n ret.ciphers = null return ret }) } else { testArray = [ imapData ] } testArray = testArray.concat ( testArray.map ( n => { const ret: IinputData = JSON.parse ( JSON.stringify ( n )) ret.ciphers = 'SSLv3' ret.smtpSsl = false return ret })) return Async.each ( testArray, ( n, next ) => { return _smtpVerify ( n, ( err: Error, success ) => { if ( err && err.message ) { if ( /Invalid login|AUTH/i.test ( err.message )) { return next ( err ) } return next () } console.log (success) if ( ! _ret ) { _ret = true imapData.smtpPortNumber = n.smtpPortNumber imapData.smtpSsl = n.smtpSsl imapData.ciphers = n.ciphers return CallBack () } }) }, ( err: Error ) => { if ( err ) { console.log ( `smtpVerify ERROR = [${ err.message }]`) return CallBack ( err ) } if ( ! _ret ) { console.log ( `smtpVerify success Async!`) return CallBack () } console.log (`smtpVerify already did CallBack!`) }) } export const getPbkdf2 = ( config: install_config, passwrod: string, CallBack ) => { return Crypto.pbkdf2 ( passwrod, config.salt, config.iterations, config.keylen, config.digest, CallBack ) } export async function makeGpgKeyOption ( config: install_config, passwrod: string, CallBack ) { const option = { privateKeys: ( await OpenPgp.key.readArmored ( config.keypair.privateKey )).keys, publicKeys: ( await OpenPgp.key.readArmored ( Fs.readFileSync ( CoNET_PublicKey, 'utf8'))).keys } return getPbkdf2 ( config, passwrod, ( err, data ) => { if ( err ) { return CallBack ( err ) } return option.privateKeys[0].decrypt ( data.toString( 'hex' )).then ( keyOK => { if ( keyOK ) { return CallBack ( null, option ) } return CallBack ( new Error ('password!')) }).catch ( CallBack ) }) } export async function saveEncryptoData ( fileName: string, data: any, config: install_config, password: string, CallBack ) { if ( ! data ) { return Fs.unlink ( fileName, CallBack ) } const _data = JSON.stringify ( data ) const publicKeys = ( await OpenPgp.key.readArmored ( config.keypair.publicKey )).keys const privateKeys = ( await OpenPgp.key.readArmored ( config.keypair.privateKey )).keys[0] const options = { message: OpenPgp.message.fromText ( _data ), //compression: OpenPgp.enums.compression.zip, publicKeys: publicKeys, privateKeys: [ privateKeys ] } //console.log (`saveEncryptoData Encrypto data with public key[${ Util.inspect (publicKeys[0].users[0].userId.userid, false, 2, true )}]`) return getPbkdf2 ( config, password, ( err, data: Buffer ) => { if ( err ) { return CallBack ( err ) } return privateKeys.decrypt ( data.toString( 'hex' )) .then ( keyOK => { console.log (`keyOK = [${ keyOK }]`) return OpenPgp.encrypt ( options ) .then ( ciphertext => { return Fs.writeFile ( fileName, ciphertext.data, { encoding: 'utf8' }, async err => { // test /* console.log (`Fs.writeFile success! doing test!\n${ ciphertext.data }\n${ JSON.stringify(ciphertext.data)}`) const option11 = { privateKeys: [privateKeys], publicKeys: publicKeys, message: await OpenPgp.message.readArmored( ciphertext.data ) } console.log (`${ Util.inspect(option11, false, 2, true )}`) OpenPgp.decrypt( option11 ).then ( plaintext => { console.log ( `OpenPgp.decrypt success!`,plaintext.data ) return CallBack () }) /** */ return CallBack ( err ) }) }) }).catch ( CallBack ) }) } export async function readEncryptoFile ( filename: string, savedPasswrod, config: install_config, CallBack ) { if ( ! savedPasswrod || ! savedPasswrod.length || ! config || ! config.keypair || ! config.keypair.createDate ) { return CallBack ( new Error ('readImapData no password or keypair data error!')) } const options11 = { message: null, publicKeys: ( await OpenPgp.key.readArmored ( config.keypair.publicKey )).keys, privateKeys: ( await OpenPgp.key.readArmored ( config.keypair.privateKey )).keys } return Async.waterfall ([ next => Fs.access ( filename, next ), ( acc, next ) => { /** * support old nodejs */ let _next = acc if ( typeof _next !== 'function') { //console.trace (` _next !== 'function' [${ typeof _next}]`) _next = next } getPbkdf2 ( config, savedPasswrod, _next ) }, ( data: Buffer, next ) => { return options11.privateKeys[0].decrypt ( data.toString( 'hex' )).then ( keyOk => { if ( !keyOk ) { return next ( new Error ( 'key password not OK!' )) } return next () }).catch ( err => { console.log ( `options.privateKey.decrypt err`, err ) next ( err ) }) }, next => { Fs.readFile ( filename, 'utf8', next ) }], async ( err, data ) => { if ( err ) { return CallBack ( err ) } try { options11.message = await OpenPgp.message.readArmored ( data.toString ()) } catch ( ex ) { console.log (`options.message error!\n${ data.toString ()}`) return CallBack ( ex ) } let _return = false return OpenPgp.decrypt ( options11 ).then ( async data => { _return = true await data.signatures[0].verified if ( data.signatures[0].verified ) { return CallBack ( null, data.data ) } return CallBack ( new Error ( 'signatures error!' )) }).catch ( ex => { if ( !_return ) { return CallBack ( ex ) } console.log (`OpenPgp.decrypt catch Error`, ex ) }) }) } export const encryptMessage = ( openKeyOption, message: string, CallBack ) => { const option = { privateKeys: openKeyOption.privateKeys[0], publicKeys: openKeyOption.publicKeys, message: OpenPgp.message.fromText ( message ), compression: OpenPgp.enums.compression.zip } return OpenPgp.encrypt ( option ).then ( ciphertext => { return CallBack ( null, ciphertext.data ) }).catch ( CallBack ) } export async function decryptoMessage ( openKeyOption, message: string, CallBack ) { const option = { privateKeys: openKeyOption.privateKeys, publicKeys: openKeyOption.publicKeys, message: null } option.message = await OpenPgp.message.readArmored ( message ) return OpenPgp.decrypt ( option ).then ( async data => { /** * verify signatures */ await data.signatures[0].verified //console.log ( Util.inspect ( data, false, 3, true )) if ( data.signatures[0].verified ) { return CallBack ( null, data.data ) } return CallBack ( new Error ('signatures error!')) }).catch ( err => { console.trace ( err ) console.log ( JSON.stringify ( message )) return CallBack ( err ) }) } const testSmtpAndSendMail = ( imapData: IinputData, CallBack ) => { let first = false if ( typeof imapData === 'object' ) { first = true } return smtpVerify ( imapData, err => { if ( err ) { if ( first ) { imapData.imapPortNumber = [25,465,587,994,2525] return smtpVerify ( imapData, CallBack ) } return CallBack ( err ) } return CallBack () }) } export const sendCoNETConnectRequestEmail = ( imapData: IinputData, openKeyOption, publicKey, toEmail: string, CallBack ) => { const qtgateCommand: QTGateCommand = { account: imapData.account, QTGateVersion: CoNET_version, imapData: imapData, command: 'connect', error: null, callback: null, language: imapData.language, publicKey: publicKey } return Async.waterfall ([ next => testSmtpAndSendMail ( imapData, next ), next => encryptMessage ( openKeyOption, JSON.stringify ( qtgateCommand ), next ), ( _data, next ) => { const option = { host: Net.isIP ( imapData.smtpServer ) ? null : imapData.smtpServer, hostname: Net.isIP ( imapData.smtpServer ) ? imapData.smtpServer : null, port: imapData.smtpPortNumber, secure: imapData.smtpSsl, auth: { user: imapData.smtpUserName, pass: imapData.smtpUserPassword }, connectionTimeout: ( 1000 * 15 ).toString (), tls: !imapData.smtpSsl ? { rejectUnauthorized: imapData.smtpIgnoreCertificate, ciphers: imapData.ciphers } : null, debug: true } const transporter = Nodemailer.createTransport ( option ) //console.log ( Util.inspect ( option )) const mailOptions = { from: imapData.smtpUserName, to: toEmail, subject:'node', attachments: [{ content: _data }] } //console.log ( Util.inspect ( mailOptions ) ) return transporter.sendMail ( mailOptions, next ) } ], CallBack ) } const testPingTimes = 5 export const deleteImapFile = () => { return Fs.unlink ( imapDataFileName1, err => { if ( err ) { console.log (`deleteImapFile get err`, err ) } }) }
the_stack
import * as React from 'react' import { Content, Header, Layout, Wrapper, SectionTitle, SectionHeader, SEO } from '../components' import Helmet from 'react-helmet' import config from '../../config/SiteConfig' import theme from '../../config/Theme' import styled from 'styled-components' import { media } from '../utils/media' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faGithub, faTwitter, faMastodon, faStackOverflow, faInstagram, faSoundcloud, faYoutube } from '@fortawesome/free-brands-svg-icons' import { RightImage } from '../components/RightImage' import { Link } from 'gatsby' export default class Portfolio extends React.Component<any> { public render() { return ( <Layout> <Helmet title={`Portfolio | ${config.siteTitle}`} /> <SEO path="/portfolio/" data={{ title: 'Ash Furrow Portfolio', description: "Ash Furrow's Professional Portfolio" }} /> <Header banner="/assets/bg/portfolio.jpg"> <SectionTitle>Portfolio</SectionTitle> </Header> <Wrapper> <Content> <_Portfolio /> </Content> </Wrapper> </Layout> ) } } const _Portfolio: React.FC = () => ( <> <p> I began my career as an &ldquo;iOS developer&rdquo; but{' '} <Link to="/blog/building-better-software-by-building-better-teams/"> I have learned </Link> , <Link to="/blog/normalizing-struggle/">I have struggled</Link>, and{' '} <Link to="/blog/perspective-of-the-polyglot/">I have grown</Link>. The problems I want to work on <em>now</em> simply cannot be solved with iOS software alone. I am interested in building <em>teams</em> as much as I am interested in building software. </p> <p> My <Link to="/blog/5-years-of-ios/">first five years</Link> and{' '} <Link to="/blog/5-more-years-of-building-software/"> my second five years </Link>{' '} of professional software development are openly documented, if you want an in-depth look. </p> <SectionHeader banner="/assets/portfolio/team.jpg" dim> <TitleCaption title="Team" subtitle="I am at my best when I'm helping others reach their best." /> </SectionHeader> <p> I started leading Artsy&apos;s Mobile Experience team in 2019, but my technical leadership spans back much further. Artsy encouraged to expand my impact so in 2015,{' '} <a href="/blog/building-online-communities/"> I began learning about team dynamics </a>{' '} and applying what I learned in my team as an individual contributor. Over the years,{' '} <a href="/blog/perspective-of-the-polyglot/"> I expanded my technical impact </a>{' '} by learning new systems and technologies, and{' '} <a href="/blog/building-better-software-by-building-better-teams/"> expanded my cultural impact </a>{' '} by learning how to foster healthy, empathetic, and productive work environments. </p> <p> My approach to guiding product development centres learning as its goal. Developers build new products in complicated business contexts, and we don&apos;t know the answers upfront. I help teams learn <em>how</em> to solve the problem effectively and efficiently. We end up building a great product, but we do so by focusing on the <em>learning</em> rather than the{' '} <em>building</em>. </p> <p> This focus means creating a team environment where we are constantly learning and then teaching what we have learned, often across disciplines. This foundation of learning has helped me scale up Artsy&apos;s mobile software expertise across many product teams{' '} <a href="https://artsy.github.io/blog/2020/09/29/becoming-mobile-first-at-artsy/"> to become a genuinely mobile-first product organization </a> . </p> <SectionHeader banner="/assets/portfolio/community_header.jpg" dim> <TitleCaption title="Community" subtitle="In my home region of Atlantic Canada, we have a saying: &ldquo;rising tides lift all boats.&rdquo;" /> </SectionHeader> <p> Since I was a teenager, I&apos;ve been fascinated with open source software. Not just the software itself, but the communities surrounding different projects. No one individual can accomplish what a community can – people can always accomplish more if they work together. </p> <p> Today, I practice a{' '} <a href="https://ashfurrow.com/blog/open-source-ideology/"> fairly radical openness </a> : I believe that unless there is a good reason to keep something secret, then it should be shared. Artsy called it &ldquo;open source by default.&rdquo; Teehan+Lax called it &ldquo;creating more value than you capture.&rdquo; These phrases gave names to the ideas that have always resonated with me. </p> <blockquote> <p> See, in all our searching, the only thing we&apos;ve found that makes the emptiness bearable is each other. — <a href="https://en.wikipedia.org/wiki/Contact_(1997_American_film)"> Contact (1997) </a> </p> </blockquote> <p> I take a lot of pride in helping others and in contributing to the developer community, and I&apos;ve tried to set a higher standard for{' '} <a href="https://ashfurrow.com/blog/minswan-for-ios/">my own behaviour</a> . In addition to building{' '} <a href="https://ashfurrow.com/blog/building-my-career/"> open source communities online </a> , I volunteer with <a href="https://www.pursuit.org">Pursuit</a>. When I moved to New York in 2015, I started a{' '} <a href="http://artsy.github.io/blog/2015/08/10/peer-lab/"> weekly Saturday morning peer lab </a> , which <a href="/blog/5-years-of-peer-lab/">ran for five years</a>. In the pre-pandemic times, I shared this idea{' '} <a href="https://peerlab.community">around the world</a> where many peer labs flourished. {/* TODO: Once this whole pandemic business blows over, uncomment this out. I have since shared this idea around the world to{' '} <a href="https://peerlab.community">dozens of cities</a>, so there might even be a peer lab near you!*/} </p> <Footer> <FooterIcons> <BigFAIcon> <FooterLink href="https://github.com/ashfurrow" title="GitHub" rel="me" > <FontAwesomeIcon icon={faGithub} /> </FooterLink> </BigFAIcon> <BigFAIcon> <FooterLink href="http://stackoverflow.com/users/516359/ash-furrow" title="Stack Overflow" rel="me" > <FontAwesomeIcon icon={faStackOverflow} /> </FooterLink> </BigFAIcon> <BigFAIcon> <FooterLink href="https://twitter.com/ashfurrow" title="Twitter" rel="me" > <FontAwesomeIcon icon={faTwitter} /> </FooterLink> </BigFAIcon> <BigFAIcon> <FooterLink href="https://mastodon.technology/@ashfurrow" title="Mastodon" rel="me" > <FontAwesomeIcon icon={faMastodon} /> </FooterLink> </BigFAIcon> </FooterIcons> </Footer> <SectionHeader banner="/assets/portfolio/software_header.jpg" dim> <TitleCaption title="Software" subtitle="Great software is software nobody notices. I write meaningful software with this in mind." /> </SectionHeader> <p> I&apos;ve began writing iOS apps in 2009, when I was still in university. Since then, I&apos;ve expanded into{' '} <a href="https://ashfurrow.com/blog/perspective-of-the-polyglot/"> many directions </a> . I now write software for whichever platform would best solve the problem at hand. </p> <div> <h3>Artsy</h3> <RightImage src="/assets/portfolio/artsy.jpg" /> <LeftDiv> <p> From 2014 until 2021, I was at{' '} <a href="https://www.artsy.net">Artsy</a>: a company working towards a future where everyone is moved by art every day. I worked on a variety of teams to realize Artsy&apos;s business goals, starting with building iOS apps, then contributing across many systems and teams, and eventually leading Artsy&apos;s Mobile Experience team. </p> <p> Artsy encouraged me to grow and learn, and to share what I learn with others; all of my work there was{' '} <a href="https://github.com/ashfurrow">done in the open</a>, and I wrote articles for{' '} <a href="http://artsy.github.io">Artsy&apos;s engineering blog</a>. </p> </LeftDiv> <h3>35mm</h3> <RightImage src="/assets/portfolio/35mm.jpg" /> <LeftDiv> <p> 35mm was an ambitious project that I undertook with a team of two others: a designer and an editor. We aimed to change the world for photography-lovers by providing curated photography without advertisements. Although the project was not a success from a financial standpoint, I learned a lot about writing Newsstand magazines for iOS, including architecting our own backend server in Node.js. </p> </LeftDiv> <h3>500px</h3> <RightImage src="/assets/portfolio/500px.jpg" /> <LeftDiv> <p> In 2011, I began as the only iOS developer at{' '} <a href="https://500px.com">500px</a>, architecting and shipping the iPad app. I helped design new features, plan the product roadmap, and respond to customer support inquiries, all while continuing to ship an amazing product. I learned a lot about how software serves the needs of the business, and collaborating towards shared goals as a team. As a team lead, I played a crucial role in the design and development of the iPhone app, which shipped late 2012. </p> </LeftDiv> </div> <SectionHeader banner="/assets/portfolio/creativity_header.jpg" dim> <TitleCaption title="Creativity" subtitle="Beyond code, beyond writing, there is art. My primary creative outlets are music and photography." /> </SectionHeader> <p> In 2011, I began developing an increasingly intense interest in photography. Working to improve my skills, I&apos;ve explored the medium on film and in the{' '} <a href="https://ashfurrow.com/blog/darkroom-printing/">dark room</a>, using film as small as 35mm to as large as{' '} <a href="https://ashfurrow.com/blog/large-format-photography/"> 4x5 inches </a> . I now shoot using my iPhone because the majority of my dedicated creative time is spent on music. </p> <p> I grew up playing music but stopped when I started university. Twelve years later, in 2016,{' '} <a href="https://ashfurrow.com/blog/learning-guitar/"> I picked up a guitar for the first </a>{' '} time and have been{' '} <a href="https://ashfurrow.com/blog/music-is-back/">(re)discovering</a> my love of music ever since. My largest music project to date has been a{' '} <a href="https://ashfurrow.com/blog/just-play/">30-day challenge</a>. I'm starting to explore songwriting, but it's still early. </p> <Footer> <FooterIcons> <BigFAIcon> <FooterLink href="http://instagram.com/ashfurrow" title="Instagram" rel="me" > <FontAwesomeIcon icon={faInstagram} /> </FooterLink> </BigFAIcon> <BigFAIcon> <FooterLink href="https://photos.ashfurrow.com/" title="Photo Blog" rel="me" > <ExposureIcon /> </FooterLink> </BigFAIcon> <BigFAIcon> <FooterLink href="https://soundcloud.com/ash-furrow" title="Soundcloud" rel="me" > <FontAwesomeIcon icon={faSoundcloud} /> </FooterLink> </BigFAIcon> <BigFAIcon> <FooterLink href="https://www.youtube.com/channel/UC-nZp66dKt_9tNHwEr6qLyQ" title="YouTube" rel="me" > <FontAwesomeIcon icon={faYoutube} /> </FooterLink> </BigFAIcon> </FooterIcons> </Footer> <SectionHeader banner="/assets/portfolio/education_header.jpg" dim> <TitleCaption title="Education" subtitle="I grew up wanting to become a teacher, and when I became a programmer, I achieved my dream." /> </SectionHeader> <div> <h3>Blogging</h3> <RightImage src="/assets/portfolio/blogging.jpg" /> <LeftDiv> <p> I&apos;ve been writing a developer-focused blog since 2011, now hosted here. At{' '} <a href="http://www.teehanlax.com/blog/author/ash/">Teehan+Lax</a>, I began contributing to company blog as part of my job. I continued that on <a href="http://artsy.github.io">Artsy&apos;s developer blog</a>. I&apos;ve also written posts for{' '} <a href="http://www.objc.io/contributors/">objc.io</a>. </p> <p> <a href="https://ashfurrow.com/blog/contemporaneous-blogging/"> Blogging </a>{' '} about has made me{' '} <a href="https://www.youtube.com/watch?v=SjjvnrqDjpM"> a better developer and a better writer </a> . At Artsy, I hosted weekly writing office hours to help others achieve their{' '} <a href="https://artsy.github.io/blog/2020/12/09/share-your-knowledge/"> knowledge-sharing goals </a> . </p> </LeftDiv> <h3>Speaking</h3> <RightImage src="/assets/portfolio/speaking.jpg" /> <LeftDiv> <p> I began speaking in the Toronto CocoaHeads group in 2011. I soon began submitting proposals to conferences. Today, I&apos;ve spoken all over the world on a variety of subjects relating to software development, team development, and open source software. </p> <p> Check out my <a href="/speaking">speaking page</a> for more. </p> </LeftDiv> <h3>Books</h3> <RightImage src="/assets/portfolio/books.jpg" /> <LeftDiv> <p> I became a published author in 2012 and have since written a number of books on iOS development (both with tradional publishers and self-published). Like with blogging, writing is a very satisfying activity. I enjoy planning a route to take a reader on, considering what to teach them (and when), and turning my ideas into educational resources. </p> <p> My work in books extends to technical editing as well.{' '} <a href="/books">Check out my books page</a> for more. </p> </LeftDiv> <h3>Workshops</h3> <RightImage src="/assets/portfolio/treehouse.jpg" /> <LeftDiv> <p> I delivered my first workshop in 2011. In March, 2014,{' '} <a href="https://teamtreehouse.com">Treehouse</a> invited me to Orlando to record a series of videos and screencasts to guide students through using Core Data to build an iOS diary app. </p> <p> I&apos;ve also given in-person workshops on subjects ranging from the basics of iOS development to functional reactive programming in Swift.{' '} <a href="https://artsy.github.io/series/swift-at-artsy/"> I also led a workshop at Artsy </a>{' '} to teach non-engineers the fundamentals of programming. </p> </LeftDiv> </div> </> ) const LeftDiv = styled.div` max-width: 50%; @media ${media.phone} { max-width: initial; } ` const FigCaption = styled.figcaption` display: block; padding: 0; text-align: left; width: 30%; max-width: 325px; position: relative; right: -70%; top: 2rem; &:before { content: ''; display: block; color: white; position: relative; width: 357px; height: 164px; right: 397px; top: 3.6em; background-image: url(/assets/portfolio/callout.svg); @media ${media.tablet} { width: 205px; max-width: initial; height: 94px; top: 2em; right: 235px; background-image: url(/assets/portfolio/callout_small.svg); } @media ${media.phone} { display: none; } } h2 { font-size: 2.5rem; } @media ${media.tablet} { h2 { font-size: 1.5rem; } p { font-size: 0.75rem; } } @media ${media.phone} { padding: 0rem 1rem; text-align: center; width: 100%; max-width: initial; position: initial; right: initial; h2 { font-size: 1.5rem; } p { font-size: 0.75rem; } } ` const TitleCaption: React.FC<{ title: string; subtitle: string }> = ({ title, subtitle }) => ( <FigCaption> <h2 style={{ margin: '0' }}>{title}</h2> <p style={{ margin: '0' }}>{subtitle}</p> </FigCaption> ) const Footer = styled.footer` text-align: center; padding-top: 1rem; span { margin: 0 1rem; @media ${media.phone} { margin: 0 0.3rem; } } ` const FooterLink = styled.a` color: ${theme.colors.grey.default}; &:hover { color: ${theme.colors.primary}; } ` const BigFAIcon: React.FC = props => ( <span className="fa-layers fa-fw fa-3x">{props.children}</span> ) const FooterIcons = styled.div` margin: 1.5rem 0; ` const ExposureIcon = styled.div` margin: auto; height: 60px; /* Matches Fontawesome */ width: 53px; background: url('/assets/portfolio/exposure.png') no-repeat; background-size: contain; @media ${media.phone} { height: 42px; width: 37px; } &:hover { /* I don't like this at all, ugh. */ background: url('/assets/portfolio/exposure_hover.png') no-repeat; background-size: contain; } ` // = props => <div style={{ height: '60px', width: '53px', background: `${} no-repeat`;}} />
the_stack
import dayjs from 'dayjs'; import { enterInput, verifyElementIsVisible, clickButton, clickElementByText, enterInputConditionally, clearField, clickKeyboardBtnByKeycode, clickButtonByIndex, waitElementToHide, verifyText, verifyTextNotExisting, clickButtonWithForce } from '../utils/util'; import { ManageEmployeesPage } from '../pageobjects/ManageEmployeesPageObject'; // INVITE EMPLOYEE BY EMAIL export const gridBtnExists = () => { verifyElementIsVisible(ManageEmployeesPage.gridButtonCss); }; export const gridBtnClick = (index) => { clickButtonByIndex(ManageEmployeesPage.gridButtonCss, index); }; export const inviteButtonVisible = () => { verifyElementIsVisible(ManageEmployeesPage.inviteButtonCss); }; export const clickInviteButton = () => { clickButton(ManageEmployeesPage.inviteButtonCss); }; export const emailInputVisible = () => { verifyElementIsVisible(ManageEmployeesPage.emailsInputCss); }; export const enterEmailData = (data) => { enterInputConditionally(ManageEmployeesPage.emailsInputCss, data); }; export const dateInputVisible = () => { verifyElementIsVisible(ManageEmployeesPage.dateInputCss); }; export const enterDateData = () => { clearField(ManageEmployeesPage.dateInputCss); const date = dayjs().format('MMM D, YYYY'); enterInput(ManageEmployeesPage.dateInputCss, date); }; export const clickKeyboardButtonByKeyCode = (keycode) => { clickKeyboardBtnByKeycode(keycode); }; export const selectProjectDropdownVisible = () => { verifyElementIsVisible(ManageEmployeesPage.selectProjectDropdownCss); }; export const clickProjectDropdown = () => { clickButton(ManageEmployeesPage.selectProjectDropdownCss); }; export const selectProjectFromDropdown = (text) => { clickElementByText( ManageEmployeesPage.selectProjectDropdownOptionCss, text ); }; export const sendInviteButtonVisible = () => { verifyElementIsVisible(ManageEmployeesPage.sendInviteButtonCss); }; export const clickSendInviteButton = () => { clickButton(ManageEmployeesPage.sendInviteButtonCss); }; // ADD NEW EMPLOYEE export const addEmployeeButtonVisible = () => { verifyElementIsVisible(ManageEmployeesPage.addEmployeeButtonCss); }; export const clickAddEmployeeButton = () => { clickButtonWithForce(ManageEmployeesPage.addEmployeeButtonCss); }; export const firstNameInputVisible = () => { verifyElementIsVisible(ManageEmployeesPage.firstNameInputCss); }; export const enterFirstNameData = (data) => { enterInput(ManageEmployeesPage.firstNameInputCss, data); }; export const lastNameInputVisible = () => { verifyElementIsVisible(ManageEmployeesPage.lastNameInputCss); }; export const enterLastNameData = (data) => { enterInput(ManageEmployeesPage.lastNameInputCss, data); }; export const usernameInputVisible = () => { verifyElementIsVisible(ManageEmployeesPage.usernameInputCss); }; export const enterUsernameData = (data) => { enterInput(ManageEmployeesPage.usernameInputCss, data); }; export const employeeEmailInputVisible = () => { verifyElementIsVisible(ManageEmployeesPage.emailInputCss); }; export const enterEmployeeEmailData = (data) => { enterInput(ManageEmployeesPage.emailInputCss, data); }; export const passwordInputVisible = () => { verifyElementIsVisible(ManageEmployeesPage.passwordInputCss); }; export const enterPasswordInputData = (data) => { enterInput(ManageEmployeesPage.passwordInputCss, data); }; export const tagsDropdownVisible = () => { verifyElementIsVisible(ManageEmployeesPage.addTagsDropdownCss); }; export const clickTagsDropdwon = () => { clickButton(ManageEmployeesPage.addTagsDropdownCss); }; export const selectTagFromDropdown = (index) => { clickButtonByIndex(ManageEmployeesPage.tagsDropdownOption, index); }; export const clickCardBody = () => { clickButton(ManageEmployeesPage.cardBodyCss); }; export const imageInputVisible = () => { verifyElementIsVisible(ManageEmployeesPage.imgInputCss); }; export const enterImageDataUrl = (url) => { enterInput(ManageEmployeesPage.imgInputCss, url); }; export const nextButtonVisible = () => { verifyElementIsVisible(ManageEmployeesPage.nextButtonCss); }; export const clickNextButton = () => { clickButton(ManageEmployeesPage.nextButtonCss); }; export const nextStepButtonVisible = () => { verifyElementIsVisible(ManageEmployeesPage.nextStepButtonCss); }; export const clickNextStepButton = () => { clickButton(ManageEmployeesPage.nextStepButtonCss); }; export const lastStepButtonVisible = () => { verifyElementIsVisible(ManageEmployeesPage.lastStepButtonCss); }; export const clickLastStepButton = () => { clickButton(ManageEmployeesPage.lastStepButtonCss); }; // EDIT EMPLOYEE export const tableRowVisible = () => { verifyElementIsVisible(ManageEmployeesPage.selectTableRowCss); }; export const selectTableRow = (index) => { clickButtonByIndex(ManageEmployeesPage.selectTableRowCss, index); }; export const editButtonVisible = () => { verifyElementIsVisible(ManageEmployeesPage.editEmployeeButtonCss); }; export const clickEditButton = () => { clickButton(ManageEmployeesPage.editEmployeeButtonCss); }; export const usernameEditInputVisible = () => { verifyElementIsVisible(ManageEmployeesPage.usernameEditSecondInputCss); }; export const enterUsernameEditInputData = (data) => { clearField(ManageEmployeesPage.usernameEditSecondInputCss); enterInput(ManageEmployeesPage.usernameEditSecondInputCss, data); }; export const emailEditInputVisible = () => { verifyElementIsVisible(ManageEmployeesPage.emailEditSecondInputCss); }; export const enterEmailEditInputData = (data) => { clearField(ManageEmployeesPage.emailEditSecondInputCss); enterInput(ManageEmployeesPage.emailEditSecondInputCss, data); }; export const firstNameEditInputVisible = () => { verifyElementIsVisible(ManageEmployeesPage.firstNameSecondEditInputCss); }; export const enterFirstNameEditInputData = (data) => { clearField(ManageEmployeesPage.firstNameSecondEditInputCss); enterInput(ManageEmployeesPage.firstNameSecondEditInputCss, data); }; export const lastNameEditInputVisible = () => { verifyElementIsVisible(ManageEmployeesPage.lastNameSecondEditInputCss); }; export const enterLastNameEditInputData = (data) => { clearField(ManageEmployeesPage.lastNameSecondEditInputCss); enterInput(ManageEmployeesPage.lastNameSecondEditInputCss, data); }; export const preferredLanguageDropdownVisible = () => { verifyElementIsVisible(ManageEmployeesPage.preferredLanguageDropdownCss); }; export const clickpreferredLanguageDropdown = () => { clickButton(ManageEmployeesPage.preferredLanguageDropdownCss); }; export const selectLanguageFromDropdown = (text) => { clickElementByText(ManageEmployeesPage.preferredLanguageOptionCss, text); }; export const saveEditButtonVisible = () => { verifyElementIsVisible(ManageEmployeesPage.saveEditButtonCss); }; export const clickSaveEditButton = () => { clickButton(ManageEmployeesPage.saveEditButtonCss); }; export const backButtonVisible = () => { verifyElementIsVisible(ManageEmployeesPage.backButtonCss); }; export const clickBackButton = () => { clickButton(ManageEmployeesPage.backButtonCss); }; // END WORK export const endWorkButtonVisible = () => { verifyElementIsVisible(ManageEmployeesPage.endWorkButtonCss); }; export const clickEndWorkButton = () => { clickButton(ManageEmployeesPage.endWorkButtonCss); }; export const confirmEndWorkButtonVisible = () => { verifyElementIsVisible(ManageEmployeesPage.confirmEndWorkButtonCss); }; export const clickConfirmEndWorkButton = () => { clickButton(ManageEmployeesPage.confirmEndWorkButtonCss); }; // DELETE EMPLOYEE export const deleteButtonVisible = () => { verifyElementIsVisible(ManageEmployeesPage.deleteEmployeeButtonCss); }; export const clickDeleteButton = () => { clickButton(ManageEmployeesPage.deleteEmployeeButtonCss); }; export const confirmDeleteButtonVisible = () => { verifyElementIsVisible(ManageEmployeesPage.confirmDeleteButtonCss); }; export const clickConfirmDeleteButton = () => { clickButton(ManageEmployeesPage.confirmDeleteButtonCss); }; // COPY INVITE LINK export const manageInvitesButtonVisible = () => { verifyElementIsVisible(ManageEmployeesPage.manageInvitesButonCss); }; export const clickManageInviteButton = () => { clickButton(ManageEmployeesPage.manageInvitesButonCss); }; export const copyLinkButtonVisible = () => { verifyElementIsVisible(ManageEmployeesPage.copyLinkButtonCss); }; export const clickCopyLinkButton = () => { clickButton(ManageEmployeesPage.copyLinkButtonCss); }; // RESEND INVITE export const resendInviteButtonVisible = () => { verifyElementIsVisible(ManageEmployeesPage.resendInviteButtonCss); }; export const clickResendInviteButton = () => { clickButton(ManageEmployeesPage.resendInviteButtonCss); }; export const confirmResendInviteButtonVisible = () => { verifyElementIsVisible(ManageEmployeesPage.confirmResendInviteButtonCss); }; export const clickConfirmResendInviteButton = () => { clickButton(ManageEmployeesPage.confirmResendInviteButtonCss); }; // DELETE INVITE export const deleteInviteButtonVisible = () => { verifyElementIsVisible(ManageEmployeesPage.deleteInviteButtonCss); }; export const clickDeleteInviteButton = () => { clickButton(ManageEmployeesPage.deleteInviteButtonCss); }; export const confirmDeleteInviteButtonVisible = () => { verifyElementIsVisible(ManageEmployeesPage.confirmDeleteInviteButtonCss); }; export const clickConfirmDeleteInviteButton = () => { clickButton(ManageEmployeesPage.confirmDeleteInviteButtonCss); }; export const waitMessageToHide = () => { waitElementToHide(ManageEmployeesPage.toastrMessageCss); }; export const verifyEmployeeExists = (text) => { verifyText(ManageEmployeesPage.verifyEmployeeCss, text); }; export const verifyEmployeeIsDeleted = (text) => { verifyTextNotExisting(ManageEmployeesPage.verifyEmployeeCss, text); }; export const verifyInviteExists = (text) => { verifyText(ManageEmployeesPage.verifyInviteCss, text); }; export const verifyInviteIsDeleted = (text) => { verifyTextNotExisting(ManageEmployeesPage.verifyInviteCss, text); };
the_stack
import { getComponent } from '@xrengine/engine/src/ecs/functions/ComponentFunctions' import { InputComponent, InputComponentType } from '../classes/InputComponent' import isInputSelected from '../functions/isInputSelected' import { SceneManager } from '../managers/SceneManager' import { InputMapping, ActionKey, Action, ActionState, SpecialAliases, MouseButtons } from './input-mappings' export default class InputManager { canvas: HTMLCanvasElement boundingClientRect: DOMRect inputComponent: InputComponentType // mouseDownTarget: any constructor(canvas) { this.canvas = canvas this.boundingClientRect = this.canvas.getBoundingClientRect() window.addEventListener('keydown', this.onKeyDown) window.addEventListener('keyup', this.onKeyUp) canvas.addEventListener('wheel', this.onWheel) canvas.addEventListener('mousemove', this.onMouseMove) canvas.addEventListener('mousedown', this.onMouseDown) canvas.addEventListener('mouseup', this.onMouseUp) canvas.addEventListener('dblclick', this.onDoubleClick) canvas.addEventListener('click', this.onClick) canvas.addEventListener('contextmenu', this.onContextMenu) window.addEventListener('blur', this.onWindowBlur) // this.mouseDownTarget = null // window.addEventListener('mousedown', this.onWindowMouseDown) // window.addEventListener('mouseup', this.onWindowMouseUp) } handleActionCallback = (action: Action, event: Event) => { if (typeof action.callback === 'function') action.callback(event, this) } handleKeyMappings(state: ActionState, inputMapping: InputMapping, event: KeyboardEvent, value: any): boolean { let eventKey = (event.key ?? String.fromCharCode(event.which || parseInt(event.code))).toLowerCase() let preventDefault = false const actionNames = Object.keys(inputMapping) for (const actionName of actionNames) { if (!Object.prototype.hasOwnProperty.call(inputMapping, actionName)) continue const key = inputMapping[actionName].key this.handleActionCallback(inputMapping[actionName], event) if (eventKey === actionName || eventKey === SpecialAliases[actionName]) { state[key] = value preventDefault = true } } return preventDefault } handlePosition(state: ActionState, positionAction: ActionKey, event: MouseEvent): void { const rect = this.boundingClientRect if (!state[positionAction]) state[positionAction] = {} state[positionAction].x = ((event.clientX - rect.left) / rect.width) * 2 - 1 state[positionAction].y = ((event.clientY - rect.top) / rect.height) * -2 + 1 } // ------------- Keyboard Events ------------- // onKeyDown = (event: KeyboardEvent): void => { // Skip actions if input field is active if (isInputSelected()) return this.inputComponent = getComponent(SceneManager.instance.editorEntity, InputComponent) const keyboardMapping = this.inputComponent.activeMapping.keyboard if (!keyboardMapping) return let preventDefault = false if (keyboardMapping.pressed) preventDefault = this.handleKeyMappings(this.inputComponent.actionState, keyboardMapping.pressed, event, 1) if (keyboardMapping.keydown) preventDefault = this.handleKeyMappings(this.inputComponent.actionState, keyboardMapping.keydown, event, 1) if (preventDefault) event.preventDefault() } onKeyUp = (event: KeyboardEvent): void => { // Skip actions if input field is active if (isInputSelected()) return this.inputComponent = getComponent(SceneManager.instance.editorEntity, InputComponent) const keyboardMapping = this.inputComponent.activeMapping.keyboard if (!keyboardMapping) return let preventDefault = false if (keyboardMapping.pressed) preventDefault = this.handleKeyMappings(this.inputComponent.actionState, keyboardMapping.pressed, event, 0) if (keyboardMapping.keyup) preventDefault = this.handleKeyMappings(this.inputComponent.actionState, keyboardMapping.keyup, event, 0) if (preventDefault) event.preventDefault() } // ------------- Keyboard Events ------------- // // ------------- Mouse Events ------------- // // onWindowMouseDown = (event: MouseEvent) => { // this.mouseDownTarget = event.target // } onMouseDown = (event: MouseEvent): void => { // this.mouseDownTarget = event.target this.inputComponent = getComponent(SceneManager.instance.editorEntity, InputComponent) const mouseMapping = this.inputComponent.activeMapping.mouse if (!mouseMapping) return const buttonKey = MouseButtons[event.button] if (mouseMapping.pressed && mouseMapping.pressed[buttonKey]) { this.inputComponent.actionState[mouseMapping.pressed[buttonKey].key] = 1 this.handleActionCallback(mouseMapping.pressed[buttonKey], event) } const mouseDown = mouseMapping.mousedown if (mouseDown) { let action = mouseDown[buttonKey] if (action) { this.inputComponent.actionState[action.key] = 1 this.handleActionCallback(action, event) } if (mouseDown.position) this.handlePosition(this.inputComponent.actionState, mouseDown.position.key, event) } } // onWindowMouseUp = (event: MouseEvent) => { // const canvas = this.canvas // const mouseDownTarget = this.mouseDownTarget // this.mouseDownTarget = null // if (event.target === canvas || mouseDownTarget !== canvas) { // return // } // this.onMouseUp(event) // } onMouseUp = (event: MouseEvent): void => { this.inputComponent = getComponent(SceneManager.instance.editorEntity, InputComponent) const mouseMapping = this.inputComponent.activeMapping.mouse if (!mouseMapping) return const buttonKey = MouseButtons[event.button] if (mouseMapping.pressed && mouseMapping.pressed[buttonKey]) { this.inputComponent.actionState[mouseMapping.pressed[buttonKey].key] = 0 this.handleActionCallback(mouseMapping.pressed[buttonKey], event) } const mouseUp = mouseMapping.mouseup if (mouseUp) { const action = mouseUp[buttonKey] if (action) { this.inputComponent.actionState[action.key] = 1 this.handleActionCallback(action, event) } if (mouseUp.position) this.handlePosition(this.inputComponent.actionState, mouseUp.position.key, event) } } onMouseMove = (event: MouseEvent): void => { this.inputComponent = getComponent(SceneManager.instance.editorEntity, InputComponent) const mouseMapping = this.inputComponent.activeMapping.mouse if (!mouseMapping) return const mouseMove = mouseMapping.move if (!mouseMove) return const actionNames = Object.keys(mouseMove) for (const actionName of actionNames) { if (!Object.prototype.hasOwnProperty.call(mouseMove, actionName)) continue const key = mouseMove[actionName].key if (actionName === 'movementX' || actionName === 'movementY') { this.inputComponent.actionState[key] += event[actionName] } else if (actionName === 'normalizedMovementX') { this.inputComponent.actionState[key] += -event.movementX / this.canvas.clientWidth } else if (actionName === 'normalizedMovementY') { this.inputComponent.actionState[key] += -event.movementY / this.canvas.clientHeight } else if (actionName === 'position') { this.handlePosition(this.inputComponent.actionState, key, event) } else { this.inputComponent.actionState[key] = event[actionName] } this.handleActionCallback(mouseMove[actionName], event) } } onWheel = (event: WheelEvent): boolean => { event.preventDefault() this.inputComponent = getComponent(SceneManager.instance.editorEntity, InputComponent) const mouseMapping = this.inputComponent.activeMapping.mouse if (!mouseMapping) return false const mouseWheel = mouseMapping.wheel if (!mouseWheel) return false const actionNames = Object.keys(mouseWheel) for (const actionName of actionNames) { if (!Object.prototype.hasOwnProperty.call(mouseWheel, actionName)) continue const key = mouseWheel[actionName].key if (actionName === 'deltaX' || actionName === 'deltaY') { this.inputComponent.actionState[key] += event[actionName] } else if (actionName === 'normalizedDeltaX') { this.inputComponent.actionState[key] = Math.sign(event.deltaX) } else if (actionName === 'normalizedDeltaY') { this.inputComponent.actionState[key] = Math.sign(event.deltaY) } else { this.inputComponent.actionState[key] = event[actionName] } this.handleActionCallback(mouseWheel[actionName], event) } return false } onClick = (event: MouseEvent): void => { this.inputComponent = getComponent(SceneManager.instance.editorEntity, InputComponent) const mouseMapping = this.inputComponent.activeMapping.mouse if (!mouseMapping) return const mouseClick = mouseMapping.click if (mouseClick && mouseClick.position) { this.handlePosition(this.inputComponent.actionState, mouseClick.position.key, event) this.handleActionCallback(mouseClick.position, event) } } onDoubleClick = (event: MouseEvent): void => { this.inputComponent = getComponent(SceneManager.instance.editorEntity, InputComponent) const mouseMapping = this.inputComponent.activeMapping.mouse if (!mouseMapping) return const mouseDblclick = mouseMapping.dblclick if (mouseDblclick && mouseDblclick.position) { this.handlePosition(this.inputComponent.actionState, mouseDblclick.position.key, event) this.handleActionCallback(mouseDblclick.position, event) } } // ------------- Mouse Events ------------- // onContextMenu = (event: Event): void => event.preventDefault() onResize = (): void => { this.boundingClientRect = this.canvas.getBoundingClientRect() } onWindowBlur = (): void => { this.inputComponent = getComponent(SceneManager.instance.editorEntity, InputComponent) const defaultState = this.inputComponent.defaultState const keys = Object.keys(defaultState) for (const key of keys) { if (Object.prototype.hasOwnProperty.call(defaultState, key)) { this.inputComponent.actionState[key] = defaultState[key] } } } dispose(): void { const canvas = this.canvas window.removeEventListener('keydown', this.onKeyDown) window.removeEventListener('keyup', this.onKeyUp) canvas.removeEventListener('wheel', this.onWheel) canvas.removeEventListener('mousemove', this.onMouseMove) canvas.removeEventListener('mousedown', this.onMouseDown) canvas.removeEventListener('mouseup', this.onMouseUp) canvas.removeEventListener('dblclick', this.onDoubleClick) canvas.removeEventListener('click', this.onClick) canvas.removeEventListener('contextmenu', this.onContextMenu) window.removeEventListener('blur', this.onWindowBlur) // window.removeEventListener('mousedown', this.onWindowMouseDown) // window.removeEventListener('mouseup', this.onWindowMouseUp) } }
the_stack
import { HexString } from '../../hex_string'; import { Deserializer, Serializer, Uint64, Bytes, Seq, Uint8, Uint128, deserializeVector, serializeVector, } from '../bcs'; import { AccountAddress } from './account_address'; import { TransactionAuthenticator } from './authenticator'; import { Identifier } from './identifier'; import { TypeTag } from './type_tag'; export class RawTransaction { /** * RawTransactions contain the metadata and payloads that can be submitted to Aptos chain for execution. * RawTransactions must be signed before Aptos chain can execute them. * * @param sender Account address of the sender. * @param sequence_number Sequence number of this transaction. This must match the sequence number stored in * the sender's account at the time the transaction executes. * @param payload Instructions for the Aptos Blockchain, including publishing a module, * execute a script function or execute a script payload. * @param max_gas_amount Maximum total gas to spend for this transaction. The account must have more * than this gas or the transaction will be discarded during validation. * @param gas_unit_price Price to be paid per gas unit. * @param expiration_timestamp_secs The blockchain timestamp at which the blockchain would discard this transaction. * @param chain_id The chain ID of the blockchain that this transaction is intended to be run on. */ constructor( public readonly sender: AccountAddress, public readonly sequence_number: Uint64, public readonly payload: TransactionPayload, public readonly max_gas_amount: Uint64, public readonly gas_unit_price: Uint64, public readonly expiration_timestamp_secs: Uint64, public readonly chain_id: ChainId, ) {} serialize(serializer: Serializer): void { this.sender.serialize(serializer); serializer.serializeU64(this.sequence_number); this.payload.serialize(serializer); serializer.serializeU64(this.max_gas_amount); serializer.serializeU64(this.gas_unit_price); serializer.serializeU64(this.expiration_timestamp_secs); this.chain_id.serialize(serializer); } static deserialize(deserializer: Deserializer): RawTransaction { const sender = AccountAddress.deserialize(deserializer); const sequence_number = deserializer.deserializeU64(); const payload = TransactionPayload.deserialize(deserializer); const max_gas_amount = deserializer.deserializeU64(); const gas_unit_price = deserializer.deserializeU64(); const expiration_timestamp_secs = deserializer.deserializeU64(); const chain_id = ChainId.deserialize(deserializer); return new RawTransaction( sender, sequence_number, payload, max_gas_amount, gas_unit_price, expiration_timestamp_secs, chain_id, ); } } export class Script { /** * Scripts contain the Move bytecodes payload that can be submitted to Aptos chain for execution. * @param code Move bytecode * @param ty_args Type arguments that bytecode requires. * * @example * A coin transfer function has one type argument "CoinType". * ``` * public(script) fun transfer<CoinType>(from: &signer, to: address, amount: u64,) * ``` * @param args Arugments to bytecode function. * * @example * A coin transfer function has three arugments "from", "to" and "amount". * ``` * public(script) fun transfer<CoinType>(from: &signer, to: address, amount: u64,) * ``` */ constructor( public readonly code: Bytes, public readonly ty_args: Seq<TypeTag>, public readonly args: Seq<TransactionArgument>, ) {} serialize(serializer: Serializer): void { serializer.serializeBytes(this.code); serializeVector<TypeTag>(this.ty_args, serializer); serializeVector<TransactionArgument>(this.args, serializer); } static deserialize(deserializer: Deserializer): Script { const code = deserializer.deserializeBytes(); const ty_args = deserializeVector(deserializer, TypeTag); const args = deserializeVector(deserializer, TransactionArgument); return new Script(code, ty_args, args); } } export class ScriptFunction { /** * Contains the payload to run a function within a module. * @param module_name Fullly qualified module name. ModuleId consists of account address and module name. * @param function_name The function to run. * @param ty_args Type arguments that move function requires. * * @example * A coin transfer function has one type argument "CoinType". * ``` * public(script) fun transfer<CoinType>(from: &signer, to: address, amount: u64,) * ``` * @param args Arugments to the move function. * * @example * A coin transfer function has three arugments "from", "to" and "amount". * ``` * public(script) fun transfer<CoinType>(from: &signer, to: address, amount: u64,) * ``` */ constructor( public readonly module_name: ModuleId, public readonly function_name: Identifier, public readonly ty_args: Seq<TypeTag>, public readonly args: Seq<Bytes>, ) {} /** * * @param module Fully qualified module name in format "AccountAddress::ModuleName" e.g. "0x1::Coin" * @param func Function name * @param ty_args Type arguments that move function requires. * * @example * A coin transfer function has one type argument "CoinType". * ``` * public(script) fun transfer<CoinType>(from: &signer, to: address, amount: u64,) * ``` * @param args Arugments to the move function. * * @example * A coin transfer function has three arugments "from", "to" and "amount". * ``` * public(script) fun transfer<CoinType>(from: &signer, to: address, amount: u64,) * ``` * @returns */ static natual(module: string, func: string, ty_args: Seq<TypeTag>, args: Seq<Bytes>): ScriptFunction { return new ScriptFunction(ModuleId.fromStr(module), new Identifier(func), ty_args, args); } serialize(serializer: Serializer): void { this.module_name.serialize(serializer); this.function_name.serialize(serializer); serializeVector<TypeTag>(this.ty_args, serializer); serializer.serializeU32AsUleb128(this.args.length); this.args.forEach((item: Bytes) => { serializer.serializeBytes(item); }); } static deserialize(deserializer: Deserializer): ScriptFunction { const module_name = ModuleId.deserialize(deserializer); const function_name = Identifier.deserialize(deserializer); const ty_args = deserializeVector(deserializer, TypeTag); const length = deserializer.deserializeUleb128AsU32(); const list: Seq<Bytes> = []; for (let i = 0; i < length; i += 1) { list.push(deserializer.deserializeBytes()); } const args = list; return new ScriptFunction(module_name, function_name, ty_args, args); } } export class Module { /** * Contains the bytecode of a Move module that can be published to the Aptos chain. * @param code Move bytecode of a module. */ constructor(public readonly code: Bytes) {} serialize(serializer: Serializer): void { serializer.serializeBytes(this.code); } static deserialize(deserializer: Deserializer): Module { const code = deserializer.deserializeBytes(); return new Module(code); } } export class ModuleBundle { /** * Contains a list of Modules that can be published together. * @param codes List of modules. */ constructor(public readonly codes: Seq<Module>) {} serialize(serializer: Serializer): void { serializeVector<Module>(this.codes, serializer); } static deserialize(deserializer: Deserializer): ModuleBundle { const codes = deserializeVector(deserializer, Module); return new ModuleBundle(codes); } } export class ModuleId { /** * Full name of a module. * @param address The account address. * @param name The name of the module under the account at "address". */ constructor(public readonly address: AccountAddress, public readonly name: Identifier) {} /** * Converts a string literal to a ModuleId * @param moduleId String literal in format "AcountAddress::ModuleName", * e.g. "0x01::Coin" * @returns */ static fromStr(moduleId: string): ModuleId { const parts = moduleId.split('::'); if (parts.length !== 2) { throw new Error('Invalid module id.'); } return new ModuleId(AccountAddress.fromHex(new HexString(parts[0])), new Identifier(parts[1])); } serialize(serializer: Serializer): void { this.address.serialize(serializer); this.name.serialize(serializer); } static deserialize(deserializer: Deserializer): ModuleId { const address = AccountAddress.deserialize(deserializer); const name = Identifier.deserialize(deserializer); return new ModuleId(address, name); } } export class ChangeSet { serialize(serializer: Serializer): void { throw new Error('Not implemented.'); } static deserialize(deserializer: Deserializer): ChangeSet { throw new Error('Not implemented.'); } } export class WriteSet { serialize(serializer: Serializer): void { throw new Error('Not implmented.'); } static deserialize(deserializer: Deserializer): WriteSet { throw new Error('Not implmented.'); } } export class SignedTransaction { /** * A SignedTransaction consists of a raw transaction and an authenticator. The authenticator * contains a client's public key and the signature of the raw transaction. * * @see {@link https://aptos.dev/guides/creating-a-signed-transaction/ | Creating a Signed Transaction} * * @param raw_txn * @param authenticator Contains a client's public key and the signature of the raw transaction. * Authenticator has 3 flavors: single signature, multi-signature and multi-agent. * @see authenticator.ts for details. */ constructor(public readonly raw_txn: RawTransaction, public readonly authenticator: TransactionAuthenticator) {} serialize(serializer: Serializer): void { this.raw_txn.serialize(serializer); this.authenticator.serialize(serializer); } static deserialize(deserializer: Deserializer): SignedTransaction { const raw_txn = RawTransaction.deserialize(deserializer); const authenticator = TransactionAuthenticator.deserialize(deserializer); return new SignedTransaction(raw_txn, authenticator); } } export abstract class TransactionPayload { abstract serialize(serializer: Serializer): void; static deserialize(deserializer: Deserializer): TransactionPayload { const index = deserializer.deserializeUleb128AsU32(); switch (index) { case 0: return TransactionPayloadWriteSet.load(deserializer); case 1: return TransactionPayloadScript.load(deserializer); case 2: return TransactionPayloadModuleBundle.load(deserializer); case 3: return TransactionPayloadScriptFunction.load(deserializer); default: throw new Error(`Unknown variant index for TransactionPayload: ${index}`); } } } export class TransactionPayloadWriteSet extends TransactionPayload { serialize(serializer: Serializer): void { throw new Error('Not implemented'); } static load(deserializer: Deserializer): TransactionPayloadWriteSet { throw new Error('Not implemented'); } } export class TransactionPayloadScript extends TransactionPayload { constructor(public readonly value: Script) { super(); } serialize(serializer: Serializer): void { serializer.serializeU32AsUleb128(1); this.value.serialize(serializer); } static load(deserializer: Deserializer): TransactionPayloadScript { const value = Script.deserialize(deserializer); return new TransactionPayloadScript(value); } } export class TransactionPayloadModuleBundle extends TransactionPayload { constructor(public readonly value: ModuleBundle) { super(); } serialize(serializer: Serializer): void { serializer.serializeU32AsUleb128(2); this.value.serialize(serializer); } static load(deserializer: Deserializer): TransactionPayloadModuleBundle { const value = ModuleBundle.deserialize(deserializer); return new TransactionPayloadModuleBundle(value); } } export class TransactionPayloadScriptFunction extends TransactionPayload { constructor(public readonly value: ScriptFunction) { super(); } serialize(serializer: Serializer): void { serializer.serializeU32AsUleb128(3); this.value.serialize(serializer); } static load(deserializer: Deserializer): TransactionPayloadScriptFunction { const value = ScriptFunction.deserialize(deserializer); return new TransactionPayloadScriptFunction(value); } } export class ChainId { constructor(public readonly value: Uint8) {} serialize(serializer: Serializer): void { serializer.serializeU8(this.value); } static deserialize(deserializer: Deserializer): ChainId { const value = deserializer.deserializeU8(); return new ChainId(value); } } export abstract class TransactionArgument { abstract serialize(serializer: Serializer): void; static deserialize(deserializer: Deserializer): TransactionArgument { const index = deserializer.deserializeUleb128AsU32(); switch (index) { case 0: return TransactionArgumentU8.load(deserializer); case 1: return TransactionArgumentU64.load(deserializer); case 2: return TransactionArgumentU128.load(deserializer); case 3: return TransactionArgumentAddress.load(deserializer); case 4: return TransactionArgumentU8Vector.load(deserializer); case 5: return TransactionArgumentBool.load(deserializer); default: throw new Error(`Unknown variant index for TransactionArgument: ${index}`); } } } export class TransactionArgumentU8 extends TransactionArgument { constructor(public readonly value: Uint8) { super(); } serialize(serializer: Serializer): void { serializer.serializeU32AsUleb128(0); serializer.serializeU8(this.value); } static load(deserializer: Deserializer): TransactionArgumentU8 { const value = deserializer.deserializeU8(); return new TransactionArgumentU8(value); } } export class TransactionArgumentU64 extends TransactionArgument { constructor(public readonly value: Uint64) { super(); } serialize(serializer: Serializer): void { serializer.serializeU32AsUleb128(1); serializer.serializeU64(this.value); } static load(deserializer: Deserializer): TransactionArgumentU64 { const value = deserializer.deserializeU64(); return new TransactionArgumentU64(value); } } export class TransactionArgumentU128 extends TransactionArgument { constructor(public readonly value: Uint128) { super(); } serialize(serializer: Serializer): void { serializer.serializeU32AsUleb128(2); serializer.serializeU128(this.value); } static load(deserializer: Deserializer): TransactionArgumentU128 { const value = deserializer.deserializeU128(); return new TransactionArgumentU128(value); } } export class TransactionArgumentAddress extends TransactionArgument { constructor(public readonly value: AccountAddress) { super(); } serialize(serializer: Serializer): void { serializer.serializeU32AsUleb128(3); this.value.serialize(serializer); } static load(deserializer: Deserializer): TransactionArgumentAddress { const value = AccountAddress.deserialize(deserializer); return new TransactionArgumentAddress(value); } } export class TransactionArgumentU8Vector extends TransactionArgument { constructor(public readonly value: Bytes) { super(); } serialize(serializer: Serializer): void { serializer.serializeU32AsUleb128(4); serializer.serializeBytes(this.value); } static load(deserializer: Deserializer): TransactionArgumentU8Vector { const value = deserializer.deserializeBytes(); return new TransactionArgumentU8Vector(value); } } export class TransactionArgumentBool extends TransactionArgument { constructor(public readonly value: boolean) { super(); } serialize(serializer: Serializer): void { serializer.serializeU32AsUleb128(5); serializer.serializeBool(this.value); } static load(deserializer: Deserializer): TransactionArgumentBool { const value = deserializer.deserializeBool(); return new TransactionArgumentBool(value); } }
the_stack
import ScriptWidget = require("ui/ScriptWidget"); import EditorUI = require("ui/EditorUI"); import TextureSelector = require("./TextureSelector"); var techniqueSource = new Atomic.UIMenuItemSource(); var solidSource = new Atomic.UIMenuItemSource(); solidSource.addItem(new Atomic.UIMenuItem("Diffuse", "Diffuse")); solidSource.addItem(new Atomic.UIMenuItem("Diffuse Emissive", "Diffuse Emissive")); solidSource.addItem(new Atomic.UIMenuItem("Diffuse Normal", "Diffuse Normal")); solidSource.addItem(new Atomic.UIMenuItem("Diffuse Specular", "Diffuse Specular")); solidSource.addItem(new Atomic.UIMenuItem("Diffuse Normal Specular", "Diffuse Normal Specular")); solidSource.addItem(new Atomic.UIMenuItem("Diffuse Unlit", "Diffuse Unlit")); solidSource.addItem(new Atomic.UIMenuItem("No Texture", "No Texture")); var tranSource = new Atomic.UIMenuItemSource(); tranSource.addItem(new Atomic.UIMenuItem("Alpha", "Alpha")); tranSource.addItem(new Atomic.UIMenuItem("Alpha Mask", "Alpha Mask")); tranSource.addItem(new Atomic.UIMenuItem("Additive", "Additive")); tranSource.addItem(new Atomic.UIMenuItem("Additive Alpha", "Additive Alpha")); tranSource.addItem(new Atomic.UIMenuItem("Emissive Alpha", "Emissive Alpha")); tranSource.addItem(new Atomic.UIMenuItem("Alpha AO", "Alpha AO")); tranSource.addItem(new Atomic.UIMenuItem("Alpha Mask AO", "Alpha Mask AO")); var lightmapSource = new Atomic.UIMenuItemSource(); lightmapSource.addItem(new Atomic.UIMenuItem("Lightmap", "Lightmap")); lightmapSource.addItem(new Atomic.UIMenuItem("Lightmap Alpha", "Lightmap Alpha")); var projectSource = new Atomic.UIMenuItemSource(); var _ = new Atomic.UIMenuItem(); var techniqueLookup = { "Techniques/Diff.xml": "Diffuse", "Techniques/DiffEmissive.xml": "Diffuse Emissive", "Techniques/DiffNormal.xml": "Diffuse Normal", "Techniques/DiffSpec.xml": "Diffuse Specular", "Techniques/DiffNormalSpec.xml": "Diffuse Normal Specular", "Techniques/DiffUnlit.xml": "Diffuse Unlit", "Techniques/DiffAlpha.xml": "Alpha", "Techniques/DiffAlphaMask.xml": "Alpha Mask", "Techniques/DiffAdd.xml": "Additive", "Techniques/NoTexture.xml": "No Texture", "Techniques/DiffLightMap.xml": "Lightmap", "Techniques/DiffLightMapAlpha.xml": "Lightmap Alpha" }; var techniqueReverseLookup = {}; var projectTechniques = {}; var projectTechniquesAddress = {}; for (var key in techniqueLookup) { techniqueReverseLookup[techniqueLookup[key]] = key; } class MaterialInspector extends ScriptWidget { currentTexture: Atomic.UITextureWidget = null; tunit: number; textureWidget: Atomic.UITextureWidget; constructor() { super(); this.fd.id = "Vera"; this.fd.size = 11; this.subscribeToEvent(ToolCore.ResourceAddedEvent((ev: ToolCore.ResourceAddedEvent) => this.refreshTechniquesPopup())); } createShaderParametersSection(): Atomic.UISection { var section = new Atomic.UISection(); section.text = "Shader Paramaters"; section.value = 1; section.fontDescription = this.fd; var attrsVerticalLayout = new Atomic.UILayout(Atomic.UI_AXIS.UI_AXIS_Y); attrsVerticalLayout.spacing = 3; attrsVerticalLayout.layoutPosition = Atomic.UI_LAYOUT_POSITION.UI_LAYOUT_POSITION_LEFT_TOP; attrsVerticalLayout.layoutSize = Atomic.UI_LAYOUT_SIZE.UI_LAYOUT_SIZE_AVAILABLE; section.contentRoot.addChild(attrsVerticalLayout); var params = this.material.getShaderParameters(); for (var i in params) { var attrLayout = new Atomic.UILayout(); attrLayout.layoutDistribution = Atomic.UI_LAYOUT_DISTRIBUTION.UI_LAYOUT_DISTRIBUTION_GRAVITY; var name = new Atomic.UITextField(); name.textAlign = Atomic.UI_TEXT_ALIGN.UI_TEXT_ALIGN_LEFT; name.skinBg = "InspectorTextAttrName"; name.text = params[i].name; name.fontDescription = this.fd; attrLayout.addChild(name); var field = new Atomic.UIEditField(); field.textAlign = Atomic.UI_TEXT_ALIGN.UI_TEXT_ALIGN_LEFT; field.skinBg = "TBAttrEditorField"; field.fontDescription = this.fd; var lp = new Atomic.UILayoutParams(); lp.width = 140; field.layoutParams = lp; field.id = params[i].name; field.text = params[i].valueString; field.subscribeToEvent(field, Atomic.UIWidgetEvent(function (ev: Atomic.UIWidgetEvent) { if (ev.type == Atomic.UI_EVENT_TYPE.UI_EVENT_TYPE_CHANGED) { var field = <Atomic.UIEditField>ev.target; this.material.setShaderParameter(field.id, field.text); } }.bind(this))); attrLayout.addChild(field); attrsVerticalLayout.addChild(attrLayout); // print(params[i].name, " : ", params[i].value, " : ", params[i].type); } return section; } getTextureThumbnail(texture: Atomic.Texture): Atomic.Texture { if (!texture) return null; var db = ToolCore.getAssetDatabase(); var asset = db.getAssetByPath(texture.name); if (!asset) return texture; var thumbnail = asset.cachePath + "_thumbnail.png"; var cache = Atomic.getResourceCache(); var thumb = <Atomic.Texture2D>cache.getTempResource("Texture2D", thumbnail); if (thumb) return thumb; return texture; } onTechniqueSet(techniqueName: string) { this.techniqueButton.text = techniqueName; var cache = Atomic.getResourceCache(); var technique = <Atomic.Technique>cache.getResource("Technique", techniqueReverseLookup[techniqueName]); var resourcePath = ToolCore.toolSystem.project.getResourcePath(); if (technique == null) { var techniquePath = ""; for (var i in projectTechniques) { if (techniqueName == projectTechniques[i]) { techniquePath = projectTechniquesAddress[i]; break; } } techniquePath = techniquePath.replace(resourcePath, ""); technique = <Atomic.Technique>cache.getResource("Technique", techniquePath); } this.material.setTechnique(0, technique); } createTechniquePopup(): Atomic.UIWidget { this.refreshTechniquesPopup(); var button = this.techniqueButton = new Atomic.UIButton(); var technique = this.material.getTechnique(0); var techniqueName = ""; if (technique != null) { techniqueName = technique.name.replace("Techniques/", "").replace(".xml", ""); } else { techniqueName = "UNDEFINED"; } button.text = techniqueName; button.fontDescription = this.fd; var lp = new Atomic.UILayoutParams(); lp.width = 140; button.layoutParams = lp; button.onClick = function () { var menu = new Atomic.UIMenuWindow(button, "technique popup"); menu.fontDescription = this.fd; menu.show(techniqueSource); button.subscribeToEvent(button, Atomic.UIWidgetEvent(function (ev: Atomic.UIWidgetEvent) { if (ev.type != Atomic.UI_EVENT_TYPE.UI_EVENT_TYPE_CLICK) return; if (ev.target && ev.target.id == "technique popup") { this.onTechniqueSet(ev.refid); } }.bind(this))); }.bind(this); return button; } acceptAssetDrag(importerTypeName: string, ev: Atomic.DragEndedEvent): ToolCore.AssetImporter { var dragObject = ev.dragObject; if (dragObject.object && dragObject.object.typeName == "Asset") { var asset = <ToolCore.Asset>dragObject.object; if (asset.importerTypeName == importerTypeName) { return asset.importer; } } return null; } openTextureSelectionBox(textureUnit: number, textureWidget: Atomic.UITextureWidget) { EditorUI.getModelOps().showResourceSelection("Select Texture", "TextureImporter", "Texture2D", function (asset: ToolCore.Asset, args: any) { if (asset == null) { this.createTextureRemoveButtonCallback(this.tunit, this.textureWidget); return; } var texture = <Atomic.Texture2D>Atomic.cache.getResource("Texture2D", asset.path); if (texture) { this.material.setTexture(textureUnit, texture); textureWidget.texture = this.getTextureThumbnail(texture); } }.bind(this)); } // Big Texture Button(referenced texture file path in project frame) createTextureButtonCallback(textureUnit: number, textureWidget: Atomic.UITextureWidget) { return () => { var texture = this.material.getTexture(textureUnit); if (textureWidget.getTexture() != null) { this.sendEvent(Editor.InspectorProjectReferenceEventData({ "path": texture.getName() })); } else { this.openTextureSelectionBox(textureUnit, textureWidget); } return true; }; } // Small Texture Button (Opens texture selection window) createTextureReferenceButtonCallback(textureUnit: number, textureWidget: Atomic.UITextureWidget) { return () => { this.tunit = textureUnit; this.textureWidget = textureWidget; this.openTextureSelectionBox(textureUnit, textureWidget); return true; }; } //Remove Texture Button createTextureRemoveButtonCallback(textureUnit: number, textureWidget: Atomic.UITextureWidget) { var texture = this.material.getTexture(textureUnit); if (texture != null && textureWidget != null) { textureWidget.setTexture(null); this.material.setTexture(textureUnit, null); } } createTextureSection(): Atomic.UISection { var section = new Atomic.UISection(); section.text = "Textures"; section.value = 1; section.fontDescription = this.fd; var attrsVerticalLayout = new Atomic.UILayout(Atomic.UI_AXIS.UI_AXIS_Y); attrsVerticalLayout.spacing = 3; attrsVerticalLayout.layoutPosition = Atomic.UI_LAYOUT_POSITION.UI_LAYOUT_POSITION_LEFT_TOP; attrsVerticalLayout.layoutSize = Atomic.UI_LAYOUT_SIZE.UI_LAYOUT_SIZE_AVAILABLE; section.contentRoot.addChild(attrsVerticalLayout); // TODO: Filter on technique var textureUnits = [Atomic.TextureUnit.TU_DIFFUSE, Atomic.TextureUnit.TU_NORMAL, Atomic.TextureUnit.TU_SPECULAR, Atomic.TextureUnit.TU_EMISSIVE]; for (var i in textureUnits) { var tunit: Atomic.TextureUnit = textureUnits[i]; var tunitName = Atomic.Material.getTextureUnitName(tunit); var attrLayout = new Atomic.UILayout(); attrLayout.layoutDistribution = Atomic.UI_LAYOUT_DISTRIBUTION.UI_LAYOUT_DISTRIBUTION_GRAVITY; var name = new Atomic.UITextField(); name.textAlign = Atomic.UI_TEXT_ALIGN.UI_TEXT_ALIGN_LEFT; name.skinBg = "InspectorTextAttrName"; name.text = tunitName; name.fontDescription = this.fd; attrLayout.addChild(name); var textureWidget = new Atomic.UITextureWidget(); var tlp = new Atomic.UILayoutParams(); tlp.width = 64; tlp.height = 64; textureWidget.layoutParams = tlp; textureWidget.texture = this.getTextureThumbnail(this.material.getTexture(tunit)); var textureButton = new Atomic.UIButton(); textureButton.skinBg = "TBButton.flatoutline"; textureButton["tunit"] = tunit; textureButton["textureWidget"] = textureWidget; //Create drop-down buttons to open Texture Selection Dialog Box var textureRefButton = new Atomic.UIButton(); textureRefButton.skinBg = "arrow.down"; textureRefButton["tunit"] = tunit; textureRefButton["textureWidget"] = textureWidget; textureButton.onClick = this.createTextureButtonCallback(tunit, textureWidget); textureRefButton.onClick = this.createTextureReferenceButtonCallback(tunit, textureWidget); textureButton.contentRoot.addChild(textureWidget); attrLayout.addChild(textureButton); attrLayout.addChild(textureRefButton); attrsVerticalLayout.addChild(attrLayout); // handle dropping of texture on widget textureButton.subscribeToEvent(textureButton, Atomic.DragEndedEvent((ev: Atomic.DragEndedEvent) => { var importer = this.acceptAssetDrag("TextureImporter", ev); if (importer) { var textureImporter = <ToolCore.TextureImporter>importer; var asset = textureImporter.asset; var texture = <Atomic.Texture2D>Atomic.cache.getResource("Texture2D", asset.path); if (texture) { this.material.setTexture(ev.target["tunit"], texture); (<Atomic.UITextureWidget>ev.target["textureWidget"]).texture = this.getTextureThumbnail(texture); // note, ButtonID has been commented out because it doesn't appear to be used anywhere this.sendEvent(Editor.InspectorProjectReferenceEventData({ "path": texture.getName() /* "ButtonID": texture.getName() */ })); } } })); } return section; } loadProjectTechniques(directory: string, menuItem: Atomic.UIMenuItemSource) { var resourcePath = ToolCore.toolSystem.project.getResourcePath(); var TechniqueAssets = ToolCore.getAssetDatabase().getFolderAssets(directory); for (var i = 0; i < TechniqueAssets.length; i++) { var asset = TechniqueAssets[i]; if (TechniqueAssets[i].isFolder()) { if (this.scanDirectoryForTechniques(asset.path)) { var subfoldersource = new Atomic.UIMenuItemSource(); _ = new Atomic.UIMenuItem(TechniqueAssets[i].name); _.subSource = subfoldersource; menuItem.addItem(_); this.loadProjectTechniques(asset.path, subfoldersource); } } else { projectTechniques[i] = TechniqueAssets[i].name; projectTechniquesAddress[i] = TechniqueAssets[i].path; menuItem.addItem(new Atomic.UIMenuItem(projectTechniques[i], projectTechniques[i])); } } } scanDirectoryForTechniques(directory: string): boolean { var techniqueAssets = ToolCore.getAssetDatabase().getFolderAssets(directory); for (var i = 0; i < techniqueAssets.length; i++) { var asset = techniqueAssets[i]; if (techniqueAssets[i].isFolder()) { if (this.scanDirectoryForTechniques(asset.path)) { return true; } } else if (techniqueAssets[i].getExtension() == ".xml") { return true; } } return false; } refreshTechniquesPopup() { techniqueSource.clear(); _ = new Atomic.UIMenuItem("Solid"); _.subSource = solidSource; techniqueSource.addItem(_); _ = new Atomic.UIMenuItem("Transparency"); _.subSource = tranSource; techniqueSource.addItem(_); _ = new Atomic.UIMenuItem("Lightmap"); _.subSource = lightmapSource; techniqueSource.addItem(_); var projectTechniquesPath = ToolCore.toolSystem.project.getResourcePath() + "Techniques"; if (Atomic.fileSystem.dirExists(projectTechniquesPath)) { if (this.scanDirectoryForTechniques(projectTechniquesPath)) { projectSource.clear(); _ = new Atomic.UIMenuItem("Project"); _.subSource = projectSource; techniqueSource.addItem(_); this.loadProjectTechniques(projectTechniquesPath, projectSource); } } } inspect(asset: ToolCore.Asset, material: Atomic.Material) { // Add folders to resource directory this.asset = asset; this.material = material; var mlp = new Atomic.UILayoutParams(); mlp.width = 310; var materialLayout = new Atomic.UILayout(); materialLayout.spacing = 4; materialLayout.layoutDistribution = Atomic.UI_LAYOUT_DISTRIBUTION.UI_LAYOUT_DISTRIBUTION_GRAVITY; materialLayout.layoutPosition = Atomic.UI_LAYOUT_POSITION.UI_LAYOUT_POSITION_LEFT_TOP; materialLayout.layoutParams = mlp; materialLayout.axis = Atomic.UI_AXIS.UI_AXIS_Y; // node attr layout var materialSection = new Atomic.UISection(); materialSection.text = "Material"; materialSection.value = 1; materialSection.fontDescription = this.fd; materialLayout.addChild(materialSection); var attrsVerticalLayout = new Atomic.UILayout(Atomic.UI_AXIS.UI_AXIS_Y); attrsVerticalLayout.spacing = 3; attrsVerticalLayout.layoutPosition = Atomic.UI_LAYOUT_POSITION.UI_LAYOUT_POSITION_LEFT_TOP; attrsVerticalLayout.layoutSize = Atomic.UI_LAYOUT_SIZE.UI_LAYOUT_SIZE_PREFERRED; // NAME var nameLayout = new Atomic.UILayout(); nameLayout.layoutDistribution = Atomic.UI_LAYOUT_DISTRIBUTION.UI_LAYOUT_DISTRIBUTION_GRAVITY; var name = new Atomic.UITextField(); name.textAlign = Atomic.UI_TEXT_ALIGN.UI_TEXT_ALIGN_LEFT; name.skinBg = "InspectorTextAttrName"; name.text = "Name"; name.fontDescription = this.fd; nameLayout.addChild(name); var field = new Atomic.UIEditField(); field.textAlign = Atomic.UI_TEXT_ALIGN.UI_TEXT_ALIGN_LEFT; field.skinBg = "TBAttrEditorField"; field.fontDescription = this.fd; var lp = new Atomic.UILayoutParams(); lp.width = 160; field.layoutParams = lp; field.text = Atomic.splitPath(material.name).fileName; nameLayout.addChild(field); attrsVerticalLayout.addChild(nameLayout); // TECHNIQUE LAYOUT var techniqueLayout = new Atomic.UILayout(); techniqueLayout.layoutSize = Atomic.UI_LAYOUT_SIZE.UI_LAYOUT_SIZE_GRAVITY; techniqueLayout.layoutDistribution = Atomic.UI_LAYOUT_DISTRIBUTION.UI_LAYOUT_DISTRIBUTION_PREFERRED; name = new Atomic.UITextField(); name.textAlign = Atomic.UI_TEXT_ALIGN.UI_TEXT_ALIGN_LEFT; name.skinBg = "InspectorTextAttrName"; name.text = "Technique"; name.fontDescription = this.fd; techniqueLayout.addChild(name); var techniquePopup = this.createTechniquePopup(); techniqueLayout.addChild(techniquePopup); attrsVerticalLayout.addChild(techniqueLayout); materialSection.contentRoot.addChild(attrsVerticalLayout); materialLayout.addChild(this.createTextureSection()); materialLayout.addChild(this.createShaderParametersSection()); var button = new Atomic.UIButton(); button.fontDescription = this.fd; button.gravity = Atomic.UI_GRAVITY.UI_GRAVITY_RIGHT; button.text = "Save"; button.onClick = function () { var importer = <ToolCore.MaterialImporter>this.asset.getImporter(); importer.saveMaterial(); }.bind(this); materialLayout.addChild(button); this.addChild(materialLayout); } techniqueButton: Atomic.UIButton; material: Atomic.Material; asset: ToolCore.Asset; nameTextField: Atomic.UITextField; fd: Atomic.UIFontDescription = new Atomic.UIFontDescription(); } export = MaterialInspector;
the_stack
import { Component, OnInit, Inject, OnDestroy, ViewChild, ViewEncapsulation } from '@angular/core'; import { Subject, Observable } from 'rxjs'; import { BpmnProperty, AmaState, selectProcessTaskAssignmentFor, selectSelectedProcess, UpdateServiceAssignmentAction, TaskAssignment, AssignmentType, AssignmentMode, ValidationResponse, Process, CodeValidatorService, selectProcessPropertiesArrayFor, CodeEditorComponent } from '@alfresco-dbp/modeling-shared/sdk'; import { COMMA, ENTER } from '@angular/cdk/keycodes'; import { IdentityUserModel, IdentityGroupModel } from '@alfresco/adf-core'; import { Store } from '@ngrx/store'; import { filter, take, takeUntil } from 'rxjs/operators'; import { AbstractControl, FormGroup, FormBuilder, Validators, FormControl, ValidatorFn, ValidationErrors } from '@angular/forms'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { MatTabChangeEvent } from '@angular/material/tabs'; import { MatSelectChange } from '@angular/material/select'; export interface AssignmentSettings { assignee: string[]; candidateUsers: string[]; candidateGroups: string[]; assignmentUpdate$?: Subject<any>; shapeId?: string; processId?: string; } export interface AssignmentParams { label: string; key: any; value?: string; } export enum AssignmentTabs { STATIC = 0, IDENTITY = 1, EXPRESSION = 2 } export interface AssignmentModel { assignments: AssignmentParams[]; } export enum AssigneeExpressionErrorMessages { assigneePattern = 'PROCESS_EDITOR.ELEMENT_PROPERTIES.TASK_ASSIGNMENT.EXPRESSION.ASSIGNEE_INVALID_ERROR', assigneeEmpty = 'PROCESS_EDITOR.ELEMENT_PROPERTIES.TASK_ASSIGNMENT.EXPRESSION.ASSIGNEE_EMPTY', candidatePattern = 'PROCESS_EDITOR.ELEMENT_PROPERTIES.TASK_ASSIGNMENT.EXPRESSION.CANDIDATE_INVALID_ERROR', candidateEmpty = 'PROCESS_EDITOR.ELEMENT_PROPERTIES.TASK_ASSIGNMENT.EXPRESSION.CANDIDATE_EMPTY' } export const identityCandidateValidator: ValidatorFn = (candidateFormGroup: FormGroup): ValidationErrors | null => { const isCandidateFormGroupDirtyTouched = candidateFormGroup.dirty && candidateFormGroup.touched; const candidateUserFormGroup = candidateFormGroup.get('candidateUserFormGroup'); const candidateUsersChips = candidateUserFormGroup.get('candidateUsersChips'); const candidateGroupsFormGroup = candidateFormGroup.get('candidateGroupFormGroup'); const candidateGroupsChips = candidateGroupsFormGroup.get('candidateGroupsChips'); const isCandidateUserChipsEmpty = isCandidateFormGroupDirtyTouched && candidateUsersChips ? candidateUsersChips.value === null || candidateUsersChips.value === '' : false; const isCandidateGroupChipsEmpty = isCandidateFormGroupDirtyTouched && candidateGroupsChips ? candidateGroupsChips.value === null || candidateGroupsChips.value === '' : false; const hasValidationError = isCandidateUserChipsEmpty && isCandidateGroupChipsEmpty; return hasValidationError ? { 'custom': true } : null; }; @Component({ selector: 'ama-assignment-dialog', templateUrl: './assignment-dialog.component.html', styleUrls: ['./assignment-dialog.component.scss'], encapsulation: ViewEncapsulation.None }) export class AssignmentDialogComponent implements OnInit, OnDestroy { static ASSIGNEE_CONTENT = JSON.stringify({ assignee: '${}' }, null, '\t'); static CANDIDATES_CONTENT = JSON.stringify({ candidateUsers: '${}', candidateGroups: '${}' }, null, '\t'); static TABS = [ AssignmentType.static, AssignmentType.identity, AssignmentType.expression ]; assignmentTypes = [ { key: AssignmentMode.assignee, label: 'PROCESS_EDITOR.ELEMENT_PROPERTIES.TASK_ASSIGNMENT.SINGLE_USER' }, { key: AssignmentMode.candidates, label: 'PROCESS_EDITOR.ELEMENT_PROPERTIES.TASK_ASSIGNMENT.CANDIDATES' } ]; @ViewChild('editor') editor: CodeEditorComponent; roles = ['ACTIVITI_USER']; selectedMode: string = AssignmentMode.assignee; selectedType: string = AssignmentType.static; currentActiveTab = AssignmentTabs.STATIC; separatorKeysCodes: number[] = [ENTER, COMMA]; staticAssignee: string; staticCandidateUsers: string[] = []; staticCandidateGroups: string[] = []; identityAssignee: IdentityUserModel[] = []; identityCandidateUsers: IdentityUserModel[] = []; identityCandidateGroups: IdentityGroupModel[] = []; loadingForm = true; expressionAssignee: string; expressionCandidateUsers: string; expressionCandidateGroups: string; expressionContent = AssignmentDialogComponent.ASSIGNEE_CONTENT; assignmentPayload: any; assignmentXML: TaskAssignment; processVariables$: Observable<any>; process$: Observable<Process>; onDestroy$: Subject<void> = new Subject<void>(); assignmentForm: FormGroup; expressionErrorMessage: string; expressionSuggestions = [ { name: 'initiator', type: 'string' }, { name: 'assignee', type: 'string' } ]; constructor( private store: Store<AmaState>, private codeValidatorService: CodeValidatorService, public dialogRef: MatDialogRef<AssignmentDialogComponent>, private formBuilder: FormBuilder, @Inject(MAT_DIALOG_DATA) public settings: AssignmentSettings) { } ngOnInit() { this.store .select(selectProcessTaskAssignmentFor(this.settings.processId, this.settings.shapeId)) .pipe(takeUntil(this.onDestroy$)) .subscribe(assignmentType => { this.assignmentXML = <any> assignmentType; }); this.process$ = this.store.select(selectSelectedProcess); this.processVariables$ = this.store.select(selectProcessPropertiesArrayFor(this.settings.processId)); this.deductConfigFromXML(); this.createAssignmentForm(); } createAssignmentForm() { this.assignmentForm = this.formBuilder.group({ staticForm: this.formBuilder.group({}), identityForm: this.formBuilder.group({}), expressionForm: this.formBuilder.group({}) }); this.createChildrenFormControls(); this.loadingForm = false; } private deductConfigFromXML() { this.selectedType = this.assignmentXML && this.assignmentXML.type ? this.assignmentXML.type : AssignmentType.static; this.selectedMode = this.assignmentXML && this.assignmentXML.assignment ? this.assignmentXML.assignment : AssignmentMode.assignee; this.selectActiveTab(); } private selectActiveTab() { if (this.isXMLStaticType()) { this.currentActiveTab = AssignmentTabs.STATIC; this.setStaticAssignments(); } else if (this.isXMLIdentityType()) { this.currentActiveTab = AssignmentTabs.IDENTITY; this.setIdentityAssignments(); } else if (this.isXMLExpressionType()) { this.currentActiveTab = AssignmentTabs.EXPRESSION; this.setExpressionAssignments(); } else { this.currentActiveTab = AssignmentTabs.STATIC; } } private createChildrenFormControls () { this.assignmentFormClean(); if (this.isIdentityType()) { this.createIdentityForm(); } else if (this.isStaticType()) { this.createStaticForm(); } else { this.createExpressionForm(); } this.assignmentForm.updateValueAndValidity(); } private createStaticForm() { this.createAssigneeCandidateForm(this.staticForm, this.staticAssignee); } private createIdentityForm() { this.createAssigneeCandidateForm(this.identityForm); } private createExpressionForm(): void { if (this.isAssigneeMode()) { this.expressionForm.addControl('assignee', new FormControl({ value: '' })); } else { this.expressionForm.addControl('candidateUsers', new FormControl({ value: '' })); this.expressionForm.addControl('candidateGroups', new FormControl({ value: '' })); } this.expressionForm.updateValueAndValidity(); } private createAssigneeCandidateForm(formGroup: FormGroup, assigneeValue?: string): void { if (this.isAssigneeMode()) { const assignee = new FormControl({ value: '', disabled: false }); const assigneeChipsFormControl = new FormControl({ value: assigneeValue, disabled: false }, [Validators.required]); formGroup.addControl('assignee', assignee); formGroup.addControl('assigneeChips', assigneeChipsFormControl); } else { const candidatesFormGroup = this.createCandidatesFormGroup(); formGroup.addControl('candidatesFormGroup', candidatesFormGroup); this.setCandidateGroupWarning(); } formGroup.updateValueAndValidity(); } private setCandidateGroupWarning() { if (this.isCandidateGroupAssigned || this.isCandidateUserAssigned) { this.candidateGroupsChipsStaticControl.setErrors({ 'custom': null }); } else if (this.candidatesStaticFormGroup) { this.candidateGroupChipsStaticCtrlValue(''); } } private createCandidatesFormGroup(): FormGroup { const candidateUserFormGroup = this.createCandidateUserFormGroup(); const candidateGroupFormGroup = this.createCandidateGroupFormGroup(); return this.formBuilder.group( { 'candidateUserFormGroup': candidateUserFormGroup, 'candidateGroupFormGroup': candidateGroupFormGroup }, { validator: identityCandidateValidator }); } private createCandidateUserFormGroup(): FormGroup { return this.formBuilder.group( { 'candidateUsers': '', 'candidateUsersChips': '' }); } private createCandidateGroupFormGroup(): FormGroup { return this.formBuilder.group( { 'candidateGroups': '', 'candidateGroupsChips': '' }); } private setStaticAssignments() { if (this.isXMLSingleMode()) { if (this.settings.assignee) { this.staticAssignee = this.settings.assignee ? this.settings.assignee[0] : ''; } } else { if (this.settings.candidateUsers) { this.staticCandidateUsers = this.settings.candidateUsers; } if (this.settings.candidateGroups) { this.staticCandidateGroups = this.settings.candidateGroups; } } } private setIdentityAssignments() { if (this.isXMLSingleMode()) { if ( this.settings.assignee && !this.isExpressionValid(this.settings.assignee.join()) ) { this.identityAssignee = this.settings.assignee.map(user => ({ username: user })); } } else { if ( this.settings.candidateUsers && !this.isExpressionValid(this.settings.candidateUsers.join()) ) { this.identityCandidateUsers = this.settings.candidateUsers.map( (username: string) => ({ username: username }) ); } if ( this.settings.candidateGroups && !this.isExpressionValid(this.settings.candidateGroups.join()) ) { this.identityCandidateGroups = this.settings.candidateGroups.map( groupName => ({ name: groupName }) ); } } } private setExpressionAssignments() { if (this.isXMLSingleMode()) { if (this.isExpressionValid(this.settings.assignee.join())) { this.expressionContent = JSON.stringify({ assignee: this.settings.assignee[0] }, null, '\t'); } else { this.expressionContent = AssignmentDialogComponent.ASSIGNEE_CONTENT; } } else { if ( this.isExpressionValid( this.settings.candidateGroups.join() || this.settings.candidateUsers.join() ) ) { this.expressionContent = JSON.stringify({ candidateUsers: this.settings.candidateUsers && this.settings.candidateUsers.length > 0 ? this.settings.candidateUsers.toString() : '${}', candidateGroups: this.settings.candidateGroups && this.settings.candidateGroups.length > 0 ? this.settings.candidateGroups.toString() : '${}' }, null, '\t'); } else { this.expressionContent = AssignmentDialogComponent.CANDIDATES_CONTENT; } } } onTabChange(currentTab: MatTabChangeEvent) { this.selectedType = AssignmentDialogComponent.TABS[currentTab.index]; this.resetProperties(); this.assignmentPayload = undefined; if (this.isOriginalSelection()) { this.restoreFromXML(); } this.createChildrenFormControls(); this.currentActiveTab = currentTab.index; } onSelect(selectedType: MatSelectChange) { this.selectedMode = selectedType.value; this.resetProperties(); this.assignmentPayload = undefined; if (this.isOriginalSelection()) { this.restoreFromXML(); } this.createChildrenFormControls(); } isOriginalSelection() { return this.selectedMode === this.assignmentXML.assignment && this.selectedType === this.assignmentXML.type; } onStaticAssigneeRemove() { this.staticAssignee = undefined; this.updatePayloadWithStaticValues(); this.assigneeChipsStaticCtrlValue(''); } onStaticCandidateUsersRemove(username: string) { this.staticCandidateUsers = this.staticCandidateUsers.filter( user => user !== username ); this.updatePayloadWithStaticValues(); if (this.staticCandidateUsers.length === 0) { this.candidateUserChipsStaticCtrlValue(''); } else { this.candidateUserChipsStaticCtrlValue(this.staticCandidateUsers[0]); } } onStaticCandidateGroupsRemove(groupName: string) { this.staticCandidateGroups = this.staticCandidateGroups.filter( group => group !== groupName ); this.updatePayloadWithStaticValues(); if (this.staticCandidateGroups.length === 0) { this.candidateGroupChipsStaticCtrlValue(''); } else { this.candidateGroupChipsStaticCtrlValue(this.staticCandidateGroups[0]); } } onStaticAssigneeChange(event: any) { const input = event.input; if (input.value) { this.staticAssignee = input.value; input.value = ''; this.updatePayloadWithStaticValues(); this.assigneeChipsStaticCtrlValue(this.staticAssignee); } } onStaticCandidateUsersChange(event: any) { const input = event.input; if (input.value && !this.isStaticCandidateUserExists(input.value)) { this.staticCandidateUsers.push(input.value); this.candidateUserChipsStaticCtrlValue(input.value); input.value = ''; this.updatePayloadWithStaticValues(); } } onStaticCandidateGroupsChange(event: any) { const input = event.input; if (input.value && !this.isStaticCandidateGroupExists(input.value)) { this.staticCandidateGroups.push(input.value); this.candidateGroupChipsStaticCtrlValue(input.value); input.value = ''; this.updatePayloadWithStaticValues(); } } private isStaticCandidateUserExists(value: string): string { return this.staticCandidateUsers.find((userName: string) => userName.trim() === value.trim()); } private isStaticCandidateGroupExists(value: string): string { return this.staticCandidateGroups.find((groupName: string) => groupName.trim() === value.trim()); } onIdentityAssigneeChange(assignee: IdentityUserModel[]) { this.identityAssignee = [...assignee]; this.updatePayloadWithIdentityValues(); } onIdentityCandidateUsersChange(candidateUsers: IdentityUserModel[]) { this.identityCandidateUsers = [...candidateUsers]; this.updatePayloadWithIdentityValues(); } onIdentityCandidateGroupsChange(candidateGroups: IdentityGroupModel[]) { this.identityCandidateGroups = [...candidateGroups]; this.updatePayloadWithIdentityValues(); } private validate(contentString: string): boolean { const validateResponse: ValidationResponse<any> = this.codeValidatorService.validateJson<any>(contentString); return validateResponse.valid; } onExpressionChange(contentString: string) { if (this.validate(contentString)) { if (this.isAssigneeMode()) { const assignee = JSON.parse(contentString); if (this.isAssigneeValid(assignee) && this.isExpressionValid(assignee.assignee)) { this.expressionAssignee = this.isExpressionValid(assignee.assignee) ? assignee.assignee : undefined; this.assigneeExpressionCtrlValue(this.expressionAssignee); } else { if (assignee.assignee === '') { this.expressionErrorMessage = AssigneeExpressionErrorMessages.assigneeEmpty; this.expressionForm.setErrors({ pattern: 'true'}); } else { this.expressionErrorMessage = AssigneeExpressionErrorMessages.assigneePattern; this.expressionForm.setErrors({ pattern: 'true' }); } } } else { const candidates = JSON.parse(contentString); if (this.isCandidatesPresentAndExpressionValid(candidates)) { this.expressionCandidateUsers = this.isExpressionValid(candidates.candidateUsers) ? candidates.candidateUsers : undefined; this.expressionCandidateGroups = this.isExpressionValid(candidates.candidateGroups) ? candidates.candidateGroups : undefined; this.candidateUserExpressionCtrlValue(this.expressionCandidateUsers); this.candidateGroupExpressionCtrlValue(this.expressionCandidateGroups); } else { this.expressionForm.setErrors({ pattern: 'true' }); } } if (this.expressionForm.valid) { this.updatePayloadWithExpressionValues(); } } else { this.expressionForm.setErrors({ pattern: 'true' }); } } onAssign() { if (this.assignmentPayload) { this.settings.assignmentUpdate$.next(this.assignmentPayload); this.settings.assignmentUpdate$.complete(); this.updateAssignment(); this.dialogRef.close(); } } isCandidatesPresentAndExpressionValid(candidates) { let isValid = false; if (this.isCandidateValid(candidates)) { if (candidates.candidateUsers !== undefined && candidates.candidateGroups !== undefined) { if (this.isExpressionValid(candidates.candidateUsers) || this.isExpressionValid(candidates.candidateGroups)) { isValid = true; } else { this.expressionForm.setErrors({ pattern: 'true' }); } } else if ((candidates.candidateUsers && this.isExpressionValid(candidates.candidateUsers)) || (candidates.candidateGroups && this.isExpressionValid(candidates.candidateGroups))) { isValid = true; } } return isValid; } updateAssignment(): void { this.store .select(selectSelectedProcess) .pipe( filter(model => !!model), take(1) ) .pipe(takeUntil(this.onDestroy$)) .subscribe(model => this.store.dispatch( new UpdateServiceAssignmentAction( model.id, this.settings.processId, this.settings.shapeId, <TaskAssignment>{ type: this.selectedType, assignment: this.selectedMode, id: this.settings.shapeId } ) ) ); } onClose() { this.settings.assignmentUpdate$.complete(); this.dialogRef.close(); } private updatePayloadWithStaticValues() { this.assignmentPayload = this.buildPayloadWithStaticValues({ assignee: this.staticAssignee, candidateUsers: this.staticCandidateUsers, candidateGroups: this.staticCandidateGroups }); } private updatePayloadWithIdentityValues() { this.assignmentPayload = this.buildPayloadWithIdentityValues({ assignee: this.identityAssignee, candidateUsers: this.identityCandidateUsers, candidateGroups: this.identityCandidateGroups }); } private updatePayloadWithExpressionValues() { this.assignmentPayload = this.buildExpressionPayload({ assignee: this.expressionAssignee, candidateUsers: this.expressionCandidateUsers, candidateGroups: this.expressionCandidateGroups }); } private buildPayloadWithStaticValues({ assignee, candidateUsers, candidateGroups }: { assignee: string; candidateUsers: string[]; candidateGroups: string[]; }): AssignmentModel { return <AssignmentModel>{ assignments: <AssignmentParams[]>[ { key: BpmnProperty.assignee, value: assignee ? assignee : undefined }, { key: BpmnProperty.candidateUsers, value: candidateUsers && candidateUsers.length > 0 ? candidateUsers.join() : undefined }, { key: BpmnProperty.candidateGroups, value: candidateGroups && candidateGroups.length > 0 ? candidateGroups.join() : undefined } ] }; } private buildPayloadWithIdentityValues({ assignee, candidateUsers, candidateGroups }: { assignee: any[]; candidateUsers: any[]; candidateGroups: any[]; }): AssignmentModel { return <AssignmentModel>{ assignments: <AssignmentParams[]>[ { key: BpmnProperty.assignee, value: assignee && assignee.length > 0 ? assignee[0].username : undefined }, { key: BpmnProperty.candidateUsers, value: candidateUsers && candidateUsers.length > 0 ? candidateUsers.map(user => user.username).join() : undefined }, { key: BpmnProperty.candidateGroups, value: candidateGroups && candidateGroups.length > 0 ? candidateGroups.map(group => group.name).join() : undefined } ] }; } private buildExpressionPayload({ assignee, candidateUsers, candidateGroups }: { assignee: string; candidateUsers: string; candidateGroups: string; }): AssignmentModel { return <AssignmentModel>{ assignments: <AssignmentParams[]>[ { key: BpmnProperty.assignee, value: assignee ? assignee : undefined }, { key: BpmnProperty.candidateUsers, value: candidateUsers ? candidateUsers : undefined }, { key: BpmnProperty.candidateGroups, value: candidateGroups ? candidateGroups : undefined } ] }; } isExpressionValid(value: string) { return /\${([^}]+)}/.test(value); } isCandidateValid(candidates): boolean { let result = false; if (Object.keys(candidates).length <= 2) { result = true; Object.keys(candidates).forEach((key: string) => { if (key !== 'candidateUsers' && key !== 'candidateGroups') { result = false; } }); } return result; } isAssigneeValid(assignee): boolean { let result = false; if (Object.keys(assignee).length === 1) { result = true; Object.keys(assignee).forEach((key: string) => { if (key !== 'assignee') { result = false; } }); } return result; } isAssigneeMode(): boolean { return this.selectedMode === AssignmentMode.assignee; } isCandidatesMode(): boolean { return this.selectedMode === AssignmentMode.candidates; } isXMLSingleMode(): boolean { return ( this.assignmentXML && this.assignmentXML.assignment === AssignmentMode.assignee ); } isXMLCandidatesMode(): boolean { return ( this.assignmentXML && this.assignmentXML.assignment === AssignmentMode.candidates ); } isXMLStaticType() { return ( this.assignmentXML && this.assignmentXML.type === AssignmentType.static ); } isXMLIdentityType() { return ( this.assignmentXML && this.assignmentXML.type === AssignmentType.identity ); } isXMLExpressionType() { return ( this.assignmentXML && this.assignmentXML.type === AssignmentType.expression ); } isStaticType() { return this.selectedType === AssignmentType.static; } isIdentityType() { return this.selectedType === AssignmentType.identity; } isExpressionType() { return this.selectedType === AssignmentType.expression; } resetProperties() { this.assignmentPayload = undefined; this.removeStaticValues(); this.removeIdentityValues(); this.removeExpressionValues(); } restoreFromXML() { if (this.isXMLStaticType()) { this.setStaticAssignments(); } else if (this.isXMLIdentityType()) { this.setIdentityAssignments(); } else if (this.isXMLExpressionType()) { this.setExpressionAssignments(); } } isTabActive(index: number) { return this.currentActiveTab === index; } private removeStaticValues() { this.staticAssignee = undefined; this.staticCandidateUsers = []; this.staticCandidateGroups = []; } private removeIdentityValues() { this.identityAssignee = [].concat([]); this.identityCandidateUsers = [].concat([]); this.identityCandidateGroups = [].concat([]); } private removeExpressionValues() { this.expressionAssignee = undefined; this.expressionCandidateUsers = undefined; this.expressionCandidateGroups = undefined; if (this.isAssigneeMode()) { this.expressionContent = AssignmentDialogComponent.ASSIGNEE_CONTENT; } else { this.expressionContent = AssignmentDialogComponent.CANDIDATES_CONTENT; } } ngOnDestroy() { this.onDestroy$.next(); this.onDestroy$.complete(); } get staticForm(): FormGroup { return <FormGroup> this.assignmentForm.get('staticForm'); } get assigneeStaticControl(): FormControl { return this.staticForm.get('assignee') as FormControl; } get assigneeChipsStaticControl(): AbstractControl { return this.staticForm.get('assigneeChips'); } private assigneeChipsStaticCtrlValue(value: string) { this.assigneeChipsStaticControl.setValue(value); this.assigneeChipsStaticControl.markAsDirty(); this.assigneeChipsStaticControl.markAsTouched(); this.assigneeChipsStaticControl.updateValueAndValidity(); } private assigneeExpressionCtrlValue(value: string) { this.assigneeExpressionControl.setValue(value); this.assigneeExpressionControl.markAsDirty(); this.assigneeExpressionControl.markAsTouched(); this.assigneeExpressionControl.updateValueAndValidity(); } private candidateUserExpressionCtrlValue(value: string) { this.candidateUsersExpressionControl.setValue(value); this.candidateUsersExpressionControl.markAsDirty(); this.candidateUsersExpressionControl.markAsTouched(); this.candidateUsersExpressionControl.updateValueAndValidity(); } private candidateGroupExpressionCtrlValue(value: string) { this.candidateGroupsExpressionControl.setValue(value); this.candidateGroupsExpressionControl.markAsDirty(); this.candidateGroupsExpressionControl.markAsTouched(); this.candidateGroupsExpressionControl.updateValueAndValidity(); } private candidateUserChipsStaticCtrlValue(value: string) { this.candidateUsersChipsStaticControl.setValue(value); this.candidateUsersChipsStaticControl.markAsDirty(); this.candidateUsersChipsStaticControl.markAsTouched(); this.candidateUsersChipsStaticControl.updateValueAndValidity(); } private candidateGroupChipsStaticCtrlValue(value: string) { this.candidateGroupsChipsStaticControl.setValue(value); this.candidateGroupsChipsStaticControl.markAsDirty(); this.candidateGroupsChipsStaticControl.markAsTouched(); this.candidateGroupsChipsStaticControl.updateValueAndValidity(); } get candidatesStaticFormGroup(): FormGroup { return <FormGroup> this.staticForm.get('candidatesFormGroup'); } get candidateUserStaticFormGroup(): FormGroup { return <FormGroup> this.candidatesStaticFormGroup.get('candidateUserFormGroup'); } get candidateUsersStaticControl(): FormControl { return this.candidateUserStaticFormGroup.get('candidateUsers') as FormControl; } get candidateUsersChipsStaticControl(): AbstractControl { return this.candidateUserStaticFormGroup.get('candidateUsersChips'); } get candidateGroupStaticFormGroup(): FormGroup { return <FormGroup> this.candidatesStaticFormGroup.get('candidateGroupFormGroup'); } get candidateGroupsStaticControl(): FormControl { return this.candidateGroupStaticFormGroup.get('candidateGroups') as FormControl; } get candidateGroupsChipsStaticControl(): AbstractControl { return this.candidateGroupStaticFormGroup.get('candidateGroupsChips'); } get identityForm(): FormGroup { return <FormGroup> this.assignmentForm.get('identityForm'); } get assigneeIdentityControl(): FormControl { return this.identityForm.get('assignee') as FormControl; } get assigneeChipsIdentityControl(): FormControl { return this.identityForm.get('assigneeChips') as FormControl; } get candidatesIdentityFormGroup(): FormGroup { return <FormGroup> this.identityForm.get('candidatesFormGroup'); } get candidateUserIdentityFormGroup(): FormGroup { return <FormGroup> this.candidatesIdentityFormGroup.get('candidateUserFormGroup'); } get candidateUsersIdentityControl(): FormControl { return this.candidateUserIdentityFormGroup.get('candidateUsers') as FormControl; } get candidateUsersChipsIdentityControl(): FormControl { return this.candidateUserIdentityFormGroup.get('candidateUsersChips') as FormControl; } get candidateGroupIdentityFormGroup(): FormGroup { return <FormGroup> this.candidatesIdentityFormGroup.get('candidateGroupFormGroup'); } get candidateGroupsChipsIdentityControl(): FormControl { return this.candidateGroupIdentityFormGroup.get('candidateGroupsChips') as FormControl; } get candidateGroupsIdentityControl(): FormControl { return this.candidateGroupIdentityFormGroup.get('candidateGroups') as FormControl; } get expressionForm(): FormGroup { return <FormGroup> this.assignmentForm.get('expressionForm'); } get assigneeExpressionControl(): AbstractControl { return this.expressionForm.get('assignee'); } get candidateUsersExpressionControl(): AbstractControl { return this.expressionForm.get('candidateUsers'); } get candidateGroupsExpressionControl(): AbstractControl { return this.expressionForm.get('candidateGroups'); } get isCandidateUserAssigned(): boolean { return this.staticCandidateUsers && this.staticCandidateUsers.length > 0; } get isCandidateGroupAssigned(): boolean { return this.staticCandidateGroups && this.staticCandidateGroups.length > 0; } private assignmentFormClean() { this.staticForm.controls = {}; this.identityForm.controls = {}; this.expressionForm.controls = {}; this.assignmentForm.reset(); } get assignmentFormEnabled() { return !this.loadingForm && this.assignmentForm.valid && this.assignmentForm.dirty && this.assignmentForm.touched; } }
the_stack
import React, { KeyboardEvent } from 'react'; import { render, fireEvent, EventType } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import cases from 'jest-in-case'; import { OPTIONS, OPTIONS_ACCENTED, OPTIONS_NUMBER_VALUE, OPTIONS_BOOLEAN_VALUE, OPTIONS_DISABLED, Option, OptionNumberValue, OptionBooleanValue, } from './constants'; import Select, { FormatOptionLabelMeta } from '../Select'; import { FilterOptionOption } from '../filters'; import { matchers } from '@emotion/jest'; import { AriaLiveMessages } from '../accessibility'; import { noop } from '../utils'; import { GroupBase } from '../types'; expect.extend(matchers); interface BasicProps { readonly className: string; readonly classNamePrefix: string; readonly onChange: () => void; readonly onInputChange: () => void; readonly onMenuClose: () => void; readonly onMenuOpen: () => void; readonly name: string; readonly options: readonly Option[]; readonly inputValue: string; readonly value: null; } const BASIC_PROPS: BasicProps = { className: 'react-select', classNamePrefix: 'react-select', onChange: jest.fn(), onInputChange: jest.fn(), onMenuClose: jest.fn(), onMenuOpen: jest.fn(), name: 'test-input-name', options: OPTIONS, inputValue: '', value: null, }; test('snapshot - defaults', () => { const { container } = render( <Select onChange={noop} onInputChange={noop} onMenuOpen={noop} onMenuClose={noop} inputValue="" value={null} /> ); expect(container).toMatchSnapshot(); }); test('instanceId prop > to have instanceId as id prefix for the select components', () => { let { container } = render( <Select {...BASIC_PROPS} menuIsOpen instanceId={'custom-id'} /> ); expect(container.querySelector('input')!.id).toContain('custom-id'); container.querySelectorAll('div.react-select__option').forEach((opt) => { expect(opt.id).toContain('custom-id'); }); }); test('hidden input field is not present if name is not passes', () => { let { container } = render( <Select onChange={noop} onInputChange={noop} onMenuOpen={noop} onMenuClose={noop} inputValue="" value={null} options={OPTIONS} /> ); expect(container.querySelector('input[type="hidden"]')).toBeNull(); }); test('hidden input field is present if name passes', () => { let { container } = render( <Select onChange={noop} onInputChange={noop} onMenuOpen={noop} onMenuClose={noop} inputValue="" value={null} name="test-input-name" options={OPTIONS} /> ); expect(container.querySelector('input[type="hidden"]')).toBeTruthy(); }); test('single select > passing multiple values > should select the first value', () => { const props = { ...BASIC_PROPS, value: [OPTIONS[0], OPTIONS[4]] }; let { container } = render(<Select {...props} />); expect(container.querySelector('.react-select__control')!.textContent).toBe( '0' ); }); test('isRtl boolean prop sets direction: rtl on container', () => { let { container } = render( <Select {...BASIC_PROPS} value={[OPTIONS[0]]} isRtl isClearable /> ); expect(container.firstChild).toHaveStyleRule('direction', 'rtl'); }); test('isOptionSelected() prop > single select > mark value as isSelected if isOptionSelected returns true for the option', () => { // Select all but option with label '1' let isOptionSelected = jest.fn((option) => option.label !== '1'); let { container } = render( <Select {...BASIC_PROPS} isOptionSelected={isOptionSelected} menuIsOpen /> ); let options = container.querySelectorAll('.react-select__option'); // Option label 0 to be selected expect(options[0].classList).toContain('react-select__option--is-selected'); // Option label 1 to be not selected expect(options[1].classList).not.toContain( 'react-select__option--is-selected' ); }); test('isOptionSelected() prop > multi select > to not show the selected options in Menu for multiSelect', () => { // Select all but option with label '1' let isOptionSelected = jest.fn((option) => option.label !== '1'); let { container } = render( <Select {...BASIC_PROPS} isMulti isOptionSelected={isOptionSelected} menuIsOpen /> ); expect(container.querySelectorAll('.react-select__option')).toHaveLength(1); expect(container.querySelector('.react-select__option')!.textContent).toBe( '1' ); }); cases( 'formatOptionLabel', ({ props, valueComponentSelector, expectedOptions }) => { let { container } = render(<Select {...props} />); let value = container.querySelector(valueComponentSelector); expect(value!.textContent).toBe(expectedOptions); }, { 'single select > should format label of options according to text returned by formatOptionLabel': { props: { ...BASIC_PROPS, formatOptionLabel: ( { label, value }: Option, { context }: FormatOptionLabelMeta<Option> ) => `${label} ${value} ${context}`, value: OPTIONS[0], }, valueComponentSelector: '.react-select__single-value', expectedOptions: '0 zero value', }, 'multi select > should format label of options according to text returned by formatOptionLabel': { props: { ...BASIC_PROPS, formatOptionLabel: ( { label, value }: Option, { context }: FormatOptionLabelMeta<Option> ) => `${label} ${value} ${context}`, isMulti: true, value: OPTIONS[0], }, valueComponentSelector: '.react-select__multi-value', expectedOptions: '0 zero value', }, } ); cases( 'name prop', ({ expectedName, props }) => { let { container } = render(<Select {...props} />); let input = container.querySelector<HTMLInputElement>('input[type=hidden]'); expect(input!.name).toBe(expectedName); }, { 'single select > should assign the given name': { props: { ...BASIC_PROPS, name: 'form-field-single-select' }, expectedName: 'form-field-single-select', }, 'multi select > should assign the given name': { props: { ...BASIC_PROPS, name: 'form-field-multi-select', isMulti: true, value: OPTIONS[2], }, expectedName: 'form-field-multi-select', }, } ); cases( 'menuIsOpen prop', ({ props = BASIC_PROPS }) => { let { container, rerender } = render(<Select {...props} />); expect(container.querySelector('.react-select__menu')).toBeFalsy(); rerender(<Select {...props} menuIsOpen />); expect(container.querySelector('.react-select__menu')).toBeTruthy(); rerender(<Select {...props} />); expect(container.querySelector('.react-select__menu')).toBeFalsy(); }, { 'single select > should show menu if menuIsOpen is true and hide menu if menuIsOpen prop is false': {}, 'multi select > should show menu if menuIsOpen is true and hide menu if menuIsOpen prop is false': { props: { ...BASIC_PROPS, isMulti: true, }, }, } ); cases( 'filterOption() prop - default filter behavior', ({ props, searchString, expectResultsLength }) => { let { container, rerender } = render(<Select {...props} />); rerender(<Select {...props} inputValue={searchString} />); expect(container.querySelectorAll('.react-select__option')).toHaveLength( expectResultsLength ); }, { 'single select > should match accented char': { props: { ...BASIC_PROPS, menuIsOpen: true, options: OPTIONS_ACCENTED, }, searchString: 'ecole', // should match "école" expectResultsLength: 1, }, 'single select > should ignore accented char in query': { props: { ...BASIC_PROPS, menuIsOpen: true, options: OPTIONS_ACCENTED, }, searchString: 'schoöl', // should match "school" expectResultsLength: 1, }, } ); cases( 'filterOption() prop - should filter only if function returns truthy for value', ({ props, searchString, expectResultsLength }) => { let { container, rerender } = render(<Select {...props} />); rerender(<Select {...props} inputValue={searchString} />); expect(container.querySelectorAll('.react-select__option')).toHaveLength( expectResultsLength ); }, { 'single select > should filter all options as per searchString': { props: { ...BASIC_PROPS, filterOption: (value: FilterOptionOption<Option>, search: string) => value.value.indexOf(search) > -1, menuIsOpen: true, value: OPTIONS[0], }, searchString: 'o', expectResultsLength: 5, }, 'multi select > should filter all options other that options in value of select': { props: { ...BASIC_PROPS, filterOption: (value: FilterOptionOption<Option>, search: string) => value.value.indexOf(search) > -1, isMulti: true, menuIsOpen: true, value: OPTIONS[0], }, searchString: 'o', expectResultsLength: 4, }, } ); cases( 'filterOption prop is null', ({ props, searchString, expectResultsLength }) => { let { container, rerender } = render(<Select {...props} />); rerender(<Select {...props} inputValue={searchString} />); expect(container.querySelectorAll('.react-select__option')).toHaveLength( expectResultsLength ); }, { 'single select > should show all the options': { props: { ...BASIC_PROPS, filterOption: null, menuIsOpen: true, value: OPTIONS[0], }, searchString: 'o', expectResultsLength: 17, }, 'multi select > should show all the options other than selected options': { props: { ...BASIC_PROPS, filterOption: null, isMulti: true, menuIsOpen: true, value: OPTIONS[0], }, searchString: 'o', expectResultsLength: 16, }, } ); cases( 'no option found on search based on filterOption prop', ({ props, searchString }) => { let { getByText, rerender } = render(<Select {...props} />); rerender(<Select {...props} inputValue={searchString} />); expect(getByText('No options').className).toContain( 'menu-notice--no-options' ); }, { 'single Select > should show NoOptionsMessage': { props: { ...BASIC_PROPS, filterOption: (value: FilterOptionOption<Option>, search: string) => value.value.indexOf(search) > -1, menuIsOpen: true, }, searchString: 'some text not in options', }, 'multi select > should show NoOptionsMessage': { props: { ...BASIC_PROPS, filterOption: (value: FilterOptionOption<Option>, search: string) => value.value.indexOf(search) > -1, menuIsOpen: true, }, searchString: 'some text not in options', }, } ); cases( 'noOptionsMessage() function prop', ({ props, expectNoOptionsMessage, searchString }) => { let { getByText, rerender } = render(<Select {...props} />); rerender(<Select {...props} inputValue={searchString} />); expect(getByText(expectNoOptionsMessage).className).toContain( 'menu-notice--no-options' ); }, { 'single Select > should show NoOptionsMessage returned from noOptionsMessage function prop': { props: { ...BASIC_PROPS, filterOption: (value: FilterOptionOption<Option>, search: string) => value.value.indexOf(search) > -1, menuIsOpen: true, noOptionsMessage: () => 'this is custom no option message for single select', }, expectNoOptionsMessage: 'this is custom no option message for single select', searchString: 'some text not in options', }, 'multi select > should show NoOptionsMessage returned from noOptionsMessage function prop': { props: { ...BASIC_PROPS, filterOption: (value: FilterOptionOption<Option>, search: string) => value.value.indexOf(search) > -1, menuIsOpen: true, noOptionsMessage: () => 'this is custom no option message for multi select', }, expectNoOptionsMessage: 'this is custom no option message for multi select', searchString: 'some text not in options', }, } ); cases( 'value prop', ({ props, expectedValue }) => { let value; render( <Select<Option | OptionNumberValue, boolean> {...props} components={{ Control: ({ getValue }) => { value = getValue(); return null; }, }} /> ); expect(value).toEqual(expectedValue); }, { 'single select > should set it as initial value': { props: { ...BASIC_PROPS, value: OPTIONS[2], }, expectedValue: [{ label: '2', value: 'two' }], }, 'single select > with option values as number > should set it as initial value': { props: { ...BASIC_PROPS, value: OPTIONS_NUMBER_VALUE[2], }, expectedValue: [{ label: '2', value: 2 }], }, 'multi select > should set it as initial value': { props: { ...BASIC_PROPS, isMulti: true, value: OPTIONS[1], }, expectedValue: [{ label: '1', value: 'one' }], }, 'multi select > with option values as number > should set it as initial value': { props: { ...BASIC_PROPS, isMulti: true, value: OPTIONS_NUMBER_VALUE[1], }, expectedValue: [{ label: '1', value: 1 }], }, } ); cases( 'update the value prop', ({ props = { ...BASIC_PROPS, value: OPTIONS[1] }, updateValueTo, expectedInitialValue, expectedUpdatedValue, }) => { let { container, rerender } = render( <Select<Option | OptionNumberValue, boolean> {...props} /> ); expect( container.querySelector<HTMLInputElement>('input[type="hidden"]')!.value ).toEqual(expectedInitialValue); rerender( <Select<Option | OptionNumberValue, boolean> {...props} value={updateValueTo} /> ); expect( container.querySelector<HTMLInputElement>('input[type="hidden"]')!.value ).toEqual(expectedUpdatedValue); }, { 'single select > should update the value when prop is updated': { updateValueTo: OPTIONS[3], expectedInitialValue: 'one', expectedUpdatedValue: 'three', }, 'single select > value of options is number > should update the value when prop is updated': { props: { ...BASIC_PROPS, options: OPTIONS_NUMBER_VALUE, value: OPTIONS_NUMBER_VALUE[2], }, updateValueTo: OPTIONS_NUMBER_VALUE[3], expectedInitialValue: '2', expectedUpdatedValue: '3', }, 'multi select > should update the value when prop is updated': { props: { ...BASIC_PROPS, isMulti: true, value: OPTIONS[1], }, updateValueTo: OPTIONS[3], expectedInitialValue: 'one', expectedUpdatedValue: 'three', }, 'multi select > value of options is number > should update the value when prop is updated': { props: { ...BASIC_PROPS, delimiter: ',', isMulti: true, options: OPTIONS_NUMBER_VALUE, value: OPTIONS_NUMBER_VALUE[2], }, updateValueTo: [OPTIONS_NUMBER_VALUE[3], OPTIONS_NUMBER_VALUE[2]], expectedInitialValue: '2', expectedUpdatedValue: '3,2', }, } ); cases( 'calls onChange on selecting an option', ({ props = { ...BASIC_PROPS, menuIsOpen: true }, event: [eventName, eventOptions], expectedSelectedOption, optionsSelected, focusedOption, expectedActionMetaOption, }) => { let onChangeSpy = jest.fn(); props = { ...props, onChange: onChangeSpy }; let { container } = render( <Select<Option | OptionNumberValue | OptionBooleanValue, boolean> {...props} /> ); if (focusedOption) { focusOption(container, focusedOption, props.options); } let selectOption = [ ...container.querySelectorAll('div.react-select__option'), ].find((n) => n.textContent === optionsSelected.label); fireEvent[eventName](selectOption!, eventOptions); expect(onChangeSpy).toHaveBeenCalledWith(expectedSelectedOption, { action: 'select-option', option: expectedActionMetaOption, name: BASIC_PROPS.name, }); }, { 'single select > option is clicked > should call onChange() prop with selected option': { event: ['click' as const] as const, optionsSelected: { label: '2', value: 'two' }, expectedSelectedOption: { label: '2', value: 'two' }, }, 'single select > option with number value > option is clicked > should call onChange() prop with selected option': { props: { ...BASIC_PROPS, menuIsOpen: true, options: OPTIONS_NUMBER_VALUE, }, event: ['click' as const] as const, optionsSelected: { label: '0', value: 0 }, expectedSelectedOption: { label: '0', value: 0 }, }, 'single select > option with boolean value > option is clicked > should call onChange() prop with selected option': { props: { ...BASIC_PROPS, menuIsOpen: true, options: OPTIONS_BOOLEAN_VALUE, }, event: ['click' as const] as const, optionsSelected: { label: 'true', value: true }, expectedSelectedOption: { label: 'true', value: true }, }, 'single select > tab key is pressed while focusing option > should call onChange() prop with selected option': { event: ['keyDown' as const, { keyCode: 9, key: 'Tab' }] as const, optionsSelected: { label: '1', value: 'one' }, focusedOption: { label: '1', value: 'one' }, expectedSelectedOption: { label: '1', value: 'one' }, }, 'single select > enter key is pressed while focusing option > should call onChange() prop with selected option': { event: ['keyDown' as const, { keyCode: 13, key: 'Enter' }] as const, optionsSelected: { label: '3', value: 'three' }, focusedOption: { label: '3', value: 'three' }, expectedSelectedOption: { label: '3', value: 'three' }, }, 'single select > space key is pressed while focusing option > should call onChange() prop with selected option': { event: ['keyDown' as const, { keyCode: 32, key: ' ' }] as const, optionsSelected: { label: '1', value: 'one' }, focusedOption: { label: '1', value: 'one' }, expectedSelectedOption: { label: '1', value: 'one' }, }, 'multi select > option is clicked > should call onChange() prop with selected option': { props: { ...BASIC_PROPS, isMulti: true, menuIsOpen: true, options: OPTIONS, }, event: ['click' as const] as const, optionsSelected: { label: '2', value: 'two' }, expectedSelectedOption: [{ label: '2', value: 'two' }], expectedActionMetaOption: { label: '2', value: 'two' }, }, 'multi select > option with number value > option is clicked > should call onChange() prop with selected option': { props: { ...BASIC_PROPS, isMulti: true, menuIsOpen: true, options: OPTIONS_NUMBER_VALUE, }, event: ['click' as const] as const, optionsSelected: { label: '0', value: 0 }, expectedSelectedOption: [{ label: '0', value: 0 }], expectedActionMetaOption: { label: '0', value: 0 }, }, 'multi select > option with boolean value > option is clicked > should call onChange() prop with selected option': { props: { ...BASIC_PROPS, isMulti: true, menuIsOpen: true, options: OPTIONS_BOOLEAN_VALUE, }, event: ['click' as const] as const, optionsSelected: { label: 'true', value: true }, expectedSelectedOption: [{ label: 'true', value: true }], expectedActionMetaOption: { label: 'true', value: true }, }, 'multi select > tab key is pressed while focusing option > should call onChange() prop with selected option': { props: { ...BASIC_PROPS, isMulti: true, menuIsOpen: true, options: OPTIONS, }, event: ['keyDown' as const, { keyCode: 9, key: 'Tab' }] as const, menuIsOpen: true, optionsSelected: { label: '1', value: 'one' }, focusedOption: { label: '1', value: 'one' }, expectedSelectedOption: [{ label: '1', value: 'one' }], expectedActionMetaOption: { label: '1', value: 'one' }, }, 'multi select > enter key is pressed while focusing option > should call onChange() prop with selected option': { props: { ...BASIC_PROPS, isMulti: true, menuIsOpen: true, options: OPTIONS, }, event: ['keyDown' as const, { keyCode: 13, key: 'Enter' }] as const, optionsSelected: { label: '3', value: 'three' }, focusedOption: { label: '3', value: 'three' }, expectedSelectedOption: [{ label: '3', value: 'three' }], expectedActionMetaOption: { label: '3', value: 'three' }, }, 'multi select > space key is pressed while focusing option > should call onChange() prop with selected option': { props: { ...BASIC_PROPS, isMulti: true, menuIsOpen: true, options: OPTIONS, }, event: ['keyDown' as const, { keyCode: 32, key: ' ' }] as const, optionsSelected: { label: '1', value: 'one' }, focusedOption: { label: '1', value: 'one' }, expectedSelectedOption: [{ label: '1', value: 'one' }], expectedActionMetaOption: { label: '1', value: 'one' }, }, } ); interface CallsOnChangeOnDeselectOptsProps extends Omit<BasicProps, 'options' | 'value'> { readonly options: readonly ( | Option | OptionNumberValue | OptionBooleanValue )[]; readonly value: | readonly Option[] | readonly OptionNumberValue[] | readonly OptionBooleanValue[] | Option; readonly menuIsOpen?: boolean; readonly hideSelectedOptions?: boolean; readonly isMulti?: boolean; } interface CallsOnOnDeselectChangeOpts { readonly props: CallsOnChangeOnDeselectOptsProps; readonly event: readonly [EventType] | readonly [EventType, {}]; readonly menuIsOpen?: boolean; readonly optionsSelected: Option | OptionNumberValue | OptionBooleanValue; readonly focusedOption?: Option | OptionNumberValue | OptionBooleanValue; readonly expectedSelectedOption: | readonly Option[] | readonly OptionNumberValue[] | readonly OptionBooleanValue[]; readonly expectedMetaOption: Option | OptionNumberValue | OptionBooleanValue; } cases<CallsOnOnDeselectChangeOpts>( 'calls onChange on de-selecting an option in multi select', ({ props, event: [eventName, eventOptions], expectedSelectedOption, expectedMetaOption, optionsSelected, focusedOption, }) => { let onChangeSpy = jest.fn(); props = { ...props, onChange: onChangeSpy, menuIsOpen: true, hideSelectedOptions: false, isMulti: true, }; let { container } = render( <Select<Option | OptionNumberValue | OptionBooleanValue, boolean> {...props} /> ); let selectOption = [ ...container.querySelectorAll('div.react-select__option'), ].find((n) => n.textContent === optionsSelected.label); if (focusedOption) { focusOption(container, focusedOption, props.options); } fireEvent[eventName](selectOption!, eventOptions); expect(onChangeSpy).toHaveBeenCalledWith(expectedSelectedOption, { action: 'deselect-option', option: expectedMetaOption, name: BASIC_PROPS.name, }); }, { 'option is clicked > should call onChange() prop with correct selected options and meta': { props: { ...BASIC_PROPS, options: OPTIONS, value: [{ label: '2', value: 'two' }], }, event: ['click'], optionsSelected: { label: '2', value: 'two' }, expectedSelectedOption: [], expectedMetaOption: { label: '2', value: 'two' }, }, 'option with number value > option is clicked > should call onChange() prop with selected option': { props: { ...BASIC_PROPS, options: OPTIONS_NUMBER_VALUE, value: [{ label: '0', value: 0 }], }, event: ['click'], optionsSelected: { label: '0', value: 0 }, expectedSelectedOption: [], expectedMetaOption: { label: '0', value: 0 }, }, 'option with boolean value > option is clicked > should call onChange() prop with selected option': { props: { ...BASIC_PROPS, options: OPTIONS_BOOLEAN_VALUE, value: [{ label: 'true', value: true }], }, event: ['click'], optionsSelected: { label: 'true', value: true }, expectedSelectedOption: [], expectedMetaOption: { label: 'true', value: true }, }, 'tab key is pressed while focusing option > should call onChange() prop with selected option': { props: { ...BASIC_PROPS, options: OPTIONS, value: [{ label: '1', value: 'one' }], }, event: ['keyDown', { keyCode: 9, key: 'Tab' }], menuIsOpen: true, optionsSelected: { label: '1', value: 'one' }, focusedOption: { label: '1', value: 'one' }, expectedSelectedOption: [], expectedMetaOption: { label: '1', value: 'one' }, }, 'enter key is pressed while focusing option > should call onChange() prop with selected option': { props: { ...BASIC_PROPS, options: OPTIONS, value: { label: '3', value: 'three' }, }, event: ['keyDown', { keyCode: 13, key: 'Enter' }], optionsSelected: { label: '3', value: 'three' }, focusedOption: { label: '3', value: 'three' }, expectedSelectedOption: [], expectedMetaOption: { label: '3', value: 'three' }, }, 'space key is pressed while focusing option > should call onChange() prop with selected option': { props: { ...BASIC_PROPS, options: OPTIONS, value: [{ label: '1', value: 'one' }], }, event: ['keyDown', { keyCode: 32, key: ' ' }], optionsSelected: { label: '1', value: 'one' }, focusedOption: { label: '1', value: 'one' }, expectedSelectedOption: [], expectedMetaOption: { label: '1', value: 'one' }, }, } ); function focusOption( container: HTMLElement, option: Option | OptionNumberValue | OptionBooleanValue, options: readonly (Option | OptionNumberValue | OptionBooleanValue)[] ) { let indexOfSelectedOption = options.findIndex( (o) => o.value === option.value ); for (let i = -1; i < indexOfSelectedOption; i++) { fireEvent.keyDown(container.querySelector('.react-select__menu')!, { keyCode: 40, key: 'ArrowDown', }); } expect( container.querySelector('.react-select__option--is-focused')!.textContent ).toEqual(option.label); } cases( 'hitting escape on select option', ({ props, event: [eventName, eventOptions], focusedOption, optionsSelected, }) => { let onChangeSpy = jest.fn(); let { container } = render( <Select {...props} onChange={onChangeSpy} onInputChange={jest.fn()} onMenuClose={jest.fn()} /> ); let selectOption = [ ...container.querySelectorAll('div.react-select__option'), ].find((n) => n.textContent === optionsSelected.label); focusOption(container, focusedOption, props.options); fireEvent[eventName](selectOption!, eventOptions); expect(onChangeSpy).not.toHaveBeenCalled(); }, { 'single select > should not call onChange prop': { props: { ...BASIC_PROPS, menuIsOpen: true, }, optionsSelected: { label: '1', value: 'one' }, focusedOption: { label: '1', value: 'one' }, event: ['keyDown' as const, { keyCode: 27 }] as const, }, 'multi select > should not call onChange prop': { props: { ...BASIC_PROPS, isMulti: true, menuIsOpen: true, }, optionsSelected: { label: '1', value: 'one' }, focusedOption: { label: '1', value: 'one' }, event: ['keyDown' as const, { keyCode: 27 }] as const, }, } ); cases( 'click to open select', ({ props = BASIC_PROPS, expectedToFocus }) => { let { container, rerender } = render( <Select {...props} onMenuOpen={() => { rerender(<Select {...props} menuIsOpen onMenuOpen={noop} />); }} /> ); fireEvent.mouseDown( container.querySelector('.react-select__dropdown-indicator')!, { button: 0 } ); expect( container.querySelector('.react-select__option--is-focused')!.textContent ).toEqual(expectedToFocus.label); }, { 'single select > should focus the first option': { expectedToFocus: { label: '0', value: 'zero' }, }, 'multi select > should focus the first option': { props: { ...BASIC_PROPS, isMulti: true, }, expectedToFocus: { label: '0', value: 'zero' }, }, } ); test('clicking when focused does not open select when openMenuOnClick=false', () => { let spy = jest.fn(); let { container } = render( <Select {...BASIC_PROPS} openMenuOnClick={false} onMenuOpen={spy} /> ); // this will get updated on input click, though click on input is not bubbling up to control component userEvent.click(container.querySelector('input.react-select__input')!); expect(spy).not.toHaveBeenCalled(); }); cases( 'focus on options > keyboard interaction with Menu', ({ props, selectedOption, nextFocusOption, keyEvent = [] }) => { let { container } = render(<Select {...props} />); let indexOfSelectedOption = props.options.indexOf(selectedOption); for (let i = -1; i < indexOfSelectedOption; i++) { fireEvent.keyDown(container.querySelector('.react-select__menu')!, { keyCode: 40, key: 'ArrowDown', }); } expect( container.querySelector('.react-select__option--is-focused')!.textContent ).toEqual(selectedOption.label); for (let event of keyEvent) { fireEvent.keyDown(container.querySelector('.react-select__menu')!, event); } expect( container.querySelector('.react-select__option--is-focused')!.textContent ).toEqual(nextFocusOption.label); }, { 'single select > ArrowDown key on first option should focus second option': { props: { ...BASIC_PROPS, menuIsOpen: true, }, keyEvent: [{ keyCode: 40, key: 'ArrowDown' }], selectedOption: OPTIONS[0], nextFocusOption: OPTIONS[1], }, 'single select > ArrowDown key on last option should focus first option': { props: { ...BASIC_PROPS, menuIsOpen: true, options: OPTIONS, }, keyEvent: [{ keyCode: 40, key: 'ArrowDown' }], selectedOption: OPTIONS[OPTIONS.length - 1], nextFocusOption: OPTIONS[0], }, 'single select > ArrowUp key on first option should focus last option': { props: { ...BASIC_PROPS, menuIsOpen: true, options: OPTIONS, }, keyEvent: [{ keyCode: 38, key: 'ArrowUp' }], selectedOption: OPTIONS[0], nextFocusOption: OPTIONS[OPTIONS.length - 1], }, 'single select > ArrowUp key on last option should focus second last option': { props: { ...BASIC_PROPS, menuIsOpen: true, options: OPTIONS, }, keyEvent: [{ keyCode: 38, key: 'ArrowUp' }], selectedOption: OPTIONS[OPTIONS.length - 1], nextFocusOption: OPTIONS[OPTIONS.length - 2], }, 'single select > disabled options should be focusable': { props: { ...BASIC_PROPS, menuIsOpen: true, options: OPTIONS_DISABLED, }, keyEvent: [{ keyCode: 40, key: 'ArrowDown' }], selectedOption: OPTIONS_DISABLED[0], nextFocusOption: OPTIONS_DISABLED[1], }, 'single select > PageDown key takes us to next page with default page size of 5': { props: { ...BASIC_PROPS, menuIsOpen: true, options: OPTIONS, }, keyEvent: [{ keyCode: 34, key: 'PageDown' }], selectedOption: OPTIONS[0], nextFocusOption: OPTIONS[5], }, 'single select > PageDown key takes us to next page with custom pageSize 7': { props: { ...BASIC_PROPS, menuIsOpen: true, pageSize: 7, options: OPTIONS, }, keyEvent: [{ keyCode: 34, key: 'PageDown' }], selectedOption: OPTIONS[0], nextFocusOption: OPTIONS[7], }, 'single select > PageDown key takes to the last option is options below is less then page size': { props: { ...BASIC_PROPS, menuIsOpen: true, options: OPTIONS, }, keyEvent: [{ keyCode: 34, key: 'PageDown' }], selectedOption: OPTIONS[OPTIONS.length - 3], nextFocusOption: OPTIONS[OPTIONS.length - 1], }, 'single select > PageUp key takes us to previous page with default page size of 5': { props: { ...BASIC_PROPS, menuIsOpen: true, options: OPTIONS, }, keyEvent: [{ keyCode: 33, key: 'PageUp' }], selectedOption: OPTIONS[6], nextFocusOption: OPTIONS[1], }, 'single select > PageUp key takes us to previous page with custom pageSize of 7': { props: { ...BASIC_PROPS, menuIsOpen: true, pageSize: 7, options: OPTIONS, }, keyEvent: [{ keyCode: 33, key: 'PageUp' }], selectedOption: OPTIONS[9], nextFocusOption: OPTIONS[2], }, 'single select > PageUp key takes us to first option - (previous options < pageSize)': { props: { ...BASIC_PROPS, menuIsOpen: true, options: OPTIONS, }, keyEvent: [{ keyCode: 33, key: 'PageUp' }], selectedOption: OPTIONS[1], nextFocusOption: OPTIONS[0], }, 'single select > Home key takes up to the first option': { props: { ...BASIC_PROPS, menuIsOpen: true, options: OPTIONS, }, keyEvent: [{ keyCode: 36, key: 'Home' }], selectedOption: OPTIONS[OPTIONS.length - 3], nextFocusOption: OPTIONS[0], }, 'single select > End key takes down to the last option': { props: { ...BASIC_PROPS, menuIsOpen: true, options: OPTIONS, }, keyEvent: [{ keyCode: 35, key: 'End' }], selectedOption: OPTIONS[2], nextFocusOption: OPTIONS[OPTIONS.length - 1], }, 'multi select > ArrowDown key on first option should focus second option': { props: { ...BASIC_PROPS, isMulti: true, menuIsOpen: true, options: OPTIONS, }, keyEvent: [{ keyCode: 40, key: 'ArrowDown' }], selectedOption: OPTIONS[0], nextFocusOption: OPTIONS[1], }, 'multi select > ArrowDown key on last option should focus first option': { props: { ...BASIC_PROPS, isMulti: true, menuIsOpen: true, options: OPTIONS, }, keyEvent: [{ keyCode: 40, key: 'ArrowDown' }], selectedOption: OPTIONS[OPTIONS.length - 1], nextFocusOption: OPTIONS[0], }, 'multi select > ArrowUp key on first option should focus last option': { props: { ...BASIC_PROPS, isMulti: true, menuIsOpen: true, options: OPTIONS, }, keyEvent: [{ keyCode: 38, key: 'ArrowUp' }], selectedOption: OPTIONS[0], nextFocusOption: OPTIONS[OPTIONS.length - 1], }, 'multi select > ArrowUp key on last option should focus second last option': { props: { ...BASIC_PROPS, isMulti: true, menuIsOpen: true, options: OPTIONS, }, keyEvent: [{ keyCode: 38, key: 'ArrowUp' }], selectedOption: OPTIONS[OPTIONS.length - 1], nextFocusOption: OPTIONS[OPTIONS.length - 2], }, 'multi select > PageDown key takes us to next page with default page size of 5': { props: { ...BASIC_PROPS, isMulti: true, menuIsOpen: true, options: OPTIONS, }, keyEvent: [{ keyCode: 34, key: 'PageDown' }], selectedOption: OPTIONS[0], nextFocusOption: OPTIONS[5], }, 'multi select > PageDown key takes us to next page with custom pageSize of 8': { props: { ...BASIC_PROPS, isMulti: true, menuIsOpen: true, pageSize: 8, options: OPTIONS, }, keyEvent: [{ keyCode: 34, key: 'PageDown' }], selectedOption: OPTIONS[0], nextFocusOption: OPTIONS[8], }, 'multi select > PageDown key takes to the last option is options below is less then page size': { props: { ...BASIC_PROPS, isMulti: true, menuIsOpen: true, options: OPTIONS, }, keyEvent: [{ keyCode: 34, key: 'PageDown' }], selectedOption: OPTIONS[OPTIONS.length - 3], nextFocusOption: OPTIONS[OPTIONS.length - 1], }, 'multi select > PageUp key takes us to previous page with default page size of 5': { props: { ...BASIC_PROPS, isMulti: true, menuIsOpen: true, options: OPTIONS, }, keyEvent: [{ keyCode: 33, key: 'PageUp' }], selectedOption: OPTIONS[6], nextFocusOption: OPTIONS[1], }, 'multi select > PageUp key takes us to previous page with default page size of 9': { props: { ...BASIC_PROPS, isMulti: true, menuIsOpen: true, pageSize: 9, options: OPTIONS, }, keyEvent: [{ keyCode: 33, key: 'PageUp' }], selectedOption: OPTIONS[10], nextFocusOption: OPTIONS[1], }, 'multi select > PageUp key takes us to first option - previous options < pageSize': { props: { ...BASIC_PROPS, isMulti: true, menuIsOpen: true, options: OPTIONS, }, keyEvent: [{ keyCode: 33, key: 'PageUp' }], selectedOption: OPTIONS[1], nextFocusOption: OPTIONS[0], }, 'multi select > Home key takes up to the first option': { props: { ...BASIC_PROPS, isMulti: true, menuIsOpen: true, options: OPTIONS, }, keyEvent: [{ keyCode: 36, key: 'Home' }], selectedOption: OPTIONS[OPTIONS.length - 3], nextFocusOption: OPTIONS[0], }, 'multi select > End key takes down to the last option': { props: { ...BASIC_PROPS, isMulti: true, menuIsOpen: true, options: OPTIONS, }, keyEvent: [{ keyCode: 35, key: 'End' }], selectedOption: OPTIONS[2], nextFocusOption: OPTIONS[OPTIONS.length - 1], }, } ); // TODO: Cover more scenario cases( 'hitting escape with inputValue in select', ({ props }) => { let spy = jest.fn(); let { container } = render( <Select {...props} onInputChange={spy} onMenuClose={jest.fn()} /> ); fireEvent.keyDown(container.querySelector('.react-select')!, { keyCode: 27, key: 'Escape', }); expect(spy).toHaveBeenCalledWith('', { action: 'menu-close', prevInputValue: 'test', }); }, { 'single select > should call onInputChange prop with empty string as inputValue': { props: { ...BASIC_PROPS, inputValue: 'test', menuIsOpen: true, value: OPTIONS[0], }, }, 'multi select > should call onInputChange prop with empty string as inputValue': { props: { ...BASIC_PROPS, inputValue: 'test', isMulti: true, menuIsOpen: true, value: OPTIONS[0], }, }, } ); cases( 'Clicking dropdown indicator on select with closed menu with primary button on mouse', ({ props = BASIC_PROPS }) => { let onMenuOpenSpy = jest.fn(); props = { ...props, onMenuOpen: onMenuOpenSpy }; let { container } = render(<Select {...props} />); // Menu is closed expect( container.querySelector('.react-select__menu') ).not.toBeInTheDocument(); fireEvent.mouseDown( container.querySelector('div.react-select__dropdown-indicator')!, { button: 0 } ); expect(onMenuOpenSpy).toHaveBeenCalled(); }, { 'single select > should call onMenuOpen prop when select is opened and onMenuClose prop when select is closed': {}, 'multi select > should call onMenuOpen prop when select is opened and onMenuClose prop when select is closed': { props: { ...BASIC_PROPS, isMulti: true, }, }, } ); cases( 'Clicking dropdown indicator on select with open menu with primary button on mouse', ({ props = BASIC_PROPS }) => { let onMenuCloseSpy = jest.fn(); props = { ...props, onMenuClose: onMenuCloseSpy }; let { container } = render(<Select {...props} menuIsOpen />); // Menu is open expect(container.querySelector('.react-select__menu')).toBeInTheDocument(); fireEvent.mouseDown( container.querySelector('div.react-select__dropdown-indicator')!, { button: 0 } ); expect(onMenuCloseSpy).toHaveBeenCalled(); }, { 'single select > should call onMenuOpen prop when select is opened and onMenuClose prop when select is closed': {}, 'multi select > should call onMenuOpen prop when select is opened and onMenuClose prop when select is closed': { props: { ...BASIC_PROPS, isMulti: true, }, }, } ); interface ClickingEnterOptsProps extends BasicProps { readonly menuIsOpen?: boolean; } interface ClickingEnterOpts { readonly props: ClickingEnterOptsProps; readonly expectedValue: boolean; } cases<ClickingEnterOpts>( 'Clicking Enter on a focused select', ({ props, expectedValue }) => { let event!: KeyboardEvent<HTMLDivElement>; let { container } = render( <div onKeyDown={(_event) => { event = _event; event.persist(); }} > <Select {...props} /> </div> ); if (props.menuIsOpen) { fireEvent.keyDown(container.querySelector('.react-select__menu')!, { keyCode: 40, key: 'ArrowDown', }); } fireEvent.keyDown(container.querySelector('.react-select')!, { key: 'Enter', keyCode: 13, }); expect(event.defaultPrevented).toBe(expectedValue); }, { 'while menuIsOpen && focusedOption && !isComposing > should invoke event.preventDefault': { props: { ...BASIC_PROPS, menuIsOpen: true, }, expectedValue: true, }, 'while !menuIsOpen > should not invoke event.preventDefault': { props: { ...BASIC_PROPS, }, expectedValue: false, }, } ); // QUESTION: Is this test right? I tried right clicking on the dropdown indicator in a browser and the select opened but this test says it shouldn't? cases( 'clicking on select using secondary button on mouse', ({ props = BASIC_PROPS }) => { let onMenuOpenSpy = jest.fn(); let onMenuCloseSpy = jest.fn(); let { container, rerender } = render( <Select {...props} onMenuClose={onMenuCloseSpy} onMenuOpen={onMenuOpenSpy} /> ); let downButton = container.querySelector( 'div.react-select__dropdown-indicator' ); // does not open menu if menu is closed fireEvent.mouseDown(downButton!, { button: 1 }); expect(onMenuOpenSpy).not.toHaveBeenCalled(); // does not close menu if menu is opened rerender( <Select {...props} menuIsOpen onMenuClose={onMenuCloseSpy} onMenuOpen={onMenuOpenSpy} /> ); fireEvent.mouseDown(downButton!, { button: 1 }); expect(onMenuCloseSpy).not.toHaveBeenCalled(); }, { 'single select > secondary click is ignored > should not call onMenuOpen and onMenuClose prop': { skip: true, }, 'multi select > secondary click is ignored > should not call onMenuOpen and onMenuClose prop': { props: { ...BASIC_PROPS, isMulti: true, }, skip: true, }, } ); interface RequiredOnInputOpts { readonly props?: BasicProps; readonly isMulti?: boolean; } cases<RequiredOnInputOpts>( 'required on input is not there by default', ({ props = BASIC_PROPS }) => { let { container } = render(<Select {...props} onInputChange={jest.fn()} />); let input = container.querySelector<HTMLInputElement>( 'input.react-select__input' ); expect(input!.required).toBe(false); }, { 'single select > should not have required attribute': {}, 'multi select > should not have required attribute': { isMulti: true }, } ); cases( 'value of hidden input control', ({ props, expectedValue }) => { let { container } = render( <Select<Option | OptionNumberValue | OptionBooleanValue, boolean> {...props} /> ); let hiddenInput = container.querySelector<HTMLInputElement>( 'input[type="hidden"]' ); expect(hiddenInput!.value).toEqual(expectedValue); }, { 'single select > should set value of input as value prop': { props: { ...BASIC_PROPS, value: OPTIONS[3], }, expectedValue: 'three', }, 'single select > options with number values > should set value of input as value prop': { props: { ...BASIC_PROPS, options: OPTIONS_NUMBER_VALUE, value: OPTIONS_NUMBER_VALUE[3], }, expectedValue: '3', }, 'single select > options with boolean values > should set value of input as value prop': { props: { ...BASIC_PROPS, options: OPTIONS_BOOLEAN_VALUE, value: OPTIONS_BOOLEAN_VALUE[1], }, expectedValue: 'false', }, 'multi select > should set value of input as value prop': { props: { ...BASIC_PROPS, isMulti: true, value: OPTIONS[3], }, expectedValue: 'three', }, 'multi select > with delimiter prop > should set value of input as value prop': { props: { ...BASIC_PROPS, delimiter: ', ', isMulti: true, value: [OPTIONS[3], OPTIONS[5]], }, expectedValue: 'three, five', }, 'multi select > options with number values > should set value of input as value prop': { props: { ...BASIC_PROPS, isMulti: true, options: OPTIONS_NUMBER_VALUE, value: OPTIONS_NUMBER_VALUE[3], }, expectedValue: '3', }, 'multi select > with delimiter prop > options with number values > should set value of input as value prop': { props: { ...BASIC_PROPS, delimiter: ', ', isMulti: true, options: OPTIONS_NUMBER_VALUE, value: [OPTIONS_NUMBER_VALUE[3], OPTIONS_NUMBER_VALUE[1]], }, expectedValue: '3, 1', }, 'multi select > options with boolean values > should set value of input as value prop': { props: { ...BASIC_PROPS, isMulti: true, options: OPTIONS_BOOLEAN_VALUE, value: OPTIONS_BOOLEAN_VALUE[1], }, expectedValue: 'false', }, 'multi select > with delimiter prop > options with boolean values > should set value of input as value prop': { props: { ...BASIC_PROPS, delimiter: ', ', isMulti: true, options: OPTIONS_BOOLEAN_VALUE, value: [OPTIONS_BOOLEAN_VALUE[1], OPTIONS_BOOLEAN_VALUE[0]], }, expectedValue: 'false, true', }, } ); cases( 'isOptionDisabled() prop', ({ props, expectedEnabledOption, expectedDisabledOption }) => { let { container } = render(<Select {...props} />); const enabledOptionsValues = [ ...container.querySelectorAll('.react-select__option'), ] .filter((n) => !n.classList.contains('react-select__option--is-disabled')) .map((option) => option.textContent); enabledOptionsValues.forEach((option) => { expect(expectedDisabledOption.indexOf(option!)).toBe(-1); }); const disabledOptionsValues = [ ...container.querySelectorAll('.react-select__option'), ] .filter((n) => n.classList.contains('react-select__option--is-disabled')) .map((option) => option.textContent); disabledOptionsValues.forEach((option) => { expect(expectedEnabledOption.indexOf(option!)).toBe(-1); }); }, { 'single select > should add isDisabled as true prop only to options that are disabled': { props: { ...BASIC_PROPS, menuIsOpen: true, isOptionDisabled: (option: Option) => ['zero', 'two', 'five', 'ten'].indexOf(option.value) > -1, }, expectedEnabledOption: ['1', '3', '11'], expectedDisabledOption: ['0', '2', '5'], }, 'multi select > should add isDisabled as true prop only to options that are disabled': { props: { ...BASIC_PROPS, isMulti: true, menuIsOpen: true, isOptionDisabled: (option: Option) => ['zero', 'two', 'five', 'ten'].indexOf(option.value) > -1, }, expectedEnabledOption: ['1', '3', '11'], expectedDisabledOption: ['0', '2', '5'], }, } ); cases( 'isDisabled prop', ({ props }) => { let { container } = render(<Select {...props} />); let control = container.querySelector('.react-select__control'); expect( control!.classList.contains('react-select__control--is-disabled') ).toBeTruthy(); let input = container.querySelector<HTMLInputElement>( '.react-select__control input' ); expect(input!.disabled).toBeTruthy(); }, { 'single select > should add isDisabled prop to select components': { props: { ...BASIC_PROPS, isDisabled: true, }, }, 'multi select > should add isDisabled prop to select components': { props: { ...BASIC_PROPS, isDisabled: true, isMulti: true, }, }, } ); test('hitting Enter on option should not call onChange if the event comes from IME', () => { let spy = jest.fn(); let { container } = render( <Select className="react-select" classNamePrefix="react-select" menuIsOpen onChange={spy} onInputChange={jest.fn()} onMenuClose={jest.fn()} onMenuOpen={jest.fn()} options={OPTIONS} tabSelectsValue={false} inputValue="" value={null} /> ); let selectOption = container.querySelector('div.react-select__option'); let menu = container.querySelector('.react-select__menu'); fireEvent.keyDown(menu!, { keyCode: 40, key: 'ArrowDown' }); fireEvent.keyDown(menu!, { keyCode: 40, key: 'ArrowDown' }); fireEvent.keyDown(selectOption!, { keyCode: 229, key: 'Enter' }); expect(spy).not.toHaveBeenCalled(); }); test('hitting tab on option should not call onChange if tabSelectsValue is false', () => { let spy = jest.fn(); let { container } = render( <Select className="react-select" classNamePrefix="react-select" menuIsOpen onChange={spy} onInputChange={jest.fn()} onMenuClose={jest.fn()} onMenuOpen={jest.fn()} options={OPTIONS} tabSelectsValue={false} inputValue="" value={null} /> ); let selectOption = container.querySelector('div.react-select__option'); let menu = container.querySelector('.react-select__menu'); fireEvent.keyDown(menu!, { keyCode: 40, key: 'ArrowDown' }); fireEvent.keyDown(menu!, { keyCode: 40, key: 'ArrowDown' }); fireEvent.keyDown(selectOption!, { keyCode: 9, key: 'Tab' }); expect(spy).not.toHaveBeenCalled(); }); test('multi select > to not show selected value in options', () => { let onInputChangeSpy = jest.fn(); let onMenuCloseSpy = jest.fn(); let { container, rerender } = render( <Select {...BASIC_PROPS} isMulti menuIsOpen onInputChange={onInputChangeSpy} onMenuClose={onMenuCloseSpy} /> ); let availableOptions = [ ...container.querySelectorAll('.react-select__option'), ].map((option) => option.textContent); expect(availableOptions.indexOf('0') > -1).toBeTruthy(); rerender( <Select {...BASIC_PROPS} isMulti menuIsOpen onInputChange={onInputChangeSpy} onMenuClose={onMenuCloseSpy} value={OPTIONS[0]} /> ); // Re-open Menu fireEvent.mouseDown( container.querySelector('div.react-select__dropdown-indicator')!, { button: 0, } ); availableOptions = [ ...container.querySelectorAll('.react-select__option'), ].map((option) => option.textContent); expect(availableOptions.indexOf('0') > -1).toBeFalsy(); }); test('multi select > to not hide the selected options from the menu if hideSelectedOptions is false', () => { let { container } = render( <Select className="react-select" classNamePrefix="react-select" hideSelectedOptions={false} isMulti menuIsOpen onChange={jest.fn()} onInputChange={jest.fn()} onMenuClose={jest.fn()} onMenuOpen={jest.fn()} options={OPTIONS} inputValue="" value={null} /> ); let firstOption = container.querySelectorAll('.react-select__option')[0]; let secondoption = container.querySelectorAll('.react-select__option')[1]; expect(firstOption.textContent).toBe('0'); expect(secondoption.textContent).toBe('1'); userEvent.click(firstOption); expect(firstOption.textContent).toBe('0'); expect(secondoption.textContent).toBe('1'); }); test('multi select > call onChange with all values but last selected value and remove event on hitting backspace', () => { let onChangeSpy = jest.fn(); let { container } = render( <Select {...BASIC_PROPS} isMulti onChange={onChangeSpy} value={[OPTIONS[0], OPTIONS[1], OPTIONS[2]]} /> ); expect(container.querySelector('.react-select__control')!.textContent).toBe( '012' ); fireEvent.keyDown(container.querySelector('.react-select__control')!, { keyCode: 8, key: 'Backspace', }); expect(onChangeSpy).toHaveBeenCalledWith( [ { label: '0', value: 'zero' }, { label: '1', value: 'one' }, ], { action: 'pop-value', removedValue: { label: '2', value: 'two' }, name: BASIC_PROPS.name, } ); }); test('should not call onChange on hitting backspace when backspaceRemovesValue is false', () => { let onChangeSpy = jest.fn(); let { container } = render( <Select {...BASIC_PROPS} backspaceRemovesValue={false} onChange={onChangeSpy} /> ); fireEvent.keyDown(container.querySelector('.react-select__control')!, { keyCode: 8, key: 'Backspace', }); expect(onChangeSpy).not.toHaveBeenCalled(); }); test('should not call onChange on hitting backspace even when backspaceRemovesValue is true if isClearable is false', () => { let onChangeSpy = jest.fn(); let { container } = render( <Select {...BASIC_PROPS} backspaceRemovesValue isClearable={false} onChange={onChangeSpy} /> ); fireEvent.keyDown(container.querySelector('.react-select__control')!, { keyCode: 8, key: 'Backspace', }); expect(onChangeSpy).not.toHaveBeenCalled(); }); test('should call onChange with `null` on hitting backspace when backspaceRemovesValue is true and isMulti is false', () => { let onChangeSpy = jest.fn(); let { container } = render( <Select {...BASIC_PROPS} backspaceRemovesValue isClearable isMulti={false} onChange={onChangeSpy} /> ); fireEvent.keyDown(container.querySelector('.react-select__control')!, { keyCode: 8, key: 'Backspace', }); expect(onChangeSpy).toHaveBeenCalledWith(null, { action: 'clear', name: 'test-input-name', removedValues: [], }); }); test('should call onChange with an array on hitting backspace when backspaceRemovesValue is true and isMulti is true', () => { let onChangeSpy = jest.fn(); let { container } = render( <Select {...BASIC_PROPS} backspaceRemovesValue isClearable isMulti onChange={onChangeSpy} /> ); fireEvent.keyDown(container.querySelector('.react-select__control')!, { keyCode: 8, key: 'Backspace', }); expect(onChangeSpy).toHaveBeenCalledWith([], { action: 'pop-value', name: 'test-input-name', removedValue: undefined, }); }); test('multi select > clicking on X next to option will call onChange with all options other that the clicked option', () => { let onChangeSpy = jest.fn(); let { container } = render( <Select {...BASIC_PROPS} isMulti onChange={onChangeSpy} value={[OPTIONS[0], OPTIONS[2], OPTIONS[4]]} /> ); // there are 3 values in select expect(container.querySelectorAll('.react-select__multi-value').length).toBe( 3 ); const selectValueElement = [ ...container.querySelectorAll('.react-select__multi-value'), ].find((multiValue) => multiValue.textContent === '4'); userEvent.click( selectValueElement!.querySelector('div.react-select__multi-value__remove')! ); expect(onChangeSpy).toHaveBeenCalledWith( [ { label: '0', value: 'zero' }, { label: '2', value: 'two' }, ], { action: 'remove-value', removedValue: { label: '4', value: 'four' }, name: BASIC_PROPS.name, } ); }); /** * TODO: Need to get hightlight a menu option and then match value with aria-activedescendant prop */ cases( 'accessibility > aria-activedescendant', ({ props = { ...BASIC_PROPS } }) => { let { container } = render(<Select {...props} menuIsOpen />); fireEvent.keyDown(container.querySelector('.react-select__menu')!, { keyCode: 40, key: 'ArrowDown', }); expect( container .querySelector('input.react-select__input')! .getAttribute('aria-activedescendant') ).toBe('1'); }, { 'single select > should update aria-activedescendant as per focused option': { skip: true, }, 'multi select > should update aria-activedescendant as per focused option': { skip: true, props: { ...BASIC_PROPS, value: { label: '2', value: 'two' }, }, }, } ); cases( 'accessibility > passes through aria-labelledby prop', ({ props = { ...BASIC_PROPS, 'aria-labelledby': 'testing' } }) => { let { container } = render(<Select {...props} />); expect( container .querySelector('input.react-select__input')! .getAttribute('aria-labelledby') ).toBe('testing'); }, { 'single select > should pass aria-labelledby prop down to input': {}, 'multi select > should pass aria-labelledby prop down to input': { props: { ...BASIC_PROPS, 'aria-labelledby': 'testing', isMulti: true, }, }, } ); cases( 'accessibility > passes through aria-errormessage prop', ({ props = { ...BASIC_PROPS, 'aria-errormessage': 'error-message' } }) => { let { container } = render(<Select {...props} />); expect( container .querySelector('input.react-select__input')! .getAttribute('aria-errormessage') ).toBe('error-message'); }, { 'single select > should pass aria-errormessage prop down to input': {}, 'multi select > should pass aria-errormessage prop down to input': { props: { ...BASIC_PROPS, 'aria-errormessage': 'error-message', isMulti: true, }, }, } ); cases( 'accessibility > passes through aria-invalid prop', ({ props = { ...BASIC_PROPS, 'aria-invalid': true } }) => { let { container } = render(<Select {...props} />); expect( container .querySelector('input.react-select__input')! .getAttribute('aria-invalid') ).toBe('true'); }, { 'single select > should pass aria-invalid prop down to input': {}, 'multi select > should pass aria-invalid prop down to input': { props: { ...BASIC_PROPS, 'aria-invalid': true, isMulti: true, }, }, } ); cases( 'accessibility > passes through aria-label prop', ({ props = { ...BASIC_PROPS, 'aria-label': 'testing' } }) => { let { container } = render(<Select {...props} />); expect( container .querySelector('input.react-select__input')! .getAttribute('aria-label') ).toBe('testing'); }, { 'single select > should pass aria-labelledby prop down to input': {}, 'multi select > should pass aria-labelledby prop down to input': { props: { ...BASIC_PROPS, 'aria-label': 'testing', isMulti: true, }, }, } ); test('accessibility > to show the number of options available in A11yText when the menu is Open', () => { let { container, rerender } = render( <Select {...BASIC_PROPS} inputValue={''} autoFocus menuIsOpen /> ); let setInputValue = (val: string) => { rerender(<Select {...BASIC_PROPS} autoFocus menuIsOpen inputValue={val} />); }; const liveRegionId = '#aria-context'; fireEvent.focus(container.querySelector('input.react-select__input')!); expect(container.querySelector(liveRegionId)!.textContent).toMatch( /17 results available/ ); setInputValue('0'); expect(container.querySelector(liveRegionId)!.textContent).toMatch( /2 results available/ ); setInputValue('10'); expect(container.querySelector(liveRegionId)!.textContent).toMatch( /1 result available/ ); setInputValue('100'); expect(container.querySelector(liveRegionId)!.textContent).toMatch( /0 results available/ ); }); test('accessibility > interacting with disabled options shows correct A11yText', () => { let { container } = render( <Select {...BASIC_PROPS} options={OPTIONS_DISABLED} inputValue={''} menuIsOpen /> ); const liveRegionId = '#aria-context'; const liveRegionEventId = '#aria-selection'; fireEvent.focus(container.querySelector('input.react-select__input')!); // navigate to disabled option let menu = container.querySelector('.react-select__menu'); fireEvent.keyDown(menu!, { keyCode: 40, key: 'ArrowDown' }); fireEvent.keyDown(menu!, { keyCode: 40, key: 'ArrowDown' }); expect(container.querySelector(liveRegionId)!.textContent).toMatch( 'option 1 focused disabled, 2 of 17. 17 results available. Use Up and Down to choose options, press Escape to exit the menu, press Tab to select the option and exit the menu.' ); // attempt to select disabled option fireEvent.keyDown(container.querySelector('.react-select__menu')!, { keyCode: 13, key: 'Enter', }); expect(container.querySelector(liveRegionEventId)!.textContent).toMatch( 'option 1 is disabled. Select another option.' ); }); test('accessibility > interacting with multi values options shows correct A11yText', () => { let renderProps = { ...BASIC_PROPS, options: OPTIONS_DISABLED, isMulti: true, value: [OPTIONS_DISABLED[0], OPTIONS_DISABLED[1]], hideSelectedOptions: false, }; let { container, rerender } = render(<Select {...renderProps} />); let openMenu = () => { rerender(<Select {...renderProps} menuIsOpen />); }; const liveRegionId = '#aria-context'; let input = container.querySelector('.react-select__value-container input')!; fireEvent.focus(container.querySelector('input.react-select__input')!); expect(container.querySelector(liveRegionId)!.textContent).toMatch( ' Select is focused ,type to refine list, press Down to open the menu, press left to focus selected values' ); fireEvent.keyDown(input, { keyCode: 37, key: 'ArrowLeft' }); expect(container.querySelector(liveRegionId)!.textContent).toMatch( 'value 1 focused, 2 of 2. Use left and right to toggle between focused values, press Backspace to remove the currently focused value' ); fireEvent.keyDown(input, { keyCode: 37, key: 'ArrowLeft' }); expect(container.querySelector(liveRegionId)!.textContent).toMatch( 'value 0 focused, 1 of 2. Use left and right to toggle between focused values, press Backspace to remove the currently focused value' ); openMenu(); let menu = container.querySelector('.react-select__menu')!; expect(container.querySelector(liveRegionId)!.textContent).toMatch( 'option 0 selected, 1 of 17. 17 results available. Use Up and Down to choose options, press Enter to select the currently focused option, press Escape to exit the menu, press Tab to select the option and exit the menu.' ); fireEvent.keyDown(menu, { keyCode: 40, key: 'ArrowDown' }); expect(container.querySelector(liveRegionId)!.textContent).toMatch( 'option 1 selected disabled, 2 of 17. 17 results available. Use Up and Down to choose options, press Escape to exit the menu, press Tab to select the option and exit the menu.' ); fireEvent.keyDown(menu, { keyCode: 40, key: 'ArrowDown' }); expect(container.querySelector(liveRegionId)!.textContent).toMatch( 'option 2 focused, 3 of 17. 17 results available. Use Up and Down to choose options, press Enter to select the currently focused option, press Escape to exit the menu, press Tab to select the option and exit the menu.' ); }); test('accessibility > screenReaderStatus function prop > to pass custom text to A11yText', () => { const screenReaderStatus = ({ count }: { count: number }) => `There are ${count} options available`; const liveRegionId = '#aria-context'; let { container, rerender } = render( <Select {...BASIC_PROPS} inputValue={''} screenReaderStatus={screenReaderStatus} menuIsOpen /> ); let setInputValue = (val: string) => { rerender( <Select {...BASIC_PROPS} screenReaderStatus={screenReaderStatus} menuIsOpen inputValue={val} /> ); }; fireEvent.focus(container.querySelector('input.react-select__input')!); expect(container.querySelector(liveRegionId)!.textContent).toMatch( 'There are 17 options available' ); setInputValue('0'); expect(container.querySelector(liveRegionId)!.textContent).toMatch( 'There are 2 options available' ); setInputValue('10'); expect(container.querySelector(liveRegionId)!.textContent).toMatch( 'There are 1 options available' ); setInputValue('100'); expect(container.querySelector(liveRegionId)!.textContent).toMatch( 'There are 0 options available' ); }); test('accessibility > A11yTexts can be provided through ariaLiveMessages prop', () => { const ariaLiveMessages: AriaLiveMessages<Option, boolean, GroupBase<Option>> = { onChange: (props) => { const { action, isDisabled, label } = props; if (action === 'select-option' && !isDisabled) { return `CUSTOM: option ${label} is selected.`; } return ''; }, }; let { container } = render( <Select {...BASIC_PROPS} ariaLiveMessages={ariaLiveMessages} options={OPTIONS} inputValue={''} menuIsOpen /> ); const liveRegionEventId = '#aria-selection'; expect(container.querySelector(liveRegionEventId)!).toBeNull(); fireEvent.focus(container.querySelector('input.react-select__input')!); let menu = container.querySelector('.react-select__menu')!; fireEvent.keyDown(menu, { keyCode: 40, key: 'ArrowDown' }); fireEvent.keyDown(container.querySelector('.react-select__menu')!, { keyCode: 13, key: 'Enter', }); expect(container.querySelector(liveRegionEventId)!.textContent).toMatch( 'CUSTOM: option 0 is selected.' ); }); test('accessibility > announces already selected values when focused', () => { let { container } = render( <Select {...BASIC_PROPS} options={OPTIONS} value={OPTIONS[0]} /> ); const liveRegionSelectionId = '#aria-selection'; const liveRegionContextId = '#aria-context'; // the live region should not be mounted yet expect(container.querySelector(liveRegionSelectionId)!).toBeNull(); fireEvent.focus(container.querySelector('input.react-select__input')!); expect(container.querySelector(liveRegionContextId)!.textContent).toMatch( ' Select is focused ,type to refine list, press Down to open the menu, ' ); expect(container.querySelector(liveRegionSelectionId)!.textContent).toMatch( 'option 0, selected.' ); }); test('accessibility > announces cleared values', () => { let { container } = render( <Select {...BASIC_PROPS} options={OPTIONS} value={OPTIONS[0]} isClearable /> ); const liveRegionSelectionId = '#aria-selection'; /** * announce deselected value */ fireEvent.focus(container.querySelector('input.react-select__input')!); fireEvent.mouseDown( container.querySelector('.react-select__clear-indicator')! ); expect(container.querySelector(liveRegionSelectionId)!.textContent).toMatch( 'All selected options have been cleared.' ); }); test('closeMenuOnSelect prop > when passed as false it should not call onMenuClose on selecting option', () => { let onMenuCloseSpy = jest.fn(); let { container } = render( <Select {...BASIC_PROPS} onMenuClose={onMenuCloseSpy} menuIsOpen closeMenuOnSelect={false} blurInputOnSelect={false} /> ); userEvent.click(container.querySelector('div.react-select__option')!); expect(onMenuCloseSpy).not.toHaveBeenCalled(); }); cases( 'autoFocus', ({ props = { ...BASIC_PROPS, autoFocus: true } }) => { let { container } = render(<Select {...props} />); expect(container.querySelector('input.react-select__input')).toBe( document.activeElement ); }, { 'single select > should focus select on mount': {}, 'multi select > should focus select on mount': { props: { ...BASIC_PROPS, isMulti: true, autoFocus: true, }, }, } ); cases( 'onFocus prop with autoFocus', ({ props = { ...BASIC_PROPS, autoFocus: true } }) => { let onFocusSpy = jest.fn(); let { container } = render(<Select {...props} onFocus={onFocusSpy} />); expect(container.querySelector('input.react-select__input')).toBe( document.activeElement ); expect(onFocusSpy).toHaveBeenCalledTimes(1); }, { 'single select > should call auto focus only once when select is autoFocus': { props: { ...BASIC_PROPS, autoFocus: true, }, }, 'multi select > should call auto focus only once when select is autoFocus': { props: { ...BASIC_PROPS, autoFocus: true, isMulti: true, }, }, } ); cases( 'onFocus prop is called on on focus of input', ({ props = { ...BASIC_PROPS } }) => { let onFocusSpy = jest.fn(); let { container } = render(<Select {...props} onFocus={onFocusSpy} />); fireEvent.focus(container.querySelector('input.react-select__input')!); expect(onFocusSpy).toHaveBeenCalledTimes(1); }, { 'single select > should call onFocus handler on focus on input': {}, 'multi select > should call onFocus handler on focus on input': { props: { ...BASIC_PROPS, isMulti: true, }, }, } ); cases( 'onBlur prop', ({ props = { ...BASIC_PROPS } }) => { let onBlurSpy = jest.fn(); let { container } = render( <Select {...props} onBlur={onBlurSpy} onInputChange={jest.fn()} onMenuClose={jest.fn()} /> ); fireEvent.blur(container.querySelector('input.react-select__input')!); expect(onBlurSpy).toHaveBeenCalledTimes(1); }, { 'single select > should call onBlur handler on blur on input': {}, 'multi select > should call onBlur handler on blur on input': { props: { ...BASIC_PROPS, isMulti: true, }, }, } ); test('onInputChange() function prop to be called on blur', () => { let onInputChangeSpy = jest.fn(); let { container } = render( <Select {...BASIC_PROPS} onBlur={jest.fn()} onInputChange={onInputChangeSpy} onMenuClose={jest.fn()} /> ); fireEvent.blur(container.querySelector('input.react-select__input')!); // Once by blur and other time by menu-close expect(onInputChangeSpy).toHaveBeenCalledTimes(2); }); test('onMenuClose() function prop to be called on blur', () => { let onMenuCloseSpy = jest.fn(); let { container } = render( <Select {...BASIC_PROPS} onBlur={jest.fn()} onInputChange={jest.fn()} onMenuClose={onMenuCloseSpy} /> ); fireEvent.blur(container.querySelector('input.react-select__input')!); expect(onMenuCloseSpy).toHaveBeenCalledTimes(1); }); cases( 'placeholder', ({ props, expectPlaceholder = 'Select...' }) => { let { container } = render(<Select {...props} />); expect(container.querySelector('.react-select__control')!.textContent).toBe( expectPlaceholder ); }, { 'single select > should display default placeholder "Select..."': { props: BASIC_PROPS, }, 'single select > should display provided string placeholder': { props: { ...BASIC_PROPS, placeholder: 'single Select...', }, expectPlaceholder: 'single Select...', }, 'single select > should display provided node placeholder': { props: { ...BASIC_PROPS, placeholder: <span>single Select...</span>, }, expectPlaceholder: 'single Select...', }, 'multi select > should display default placeholder "Select..."': { props: { ...BASIC_PROPS, isMulti: true, }, }, 'multi select > should display provided placeholder': { props: { ...BASIC_PROPS, isMulti: true, placeholder: 'multi Select...', }, expectPlaceholder: 'multi Select...', }, } ); cases( 'display placeholder once value is removed', ({ props }) => { let { container, rerender } = render(<Select {...props} />); expect( container.querySelector('.react-select__placeholder') ).not.toBeInTheDocument(); rerender(<Select {...props} value={null} />); expect( container.querySelector('.react-select__placeholder') ).toBeInTheDocument(); }, { 'single select > should display placeholder once the value is removed from select': { props: { ...BASIC_PROPS, value: OPTIONS[0], }, }, 'multi select > should display placeholder once the value is removed from select': { props: { ...BASIC_PROPS, value: OPTIONS[0], }, }, } ); test('sets inputMode="none" when isSearchable is false', () => { let { container } = render( <Select classNamePrefix="react-select" options={OPTIONS} isSearchable={false} onChange={noop} onInputChange={noop} onMenuOpen={noop} onMenuClose={noop} inputValue="" value={null} /> ); let input = container.querySelector<HTMLInputElement>( '.react-select__value-container input' ); expect(input!.inputMode).toBe('none'); expect( window.getComputedStyle(input!).getPropertyValue('caret-color') ).toEqual('transparent'); }); cases( 'clicking on disabled option', ({ props = BASIC_PROPS, optionsSelected }) => { let onChangeSpy = jest.fn(); props = { ...props, onChange: onChangeSpy }; let { container } = render(<Select {...props} menuIsOpen />); let selectOption = [ ...container.querySelectorAll('div.react-select__option'), ].find((n) => n.textContent === optionsSelected); userEvent.click(selectOption!); expect(onChangeSpy).not.toHaveBeenCalled(); }, { 'single select > should not select the disabled option': { props: { ...BASIC_PROPS, options: [ { label: 'option 1', value: 'opt1' }, { label: 'option 2', value: 'opt2', isDisabled: true }, ], }, optionsSelected: 'option 2', }, 'multi select > should not select the disabled option': { props: { ...BASIC_PROPS, options: [ { label: 'option 1', value: 'opt1' }, { label: 'option 2', value: 'opt2', isDisabled: true }, ], }, optionsSelected: 'option 2', }, } ); cases( 'pressing enter on disabled option', ({ props = BASIC_PROPS, optionsSelected }) => { let onChangeSpy = jest.fn(); props = { ...props, onChange: onChangeSpy }; let { container } = render(<Select {...props} menuIsOpen />); let selectOption = [ ...container.querySelectorAll('div.react-select__option'), ].find((n) => n.textContent === optionsSelected); fireEvent.keyDown(selectOption!, { keyCode: 13, key: 'Enter' }); expect(onChangeSpy).not.toHaveBeenCalled(); }, { 'single select > should not select the disabled option': { props: { ...BASIC_PROPS, options: [ { label: 'option 1', value: 'opt1' }, { label: 'option 2', value: 'opt2', isDisabled: true }, ], }, optionsSelected: 'option 2', }, 'multi select > should not select the disabled option': { props: { ...BASIC_PROPS, options: [ { label: 'option 1', value: 'opt1' }, { label: 'option 2', value: 'opt2', isDisabled: true }, ], }, optionsSelected: 'option 2', }, } ); test('does not select anything when a disabled option is the only item in the list after a search', () => { let onChangeSpy = jest.fn(); const options = [ { label: 'opt', value: 'opt1', isDisabled: true }, ...OPTIONS, ]; const props = { ...BASIC_PROPS, onChange: onChangeSpy, options }; let { container, rerender } = render( <Select {...props} menuIsOpen inputValue="" /> ); rerender(<Select {...props} menuIsOpen inputValue="opt" />); fireEvent.keyDown(container.querySelector('.react-select__menu')!, { keyCode: 13, key: 'Enter', }); expect(onChangeSpy).not.toHaveBeenCalled(); // Menu is still open expect(container.querySelector('.react-select__option')!.textContent).toBe( 'opt' ); }); test('render custom Input Component', () => { const InputComponent = () => <div className="my-input-component" />; let { container } = render( <Select {...BASIC_PROPS} components={{ Input: InputComponent }} /> ); expect( container.querySelector('input.react-select__input') ).not.toBeInTheDocument(); expect(container.querySelector('.my-input-component')).toBeInTheDocument(); }); test('render custom Menu Component', () => { const MenuComponent = () => <div className="my-menu-component" />; let { container } = render( <Select {...BASIC_PROPS} menuIsOpen components={{ Menu: MenuComponent }} /> ); expect( container.querySelector('.react-select__menu') ).not.toBeInTheDocument(); expect(container.querySelector('.my-menu-component')).toBeInTheDocument(); }); test('render custom Option Component', () => { const OptionComponent = () => <div className="my-option-component" />; let { container } = render( <Select {...BASIC_PROPS} components={{ Option: OptionComponent }} menuIsOpen /> ); expect( container.querySelector('.react-select__option') ).not.toBeInTheDocument(); expect(container.querySelector('.my-option-component')).toBeInTheDocument(); }); cases( 'isClearable is false', ({ props = BASIC_PROPS }) => { let { container } = render(<Select {...props} />); expect( container.querySelector('react-select__clear-indicator') ).not.toBeInTheDocument(); }, { 'single select > should not show the X (clear) button': { props: { ...BASIC_PROPS, isClearable: false, value: OPTIONS[0], }, }, 'multi select > should not show X (clear) button': { ...BASIC_PROPS, isMulti: true, isClearable: false, value: [OPTIONS[0]], }, } ); test('clear select by clicking on clear button > should not call onMenuOpen', () => { let onChangeSpy = jest.fn(); let props = { ...BASIC_PROPS, onChange: onChangeSpy }; let { container } = render( <Select {...props} isMulti value={[OPTIONS[0]]} /> ); expect(container.querySelectorAll('.react-select__multi-value').length).toBe( 1 ); fireEvent.mouseDown( container.querySelector('.react-select__clear-indicator')!, { button: 0 } ); expect(onChangeSpy).toBeCalledWith([], { action: 'clear', name: BASIC_PROPS.name, removedValues: [{ label: '0', value: 'zero' }], }); }); test('clearing select using clear button to not call onMenuOpen or onMenuClose', () => { let onMenuCloseSpy = jest.fn(); let onMenuOpenSpy = jest.fn(); let props = { ...BASIC_PROPS, onMenuClose: onMenuCloseSpy, onMenuOpen: onMenuOpenSpy, }; let { container } = render( <Select {...props} isMulti value={[OPTIONS[0]]} /> ); expect(container.querySelectorAll('.react-select__multi-value').length).toBe( 1 ); fireEvent.mouseDown( container.querySelector('.react-select__clear-indicator')!, { button: 0 } ); expect(onMenuOpenSpy).not.toHaveBeenCalled(); expect(onMenuCloseSpy).not.toHaveBeenCalled(); }); test('multi select > calls onChange when option is selected and isSearchable is false', () => { let onChangeSpy = jest.fn(); let props = { ...BASIC_PROPS, onChange: onChangeSpy }; let { container } = render( <Select {...props} isMulti menuIsOpen delimiter="," isSearchable={false} /> ); userEvent.click(container.querySelector('.react-select__option')!); const selectedOption = { label: '0', value: 'zero' }; expect(onChangeSpy).toHaveBeenCalledWith([selectedOption], { action: 'select-option', option: selectedOption, name: BASIC_PROPS.name, }); }); test('getOptionLabel() prop > to format the option label', () => { const getOptionLabel = (option: Option) => `This a custom option ${option.label} label`; const { container } = render( <Select {...BASIC_PROPS} menuIsOpen getOptionLabel={getOptionLabel} /> ); expect(container.querySelector('.react-select__option')!.textContent).toBe( 'This a custom option 0 label' ); }); test('formatGroupLabel function prop > to format Group label', () => { const formatGroupLabel = (group: Group) => `This is custom ${group.label} header`; interface GroupOption { readonly value: number; readonly label: string; } interface Group { readonly label: string; readonly options: readonly GroupOption[]; } const options = [ { label: 'group 1', options: [ { value: 1, label: '1' }, { value: 2, label: '2' }, ], }, ]; const { container } = render( <Select<GroupOption, false, Group> classNamePrefix="react-select" options={options} menuIsOpen formatGroupLabel={formatGroupLabel} onChange={noop} onInputChange={noop} onMenuOpen={noop} onMenuClose={noop} inputValue="" value={null} /> ); expect( container.querySelector('.react-select__group-heading')!.textContent ).toBe('This is custom group 1 header'); }); test('to only render groups with at least one match when filtering', () => { const options = [ { label: 'group 1', options: [ { value: 1, label: '1' }, { value: 2, label: '2' }, ], }, { label: 'group 2', options: [ { value: 3, label: '3' }, { value: 4, label: '4' }, ], }, ]; const { container } = render( <Select classNamePrefix="react-select" options={options} menuIsOpen inputValue="1" onChange={noop} onInputChange={noop} onMenuOpen={noop} onMenuClose={noop} value={null} /> ); expect(container.querySelectorAll('.react-select__group').length).toBe(1); expect( container .querySelector('.react-select__group')! .querySelectorAll('.react-select__option').length ).toBe(1); }); test('not render any groups when there is not a single match when filtering', () => { const options = [ { label: 'group 1', options: [ { value: 1, label: '1' }, { value: 2, label: '2' }, ], }, { label: 'group 2', options: [ { value: 3, label: '3' }, { value: 4, label: '4' }, ], }, ]; const { container } = render( <Select classNamePrefix="react-select" options={options} menuIsOpen inputValue="5" onChange={noop} onInputChange={noop} onMenuOpen={noop} onMenuClose={noop} value={null} /> ); expect(container.querySelectorAll('.react-select__group').length).toBe(0); }); test('multi select > have default value delimiter seperated', () => { let { container } = render( <Select {...BASIC_PROPS} delimiter={';'} isMulti value={[OPTIONS[0], OPTIONS[1]]} /> ); expect( container.querySelector<HTMLInputElement>('input[type="hidden"]')!.value ).toBe('zero;one'); }); test('multi select > with multi character delimiter', () => { let { container } = render( <Select {...BASIC_PROPS} delimiter={'===&==='} isMulti value={[OPTIONS[0], OPTIONS[1]]} /> ); expect( container.querySelector<HTMLInputElement>('input[type="hidden"]')!.value ).toBe('zero===&===one'); }); test('hitting spacebar should select option if isSearchable is false', () => { let onChangeSpy = jest.fn(); let props = { ...BASIC_PROPS, onChange: onChangeSpy }; let { container } = render(<Select {...props} isSearchable menuIsOpen />); // focus the first option fireEvent.keyDown(container.querySelector('.react-select__menu')!, { keyCode: 40, key: 'ArrowDown', }); fireEvent.keyDown(container.querySelector('.react-select')!, { keyCode: 32, key: ' ', }); expect(onChangeSpy).toHaveBeenCalledWith( { label: '0', value: 'zero' }, { action: 'select-option', name: BASIC_PROPS.name } ); }); test('hitting escape does not call onChange if menu is Open', () => { let onChangeSpy = jest.fn(); let props = { ...BASIC_PROPS, onChange: onChangeSpy }; let { container } = render( <Select {...props} menuIsOpen escapeClearsValue isClearable /> ); // focus the first option fireEvent.keyDown(container.querySelector('.react-select__menu')!, { keyCode: 40, key: 'ArrowDown', }); expect(onChangeSpy).not.toHaveBeenCalled(); }); test('multi select > removes the selected option from the menu options when isSearchable is false', () => { let { container, rerender } = render( <Select {...BASIC_PROPS} delimiter="," isMulti isSearchable={false} menuIsOpen /> ); expect(container.querySelectorAll('.react-select__option').length).toBe(17); rerender( <Select {...BASIC_PROPS} delimiter="," isMulti isSearchable={false} menuIsOpen value={OPTIONS[0]} /> ); // expect '0' to not be options container.querySelectorAll('.react-select__option').forEach((option) => { expect(option.textContent).not.toBe('0'); }); expect(container.querySelectorAll('.react-select__option').length).toBe(16); }); test('hitting ArrowUp key on closed select should focus last element', () => { let { container } = render(<Select {...BASIC_PROPS} menuIsOpen />); fireEvent.keyDown(container.querySelector('.react-select__control')!, { keyCode: 38, key: 'ArrowUp', }); expect( container.querySelector('.react-select__option--is-focused')!.textContent ).toEqual('16'); }); test('close menu on hitting escape and clear input value if menu is open even if escapeClearsValue and isClearable are true', () => { let onMenuCloseSpy = jest.fn(); let onInputChangeSpy = jest.fn(); let props = { ...BASIC_PROPS, onInputChange: onInputChangeSpy, onMenuClose: onMenuCloseSpy, value: OPTIONS[0], }; let { container } = render( <Select {...props} menuIsOpen escapeClearsValue isClearable /> ); fireEvent.keyDown(container.querySelector('.react-select')!, { keyCode: 27, key: 'Escape', }); expect( container.querySelector('.react-select__single-value')!.textContent ).toEqual('0'); expect(onMenuCloseSpy).toHaveBeenCalled(); // once by onMenuClose and other is direct expect(onInputChangeSpy).toHaveBeenCalledTimes(2); expect(onInputChangeSpy).toHaveBeenCalledWith('', { action: 'menu-close', prevInputValue: '', }); expect(onInputChangeSpy).toHaveBeenLastCalledWith('', { action: 'menu-close', prevInputValue: '', }); }); test('to not clear value when hitting escape if escapeClearsValue is false (default) and isClearable is false', () => { let onChangeSpy = jest.fn(); let props = { ...BASIC_PROPS, onChange: onChangeSpy, value: OPTIONS[0] }; let { container } = render( <Select {...props} escapeClearsValue isClearable={false} /> ); fireEvent.keyDown(container.querySelector('.react-select')!, { keyCode: 27, key: 'Escape', }); expect(onChangeSpy).not.toHaveBeenCalled(); }); test('to not clear value when hitting escape if escapeClearsValue is true and isClearable is false', () => { let onChangeSpy = jest.fn(); let props = { ...BASIC_PROPS, onChange: onChangeSpy, value: OPTIONS[0] }; let { container } = render( <Select {...props} escapeClearsValue isClearable={false} /> ); fireEvent.keyDown(container.querySelector('.react-select')!, { keyCode: 27, key: 'Escape', }); expect(onChangeSpy).not.toHaveBeenCalled(); }); test('to not clear value when hitting escape if escapeClearsValue is false (default) and isClearable is true', () => { let onChangeSpy = jest.fn(); let props = { ...BASIC_PROPS, onChange: onChangeSpy, value: OPTIONS[0] }; let { container } = render(<Select {...props} isClearable />); fireEvent.keyDown(container.querySelector('.react-select')!, { keyCode: 27, key: 'Escape', }); expect(onChangeSpy).not.toHaveBeenCalled(); }); test('to clear value when hitting escape if escapeClearsValue and isClearable are true', () => { let onInputChangeSpy = jest.fn(); let props = { ...BASIC_PROPS, onChange: onInputChangeSpy, value: OPTIONS[0] }; let { container } = render( <Select {...props} isClearable escapeClearsValue /> ); fireEvent.keyDown(container.querySelector('.react-select')!, { keyCode: 27, key: 'Escape', }); expect(onInputChangeSpy).toHaveBeenCalledWith(null, { action: 'clear', name: BASIC_PROPS.name, removedValues: [{ label: '0', value: 'zero' }], }); }); test('hitting spacebar should not select option if isSearchable is true (default)', () => { let onChangeSpy = jest.fn(); let props = { ...BASIC_PROPS, onChange: onChangeSpy }; let { container } = render(<Select {...props} menuIsOpen />); // Open Menu fireEvent.keyDown(container, { keyCode: 32, key: ' ' }); expect(onChangeSpy).not.toHaveBeenCalled(); }); test('renders with custom theme', () => { const primary = 'rgb(255, 164, 83)'; const { container } = render( <Select {...BASIC_PROPS} value={OPTIONS[0]} menuIsOpen theme={(theme) => ({ ...theme, borderRadius: 180, colors: { ...theme.colors, primary, }, })} /> ); const menu = container.querySelector('.react-select__menu'); expect( window.getComputedStyle(menu!).getPropertyValue('border-radius') ).toEqual('180px'); const firstOption = container.querySelector('.react-select__option'); expect( window.getComputedStyle(firstOption!).getPropertyValue('background-color') ).toEqual(primary); });
the_stack
import fs from 'fs'; import { EventEmitter } from 'events'; import invariant from 'invariant'; import sleep from 'delay'; import warning from 'warning'; import { FacebookBatchQueue } from 'facebook-batch'; import { JsonObject } from 'type-fest'; import { MessengerBatch, MessengerClient } from 'messaging-api-messenger'; import Context from '../context/Context'; import Session from '../session/Session'; import { RequestContext } from '../types'; import MessengerEvent from './MessengerEvent'; import * as MessengerTypes from './MessengerTypes'; export type MessengerContextOptions = { appId?: string; client: MessengerClient; event: MessengerEvent; session?: Session; initialState?: JsonObject; requestContext?: RequestContext; customAccessToken?: string; batchQueue?: FacebookBatchQueue | null; emitter?: EventEmitter; }; class MessengerContext extends Context<MessengerClient, MessengerEvent> { _appId: string | null; _customAccessToken: string | null; _personaId: string | null = null; _batchQueue: FacebookBatchQueue | null; constructor({ appId, client, event, session, initialState, requestContext, customAccessToken, batchQueue, emitter, }: MessengerContextOptions) { super({ client, event, session, initialState, requestContext, emitter }); this._customAccessToken = customAccessToken || null; this._batchQueue = batchQueue || null; this._appId = appId || null; } /** * The name of the platform. * */ get platform(): 'messenger' { return 'messenger'; } get accessToken(): string | null { return this._customAccessToken || this._client.accessToken; } _getMethodOptions<O extends object>( options: O ): { accessToken?: string; } & O { return { ...(this._customAccessToken ? { accessToken: this._customAccessToken } : undefined), ...options, }; } _getSenderActionMethodOptions<O extends object>( options: O ): { accessToken?: string; personaId?: string; } & O { return { ...(this._personaId ? { personaId: this._personaId } : undefined), ...this._getMethodOptions(options), }; } _getSendMethodOptions< O extends { tag?: MessengerTypes.MessageTag; } >( options: O ): { accessToken?: string; personaId?: string; messagingType: MessengerTypes.MessagingType; } & O { const messagingType: MessengerTypes.MessagingType = options && options.tag ? 'MESSAGE_TAG' : 'RESPONSE'; return { messagingType, ...(this._personaId ? { personaId: this._personaId } : undefined), ...this._getMethodOptions(options), }; } /** * Inject persona for the context. * */ usePersona(personaId: string): void { this._personaId = personaId; } /** * Inject access token for the context. * */ useAccessToken(accessToken: string): void { this._customAccessToken = accessToken; } /** * Delay and show indicators for milliseconds. * */ async typing(milliseconds: number): Promise<void> { if (milliseconds > 0) { await this.typingOn(); await sleep(milliseconds); await this.typingOff(); } } /** * Send text to the owner of the session. * */ async sendText( text: string, options: MessengerTypes.SendOption = {} ): Promise<MessengerTypes.SendMessageSuccessResponse | undefined> { if (!this._session) { warning( false, 'sendText: should not be called in context without session' ); return; } if (this._event.isEcho || this._event.isDelivery || this._event.isRead) { warning( false, 'sendText: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); return; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.SendMessageSuccessResponse>( MessengerBatch.sendText( this._session.user.id, text, this._getSendMethodOptions(options) ) ); } return this._client.sendText( this._session.user.id, text, this._getSendMethodOptions(options) ); } async getUserProfile( options: { fields?: MessengerTypes.UserProfileField[]; } = {} ): Promise<MessengerTypes.User | null> { if (!this._session) { warning( false, 'getUserProfile: should not be called in context without session' ); return null; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.User>( MessengerBatch.getUserProfile( this._session.user.id, this._getMethodOptions(options) ) ); } return this._client.getUserProfile(this._session.user.id, options); } async getUserPersistentMenu(): Promise<MessengerTypes.PersistentMenu | null> { if (!this._session) { warning( false, `getUserPersistentMenu: should not be called in context without session` ); return null; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.PersistentMenu>( MessengerBatch.getUserPersistentMenu( this._session.user.id, this._getMethodOptions({}) ) ); } return this._client.getUserPersistentMenu(this._session.user.id); } async setUserPersistentMenu( attrs: MessengerTypes.PersistentMenu, options: { composerInputDisabled?: boolean; } = {} ): Promise<MessengerTypes.MutationSuccessResponse | undefined> { if (!this._session) { warning( false, `setUserPersistentMenu: should not be called in context without session` ); return; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.MutationSuccessResponse>( MessengerBatch.setUserPersistentMenu( this._session.user.id, attrs, this._getMethodOptions(options) ) ); } return this._client.setUserPersistentMenu( this._session.user.id, attrs, options ); } async deleteUserPersistentMenu(): Promise< MessengerTypes.MutationSuccessResponse | undefined > { if (!this._session) { warning( false, `deleteUserPersistentMenu: should not be called in context without session` ); return; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.MutationSuccessResponse>( MessengerBatch.deleteUserPersistentMenu( this._session.user.id, this._getMethodOptions({}) ) ); } return this._client.deleteUserPersistentMenu(this._session.user.id); } /** * Sender Actions * * https://github.com/Yoctol/messaging-apis/tree/master/packages/messaging-api-messenger#sender-actions */ /** * https://github.com/Yoctol/messaging-apis/tree/master/packages/messaging-api-messenger#sendsenderactionuserid-action */ async sendSenderAction( senderAction: MessengerTypes.SenderAction, options: MessengerTypes.SendOption = {} ): Promise<MessengerTypes.SendSenderActionResponse | undefined> { if (!this._session) { warning( false, 'sendSenderAction: should not be called in context without session' ); return; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.SendSenderActionResponse>( MessengerBatch.sendSenderAction( this._session.user.id, senderAction, this._getSenderActionMethodOptions(options) ) ); } return this._client.sendSenderAction( this._session.user.id, senderAction, this._getSenderActionMethodOptions(options) ); } /** * https://github.com/Yoctol/messaging-apis/tree/master/packages/messaging-api-messenger#typingonuserid */ async typingOn( options: MessengerTypes.SendOption = {} ): Promise<MessengerTypes.SendSenderActionResponse | undefined> { if (!this._session) { warning( false, 'typingOn: should not be called in context without session' ); return; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.SendSenderActionResponse>( MessengerBatch.typingOn( this._session.user.id, this._getSenderActionMethodOptions(options) ) ); } return this._client.typingOn( this._session.user.id, this._getSenderActionMethodOptions(options) ); } /** * https://github.com/Yoctol/messaging-apis/tree/master/packages/messaging-api-messenger#typingoffuserid */ async typingOff( options: MessengerTypes.SendOption = {} ): Promise<MessengerTypes.SendSenderActionResponse | undefined> { if (!this._session) { warning( false, 'typingOff: should not be called in context without session' ); return; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.SendSenderActionResponse>( MessengerBatch.typingOff( this._session.user.id, this._getSenderActionMethodOptions(options) ) ); } return this._client.typingOff( this._session.user.id, this._getSenderActionMethodOptions(options) ); } /** * https://github.com/Yoctol/messaging-apis/tree/master/packages/messaging-api-messenger#markseenuserid */ async markSeen(): Promise< MessengerTypes.SendSenderActionResponse | undefined > { if (!this._session) { warning( false, 'markSeen: should not be called in context without session' ); return; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.SendSenderActionResponse>( MessengerBatch.markSeen( this._session.user.id, // FIXME: this type should be fixed in MessengerBatch this._getMethodOptions({}) as any ) ); } return this._client.markSeen(this._session.user.id); } /** * Handover Protocol * * https://github.com/Yoctol/messaging-apis/tree/master/packages/messaging-api-messenger#handover-protocol-api */ /** * https://github.com/Yoctol/messaging-apis/tree/master/packages/messaging-api-messenger#passthreadcontroluserid-targetappid-metadata---official-docs */ async passThreadControl( targetAppId: number, metadata?: string ): Promise<{ success: true } | undefined> { if (!this._session) { warning( false, 'passThreadControl: should not be called in context without session' ); return; } if (this._batchQueue) { return this._batchQueue.push<{ success: true }>( MessengerBatch.passThreadControl( this._session.user.id, targetAppId, metadata, this._getMethodOptions({}) ) ); } return this._client.passThreadControl( this._session.user.id, targetAppId, metadata ); } /** * https://github.com/Yoctol/messaging-apis/tree/master/packages/messaging-api-messenger#passthreadcontroltopageinboxuserid-metadata---official-docs */ async passThreadControlToPageInbox( metadata?: string ): Promise<{ success: true } | undefined> { if (!this._session) { warning( false, 'passThreadControlToPageInbox: should not be called in context without session' ); return; } if (this._batchQueue) { return this._batchQueue.push<{ success: true }>( MessengerBatch.passThreadControlToPageInbox( this._session.user.id, metadata, this._getMethodOptions({}) ) ); } return this._client.passThreadControlToPageInbox( this._session.user.id, metadata ); } /** * https://github.com/Yoctol/messaging-apis/tree/master/packages/messaging-api-messenger#takethreadcontroluserid-metadata---official-docs */ async takeThreadControl( metadata?: string ): Promise<{ success: true } | undefined> { if (!this._session) { warning( false, 'takeThreadControl: should not be called in context without session' ); return; } if (this._batchQueue) { return this._batchQueue.push<{ success: true }>( MessengerBatch.takeThreadControl( this._session.user.id, metadata, this._getMethodOptions({}) ) ); } return this._client.takeThreadControl(this._session.user.id, metadata); } /** * https://github.com/Yoctol/messaging-apis/blob/master/packages/messaging-api-messenger/README.md#requestthreadcontroluserid-metadata---official-docs */ async requestThreadControl( metadata?: string ): Promise<{ success: true } | undefined> { if (!this._session) { warning( false, 'requestThreadControl: should not be called in context without session' ); return; } if (this._batchQueue) { return this._batchQueue.push<{ success: true }>( MessengerBatch.requestThreadControl( this._session.user.id, metadata, this._getMethodOptions({}) ) ); } return this._client.requestThreadControl(this._session.user.id, metadata); } /** * https://github.com/Yoctol/messaging-apis/blob/master/packages/messaging-api-messenger/README.md#requestthreadcontroluserid-metadata---official-docs */ async getThreadOwner(): Promise<{ appId: string } | undefined> { if (!this._session) { warning( false, 'getThreadOwner: should not be called in context without session' ); return; } if (this._batchQueue) { return this._batchQueue.push<{ appId: string }>( MessengerBatch.getThreadOwner( this._session.user.id, this._getMethodOptions({}) ) ); } return this._client.getThreadOwner(this._session.user.id); } async isThreadOwner(): Promise<boolean> { invariant( this._appId, 'isThreadOwner: must provide appId to use this feature' ); const threadOwner = await this.getThreadOwner(); if (!threadOwner) { return false; } const { appId } = threadOwner; return `${appId}` === `${this._appId}`; } /** * Targeting Broadcast Messages * * https://github.com/Yoctol/messaging-apis/tree/master/packages/messaging-api-messenger#targeting-broadcast-messages---official-docs */ /** * https://github.com/Yoctol/messaging-apis/tree/master/packages/messaging-api-messenger#associatelabeluserid-labelid */ async associateLabel( labelId: number ): Promise<{ success: true } | undefined> { if (!this._session) { warning( false, 'associateLabel: should not be called in context without session' ); return; } if (this._batchQueue) { return this._batchQueue.push<{ success: true }>( MessengerBatch.associateLabel( this._session.user.id, labelId, this._getMethodOptions({}) ) ); } return this._client.associateLabel(this._session.user.id, labelId); } /** * https://github.com/Yoctol/messaging-apis/tree/master/packages/messaging-api-messenger#dissociatelabeluserid-labelid */ async dissociateLabel( labelId: number ): Promise<{ success: true } | undefined> { if (!this._session) { warning( false, 'dissociateLabel: should not be called in context without session' ); return; } if (this._batchQueue) { return this._batchQueue.push<{ success: true }>( MessengerBatch.dissociateLabel( this._session.user.id, labelId, this._getMethodOptions({}) ) ); } return this._client.dissociateLabel(this._session.user.id, labelId); } /** * https://github.com/Yoctol/messaging-apis/tree/master/packages/messaging-api-messenger#getassociatedlabelsuserid */ async getAssociatedLabels(): Promise< | { data: { name: string; id: string; }[]; paging: { cursors: { before: string; after: string; }; }; } | undefined > { if (!this._session) { warning( false, 'getAssociatedLabels: should not be called in context without session' ); return; } if (this._batchQueue) { return this._batchQueue.push<{ data: { name: string; id: string; }[]; paging: { cursors: { before: string; after: string; }; }; }>( MessengerBatch.getAssociatedLabels( this._session.user.id, this._getMethodOptions({}) ) ); } return this._client.getAssociatedLabels(this._session.user.id); } async sendMessage( message: MessengerTypes.Message, options: MessengerTypes.SendOption = {} ): Promise<MessengerTypes.SendMessageSuccessResponse | undefined> { if (!this._session) { warning( false, 'sendMessage: should not be called in context without session' ); return; } if (this._event.isEcho || this._event.isDelivery || this._event.isRead) { warning( false, `sendMessage: calling Send APIs in \`message_reads\`(event.isRead), \`message_deliveries\`(event.isDelivery) or \`message_echoes\`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.` ); return; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.SendMessageSuccessResponse>( MessengerBatch.sendMessage( this._session.user.id, message, this._getSendMethodOptions(options) ) ); } return this._client.sendMessage( this._session.user.id, message, this._getSendMethodOptions(options) ); } async sendAttachment( attachment: MessengerTypes.Attachment, options: MessengerTypes.SendOption = {} ): Promise<MessengerTypes.SendMessageSuccessResponse | undefined> { if (!this._session) { warning( false, 'sendAttachment: should not be called in context without session' ); return; } if (this._event.isEcho || this._event.isDelivery || this._event.isRead) { warning( false, 'sendAttachment: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); return; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.SendMessageSuccessResponse>( MessengerBatch.sendAttachment( this._session.user.id, attachment, this._getSendMethodOptions(options) ) ); } return this._client.sendAttachment( this._session.user.id, attachment, this._getSendMethodOptions(options) ); } async sendImage( image: | string | MessengerTypes.FileData | MessengerTypes.MediaAttachmentPayload, options: MessengerTypes.SendOption = {} ): Promise<MessengerTypes.SendMessageSuccessResponse | undefined> { if (!this._session) { warning( false, 'sendImage: should not be called in context without session' ); return; } if (this._event.isEcho || this._event.isDelivery || this._event.isRead) { warning( false, 'sendImage: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); return; } if ( this._batchQueue && !Buffer.isBuffer(image) && !(image instanceof fs.ReadStream) ) { return this._batchQueue.push<MessengerTypes.SendMessageSuccessResponse>( MessengerBatch.sendImage( this._session.user.id, image, this._getSendMethodOptions(options) ) ); } return this._client.sendImage( this._session.user.id, image, this._getSendMethodOptions(options) ); } async sendAudio( audio: | string | MessengerTypes.FileData | MessengerTypes.MediaAttachmentPayload, options: MessengerTypes.SendOption = {} ): Promise<MessengerTypes.SendMessageSuccessResponse | undefined> { if (!this._session) { warning( false, 'sendAudio: should not be called in context without session' ); return; } if (this._event.isEcho || this._event.isDelivery || this._event.isRead) { warning( false, 'sendAudio: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); return; } if ( this._batchQueue && !Buffer.isBuffer(audio) && !(audio instanceof fs.ReadStream) ) { return this._batchQueue.push<MessengerTypes.SendMessageSuccessResponse>( MessengerBatch.sendAudio( this._session.user.id, audio, this._getSendMethodOptions(options) ) ); } return this._client.sendAudio( this._session.user.id, audio, this._getSendMethodOptions(options) ); } async sendVideo( video: | string | MessengerTypes.FileData | MessengerTypes.MediaAttachmentPayload, options: MessengerTypes.SendOption = {} ): Promise<MessengerTypes.SendMessageSuccessResponse | undefined> { if (!this._session) { warning( false, 'sendVideo: should not be called in context without session' ); return; } if (this._event.isEcho || this._event.isDelivery || this._event.isRead) { warning( false, 'sendVideo: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); return; } if ( this._batchQueue && !Buffer.isBuffer(video) && !(video instanceof fs.ReadStream) ) { return this._batchQueue.push<MessengerTypes.SendMessageSuccessResponse>( MessengerBatch.sendVideo( this._session.user.id, video, this._getSendMethodOptions(options) ) ); } return this._client.sendVideo( this._session.user.id, video, this._getSendMethodOptions(options) ); } async sendFile( file: | string | MessengerTypes.FileData | MessengerTypes.MediaAttachmentPayload, options: MessengerTypes.SendOption = {} ): Promise<MessengerTypes.SendMessageSuccessResponse | undefined> { if (!this._session) { warning( false, 'sendFile: should not be called in context without session' ); return; } if (this._event.isEcho || this._event.isDelivery || this._event.isRead) { warning( false, 'sendFile: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); return; } if ( this._batchQueue && !Buffer.isBuffer(file) && !(file instanceof fs.ReadStream) ) { return this._batchQueue.push<MessengerTypes.SendMessageSuccessResponse>( MessengerBatch.sendFile( this._session.user.id, file, this._getSendMethodOptions(options) ) ); } return this._client.sendFile( this._session.user.id, file, this._getSendMethodOptions(options) ); } async sendTemplate( payload: MessengerTypes.TemplateAttachmentPayload, options: MessengerTypes.SendOption = {} ): Promise<MessengerTypes.SendMessageSuccessResponse | undefined> { if (!this._session) { warning( false, 'sendTemplate: should not be called in context without session' ); return; } if (this._event.isEcho || this._event.isDelivery || this._event.isRead) { warning( false, 'sendTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); return; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.SendMessageSuccessResponse>( MessengerBatch.sendTemplate( this._session.user.id, payload, this._getSendMethodOptions(options) ) ); } return this._client.sendTemplate( this._session.user.id, payload, this._getSendMethodOptions(options) ); } async sendGenericTemplate( elements: MessengerTypes.TemplateElement[], options: { imageAspectRatio?: 'horizontal' | 'square'; } & MessengerTypes.SendOption ): Promise<MessengerTypes.SendMessageSuccessResponse | undefined> { if (!this._session) { warning( false, 'sendGenericTemplate: should not be called in context without session' ); return; } if (this._event.isEcho || this._event.isDelivery || this._event.isRead) { warning( false, 'sendGenericTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); return; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.SendMessageSuccessResponse>( MessengerBatch.sendGenericTemplate( this._session.user.id, elements, this._getSendMethodOptions(options) ) ); } return this._client.sendGenericTemplate( this._session.user.id, elements, this._getSendMethodOptions(options) ); } async sendButtonTemplate( text: string, buttons: MessengerTypes.TemplateButton[], options: MessengerTypes.SendOption = {} ): Promise<MessengerTypes.SendMessageSuccessResponse | undefined> { if (!this._session) { warning( false, 'sendButtonTemplate: should not be called in context without session' ); return; } if (this._event.isEcho || this._event.isDelivery || this._event.isRead) { warning( false, 'sendButtonTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); return; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.SendMessageSuccessResponse>( MessengerBatch.sendButtonTemplate( this._session.user.id, text, buttons, this._getSendMethodOptions(options) ) ); } return this._client.sendButtonTemplate( this._session.user.id, text, buttons, this._getSendMethodOptions(options) ); } async sendMediaTemplate( elements: MessengerTypes.MediaElement[], options: MessengerTypes.SendOption = {} ): Promise<MessengerTypes.SendMessageSuccessResponse | undefined> { if (!this._session) { warning( false, 'sendMediaTemplate: should not be called in context without session' ); return; } if (this._event.isEcho || this._event.isDelivery || this._event.isRead) { warning( false, 'sendMediaTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); return; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.SendMessageSuccessResponse>( MessengerBatch.sendMediaTemplate( this._session.user.id, elements, this._getSendMethodOptions(options) ) ); } return this._client.sendMediaTemplate( this._session.user.id, elements, this._getSendMethodOptions(options) ); } async sendReceiptTemplate( attrs: MessengerTypes.ReceiptAttributes, options: MessengerTypes.SendOption = {} ): Promise<MessengerTypes.SendMessageSuccessResponse | undefined> { if (!this._session) { warning( false, 'sendReceiptTemplate: should not be called in context without session' ); return; } if (this._event.isEcho || this._event.isDelivery || this._event.isRead) { warning( false, 'sendReceiptTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); return; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.SendMessageSuccessResponse>( MessengerBatch.sendReceiptTemplate( this._session.user.id, attrs, this._getSendMethodOptions(options) ) ); } return this._client.sendReceiptTemplate( this._session.user.id, attrs, this._getSendMethodOptions(options) ); } async sendAirlineBoardingPassTemplate( attrs: MessengerTypes.AirlineBoardingPassAttributes, options: MessengerTypes.SendOption = {} ): Promise<MessengerTypes.SendMessageSuccessResponse | undefined> { if (!this._session) { warning( false, 'sendAirlineBoardingPassTemplate: should not be called in context without session' ); return; } if (this._event.isEcho || this._event.isDelivery || this._event.isRead) { warning( false, 'sendAirlineBoardingPassTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); return; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.SendMessageSuccessResponse>( MessengerBatch.sendAirlineBoardingPassTemplate( this._session.user.id, attrs, this._getSendMethodOptions(options) ) ); } return this._client.sendAirlineBoardingPassTemplate( this._session.user.id, attrs, this._getSendMethodOptions(options) ); } async sendAirlineCheckinTemplate( attrs: MessengerTypes.AirlineCheckinAttributes, options: MessengerTypes.SendOption = {} ): Promise<MessengerTypes.SendMessageSuccessResponse | undefined> { if (!this._session) { warning( false, 'sendAirlineCheckinTemplate: should not be called in context without session' ); return; } if (this._event.isEcho || this._event.isDelivery || this._event.isRead) { warning( false, 'sendAirlineCheckinTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); return; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.SendMessageSuccessResponse>( MessengerBatch.sendAirlineCheckinTemplate( this._session.user.id, attrs, this._getSendMethodOptions(options) ) ); } return this._client.sendAirlineCheckinTemplate( this._session.user.id, attrs, this._getSendMethodOptions(options) ); } async sendAirlineItineraryTemplate( attrs: MessengerTypes.AirlineItineraryAttributes, options: MessengerTypes.SendOption = {} ): Promise<MessengerTypes.SendMessageSuccessResponse | undefined> { if (!this._session) { warning( false, 'sendAirlineItineraryTemplate: should not be called in context without session' ); return; } if (this._event.isEcho || this._event.isDelivery || this._event.isRead) { warning( false, 'sendAirlineItineraryTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); return; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.SendMessageSuccessResponse>( MessengerBatch.sendAirlineItineraryTemplate( this._session.user.id, attrs, this._getSendMethodOptions(options) ) ); } return this._client.sendAirlineItineraryTemplate( this._session.user.id, attrs, this._getSendMethodOptions(options) ); } async sendAirlineUpdateTemplate( attrs: MessengerTypes.AirlineUpdateAttributes, options: MessengerTypes.SendOption = {} ): Promise<MessengerTypes.SendMessageSuccessResponse | undefined> { if (!this._session) { warning( false, 'sendAirlineUpdateTemplate: should not be called in context without session' ); return; } if (this._event.isEcho || this._event.isDelivery || this._event.isRead) { warning( false, 'sendAirlineUpdateTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); return; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.SendMessageSuccessResponse>( MessengerBatch.sendAirlineUpdateTemplate( this._session.user.id, attrs, this._getSendMethodOptions(options) ) ); } return this._client.sendAirlineUpdateTemplate( this._session.user.id, attrs, this._getSendMethodOptions(options) ); } async sendOneTimeNotifReqTemplate( attrs: MessengerTypes.OneTimeNotifReqAttributes, options: MessengerTypes.SendOption = {} ): Promise<MessengerTypes.SendMessageSuccessResponse | undefined> { if (!this._session) { warning( false, 'sendOneTimeNotifReqTemplate: should not be called in context without session' ); return; } if (this._event.isEcho || this._event.isDelivery || this._event.isRead) { warning( false, 'sendOneTimeNotifReqTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); return; } if (this._batchQueue) { return this._batchQueue.push<MessengerTypes.SendMessageSuccessResponse>( MessengerBatch.sendOneTimeNotifReqTemplate( this._session.user.id, attrs, this._getSendMethodOptions(options) ) ); } return this._client.sendOneTimeNotifReqTemplate( this._session.user.id, attrs, this._getSendMethodOptions(options) ); } } export default MessengerContext;
the_stack
import { notAllowedOptionalAssignment } from "../../src/transformation/utils/diagnostics"; import * as util from "../util"; import { ScriptTarget } from "typescript"; test.each(["null", "undefined", '{ foo: "foo" }'])("optional chaining (%p)", value => { util.testFunction` const obj: any = ${value}; return obj?.foo; `.expectToMatchJsResult(); }); test("long optional chain", () => { util.testFunction` const a = { b: { c: { d: { e: { f: "hello!"}}}}}; return a.b?.c?.d.e.f; `.expectToMatchJsResult(); }); test.each(["undefined", "{}", "{ foo: {} }", "{ foo: {bar: 'baz'}}"])("nested optional chaining (%p)", value => { util.testFunction` const obj: { foo?: { bar?: string } } | undefined = ${value}; return obj?.foo?.bar; `.expectToMatchJsResult(); }); test.each(["undefined", "{}", "{ foo: {} }", "{ foo: {bar: 'baz'}}"])( "nested optional chaining combined with coalescing (%p)", value => { util.testFunction` const obj: { foo?: { bar?: string } } | undefined = ${value}; return obj?.foo?.bar ?? "not found"; `.expectToMatchJsResult(); } ); test.each(["[1, 2, 3, 4]", "undefined"])("optional array access (%p)", value => { util.testFunction` const arr: number[] | undefined = ${value}; return arr?.[2]; `.expectToMatchJsResult(); }); test.each(["[1, [2, [3, [4, 5]]]]", "[1, [2, [3, undefined]]] ", "[1, undefined]"])( "optional element access nested (%p)", value => { util.testFunction` const arr: [number, [number, [number, [number, number] | undefined]]] | [number, undefined] = ${value}; return arr[1]?.[1][1]?.[0]; `.expectToMatchJsResult(); } ); test.each(["{ }", "{ a: { } }", "{ a: { b: [{ c: 10 }] } }"])( "optional nested element access properties (%p)", value => { util.testFunction` const obj: {a?: {b?: Array<{c: number }> } } = ${value}; return [obj["a"]?.["b"]?.[0]?.["c"] ?? "not found", obj["a"]?.["b"]?.[2]?.["c"] ?? "not found"]; `.expectToMatchJsResult(); } ); test("optional element function calls", () => { util.testFunction` const obj: { value: string; foo?(this: void, v: number): number; bar?(this: void, v: number): number; } = { value: "foobar", foo: (v: number) => v + 10 } const fooKey = "foo"; const barKey = "bar"; return obj[barKey]?.(5) ?? obj[fooKey]?.(15); `.expectToMatchJsResult(); }); describe("optional access method calls", () => { test("element access call", () => { util.testFunction` const obj: { value: string; foo?(prefix: string): string; bar?(prefix: string): string; } = { value: "foobar", foo(prefix: string) { return prefix + this.value; } } const fooKey = "foo"; const barKey = "bar"; return obj[barKey]?.("bar?") ?? obj[fooKey]?.("foo?"); `.expectToMatchJsResult(); }); test("optional access call", () => { util.testFunction` const obj: { value: string; foo?(prefix: string): string; bar?(prefix: string): string; } = { value: "foobar", foo(prefix: string) { return prefix + this.value; } } return obj.foo?.("bar?") ?? obj.bar?.("foo?"); `.expectToMatchJsResult(); }); test("nested optional element access call", () => { util.testFunction` const obj: { value: string; foo?(prefix: string): string; bar?(prefix: string): string; } = { value: "foobar", foo(prefix: string) { return prefix + this.value; } } const fooKey = "foo"; const barKey = "bar"; return obj?.[barKey]?.("bar?") ?? obj?.[fooKey]?.("foo?"); `.expectToMatchJsResult(); }); test("nested optional property access call", () => { util.testFunction` const obj: { value: string; foo?(prefix: string): string; bar?(prefix: string): string; } = { value: "foobar", foo(prefix: string) { return prefix + this.value; } } return obj?.foo?.("bar?") ?? obj?.bar?.("foo?"); `.expectToMatchJsResult(); }); }); test("no side effects", () => { util.testFunction` function getFoo(): { foo: number } | undefined { return { foo: 42 }; } let barCalls = 0; function getBar(): { bar: number } | undefined { barCalls += 1; return undefined; } const result = getFoo()?.foo ?? getBar()?.bar; return { result, barCalls }; `.expectToMatchJsResult(); }); // Test for https://github.com/TypeScriptToLua/TypeScriptToLua/issues/1044 test("does not crash when incorrectly used in assignment (#1044)", () => { const { diagnostics } = util.testFunction` foo?.bar = "foo"; `.getLuaResult(); expect(diagnostics.find(d => d.code === notAllowedOptionalAssignment.code)).toBeDefined(); }); describe("optional chaining function calls", () => { test.each(["() => 4", "undefined"])("stand-alone optional function (%p)", value => { util.testFunction` const f: (() => number) | undefined = ${value}; return f?.(); `.expectToMatchJsResult(); }); test("methods present", () => { util.testFunction` const objWithMethods = { foo() { return 3; }, bar(this: void) { return 5; } }; return [objWithMethods?.foo(), objWithMethods?.bar()]; `.expectToMatchJsResult(); }); test("object with method can be undefined", () => { util.testFunction` const objWithMethods: { foo: () => number, bar: (this: void) => number } | undefined = undefined; return [objWithMethods?.foo() ?? "no foo", objWithMethods?.bar() ?? "no bar"]; `.expectToMatchJsResult(); }); test("nested optional method call", () => { util.testFunction` type typeWithOptional = { a?: { b: { c: () => number } } }; const objWithMethods: typeWithOptional = {}; const objWithMethods2: typeWithOptional = { a: { b: { c: () => 4 } } }; return { expectNil: objWithMethods.a?.b.c(), expectFour: objWithMethods2.a?.b.c() }; `.expectToMatchJsResult(); }); test("methods are undefined", () => { util.testFunction` const objWithMethods: { foo?: () => number, bar?: (this: void) => number } = {}; return [objWithMethods.foo?.() ?? "no foo", objWithMethods.bar?.() ?? "no bar"]; `.expectToMatchJsResult(); }); test("optional method of optional method result", () => { util.testFunction` const obj: { a?: () => {b: {c?: () => number }}} = {}; const obj2: { a?: () => {b: {c?: () => number }}} = { a: () => ({b: {}})}; const obj3: { a?: () => {b: {c?: () => number }}} = { a: () => ({b: { c: () => 5 }})}; return [obj.a?.().b.c?.() ?? "nil", obj2.a?.().b.c?.() ?? "nil", obj3.a?.().b.c?.() ?? "nil"]; `.expectToMatchJsResult(); }); // https://github.com/TypeScriptToLua/TypeScriptToLua/issues/1085 test("incorrect type, method is not a function", () => { util.testFunction` const obj: any = {}; obj?.foo(); `.expectToEqual(new util.ExecutionError("attempt to call a nil value (method 'foo')")); }); describe("builtins", () => { test.each([ ["undefined", undefined], ["{foo: 0}", true], ])("LuaTable: %p", (expr, value) => { util.testFunction` const table: LuaTable = ${expr} as any const bar = table?.has("foo") return bar ` .withLanguageExtensions() .expectToEqual(value); }); test.each(["undefined", "foo"])("Function call: %p", e => { util.testFunction` const result = [] function foo(this: unknown, arg: unknown) { return [this, arg] } const bar = ${e} as typeof foo | undefined return bar?.call(1, 2) `.expectToMatchJsResult(); }); test.each([undefined, "[1, 2, 3, 4]"])("Array: %p", expr => { util.testFunction` const value: any[] | undefined = ${expr} return value?.map(x=>x+1) `.expectToMatchJsResult(); }); }); test.each([true, false])("Default call context, strict %s", strict => { util.testFunction` function func(this: unknown, arg: unknown) { return [this === globalThis ? "_G" : this === undefined ? "nil" : "neither", arg]; } let i = 0 const result = func?.(i++); ` .setOptions({ alwaysStrict: strict, target: ScriptTarget.ES5, }) .expectToMatchJsResult(); }); }); describe("Unsupported optional chains", () => { test("Language extensions", () => { util.testModule` new LuaTable().has?.(3) ` .withLanguageExtensions() .expectDiagnosticsToMatchSnapshot(); }); test("Builtin prototype method", () => { util.testModule` [1,2,3,4].forEach?.(()=>{}) `.expectDiagnosticsToMatchSnapshot(); }); test("Builtin global method", () => { util.testModule` Number?.("3") `.expectDiagnosticsToMatchSnapshot(); }); test("Builtin global property", () => { util.testModule` console?.log("3") ` .setOptions({ lib: ["lib.esnext.d.ts", "lib.dom.d.ts"], }) .expectDiagnosticsToMatchSnapshot(); }); test("Compile members only", () => { util.testFunction` /** @compileMembersOnly */ enum TestEnum { A = 0, B = 2, C, D = "D", } TestEnum?.B `.expectDiagnosticsToMatchSnapshot(); }); }); describe("optional delete", () => { test("successful", () => { util.testFunction` const table = { bar: 3 } return [delete table?.bar, table] `.expectToMatchJsResult(); }); test("unsuccessful", () => { util.testFunction` const table : { bar?: number } = {} return [delete table?.bar, table] `.expectToMatchJsResult(); }); test("delete on undefined", () => { util.testFunction` const table : { bar: number } | undefined = undefined return [delete table?.bar, table ?? "nil"] `.expectToMatchJsResult(); }); }); describe("Non-null chain", () => { test("Single non-null chain", () => { util.testFunction` const foo = {a: { b: 3} } return foo?.a!.b `.expectToMatchJsResult(); }); test("Many non-null chains", () => { util.testFunction` const foo = {a: { b: 3} } return foo?.a!!!.b!!! `.expectToMatchJsResult(); }); });
the_stack
namespace gdjs { export type ParticleEmitterObjectDataType = { emitterAngleA: number; emitterForceMin: number; emitterAngleB: number; zoneRadius: number; emitterForceMax: number; particleLifeTimeMax: number; particleLifeTimeMin: number; particleGravityY: number; particleGravityX: number; particleRed2: number; particleRed1: number; particleGreen2: number; particleGreen1: number; particleBlue2: number; particleBlue1: number; particleSize2: number; particleSize1: number; particleAngle2: number; particleAngle1: number; particleAlpha1: number; rendererType: string; particleAlpha2: number; rendererParam2: number; rendererParam1: number; particleSizeRandomness1: number; particleSizeRandomness2: number; maxParticleNb: number; additive: boolean; /** Resource name for image in particle */ textureParticleName: string; tank: number; flow: number; /** Destroy the object when there is no particles? */ destroyWhenNoParticles: boolean; }; export type ParticleEmitterObjectData = ObjectData & ParticleEmitterObjectDataType; /** * Displays particles. */ export class ParticleEmitterObject extends gdjs.RuntimeObject { angleA: number; angleB: number; forceMin: number; forceMax: float; zoneRadius: number; lifeTimeMin: number; lifeTimeMax: float; gravityX: number; gravityY: number; colorR1: number; colorR2: number; colorG1: number; colorG2: number; colorB1: number; colorB2: number; size1: number; size2: number; alpha1: number; alpha2: number; rendererType: string; rendererParam1: number; rendererParam2: number; texture: string; flow: number; tank: number; destroyWhenNoParticles: boolean; _posDirty: boolean = true; _angleDirty: boolean = true; _forceDirty: boolean = true; _zoneRadiusDirty: boolean = true; _lifeTimeDirty: boolean = true; _gravityDirty: boolean = true; _colorDirty: boolean = true; _sizeDirty: boolean = true; _alphaDirty: boolean = true; _flowDirty: boolean = true; _tankDirty: boolean = true; // Don't mark texture as dirty if not using one. _textureDirty: boolean; // @ts-ignore _renderer: gdjs.ParticleEmitterObjectRenderer; /** * @param the object belongs to * @param particleObjectData The initial properties of the object */ constructor( runtimeScene: gdjs.RuntimeScene, particleObjectData: ParticleEmitterObjectData ) { super(runtimeScene, particleObjectData); this._renderer = new gdjs.ParticleEmitterObjectRenderer( runtimeScene, this, particleObjectData ); this.angleA = particleObjectData.emitterAngleA; this.angleB = particleObjectData.emitterAngleB; this.forceMin = particleObjectData.emitterForceMin; this.forceMax = particleObjectData.emitterForceMax; this.zoneRadius = particleObjectData.zoneRadius; this.lifeTimeMin = particleObjectData.particleLifeTimeMin; this.lifeTimeMax = particleObjectData.particleLifeTimeMax; this.gravityX = particleObjectData.particleGravityX; this.gravityY = particleObjectData.particleGravityY; this.colorR1 = particleObjectData.particleRed1; this.colorR2 = particleObjectData.particleRed2; this.colorG1 = particleObjectData.particleGreen1; this.colorG2 = particleObjectData.particleGreen2; this.colorB1 = particleObjectData.particleBlue1; this.colorB2 = particleObjectData.particleBlue2; this.size1 = particleObjectData.particleSize1; this.size2 = particleObjectData.particleSize2; this.alpha1 = particleObjectData.particleAlpha1; this.alpha2 = particleObjectData.particleAlpha2; this.rendererType = particleObjectData.rendererType; this.rendererParam1 = particleObjectData.rendererParam1; this.rendererParam2 = particleObjectData.rendererParam2; this.texture = particleObjectData.textureParticleName; this.flow = particleObjectData.flow; this.tank = particleObjectData.tank; this.destroyWhenNoParticles = particleObjectData.destroyWhenNoParticles; this._textureDirty = this.texture !== ''; // *ALWAYS* call `this.onCreated()` at the very end of your object constructor. this.onCreated(); } setX(x: number): void { if (this.x !== x) { this._posDirty = true; } super.setX(x); } setY(y: number): void { if (this.y !== y) { this._posDirty = true; } super.setY(y); } setAngle(angle): void { if (this.angle !== angle) { this._angleDirty = true; } super.setAngle(angle); } getRendererObject() { return this._renderer.getRendererObject(); } updateFromObjectData( oldObjectData: ParticleEmitterObjectData, newObjectData: ParticleEmitterObjectData ): boolean { if (oldObjectData.emitterAngleA !== newObjectData.emitterAngleA) { this.setEmitterAngleA(newObjectData.emitterAngleA); } if (oldObjectData.emitterAngleB !== newObjectData.emitterAngleB) { this.setEmitterAngleB(newObjectData.emitterAngleB); } if (oldObjectData.emitterForceMin !== newObjectData.emitterForceMin) { this.setEmitterForceMin(newObjectData.emitterForceMin); } if (oldObjectData.emitterForceMax !== newObjectData.emitterForceMax) { this.setEmitterForceMax(newObjectData.emitterForceMax); } if (oldObjectData.zoneRadius !== newObjectData.zoneRadius) { this.setZoneRadius(newObjectData.zoneRadius); } if ( oldObjectData.particleLifeTimeMin !== newObjectData.particleLifeTimeMin ) { this.setParticleLifeTimeMin(newObjectData.particleLifeTimeMin); } if ( oldObjectData.particleLifeTimeMax !== newObjectData.particleLifeTimeMax ) { this.setParticleLifeTimeMax(newObjectData.particleLifeTimeMax); } if (oldObjectData.particleGravityX !== newObjectData.particleGravityX) { this.setParticleGravityX(newObjectData.particleGravityX); } if (oldObjectData.particleGravityY !== newObjectData.particleGravityY) { this.setParticleGravityY(newObjectData.particleGravityY); } if (oldObjectData.particleRed1 !== newObjectData.particleRed1) { this.setParticleRed1(newObjectData.particleRed1); } if (oldObjectData.particleRed2 !== newObjectData.particleRed2) { this.setParticleRed2(newObjectData.particleRed2); } if (oldObjectData.particleGreen1 !== newObjectData.particleGreen1) { this.setParticleGreen1(newObjectData.particleGreen1); } if (oldObjectData.particleGreen2 !== newObjectData.particleGreen2) { this.setParticleGreen2(newObjectData.particleGreen2); } if (oldObjectData.particleBlue1 !== newObjectData.particleBlue1) { this.setParticleBlue1(newObjectData.particleBlue1); } if (oldObjectData.particleBlue2 !== newObjectData.particleBlue2) { this.setParticleBlue2(newObjectData.particleBlue2); } if (oldObjectData.particleSize1 !== newObjectData.particleSize1) { this.setParticleSize1(newObjectData.particleSize1); } if (oldObjectData.particleSize2 !== newObjectData.particleSize2) { this.setParticleSize2(newObjectData.particleSize2); } if (oldObjectData.particleAlpha1 !== newObjectData.particleAlpha1) { this.setParticleAlpha1(newObjectData.particleAlpha1); } if (oldObjectData.particleAlpha2 !== newObjectData.particleAlpha2) { this.setParticleAlpha2(newObjectData.particleAlpha2); } if ( oldObjectData.textureParticleName !== newObjectData.textureParticleName ) { this.setTexture(newObjectData.textureParticleName, this._runtimeScene); } if (oldObjectData.flow !== newObjectData.flow) { this.setFlow(newObjectData.flow); } if (oldObjectData.tank !== newObjectData.tank) { this.setTank(newObjectData.tank); } if ( oldObjectData.destroyWhenNoParticles !== newObjectData.destroyWhenNoParticles ) { this.destroyWhenNoParticles = newObjectData.destroyWhenNoParticles; } if ( oldObjectData.particleSizeRandomness1 !== newObjectData.particleSizeRandomness1 || oldObjectData.particleSizeRandomness2 !== newObjectData.particleSizeRandomness2 || oldObjectData.particleAngle1 !== newObjectData.particleAngle1 || oldObjectData.particleAngle2 !== newObjectData.particleAngle2 || oldObjectData.maxParticleNb !== newObjectData.maxParticleNb || oldObjectData.additive !== newObjectData.additive || oldObjectData.rendererType !== newObjectData.rendererType || oldObjectData.rendererParam1 !== newObjectData.rendererParam1 || oldObjectData.rendererParam2 !== newObjectData.rendererParam2 ) { // Destroy the renderer, ensure it's removed from the layer. const layer = this._runtimeScene.getLayer(this.layer); layer .getRenderer() .removeRendererObject(this._renderer.getRendererObject()); this._renderer.destroy(); // and recreate the renderer, which will add itself to the layer. this._renderer = new gdjs.ParticleEmitterObjectRenderer( this._runtimeScene, this, newObjectData ); // Consider every state dirty as the renderer was just re-created, so it needs // to be repositioned, angle updated, etc... this._posDirty = this._angleDirty = this._forceDirty = this._zoneRadiusDirty = true; this._lifeTimeDirty = this._gravityDirty = this._colorDirty = this._sizeDirty = true; this._alphaDirty = this._flowDirty = this._tankDirty = this._textureDirty = true; } return true; } update(runtimeScene): void { if (this._posDirty) { this._renderer.setPosition(this.getX(), this.getY()); } if (this._angleDirty) { const angle = this.getAngle(); this._renderer.setAngle( this.angle - this.angleB / 2.0, this.angle + this.angleB / 2.0 ); } if (this._forceDirty) { this._renderer.setForce(this.forceMin, this.forceMax); } if (this._zoneRadiusDirty) { this._renderer.setZoneRadius(this.zoneRadius); } if (this._lifeTimeDirty) { this._renderer.setLifeTime(this.lifeTimeMin, this.lifeTimeMax); } if (this._gravityDirty) { this._renderer.setGravity(this.gravityX, this.gravityY); } if (this._colorDirty) { this._renderer.setColor( this.colorR1, this.colorG1, this.colorB1, this.colorR2, this.colorG2, this.colorB2 ); } if (this._sizeDirty) { this._renderer.setSize(this.size1, this.size2); } if (this._alphaDirty) { this._renderer.setAlpha(this.alpha1, this.alpha2); } if (this._flowDirty || this._tankDirty) { this._renderer.resetEmission(this.flow, this.tank); } if (this._textureDirty) { this._renderer.setTextureName(this.texture, runtimeScene); } this._posDirty = this._angleDirty = this._forceDirty = this._zoneRadiusDirty = false; this._lifeTimeDirty = this._gravityDirty = this._colorDirty = this._sizeDirty = false; this._alphaDirty = this._flowDirty = this._textureDirty = this._tankDirty = false; this._renderer.update(this.getElapsedTime(runtimeScene) / 1000.0); if ( this._renderer.hasStarted() && this.getParticleCount() === 0 && this.destroyWhenNoParticles ) { this.deleteFromScene(runtimeScene); } } onDestroyFromScene(runtimeScene: gdjs.RuntimeScene): void { this._renderer.destroy(); super.onDestroyFromScene(runtimeScene); } getEmitterForceMin(): number { return this.forceMin; } setEmitterForceMin(force: float): void { if (force < 0) { force = 0; } if (this.forceMin !== force) { this._forceDirty = true; this.forceMin = force; } } getEmitterForceMax(): number { return this.forceMax; } setEmitterForceMax(force: float): void { if (force < 0) { force = 0; } if (this.forceMax !== force) { this._forceDirty = true; this.forceMax = force; } } getEmitterAngle(): float { return (this.angleA + this.angleB) / 2.0; } setEmitterAngle(angle: float): void { const oldAngle = this.getEmitterAngle(); if (angle !== oldAngle) { this._angleDirty = true; this.angleA += angle - oldAngle; this.angleB += angle - oldAngle; } } getEmitterAngleA(): float { return this.angleA; } setEmitterAngleA(angle: float): void { if (this.angleA !== angle) { this._angleDirty = true; this.angleA = angle; } } getEmitterAngleB(): float { return this.angleB; } setEmitterAngleB(angle: float): void { if (this.angleB !== angle) { this._angleDirty = true; this.angleB = angle; } } getConeSprayAngle(): float { return Math.abs(this.angleB - this.angleA); } setConeSprayAngle(angle: float): void { const oldCone = this.getConeSprayAngle(); if (oldCone !== angle) { this._angleDirty = true; const midAngle = this.getEmitterAngle(); this.angleA = midAngle - angle / 2.0; this.angleB = midAngle + angle / 2.0; } } getZoneRadius(): float { return this.zoneRadius; } setZoneRadius(radius: float): void { if (radius < 0) { radius = 0; } if (this.zoneRadius !== radius && radius > 0) { this._zoneRadiusDirty = true; this.zoneRadius = radius; } } getParticleLifeTimeMin(): float { return this.lifeTimeMin; } setParticleLifeTimeMin(lifeTime: float): void { if (lifeTime < 0) { lifeTime = 0; } if (this.lifeTimeMin !== lifeTime) { this._lifeTimeDirty = true; this.lifeTimeMin = lifeTime; } } getParticleLifeTimeMax(): float { return this.lifeTimeMax; } setParticleLifeTimeMax(lifeTime: float): void { if (lifeTime < 0) { lifeTime = 0; } if (this.lifeTimeMax !== lifeTime) { this._lifeTimeDirty = true; this.lifeTimeMax = lifeTime; } } getParticleGravityX(): float { return this.gravityX; } setParticleGravityX(x: float): void { if (this.gravityX !== x) { this._gravityDirty = true; this.gravityX = x; } } getParticleGravityY(): float { return this.gravityY; } setParticleGravityY(y: float): void { if (this.gravityY !== y) { this._gravityDirty = true; this.gravityY = y; } } getParticleGravityAngle(): float { return (Math.atan2(this.gravityY, this.gravityX) * 180.0) / Math.PI; } setParticleGravityAngle(angle: float): void { const oldAngle = this.getParticleGravityAngle(); if (oldAngle !== angle) { this._gravityDirty = true; const length = this.getParticleGravityLength(); this.gravityX = length * Math.cos((angle * Math.PI) / 180.0); this.gravityY = length * Math.sin((angle * Math.PI) / 180.0); } } getParticleGravityLength(): float { return Math.sqrt( this.gravityX * this.gravityX + this.gravityY * this.gravityY ); } setParticleGravityLength(length: float): void { if (length < 0) { length = 0; } const oldLength = this.getParticleGravityLength(); if (oldLength !== length) { this._gravityDirty = true; this.gravityX *= length / oldLength; this.gravityY *= length / oldLength; } } getParticleRed1(): number { return this.colorR1; } setParticleRed1(red: number): void { if (red < 0) { red = 0; } if (red > 255) { red = 255; } if (this.colorR1 !== red) { this._colorDirty = true; this.colorR1 = red; } } getParticleRed2(): number { return this.colorR2; } setParticleRed2(red: number): void { if (red < 0) { red = 0; } if (red > 255) { red = 255; } if (this.colorR2 !== red) { this._colorDirty = true; this.colorR2 = red; } } getParticleGreen1(): number { return this.colorG1; } setParticleGreen1(green: number): void { if (green < 0) { green = 0; } if (green > 255) { green = 255; } if (this.colorG1 !== green) { this._colorDirty = true; this.colorG1 = green; } } getParticleGreen2(): number { return this.colorG2; } setParticleGreen2(green: number): void { if (green < 0) { green = 0; } if (green > 255) { green = 255; } if (this.colorG2 !== green) { this._colorDirty = true; this.colorG2 = green; } } getParticleBlue1(): number { return this.colorB1; } setParticleBlue1(blue: number): void { if (blue < 0) { blue = 0; } if (blue > 255) { blue = 255; } if (this.colorB1 !== blue) { this._colorDirty = true; this.colorB1 = blue; } } getParticleBlue2(): number { return this.colorB2; } setParticleBlue2(blue: number): void { if (blue < 0) { blue = 0; } if (blue > 255) { blue = 255; } if (this.colorB2 !== blue) { this._colorDirty = true; this.colorB2 = blue; } } setParticleColor1(rgbColor: string): void { const colors = rgbColor.split(';'); if (colors.length < 3) { return; } this.setParticleRed1(parseInt(colors[0], 10)); this.setParticleGreen1(parseInt(colors[1], 10)); this.setParticleBlue1(parseInt(colors[2], 10)); } setParticleColor2(rgbColor: string): void { const colors = rgbColor.split(';'); if (colors.length < 3) { return; } this.setParticleRed2(parseInt(colors[0], 10)); this.setParticleGreen2(parseInt(colors[1], 10)); this.setParticleBlue2(parseInt(colors[2], 10)); } getParticleSize1(): float { return this.size1; } setParticleSize1(size: float): void { if (size < 0) { size = 0; } if (this.size1 !== size) { this._sizeDirty = true; this.size1 = size; } } getParticleSize2(): float { return this.size2; } setParticleSize2(size: float): void { if (this.size2 !== size) { this._sizeDirty = true; this.size2 = size; } } getParticleAlpha1(): number { return this.alpha1; } setParticleAlpha1(alpha: number): void { if (this.alpha1 !== alpha) { this._alphaDirty = true; this.alpha1 = alpha; } } getParticleAlpha2(): number { return this.alpha2; } setParticleAlpha2(alpha: number): void { if (this.alpha2 !== alpha) { this._alphaDirty = true; this.alpha2 = alpha; } } startEmission(): void { this._renderer.start(); } stopEmission(): void { this._renderer.stop(); } isEmitting(): boolean { return this._renderer.emitter.emit; } noMoreParticles(): boolean { return !this.isEmitting(); } recreateParticleSystem(): void { this._renderer.recreate(); } getFlow(): number { return this.flow; } setFlow(flow: number): void { if (this.flow !== flow) { this.flow = flow; this._flowDirty = true; } } getParticleCount(): number { return this._renderer.getParticleCount(); } getTank(): number { return this.tank; } setTank(tank: number): void { this.tank = tank; this._tankDirty = true; } getTexture(): string { return this.texture; } setTexture(texture: string, runtimeScene: gdjs.RuntimeScene): void { if (this.texture !== texture) { if (this._renderer.isTextureNameValid(texture, runtimeScene)) { this.texture = texture; this._textureDirty = true; } } } } gdjs.registerObject( 'ParticleSystem::ParticleEmitter', gdjs.ParticleEmitterObject ); }
the_stack
import { Trigger } from "@akashic/trigger"; import { Timer, TimerManager, TimerIdentifier } from ".."; import { customMatchers } from "./helpers"; expect.extend(customMatchers); describe("test TimerManager", () => { let trigger: Trigger<void>; beforeEach(() => { trigger = new Trigger(); }); function loopFire(count: number): void { let i = 0; while (i < count) { trigger.fire.call(trigger); i++; } } it("constructor", () => { const m = new TimerManager(trigger, 30); expect(m._timers.length).toEqual(0); expect(m._trigger).toBe(trigger); expect(m._identifiers.length).toEqual(0); expect(m._fps).toBe(30); expect(m._registered).toBe(false); expect(m._trigger.contains(m._tick, m)).toBe(false); }); it("createTimer", () => { const m = new TimerManager(trigger, 30); const timer = m.createTimer(100); expect(m._timers.length).toBe(1); expect(m._timers[0]).toBe(timer); expect(m._registered).toBe(true); expect(m._trigger.contains(m._tick, m)).toBe(true); expect(m._identifiers.length).toEqual(0); }); it("createTimer - shared timer(same interval)", () => { const m = new TimerManager(trigger, 30); const timer1 = m.createTimer(100); const timer2 = m.createTimer(100); expect(m._timers.length).toBe(1); expect(timer1).toBe(timer2); }); it("createTimer - new timer(different interval)", () => { const m = new TimerManager(trigger, 30); const timer1 = m.createTimer(100); const timer2 = m.createTimer(101); expect(m._timers.length).toBe(2); expect(timer1).not.toBe(timer2); }); it("createTimer - new timer(same interval)", () => { const m = new TimerManager(trigger, 30); const timer1 = m.createTimer(100); trigger.fire(); const timer2 = m.createTimer(100); expect(m._timers.length).toBe(2); expect(timer1).not.toBe(timer2); }); it("createTimer - error", () => { const m = new TimerManager(trigger, 30); expect(() => { m.createTimer(-1); }).toThrowError("AssertionError"); }); it("deleteTimer", () => { const m = new TimerManager(trigger, 30); const timer = m.createTimer(100); expect(m._timers.length).toBe(1); expect(m._identifiers.length).toEqual(0); expect(m._timers[0]).toBe(timer); expect(m._registered).toBe(true); m.deleteTimer(timer); expect(m._timers.length).toBe(0); expect(m._registered).toBe(false); expect(timer.destroyed()).toBe(true); expect(trigger.contains(m._tick, m)).toBe(false); }); it("deleteTimer - handler remains", () => { const m = new TimerManager(trigger, 30); const timer1 = m.createTimer(100); const timer2 = m.createTimer(101); m.deleteTimer(timer1); expect(timer1.destroyed()).toBe(true); expect(m._registered).toBe(true); expect(m._trigger.contains(m._tick, m)).toBe(true); m.deleteTimer(timer2); expect(timer2.destroyed()).toBe(true); expect(m._registered).toBe(false); expect(m._trigger.contains(m._tick, m)).toBe(false); }); it("deleteTimer - error (invalid context)", () => { const m = new TimerManager(trigger, 30); const t = new Timer(100, undefined!); expect(() => { m.deleteTimer(t); }).toThrowError("AssertionError"); }); it("deleteTimer - error (invalid status)", () => { const m = new TimerManager(trigger, 30); const t = m.createTimer(100); m._registered = false; expect(() => { m.deleteTimer(t); }).toThrowError("AssertionError"); }); it("setTimeout", () => { const m = new TimerManager(trigger, 30); const parent = new Object(); let passedOwner = null; let count = 0; m.setTimeout( function (this: any): void { count++; passedOwner = this; }, 1000, parent ); expect(m._identifiers.length).toEqual(1); loopFire(29); // 966.666ms expect(count).toBe(0); trigger.fire(); // 1000ms expect(count).toBe(1); loopFire(30); // 2000ms expect(count).toBe(1); expect(passedOwner).toBe(parent); expect(m._identifiers.length).toEqual(0); }); it("setInterval - check calculation error", () => { const m = new TimerManager(trigger, 30); const parent = new Object(); let count = 0; m.setInterval( () => { count++; }, 2000, parent ); loopFire(60); expect(count).toBe(1); }); it("setTimeout - invalid status", () => { const m = new TimerManager(trigger, 30); const parent = new Object(); m.setTimeout( () => { /* do nothing */ }, 1000, parent ); expect(m._identifiers.length).toEqual(1); m._identifiers.length = 0; expect(() => { loopFire(30); }).toThrowError("AssertionError"); }); it("setTimeout - serial two timers(same interval)", () => { const m = new TimerManager(trigger, 30); let count1 = 0; let count2 = 0; m.setTimeout(() => { count1++; }, 1000); expect(m._identifiers.length).toEqual(1); loopFire(30); // 1000ms expect(m._identifiers.length).toEqual(0); expect(count1).toBe(1); m.setTimeout(() => { count2++; }, 1000); expect(m._identifiers.length).toEqual(1); loopFire(29); // 1966.666ms expect(count2).toBe(0); trigger.fire(); // 2000ms expect(count2).toBe(1); expect(m._identifiers.length).toEqual(0); loopFire(30); // 3000ms expect(count2).toBe(1); expect(count1).toBe(1); }); it("setTimeout - parallel two timers(same interval)", () => { const m = new TimerManager(trigger, 30); let count1 = 0; let count2 = 0; m.setTimeout(() => { count1++; }, 1000); m.setTimeout(() => { count2++; }, 1000); expect(m._identifiers.length).toEqual(2); loopFire(29); // 966.666ms expect(count1).toBe(0); expect(count2).toBe(0); trigger.fire(); // 1000ms expect(count1).toBe(1); expect(count2).toBe(1); expect(m._identifiers.length).toEqual(0); loopFire(30); // 2000ms expect(count1).toBe(1); expect(count2).toBe(1); }); it("setTimeout - serial two timers(different interval)", () => { const m = new TimerManager(trigger, 10); let count1 = 0; let count2 = 0; m.setTimeout(() => { count1++; }, 500); loopFire(5); // 500ms expect(count1).toBe(1); m.setTimeout(() => { count2++; }, 1000); loopFire(10); // 1500ms expect(count2).toBe(1); loopFire(15); // 3000ms expect(count2).toBe(1); expect(count1).toBe(1); expect(m._identifiers.length).toEqual(0); }); it("setTimeout - parallel two timers(different interval)", () => { const m = new TimerManager(trigger, 10); let count1 = 0; let count2 = 0; m.setTimeout(() => { count1++; }, 500); m.setTimeout(() => { count2++; }, 1000); loopFire(5); // 500ms expect(count1).toBe(1); expect(count2).toBe(0); loopFire(5); // 1000ms expect(count1).toBe(1); expect(count2).toBe(1); expect(m._identifiers.length).toEqual(0); }); it("setTimeout - zero interval", () => { const m = new TimerManager(trigger, 10); let count = 0; m.setTimeout(() => { count++; }, 0); loopFire(1); // 100ms expect(count).toBe(1); loopFire(10); // 1100ms expect(count).toBe(1); }); it("clearTimeout", () => { const m = new TimerManager(trigger, 10); let count = 0; const timeout = m.setTimeout(() => { count++; }, 500); expect(m._identifiers.length).toEqual(1); loopFire(3); // 300ms m.clearTimeout(timeout); expect(m._identifiers.length).toEqual(0); loopFire(2); // 500ms expect(count).toBe(0); loopFire(5); // 1000ms expect(count).toBe(0); }); it("clearTimeout - error(not found)", () => { const m = new TimerManager(trigger, 10); const timeout = m.setTimeout(() => { /* do nothing */ }, 500); loopFire(3); m.clearTimeout(timeout); expect(() => { m.clearTimeout(timeout); }).toThrowError("AssertionError"); }); it("clearTimeout - error(invalid identifier)", () => { const m = new TimerManager(trigger, 10); const timeout = m.setTimeout(() => { /* do nothing */ }, 500); loopFire(3); timeout.destroy(); expect(() => { m.clearTimeout(timeout); }).toThrowError("AssertionError"); }); it("clearTimeout - parallel two timers", () => { const m = new TimerManager(trigger, 10); let count1 = 0; let count2 = 0; const timeout1 = m.setTimeout(() => { count1++; }, 500); m.setTimeout(() => { count2++; }, 500); loopFire(3); // 300ms m.clearTimeout(timeout1); loopFire(2); // 500ms expect(count1).toBe(0); expect(count2).toBe(1); }); it("clearTimeout - zero interval", () => { const m = new TimerManager(trigger, 10); let count = 0; const timeout = m.setTimeout(() => { count++; }, 0); m.clearTimeout(timeout); loopFire(10); // 1000ms expect(count).toBe(0); }); it("setInterval", () => { const m = new TimerManager(trigger, 10); const parent = new Object(); let passedOwner = null; let count = 0; m.setInterval( function (this: any): void { count++; passedOwner = this; }, 500, parent ); loopFire(4); // 400ms expect(count).toBe(0); trigger.fire(); // 500ms expect(count).toBe(1); loopFire(5); // 1000ms expect(count).toBe(2); loopFire(5); // 1500ms expect(count).toBe(3); loopFire(5); // 2000ms expect(count).toBe(4); expect(passedOwner).toBe(parent); expect(m._identifiers.length).toEqual(1); }); it("setInterval - two timers(same interval)", () => { const m = new TimerManager(trigger, 10); let count1 = 0; let count2 = 0; m.setInterval(() => { count1++; }, 500); m.setInterval(() => { count2++; }, 500); loopFire(4); // 400ms expect(count1).toBe(0); expect(count2).toBe(0); trigger.fire(); // 500ms expect(count1).toBe(1); expect(count2).toBe(1); loopFire(5); // 1000ms expect(count1).toBe(2); expect(count2).toBe(2); loopFire(5); // 1500ms expect(count1).toBe(3); expect(count2).toBe(3); loopFire(5); // 2000ms expect(count1).toBe(4); expect(count2).toBe(4); expect(m._identifiers.length).toEqual(2); }); it("setInterval - two timers(different interval)", () => { const m = new TimerManager(trigger, 10); let count1 = 0; let count2 = 0; m.setInterval(() => { count1++; }, 500); m.setInterval(() => { count2++; }, 1000); loopFire(5); // 500ms expect(count1).toBe(1); expect(count2).toBe(0); loopFire(5); // 1000ms expect(count1).toBe(2); expect(count2).toBe(1); loopFire(5); // 1500ms expect(count1).toBe(3); expect(count2).toBe(1); loopFire(5); // 2000ms expect(count1).toBe(4); expect(count2).toBe(2); expect(m._identifiers.length).toEqual(2); }); it("setInterval - zero interval", () => { const m = new TimerManager(trigger, 10); let count = 0; m.setInterval(() => { count++; }, 0); loopFire(10); // 1000ms expect(count).toBe(1000); }); it("clearInterval", () => { const m = new TimerManager(trigger, 10); let count = 0; const interval = m.setInterval(() => { count++; }, 500); loopFire(20); // 2000ms expect(count).toBe(4); m.clearInterval(interval); expect(m._identifiers.length).toEqual(0); loopFire(20); // 4000ms expect(count).toBe(4); }); it("clearInterval - error(not found)", () => { const m = new TimerManager(trigger, 10); const interval = m.setInterval(() => { /* do nothing */ }, 500); loopFire(3); m.clearInterval(interval); expect(() => { m.clearInterval(interval); }).toThrowError("AssertionError"); }); it("clearInterval - error(invalid identifier)", () => { const m = new TimerManager(trigger, 10); const interval = m.setInterval(() => { /* do nothing */ }, 500); loopFire(3); interval.destroy(); expect(() => { m.clearInterval(interval); }).toThrowError("AssertionError"); }); it("clearInterval - two timers", () => { const m = new TimerManager(trigger, 10); let count1 = 0; let count2 = 0; const interval1 = m.setInterval(() => { count1++; }, 500); const interval2 = m.setInterval(() => { count2++; }, 500); expect(m._identifiers.length).toEqual(2); loopFire(20); // 2000ms m.clearInterval(interval1); loopFire(20); // 4000ms expect(count1).toBe(4); expect(count2).toBe(8); m.clearInterval(interval2); loopFire(20); // 6000ms expect(count1).toBe(4); expect(count2).toBe(8); expect(m._identifiers.length).toEqual(0); }); it("destroy", () => { const m = new TimerManager(trigger, 10); const timeout1 = m.setTimeout(() => { /* do nothing */ }, 100); const timeout2 = m.setTimeout(() => { /* do nothing */ }, 200); const timeout3 = m.setTimeout(() => { /* do nothing */ }, 300); const timer1 = timeout1._timer; const timer2 = timeout1._timer; const timer3 = timeout1._timer; expect(m._timers.length).toBe(3); expect(m.destroyed()).toBe(false); expect(timeout1.destroyed()).toBe(false); expect(timeout2.destroyed()).toBe(false); expect(timeout3.destroyed()).toBe(false); expect(timer1.destroyed()).toBe(false); expect(timer2.destroyed()).toBe(false); expect(timer3.destroyed()).toBe(false); expect(m._identifiers.length).toEqual(3); m.destroy(); expect(m._timers).toBeUndefined(); expect(timeout1.destroyed()).toBe(true); expect(timeout2.destroyed()).toBe(true); expect(timeout3.destroyed()).toBe(true); expect(timer1.destroyed()).toBe(true); expect(timer2.destroyed()).toBe(true); expect(timer3.destroyed()).toBe(true); expect(m._identifiers).toBeUndefined(); }); it("clearInterval - same time", () => { const m = new TimerManager(trigger, 10); let cnt1 = 0; let cnt2 = 0; let timer2: TimerIdentifier; const timer1 = m.setInterval(() => { // 同タイミングでタイマが完了した場合、先行する timer1 の処理で timer2 を clearInterval() しても timer2 のハンドラが実行されない事を確認する。 if (!timer2.destroyed()) m.clearInterval(timer2); cnt1++; }, 200); timer2 = m.setInterval(() => { cnt2++; }, 200); loopFire(5); // 500ms m.clearInterval(timer1); expect(cnt1).toBe(2); expect(cnt2).toBe(0); }); });
the_stack
import { Button } from '../src/button/button'; import { createElement, detach } from '@syncfusion/ej2-base'; import { profile , inMB, getMemoryProfile } from './common.spec'; /** * @param {} 'Button' * @param {} function( */ describe('Button', () => { beforeAll(() => { const isDef: any = (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 button: Button; const element: any = createElement('button', { id: 'button' }); document.body.appendChild(element); describe('DOM', () => { afterEach(() => { button.destroy(); }); it('Normal button testing', () => { button = new Button(); button.appendTo('#button'); expect(element.classList.contains('e-btn')).toEqual(true); }); it('Primary button testing', () => { button = new Button({ isPrimary: true }); button.appendTo('#button'); expect(element.classList.contains('e-primary')).toEqual(true); }); it('Disable state testing', () => { button = new Button({ disabled: true }); button.appendTo('#button'); expect(element.getAttribute('disabled')).toEqual(''); }); it('Small button testing', () => { button = new Button({ cssClass: 'e-small' }); button.appendTo('#button'); expect(element.classList.contains('e-small')).toEqual(true); }); it('Icon button testing', () => { button = new Button({ iconCss: 'iconcss' }); button.appendTo('#button'); expect(element.children[0].classList.contains('iconcss')).toEqual(true); }); it('Icon and text button testing', () => { element.textContent = 'Button'; button = new Button({ iconCss: 'iconcss' }); button.appendTo('#button'); expect(element.children[0].classList.contains('iconcss')).toEqual(true); expect(element.textContent).toEqual('Button'); }); it('Text and Icon button testing', () => { element.textContent = 'Button'; button = new Button({ iconCss: 'iconcss', iconPosition: 'Right' }); button.appendTo('#button'); expect(element.textContent).toEqual('Button'); expect(element.children[0].classList.contains('iconcss')).toEqual(true); }); it('Text and Top Icon button testing', () => { element.textContent = 'Button'; button = new Button({ iconCss: 'iconcss', iconPosition: 'Top' }); button.appendTo('#button'); expect(element.classList).toContain('e-top-icon-btn'); expect(element.childNodes[0].classList).toContain('e-icon-top'); }); it('Text and Bottom Icon button testing', () => { element.textContent = 'Button'; button = new Button({ iconCss: 'iconcss', iconPosition: 'Bottom' }); button.appendTo('#button'); expect(element.classList).toContain('e-bottom-icon-btn'); expect(element.childNodes[1].classList).toContain('e-icon-bottom'); }); it('RTL testing', () => { button = new Button({ enableRtl: true }); button.appendTo('#button'); expect(element.classList.contains('e-rtl')).toEqual(true); }); it('CSS class testing', () => { button = new Button({ cssClass: 'e-secondary' }); button.appendTo('#button'); expect(element.classList.contains('e-secondary')).toEqual(true); }); it('Content testing', () => { button = new Button({ content: '<span class="e-icons e-btn-icon e-add-icon e-icon-left"></span>Button' }, '#button'); expect(element.childNodes[0].nodeName).toEqual('SPAN'); expect(element.textContent).toEqual('Button'); }); it('Content and IconCss Testing', () => { button = new Button({ content: 'Button', iconCss: 'e-icons e-add-icon' }, '#button'); expect(element.childNodes[0].nodeName).toEqual('SPAN'); expect(element.textContent).toEqual('Button'); button.destroy(); button = new Button({ content: '<div>Button</div>', iconCss: 'e-icons e-add-icon', iconPosition: 'Right' }, '#button'); expect(element.childNodes[0].nodeName).toEqual('DIV'); expect(element.childNodes[1].nodeName).toEqual('SPAN'); expect(element.textContent).toEqual('Button'); }); it('Toggle Button Testing', () => { button = new Button({ content: 'Button', isToggle: true }, '#button'); button.element.click(); expect(element.classList).toContain('e-active'); button.element.click(); expect(element.classList).not.toContain('e-active'); }); }); describe('Property', () => { afterEach(() => { button.destroy(); }); it('Primary button testing', () => { button = new Button({ isPrimary: true }); button.appendTo('#button'); expect(button.isPrimary).toEqual(true); }); it('Disable state testing', () => { button = new Button({ disabled: true }); button.appendTo('#button'); expect(button.disabled).toEqual(true); }); it('Icon button testing', () => { button = new Button({ iconCss: 'iconcss' }); button.appendTo('#button'); expect(button.iconCss).toEqual('iconcss'); }); it('Icon and text button testing', () => { element.textContent = 'Button'; button = new Button({ iconCss: 'iconcss' }); button.appendTo('#button'); expect(button.iconCss).toEqual('iconcss'); expect(button.iconPosition).toEqual('Left'); }); it('Text and Icon button testing', () => { element.textContent = 'Button'; button = new Button({ iconCss: 'iconcss', iconPosition: 'Right' }); button.appendTo('#button'); expect(button.iconCss).toEqual('iconcss'); expect(button.iconPosition).toEqual('Right'); }); it('RTL testing', () => { button = new Button({ enableRtl: true }); button.appendTo('#button'); expect(button.enableRtl).toEqual(true); }); it('CSS class testing', () => { button = new Button({ cssClass: 'e-secondary' }); button.appendTo('#button'); expect(button.cssClass).toEqual('e-secondary'); }); it('Content testing', () => { button = new Button({ content: '<span class="e-icons e-btn-icon e-add-icon e-icon-left"></span>Button' }, '#button'); expect(button.content).toEqual('<span class="e-icons e-btn-icon e-add-icon e-icon-left"></span>Button'); }); it('Toggle Button Testing', () => { button = new Button({ isToggle: true }, '#button'); expect(button.isToggle).toEqual(true); }); it('Enable Html Sanitizer testing', () => { button = new Button({ content: 'Button<style>body{background:rgb(0, 0, 255)}</style>', enableHtmlSanitizer: true }, '#button'); const htmlele: Element = document.body; expect(button.content).toEqual('Button<style>body{background:rgb(0, 0, 255)}</style>'); expect(window.getComputedStyle(htmlele).backgroundColor).not.toBe('rgb(0, 0, 255)'); }); it('Enable Html Sanitizer disabled testing', () => { button = new Button({ content: '<style>body{background:rgb(0, 0, 255)}</style>' }, '#button'); const htmlele: Element = document.body; expect(window.getComputedStyle(htmlele).backgroundColor).toBe('rgb(0, 0, 255)'); }); }); describe('notify property changes of', () => { afterEach(() => { button.destroy(); }); it('Primary in onPropertyChanged', () => { button = new Button(); button.appendTo('#button'); button.isPrimary = true; button.dataBind(); expect(element.classList.contains('e-primary')).toEqual(true); button.isPrimary = false; button.dataBind(); expect(element.classList.contains('e-primary')).toEqual(false); }); it('Disabled in onPropertyChanged', () => { button = new Button(); button.appendTo('#button'); button.disabled = true; button.dataBind(); expect(element.getAttribute('disabled')).toEqual(''); button.disabled = false; button.dataBind(); expect(element.getAttribute('disabled')).toEqual(null); }); it('IconCss in onPropertyChanged', () => { button = new Button({ iconCss: 'icon', content: 'iconcss' }); button.appendTo('#button'); button.iconCss = 'iconcss'; button.dataBind(); expect(element.children[0].classList.contains('iconcss')).toEqual(true); element.innerHTML = ''; button.iconCss = 'iconclass'; button.dataBind(); expect(element.children[0].classList.contains('iconclass')).toEqual(true); button.destroy(); button.iconPosition = 'Right'; button.iconCss = 'iconcss'; button.dataBind(); expect(element.children[0].classList.contains('iconcss')).toEqual(true); }); it('IconPosition right in onPropertyChanged', () => { element.textContent = 'Button'; button = new Button({ iconCss: 'iconcss' }); button.appendTo('#button'); button.iconCss = 'icon-right'; button.iconPosition = 'Right'; button.dataBind(); expect(element.textContent).toEqual('Button'); expect(element.children[0].classList.contains('icon-right')).toEqual(true); expect(element.children[0].classList.contains('e-icon-right')).toEqual(true); }); it('IconPosition left in onPropertyChanged', () => { element.textContent = 'Button'; button = new Button({ iconCss: 'iconcss', iconPosition: 'Right' }); button.appendTo('#button'); button.iconPosition = 'Left'; button.dataBind(); expect(element.children[0].classList.contains('iconcss')).toEqual(true); expect(element.textContent).toEqual('Button'); button.destroy(); button.element.innerHTML = ''; button.element.textContent = 'Button'; button = new Button({ iconCss: 'iconcss' }); button.appendTo('#button'); detach(button.element.getElementsByTagName('span')[0]); button.iconPosition = 'Right'; button.dataBind(); expect(element.children[0].classList.contains('iconcss')).toEqual(true); expect(element.textContent).toEqual('Button'); }); it('CssClass in onPropertyChanged', () => { button = new Button({ cssClass: 'class' }); button.appendTo('#button'); button.cssClass = 'styleclass'; button.dataBind(); expect(element.classList.contains('styleclass')).toEqual(true); button = new Button(); button.appendTo('#button'); button.cssClass = 'styleclass'; button.dataBind(); expect(element.classList.contains('styleclass')).toEqual(true); }); it('EnableRtl in onPropertyChanged', () => { button = new Button(); button.appendTo('#button'); button.enableRtl = true; button.dataBind(); expect(element.classList.contains('e-rtl')).toEqual(true); button.enableRtl = false; button.dataBind(); expect(element.classList.contains('e-rtl')).toEqual(false); }); it('Content in onPropertyChanged', () => { button = new Button(); button.appendTo('#button'); button.content = 'play'; button.dataBind(); expect(element.textContent).toEqual('play'); button.iconCss = 'e-icons e-add-icon'; button.iconPosition = 'Left'; button.dataBind(); expect(element.childNodes[0].nodeName).toEqual('SPAN'); expect(element.childNodes[1].nodeName).toEqual('#text'); expect(element.textContent).toEqual('play'); button.element.innerHTML = ''; button.content = 'Content'; button.dataBind(); expect(element.childNodes[0].nodeName).toEqual('SPAN'); expect(element.textContent).toEqual('Content'); }); it('Toggle in onPropertyChanged', () => { button = new Button({}, '#button'); button.isToggle = true; button.dataBind(); button.element.click(); expect(element.classList).toContain('e-active'); button.isToggle = false; button.dataBind(); button.element.click(); expect(element.classList).not.toContain('e-active'); }); }); describe('methods', () => { it('destroy method', () => { button = new Button(); button.appendTo('#button'); button.destroy(); expect(element.classList.contains('e-btn')).toEqual(false); }); it('getModuleName method', () => { button = new Button(); button.appendTo('#button'); expect(button.getModuleName()).toEqual('btn'); }); it('getPersistData & inject method', () => { button = new Button({ enablePersistence: true }); button.appendTo('#button'); expect(button.getPersistData()).toEqual('{}'); Button.Inject(); }); it('Native methods - Click and Focus ', () => { button = new Button(); button.appendTo('#button'); button.click(); button.focusIn(); }); }); it('memory leak', () => { profile.sample(); const average: any = inMB(profile.averageChange); // check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); const 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); }); });
the_stack
import { IDiagnosticLogger, IPlugin, getPerformance, getExceptionName as coreGetExceptionName, dumpObj, isNullOrUndefined, strTrim, random32, isArray, isError, isDate, newId, generateW3CId, toISOString, arrForEach, getIEVersion, attachEvent, dateNow, uaDisallowsSameSiteNone, disableCookies as coreDisableCookies, canUseCookies as coreCanUseCookies, getCookie as coreGetCookie, setCookie as coreSetCookie, deleteCookie as coreDeleteCookie, isBeaconsSupported, arrIndexOf, IDistributedTraceContext, isValidTraceId, isValidSpanId } from "@microsoft/applicationinsights-core-js"; import { eRequestHeaders, RequestHeaders } from "./RequestResponseHeaders"; import { dataSanitizeString } from "./Telemetry/Common/DataSanitizer"; import { ICorrelationConfig } from "./Interfaces/ICorrelationConfig"; import { createDomEvent } from "./DomHelperFuncs"; import { stringToBoolOrDefault, msToTimeSpan, isCrossOriginError, getExtensionByName } from "./HelperFuncs"; import { strNotSpecified } from "./Constants"; import { utlCanUseLocalStorage, utlCanUseSessionStorage, utlDisableStorage, utlGetSessionStorage, utlGetSessionStorageKeys, utlGetLocalStorage, utlRemoveSessionStorage, utlRemoveStorage, utlSetSessionStorage, utlSetLocalStorage } from "./StorageHelperFuncs"; import { urlGetAbsoluteUrl, urlGetCompleteUrl, urlGetPathName, urlParseFullHost, urlParseHost, urlParseUrl } from "./UrlHelperFuncs"; import { ITelemetryTrace } from "./Interfaces/Context/ITelemetryTrace"; // listing only non-geo specific locations const _internalEndpoints: string[] = [ "https://dc.services.visualstudio.com/v2/track", "https://breeze.aimon.applicationinsights.io/v2/track", "https://dc-int.services.visualstudio.com/v2/track" ]; export function isInternalApplicationInsightsEndpoint(endpointUrl: string): boolean { return arrIndexOf(_internalEndpoints, endpointUrl.toLowerCase()) !== -1; } export interface IUtil { NotSpecified: string, createDomEvent: (eventName: string) => Event, /* * Force the SDK not to use local and session storage */ disableStorage: () => void, /** * Checks if endpoint URL is application insights internal injestion service URL. * * @param endpointUrl Endpoint URL to check. * @returns {boolean} True if if endpoint URL is application insights internal injestion service URL. */ isInternalApplicationInsightsEndpoint: (endpointUrl: string) => boolean, /** * Check if the browser supports local storage. * * @returns {boolean} True if local storage is supported. */ canUseLocalStorage: () => boolean, /** * Get an object from the browser's local storage * * @param {string} name - the name of the object to get from storage * @returns {string} The contents of the storage object with the given name. Null if storage is not supported. */ getStorage: (logger: IDiagnosticLogger, name: string) => string, /** * Set the contents of an object in the browser's local storage * * @param {string} name - the name of the object to set in storage * @param {string} data - the contents of the object to set in storage * @returns {boolean} True if the storage object could be written. */ setStorage: (logger: IDiagnosticLogger, name: string, data: string) => boolean, /** * Remove an object from the browser's local storage * * @param {string} name - the name of the object to remove from storage * @returns {boolean} True if the storage object could be removed. */ removeStorage: (logger: IDiagnosticLogger, name: string) => boolean, /** * Check if the browser supports session storage. * * @returns {boolean} True if session storage is supported. */ canUseSessionStorage: () => boolean, /** * Gets the list of session storage keys * * @returns {string[]} List of session storage keys */ getSessionStorageKeys: () => string[], /** * Get an object from the browser's session storage * * @param {string} name - the name of the object to get from storage * @returns {string} The contents of the storage object with the given name. Null if storage is not supported. */ getSessionStorage: (logger: IDiagnosticLogger, name: string) => string, /** * Set the contents of an object in the browser's session storage * * @param {string} name - the name of the object to set in storage * @param {string} data - the contents of the object to set in storage * @returns {boolean} True if the storage object could be written. */ setSessionStorage: (logger: IDiagnosticLogger, name: string, data: string) => boolean, /** * Remove an object from the browser's session storage * * @param {string} name - the name of the object to remove from storage * @returns {boolean} True if the storage object could be removed. */ removeSessionStorage: (logger: IDiagnosticLogger, name: string) => boolean, /** * @deprecated - Use the core.getCookieMgr().disable() * Force the SDK not to store and read any data from cookies. */ disableCookies: () => void, /** * @deprecated - Use the core.getCookieMgr().isEnabled() * Helper method to tell if document.cookie object is available and whether it can be used. */ canUseCookies: (logger: IDiagnosticLogger) => any, disallowsSameSiteNone: (userAgent: string) => boolean, /** * @deprecated - Use the core.getCookieMgr().set() * helper method to set userId and sessionId cookie */ setCookie: (logger: IDiagnosticLogger, name: string, value: string, domain?: string) => void, stringToBoolOrDefault: (str: any, defaultValue?: boolean) => boolean, /** * @deprecated - Use the core.getCookieMgr().get() * helper method to access userId and sessionId cookie */ getCookie: (logger: IDiagnosticLogger, name: string) => string, /** * @deprecated - Use the core.getCookieMgr().del() * Deletes a cookie by setting it's expiration time in the past. * @param name - The name of the cookie to delete. */ deleteCookie: (logger: IDiagnosticLogger, name: string) => void, /** * helper method to trim strings (IE8 does not implement String.prototype.trim) */ trim: (str: any) => string, /** * generate random id string */ newId: () => string, /** * generate a random 32bit number (-0x80000000..0x7FFFFFFF). */ random32: () => number, /** * generate W3C trace id */ generateW3CId: () => string, /** * Check if an object is of type Array */ isArray: (obj: any) => boolean, /** * Check if an object is of type Error */ isError: (obj: any) => obj is Error, /** * Check if an object is of type Date */ isDate: (obj: any) => obj is Date, // Keeping this name for backward compatibility (for now) toISOStringForIE8: (date: Date) => string, /** * Gets IE version returning the document emulation mode if we are running on IE, or null otherwise */ getIEVersion: (userAgentStr?: string) => number, /** * Convert ms to c# time span format */ msToTimeSpan: (totalms: number) => string, /** * Checks if error has no meaningful data inside. Ususally such errors are received by window.onerror when error * happens in a script from other domain (cross origin, CORS). */ isCrossOriginError: (message: string|Event, url: string, lineNumber: number, columnNumber: number, error: Error) => boolean, /** * Returns string representation of an object suitable for diagnostics logging. */ dump: (object: any) => string, /** * Returns the name of object if it's an Error. Otherwise, returns empty string. */ getExceptionName: (object: any) => string, /** * Adds an event handler for the specified event to the window * @param eventName {string} - The name of the event * @param callback {any} - The callback function that needs to be executed for the given event * @return {boolean} - true if the handler was successfully added */ addEventHandler: (obj: any, eventNameWithoutOn: string, handlerRef: any, useCapture: boolean) => boolean, /** * Tells if a browser supports a Beacon API */ IsBeaconApiSupported: () => boolean, getExtension: (extensions: IPlugin[], identifier: string) => IPlugin | null } export const Util: IUtil = { NotSpecified: strNotSpecified, createDomEvent, disableStorage: utlDisableStorage, isInternalApplicationInsightsEndpoint, canUseLocalStorage: utlCanUseLocalStorage, getStorage: utlGetLocalStorage, setStorage: utlSetLocalStorage, removeStorage: utlRemoveStorage, canUseSessionStorage: utlCanUseSessionStorage, getSessionStorageKeys: utlGetSessionStorageKeys, getSessionStorage: utlGetSessionStorage, setSessionStorage: utlSetSessionStorage, removeSessionStorage: utlRemoveSessionStorage, disableCookies: coreDisableCookies, canUseCookies: coreCanUseCookies, disallowsSameSiteNone: uaDisallowsSameSiteNone, setCookie: coreSetCookie, stringToBoolOrDefault, getCookie: coreGetCookie, deleteCookie: coreDeleteCookie, trim: strTrim, newId, random32() { return random32(true); }, generateW3CId, isArray, isError, isDate, toISOStringForIE8: toISOString, getIEVersion, msToTimeSpan, isCrossOriginError, dump: dumpObj, getExceptionName: coreGetExceptionName, addEventHandler: attachEvent, IsBeaconApiSupported: isBeaconsSupported, getExtension: getExtensionByName }; export interface IUrlHelper { parseUrl: (url: string) => HTMLAnchorElement, getAbsoluteUrl: (url: string) => string, getPathName: (url: string) => string, getCompleteUrl: (method: string, absoluteUrl: string) => string, // Fallback method to grab host from url if document.createElement method is not available parseHost: (url: string, inclPort?: boolean) => string, /** * Get the full host from the url, optionally including the port */ parseFullHost: (url: string, inclPort?: boolean) => string } export const UrlHelper: IUrlHelper = { parseUrl: urlParseUrl, getAbsoluteUrl: urlGetAbsoluteUrl, getPathName: urlGetPathName, getCompleteUrl: urlGetCompleteUrl, parseHost: urlParseHost, parseFullHost: urlParseFullHost }; export interface ICorrelationIdHelper { correlationIdPrefix: string; /** * Checks if a request url is not on a excluded domain list and if it is safe to add correlation headers. * Headers are always included if the current domain matches the request domain. If they do not match (CORS), * they are regex-ed across correlationHeaderDomains and correlationHeaderExcludedDomains to determine if headers are included. * Some environments don't give information on currentHost via window.location.host (e.g. Cordova). In these cases, the user must * manually supply domains to include correlation headers on. Else, no headers will be included at all. */ canIncludeCorrelationHeader(config: ICorrelationConfig, requestUrl: string, currentHost?: string): boolean; /** * Combines target appId and target role name from response header. */ getCorrelationContext(responseHeader: string): string | undefined; /** * Gets key from correlation response header */ getCorrelationContextValue(responseHeader: string, key: string): string | undefined; } export const CorrelationIdHelper: ICorrelationIdHelper = { correlationIdPrefix: "cid-v1:", /** * Checks if a request url is not on a excluded domain list and if it is safe to add correlation headers. * Headers are always included if the current domain matches the request domain. If they do not match (CORS), * they are regex-ed across correlationHeaderDomains and correlationHeaderExcludedDomains to determine if headers are included. * Some environments don't give information on currentHost via window.location.host (e.g. Cordova). In these cases, the user must * manually supply domains to include correlation headers on. Else, no headers will be included at all. */ canIncludeCorrelationHeader(config: ICorrelationConfig, requestUrl: string, currentHost?: string) { if (!requestUrl || (config && config.disableCorrelationHeaders)) { return false; } if (config && config.correlationHeaderExcludePatterns) { for (let i = 0; i < config.correlationHeaderExcludePatterns.length; i++) { if (config.correlationHeaderExcludePatterns[i].test(requestUrl)) { return false; } } } let requestHost = urlParseUrl(requestUrl).host.toLowerCase(); if (requestHost && (requestHost.indexOf(":443") !== -1 || requestHost.indexOf(":80") !== -1)) { // [Bug #1260] IE can include the port even for http and https URLs so if present // try and parse it to remove if it matches the default protocol port requestHost = (urlParseFullHost(requestUrl, true) || "").toLowerCase(); } if ((!config || !config.enableCorsCorrelation) && (requestHost && requestHost !== currentHost)) { return false; } const includedDomains = config && config.correlationHeaderDomains; if (includedDomains) { let matchExists: boolean; arrForEach(includedDomains, (domain) => { const regex = new RegExp(domain.toLowerCase().replace(/\\/g, "\\\\").replace(/\./g, "\\.").replace(/\*/g, ".*")); matchExists = matchExists || regex.test(requestHost); }); if (!matchExists) { return false; } } const excludedDomains = config && config.correlationHeaderExcludedDomains; if (!excludedDomains || excludedDomains.length === 0) { return true; } for (let i = 0; i < excludedDomains.length; i++) { const regex = new RegExp(excludedDomains[i].toLowerCase().replace(/\\/g, "\\\\").replace(/\./g, "\\.").replace(/\*/g, ".*")); if (regex.test(requestHost)) { return false; } } // if we don't know anything about the requestHost, require the user to use included/excludedDomains. // Previously we always returned false for a falsy requestHost return requestHost && requestHost.length > 0; }, /** * Combines target appId and target role name from response header. */ getCorrelationContext(responseHeader: string) { if (responseHeader) { const correlationId = CorrelationIdHelper.getCorrelationContextValue(responseHeader, RequestHeaders[eRequestHeaders.requestContextTargetKey]); if (correlationId && correlationId !== CorrelationIdHelper.correlationIdPrefix) { return correlationId; } } }, /** * Gets key from correlation response header */ getCorrelationContextValue(responseHeader: string, key: string) { if (responseHeader) { const keyValues = responseHeader.split(","); for (let i = 0; i < keyValues.length; ++i) { const keyValue = keyValues[i].split("="); if (keyValue.length === 2 && keyValue[0] === key) { return keyValue[1]; } } } } }; export function AjaxHelperParseDependencyPath(logger: IDiagnosticLogger, absoluteUrl: string, method: string, commandName: string) { let target, name = commandName, data = commandName; if (absoluteUrl && absoluteUrl.length > 0) { const parsedUrl: HTMLAnchorElement = urlParseUrl(absoluteUrl); target = parsedUrl.host; if (!name) { if (parsedUrl.pathname != null) { let pathName: string = (parsedUrl.pathname.length === 0) ? "/" : parsedUrl.pathname; if (pathName.charAt(0) !== "/") { pathName = "/" + pathName; } data = parsedUrl.pathname; name = dataSanitizeString(logger, method ? method + " " + pathName : pathName); } else { name = dataSanitizeString(logger, absoluteUrl); } } } else { target = commandName; name = commandName; } return { target, name, data }; } export function dateTimeUtilsNow() { // returns the window or webworker performance object let perf = getPerformance(); if (perf && perf.now && perf.timing) { let now = perf.now() + perf.timing.navigationStart; // Known issue with IE where this calculation can be negative, so if it is then ignore and fallback if (now > 0) { return now; } } return dateNow(); } export function dateTimeUtilsDuration(start: number, end: number): number { let result = null; if (start !== 0 && end !== 0 && !isNullOrUndefined(start) && !isNullOrUndefined(end)) { result = end - start; } return result; } export interface IDateTimeUtils { /** * Get the number of milliseconds since 1970/01/01 in local timezone */ Now: () => number; /** * Gets duration between two timestamps */ GetDuration: (start: number, end: number) => number; } /** * A utility class that helps getting time related parameters */ export const DateTimeUtils: IDateTimeUtils = { Now: dateTimeUtilsNow, GetDuration: dateTimeUtilsDuration }; /** * Creates a IDistributedTraceContext from an optional telemetryTrace * @param telemetryTrace - The telemetryTrace instance that is being wrapped * @param parentCtx - An optional parent distributed trace instance, almost always undefined as this scenario is only used in the case of multiple property handlers. * @returns A new IDistributedTraceContext instance that is backed by the telemetryTrace or temporary object */ export function createDistributedTraceContextFromTrace(telemetryTrace?: ITelemetryTrace, parentCtx?: IDistributedTraceContext): IDistributedTraceContext { let trace: ITelemetryTrace = telemetryTrace || {}; return { getName: (): string => { return trace.name; }, setName: (newValue: string): void => { parentCtx && parentCtx.setName(newValue); trace.name = newValue; }, getTraceId: (): string => { return trace.traceID; }, setTraceId: (newValue: string): void => { parentCtx && parentCtx.setTraceId(newValue); if (isValidTraceId(newValue)) { trace.traceID = newValue } }, getSpanId: (): string => { return trace.parentID; }, setSpanId: (newValue: string): void => { parentCtx && parentCtx.setSpanId(newValue); if (isValidSpanId(newValue)) { trace.parentID = newValue } }, getTraceFlags: (): number => { return trace.traceFlags; }, setTraceFlags: (newTraceFlags?: number): void => { parentCtx && parentCtx.setTraceFlags(newTraceFlags); trace.traceFlags = newTraceFlags } }; }
the_stack
import { $, $$, browser, by, element } from 'protractor'; import { fakeServer } from './helpers/fake_server'; describe('Integrations', () => { beforeAll(() => { browser.waitForAngularEnabled(false); }); describe('integrations view', () => { beforeEach(() => { fakeServer() .post('/api/v0/nodemanagers/search', '{}') .any() .reply(200, JSON.stringify({ managers: [ { id: 'e69dc612-7e67-43f2-9b19-256afd385820', name: 'Automate', type: 'automate', credential_id: '', instance_credentials: [], status: '', account_id: '', date_added: '2018-11-19T04:37:13Z', credential_data: [] }, { id: 'f69dc612-7e67-43f2-9b19-256afd385820', name: 'aws-manager-1', type: 'aws-api', credential_id: '', instance_credentials: [], status: '', account_id: '', date_added: '2018-11-19T04:37:13Z', credential_data: [] }, { id: 'f69dc612-7e67-43f2-9b19-256afd385821', name: 'aws-manager-2', type: 'aws-api', credential_id: '', instance_credentials: [], status: '', account_id: '', date_added: '2018-11-19T04:52:13Z', credential_data: [] } ], total: 1 })); }); it('has a heading and a subheading', () => { browser.get('/settings/node-integrations'); const heading = $('chef-page-header chef-heading'); const subheading = $('chef-page-header chef-subheading'); expect(heading.getText()) .toBe('Node Integrations'); expect(subheading.getText()) .toBe('Connect Chef Automate to cloud services.'); }); it('displays list of integrations', () => { browser.get('/settings/node-integrations'); const list = $('chef-table'); const nameColumn = list.$$('chef-tbody chef-tr:not(.new-row)').map(row => { return row.$('chef-td:first-child').getText(); }); expect(list.isDisplayed()).toEqual(true); expect(nameColumn).toEqual([ 'aws-manager-1', 'aws-manager-2' ]); }); describe('integrations list item', () => { it('has a link to detail view', () => { browser.get('/settings/node-integrations'); const listItem = $$('chef-tbody chef-tr').first(); const link = listItem.element(by.css('.link')); expect(link.isDisplayed()).toEqual(true); expect(link.getText()).toEqual('aws-manager-1'); expect(link.getAttribute('href')) .toContain('/settings/node-integrations/f69dc612-7e67-43f2-9b19-256afd385820'); }); it('has control menu (delete button)', () => { browser.get('/settings/node-integrations'); const listItem = $$('chef-tbody chef-tr:not(.new-row)').filter(row => { return row.$('chef-td:first-child').getText().then(text => { return text !== 'Automate'; }); }).first(); const controlMenu = listItem.element(by.tagName('mat-select')); expect(controlMenu.isDisplayed()).toBe(true); }); }); }); describe('integrations-add view', () => { it('has a heading and a subheading', () => { browser.get('/settings/node-integrations/add'); const heading = $('chef-page-header chef-heading'); const subheading = $('chef-page-header chef-subheading'); expect(heading.getText()) .toBe('Add a new cloud management service'); expect(subheading.getText()) .toBe('Select a cloud management service and add your credentials for the account.'); }); it('has a `cancel` button', () => { browser.get('/settings/node-integrations/add'); const button = element(by.cssContainingText('chef-button', 'Cancel')); expect(button.isDisplayed()).toEqual(true); }); describe('clicking `cancel` button', () => { it('navigates back to credential-list view', () => { browser.get('/settings/node-integrations/add'); const button = element(by.cssContainingText('chef-button', 'Cancel')); button.click(); expect(browser.getCurrentUrl()).toMatch(/\/settings\/node-integrations$/); }); }); it('has options for selecting an integration type', () => { browser.get('/settings/node-integrations/add'); const label = element(by.cssContainingText('.label', 'Select a node management service')); const options = $$('.integration-services chef-option'); expect(label.isDisplayed()).toEqual(true); expect(options.map(el => el.getAttribute('value'))).toEqual([ 'aws', 'azure', 'gcp' ]); }); describe('gcp form', () => { beforeEach(() => { browser.get('/settings/node-integrations/add'); const option = $('chef-option[value="gcp"]'); option.click(); }); it('has a name input', () => { const label = element(by.cssContainingText('.label', 'Name')); const input = $('input[formcontrolname="name"]'); expect(label.isDisplayed()).toEqual(true); expect(input.isDisplayed()).toEqual(true); }); it('has a textarea to enter credentials JSON', () => { const label = element( by.cssContainingText('.label', 'Enter your service account JSON credentials') ); const textarea = $('textarea[formcontrolname="google_credentials_json"]'); expect(label.isDisplayed()).toEqual(true); expect(textarea.isDisplayed()).toEqual(true); }); }); }); describe('integrations-edit view', () => { beforeEach(() => { fakeServer() .get('/api/v0/nodemanagers/id/be56f1e3-4ac9-4e74-8d69-f67bea007cd3') .many() .reply(200, JSON.stringify({ id: 'be56f1e3-4ac9-4e74-8d69-f67bea007cd3', name: 'gcp-test-manager', type: 'gcp-api', credential_id: 'e68d4cb7-5a1c-41cf-870e-6af7b2a15e5c', instance_credentials: [], status: 'reachable', account_id: 'alex-pop-project', date_added: '2018-10-16T04:10:51Z', credential_data: [] })); browser.get('/settings/node-integrations/edit/be56f1e3-4ac9-4e74-8d69-f67bea007cd3'); }); it('has a heading and a subheading', () => { const heading = $('chef-page-header chef-heading'); const subheading = $('chef-page-header chef-subheading'); expect(heading.getText()) .toBe('Update cloud management service'); expect(subheading.getText()) .toBe('Select a cloud management service and add your credentials for the account.'); }); it('has a `cancel` button', () => { const button = element(by.cssContainingText('chef-button', 'Cancel')); expect(button.isDisplayed()).toEqual(true); }); describe('clicking `cancel` button', () => { it('navigates back to credential-list view', () => { const button = element(by.cssContainingText('chef-button', 'Cancel')); button.click(); expect(browser.getCurrentUrl()).toMatch(/\/settings\/node-integrations$/); }); }); it('has options for selecting an integration type', () => { const label = element(by.cssContainingText('.label', 'Select a node management service')); const options = $$('.integration-services chef-option'); expect(label.isDisplayed()).toEqual(true); expect(options.map(el => el.getAttribute('value'))).toEqual([ 'aws', 'azure', 'gcp' ]); }); // Note(sr) 2018-11-19: this seems to be flakey. Disabled until someone has // a look. xit('has the correct integration type option selected', () => { const selected = $('.integration-services chef-option.selected'); expect(selected.getAttribute('value')).toEqual('gcp'); }); describe('gcp form', () => { it('has a name input filled with correct value', () => { const label = element(by.cssContainingText('.label', 'Name')); const input = $('input[formcontrolname="name"]'); expect(label.isDisplayed()).toEqual(true); expect(input.isDisplayed()).toEqual(true); expect(input.getAttribute('value')).toEqual('gcp-test-manager'); }); it('has an empty textarea to update credentials JSON', () => { const label = element( by.cssContainingText('.label', 'Enter your service account JSON credentials') ); const textarea = $('textarea[formcontrolname="google_credentials_json"]'); expect(label.isDisplayed()).toEqual(true); expect(textarea.isDisplayed()).toEqual(true); expect(textarea.getText()).toEqual(''); }); }); }); describe('integrations-detail view', () => { beforeEach(() => { // Request for nodemanager info fakeServer() .get('/api/v0/nodemanagers/id/be56f1e3-4ac9-4e74-8d69-f67bea007cd3') .many() .reply(200, JSON.stringify({ id: 'be56f1e3-4ac9-4e74-8d69-f67bea007cd3', name: 'gcp-test-manager', type: 'gcp-api', credential_id: 'e68d4cb7-5a1c-41cf-870e-6af7b2a15e5c', instance_credentials: [], status: 'reachable', account_id: 'alex-pop-project', date_added: '2018-10-16T04:10:51Z', credential_data: [] })); // Request for list of nodes belonging to nodemanager fakeServer() .post('/api/v0/nodes/search', JSON.stringify({ 'filters': [ { 'key': 'manager_id', 'values': ['be56f1e3-4ac9-4e74-8d69-f67bea007cd3'] } ], 'page': 1, 'per_page': 100 })) .many() .reply(200, JSON.stringify({ 'nodes': [ { 'id': '659e200d-35d2-4146-b98a-50e969855f2a', 'name': 'test-node-1', 'platform': 'ubuntu', 'platform_version': '18.04', 'manager': 'gcp-api', 'tags': [], 'last_contact': '2019-03-12T06:14:36Z', 'status': 'reachable', 'last_job': null, 'target_config': null, 'manager_ids': ['be56f1e3-4ac9-4e74-8d69-f67bea007cd3'], 'state': 'RUNNING', 'name_prefix': '', 'projects': [] }, { 'id': '659e200d-35d2-4146-b98a-50e969855f2b', 'name': 'test-node-2', 'platform': 'ubuntu', 'platform_version': '18.04', 'manager': 'gcp-api', 'tags': [], 'last_contact': '2019-03-12T06:14:36Z', 'status': 'unreachable', 'last_job': null, 'target_config': null, 'manager_ids': ['be56f1e3-4ac9-4e74-8d69-f67bea007cd3'], 'state': 'RUNNING', 'name_prefix': '', 'projects': [] } ], 'total': 2, 'total_unreachable': 1, 'total_reachable': 1, 'total_unknown': 0 })); browser.get('/settings/node-integrations/be56f1e3-4ac9-4e74-8d69-f67bea007cd3'); }); it('displays a heading with the manager name', () => { const heading = $('chef-page-header chef-heading'); expect(heading.getText()).toEqual('gcp-test-manager'); }); it('displays a manager type', () => { const label = $('#manager-info th:nth-child(1)'); const value = $('#manager-info td:nth-child(1)'); expect(label.getText()).toEqual('Manager'); expect(value.getText()).toEqual('gcp-api'); }); it('displays a manager status', () => { const label = $('#manager-info th:nth-child(2)'); const value = $('#manager-info td:nth-child(2)'); expect(label.getText()).toEqual('Status'); expect(value.getText()).toEqual('reachable'); }); it('displays a manager node count', () => { const label = $('#manager-info th:nth-child(3)'); const value = $('#manager-info td:nth-child(3)'); expect(label.getText()).toEqual('Node Count'); expect(value.getText()).toEqual('2'); }); it('displays a list of nodes belonging to the nodemanager', () => { const list = $('#manager-nodes-list'); const nameColumn = list.$$('chef-tbody chef-tr').map(row => { return row.$('chef-td:nth-child(2)').getText(); }); expect(list.isDisplayed()).toEqual(true); expect(nameColumn).toEqual([ 'test-node-1', 'test-node-2' ]); }); }); });
the_stack
import { expect } from "chai"; import { IModelConnection, SnapshotConnection } from "@itwin/core-frontend"; import { ContentSpecificationTypes, KeySet, RelationshipDirection, Ruleset, RuleTypes } from "@itwin/presentation-common"; import { Presentation } from "@itwin/presentation-frontend"; import { initialize, terminate } from "../../../IntegrationTests"; import { getFieldByLabel, tryGetFieldByLabel } from "../../../Utils"; import { printRuleset } from "../../Utils"; describe("Learning Snippets", () => { let imodel: IModelConnection; beforeEach(async () => { await initialize(); imodel = await SnapshotConnection.openFile("assets/datasets/Properties_60InstancesWithUrl2.ibim"); }); afterEach(async () => { await imodel.close(); await terminate(); }); describe("Content Rules", () => { describe("ContentModifier", () => { it("uses `class` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.ContentModifier.Class.Ruleset // The ruleset has a content rule that returns content of all `bis.SpatialCategory` and `bis.GeometricModel` // instances.There's also a content modifier that creates a custom calculated property only for `bis.Category` instances. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [{ // load content for all `bis.SpatialCategory` and `bis.GeometricModel` instances specType: ContentSpecificationTypes.ContentInstancesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["SpatialCategory", "GeometricModel"] }, handleInstancesPolymorphically: true, }], }, { ruleType: RuleTypes.ContentModifier, class: { schemaName: "BisCore", className: "Category" }, calculatedProperties: [{ label: "Calculated", value: `"PREFIX_" & this.CodeValue`, }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Ensure only the `bis.Category` instance has the calculated property const content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet(), descriptor: {}, }); expect(content!.descriptor.fields).to.containSubset([{ label: "Model", }, { label: "Code", }, { label: "User Label", }, { label: "Is Private", }, { label: "Calculated", }, { label: "Modeled Element", }]).and.to.have.lengthOf(6); const calculatedField = tryGetFieldByLabel(content!.descriptor.fields, "Calculated"); expect(content!.contentSet[0].displayValues[calculatedField!.name]).to.be.undefined; expect(content!.contentSet[1].displayValues[calculatedField!.name]).to.eq("PREFIX_Uncategorized"); }); it("uses `requiredSchemas` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.ContentModifier.RequiredSchemas.Ruleset // The ruleset has a content rule that returns content of given input instances. There's also // a content modifier that tells us to load `bis.ExternalSourceAspect` related properties, but the // ECClass was introduced in BisCore version 1.0.2, so the modifier needs a `requiredSchemas` attribute // to only use the rule if the version meets the requirement. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [{ // load content for given input instances specType: ContentSpecificationTypes.SelectedNodeInstances, }], }, { ruleType: RuleTypes.ContentModifier, requiredSchemas: [{ name: "BisCore", minVersion: "1.0.2" }], class: { schemaName: "BisCore", className: "ExternalSourceAspect" }, relatedProperties: [{ // request to include properties of related ExternalSourceAspect instances propertiesSource: { relationship: { schemaName: "BisCore", className: "ElementOwnsMultiAspects" }, direction: RelationshipDirection.Forward, targetClass: { schemaName: "BisCore", className: "ExternalSourceAspect" }, }, }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // The iModel uses BisCore older than 1.0.2 - the returned content should not // include ExternalSourceAspect properties const content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet([{ className: "BisCore:Element", id: "0x61" }]), descriptor: {}, }); expect(content!.descriptor.fields).to.not.containSubset([{ label: "External Source Aspect", }]).and.to.have.lengthOf(1); }); it("uses `priority` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.ContentModifier.Priority.Ruleset // The ruleset has a content rule that returns content of all `bis.SpatialCategory` // instances.There's also a content modifier that tells us to hide all properties // of `bis.Element` instances and a higher priority modifier that tells us to show // its `CodeValue` property. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [{ // load content of all `bis.SpatialCategory` instances specType: ContentSpecificationTypes.ContentInstancesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["SpatialCategory"] }, handleInstancesPolymorphically: true, }], }, { ruleType: RuleTypes.ContentModifier, class: { schemaName: "BisCore", className: "SpatialCategory" }, priority: 1, propertyOverrides: [{ // hide all properties name: "*", isDisplayed: false, }], }, { ruleType: RuleTypes.ContentModifier, class: { schemaName: "BisCore", className: "SpatialCategory" }, priority: 2, propertyOverrides: [{ // display the CodeValue property name: "CodeValue", isDisplayed: true, doNotHideOtherPropertiesOnDisplayOverride: true, }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Expect to get one `bis.SpatialCategory` field and one related content field. const content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet(), descriptor: {}, }); expect(content!.contentSet.length).to.eq(1); expect(content!.descriptor.fields).to.containSubset([{ label: "Code", }]).and.to.have.lengthOf(1); }); it("uses `relatedProperties` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.ContentModifier.RelatedProperties.Ruleset // The ruleset has a content rule that returns content of given input instances. There's also // a content modifier that includes properties of the related `bis.Category` for all `bis.GeometricElement3d` // instances' content. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [{ // load content for given input instances specType: ContentSpecificationTypes.SelectedNodeInstances, }], }, { ruleType: RuleTypes.ContentModifier, class: { schemaName: "BisCore", className: "GeometricElement3d" }, relatedProperties: [{ propertiesSource: { relationship: { schemaName: "BisCore", className: "GeometricElement3dIsInCategory" }, direction: RelationshipDirection.Forward, }, handleTargetClassPolymorphically: true, }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Ensure content contains Category's properties const content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet([{ className: "BisCore:Element", id: "0x61" }]), descriptor: {}, }); expect(content!.contentSet.length).to.eq(1); expect(content!.descriptor.fields).to.containSubset([{ label: "Spatial Category", nestedFields: [{ label: "Code" }, { label: "Is Private" }, { label: "Model" }, { label: "User Label" }], }]); }); it("uses `calculatedProperties` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.ContentModifier.CalculatedProperties.Ruleset // The ruleset has a content rule that returns content of given input instances. There's also // a content modifier that creates a calculated property for `bis.GeometricElement3d` instances. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [{ // load content for given input instances specType: ContentSpecificationTypes.SelectedNodeInstances, }], }, { ruleType: RuleTypes.ContentModifier, class: { schemaName: "BisCore", className: "GeometricElement3d" }, calculatedProperties: [{ label: "Yaw & Pitch & Roll", value: `this.Yaw & " & " & this.Pitch & " & " & this.Roll`, }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Ensure content contains the calculated property and correct value const content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet([{ className: "BisCore:Element", id: "0x61" }]), descriptor: {}, }); expect(content!.descriptor.fields).to.containSubset([{ label: "Yaw & Pitch & Roll", }]); expect(content!.contentSet.length).to.eq(1); expect(content!.contentSet[0].displayValues[getFieldByLabel(content!.descriptor.fields, "Yaw & Pitch & Roll").name]).to.eq("0.000000 & 0.000000 & 90.000000"); }); it("uses `propertyCategories` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.ContentModifier.PropertyCategories.Ruleset // The ruleset has a content rule that returns content of given input instances. There's also // a content modifier that moves all `bis.GeometricElement3d` properties into a custom category. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [{ // load content for given input instances specType: ContentSpecificationTypes.SelectedNodeInstances, }], }, { ruleType: RuleTypes.ContentModifier, class: { schemaName: "BisCore", className: "GeometricElement3d" }, propertyCategories: [{ id: "custom-category", label: "Custom Category", }], propertyOverrides: [{ name: "*", categoryId: "custom-category", }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Ensure all `bis.GeometricElement3d` properties are in the custom category const content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet([{ className: "BisCore:Element", id: "0x61" }]), descriptor: {}, }); expect(content!.descriptor.fields).to.containSubset([{ label: "Category", category: { label: "Custom Category" }, }, { label: "Code", category: { label: "Custom Category" }, }, { label: "Model", category: { label: "Custom Category" }, }, { label: "User Label", category: { label: "Custom Category" }, }]); }); it("uses `propertyOverrides` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.ContentModifier.PropertyOverrides.Ruleset // The ruleset has a content rule that returns content of given input instances. There's also // a content modifier that customizes display of `bis.GeometricElement3d` properties. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [{ // load content for given input instances specType: ContentSpecificationTypes.SelectedNodeInstances, }], }, { ruleType: RuleTypes.ContentModifier, class: { schemaName: "BisCore", className: "GeometricElement3d" }, propertyOverrides: [{ // force hide the UserLabel property name: "UserLabel", isDisplayed: false, }, { // force show the Parent property which is hidden by default through ECSchema name: "Parent", isDisplayed: true, doNotHideOtherPropertiesOnDisplayOverride: true, }, { // override label of CodeValue property name: "CodeValue", labelOverride: "Overriden Label", }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Ensure customizations have been made const content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet([{ className: "BisCore:Element", id: "0x61" }]), descriptor: {}, }); expect(content!.descriptor.fields.length).to.eq(20); expect(tryGetFieldByLabel(content!.descriptor.fields, "User Label")).to.be.undefined; expect(tryGetFieldByLabel(content!.descriptor.fields, "Parent")).to.not.be.undefined; expect(tryGetFieldByLabel(content!.descriptor.fields, "Overriden Label")).to.not.be.undefined; }); }); }); });
the_stack
declare namespace Bob { // https://ripperhe.gitee.io/bob/#/plugin/addtion/language enum LanguagesEnum { 'auto' = '自动', 'zh-Hans' = '中文简体', 'zh-Hant' = '中文繁体', 'yue' = '粤语', 'wyw' = '文言文', 'pysx' = '拼音缩写', 'en' = '英语', 'ja' = '日语', 'ko' = '韩语', 'fr' = '法语', 'de' = '德语', 'es' = '西班牙语', 'it' = '意大利语', 'ru' = '俄语', 'pt' = '葡萄牙语', 'nl' = '荷兰语', 'pl' = '波兰语', 'ar' = '阿拉伯语', 'af' = '南非语', 'am' = '阿姆哈拉语', 'az' = '阿塞拜疆语', 'be' = '白俄罗斯语', 'bg' = '保加利亚语', 'bn' = '孟加拉语', 'bo' = '藏语', 'bs' = '波斯尼亚语', 'ca' = '加泰隆语', 'ceb' = '宿务语', 'chr' = '切罗基语', 'co' = '科西嘉语', 'cs' = '捷克语', 'cy' = '威尔士语', 'da' = '丹麦语', 'el' = '希腊语', 'eo' = '世界语', 'et' = '爱沙尼亚语', 'eu' = '巴斯克语', 'fa' = '波斯语', 'fi' = '芬兰语', 'fj' = '斐济语', 'fy' = '弗里西语', 'ga' = '爱尔兰语', 'gd' = '苏格兰盖尔语', 'gl' = '加利西亚语', 'gu' = '古吉拉特语', 'ha' = '豪萨语', 'haw' = '夏威夷语', 'he' = '希伯来语', 'hi' = '印地语', 'hmn' = '苗语', 'hr' = '克罗地亚语', 'ht' = '海地克里奥尔语', 'hu' = '匈牙利语', 'hy' = '亚美尼亚语', 'id' = '印尼语', 'ig' = '伊博语', 'is' = '冰岛语', 'jw' = '爪哇语', 'ka' = '格鲁吉亚语', 'kk' = '哈萨克语', 'km' = '高棉语', 'kn' = '卡纳达语', 'ku' = '库尔德语', 'ky' = '柯尔克孜语', 'la' = '老挝语', 'lb' = '卢森堡语', 'lo' = '老挝语', 'lt' = '立陶宛语', 'lv' = '拉脱维亚语', 'mg' = '马尔加什语', 'mi' = '毛利语', 'mk' = '马其顿语', 'ml' = '马拉雅拉姆语', 'mn' = '蒙古语', 'mr' = '马拉地语', 'ms' = '马来语', 'mt' = '马耳他语', 'mww' = '白苗语', 'my' = '缅甸语', 'ne' = '尼泊尔语', 'no' = '挪威语', 'ny' = '齐切瓦语', 'or' = '奥里亚语', 'otq' = '克雷塔罗奥托米语', 'pa' = '旁遮普语', 'ps' = '普什图语', 'ro' = '罗马尼亚语', 'rw' = '卢旺达语', 'sd' = '信德语', 'si' = '僧伽罗语', 'sk' = '斯洛伐克语', 'sl' = '斯洛文尼亚语', 'sm' = '萨摩亚语', 'sn' = '修纳语', 'so' = '索马里语', 'sq' = '阿尔巴尼亚语', 'sr' = '塞尔维亚语', 'sr-Cyrl' = '塞尔维亚语-西里尔文', 'sr-Latn' = '塞尔维亚语-拉丁文', 'st' = '塞索托语', 'su' = '巽他语', 'sv' = '瑞典语', 'sw' = '斯瓦希里语', 'ta' = '泰米尔语', 'te' = '泰卢固语', 'tg' = '塔吉克语', 'th' = '泰语', 'tk' = '土库曼语', 'tl' = '菲律宾语', 'tlh' = '克林贡语', 'to' = '汤加语', 'tr' = '土耳其语', 'tt' = '鞑靼语', 'ty' = '塔希提语', 'ug' = '维吾尔语', 'uk' = '乌克兰语', 'ur' = '乌尔都语', 'uz' = '乌兹别克语', 'vi' = '越南语', 'xh' = '科萨语', 'yi' = '意第绪语', 'yo' = '约鲁巴语', 'yua' = '尤卡坦玛雅语', 'zu' = '祖鲁语', } type Languages = Array<keyof typeof LanguagesEnum>; type supportLanguages = Languages; type Language = keyof typeof LanguagesEnum; // https://ripperhe.gitee.io/bob/#/plugin/quickstart/translate type Translate = (query: TranslateQuery, completion: Completion) => void; type completionResult = { result: Result }; type CompletionResult = { error: ServiceError }; type Completion = (args: completionResult | CompletionResult) => void; interface TranslateQuery { text: string; // 需要翻译的文本 from: Language; // 用户选中的源语种标准码 to: Language; // 用户选中的目标语种标准码 detectFrom: Exclude<Language, 'auto'>; // 检测过后的源语种 detectTo: Exclude<Language, 'auto'>; // 检测过后的目标语种 } interface OcrQuery { from: Language; // 目前用户选中的源语言 image: Data; // 需要识别的图片数据 detectFrom: Exclude<Language, 'auto'>; // 图片中最可能的语言,如果插件不具备检测语种的能力,可直接使用该属性。 } interface TTSQuery { text: string; // 需要合成的文本 lang: Exclude<Language, 'auto'>; // 当前文本的语种。 } type Query = TranslateQuery | OcrQuery | TTSQuery; // https://ripperhe.gitee.io/bob/#/plugin/quickstart/info interface Info { identifier: string; // 插件的唯一标识符,必须由数字、小写字母和 . 组成。 category: 'translate' | 'ocr' | 'tts'; // 插件类别,分别对应文本翻译、文本识别和语音合成。 version: string; // 插件版本号,必须由数字、小写字母和 . 组成。 name: string; // 插件名称,无限制,建议别太长。 summary?: string; // 插件描述信息。 icon?: string; // 插件图标标识符,如果插件根目录有 icon.png 文件,则会将其作为插件图标,不会读取该字段;如果没有,会读取该字段,值可以为 这个图标列表 中所包含的任意一个ID。 author?: string; // 插件作者。 homepage?: string; // 插件主页网址。 appcast?: string; // 插件发布信息 URL。 minBobVersion?: string; // 最低支持本插件的 Bob 版本,建议填写您开发插件时候的调试插件的 Bob 版本,目前应该是 0.5.0。 options?: OptionObject[]; } interface MenuObject { title: string; // 菜单选项名称,用于展示。 value: string; // 当前菜单被选中时的值。 } interface OptionObject { identifier: string; // 选项唯一标识符,取值时使用。 type: 'text' | 'menu'; // 选项类型,分别对应输入框和菜单。 title: string; // 选项名称,用于展示。 defaultValue?: string; // 默认值。 menuValues?: MenuObject[]; // type 为 menu 时必须有菜单选项数组,详情见 menu object。 } // https://ripperhe.gitee.io/bob/#/plugin/quickstart/publish interface Appcast { identifier: string; // 插件的唯一标识符,需和插件 info.json 文件中的唯一标识符一致。 versions: Array<VersionObject>; // 版本信息数组,请倒序排列,新版本放前面。具体结构看 version object。 } interface VersionObject { version: string; // 版本号,请与对应插件包 info.json 中的信息一致。 desc: string; // 插件的更新内容。 sha256: string; // 插件包 SHA256 哈希值,会和从 url 中下载的插件包进行校验。 url: string; // 插件包下载地址。 minBobVersion?: string; // 最低支持本插件的 Bob 版本,请与对应插件包 info.json 中的信息一致。 } // https://ripperhe.gitee.io/bob/#/plugin/api/option type Option = { [propName: string]: string; }; // https://ripperhe.gitee.io/bob/#/plugin/api/log interface Log { public static info: (msg: string) => void; // 用于打印一些常规的信息 public static error: (msg: string) => void; // 用于打印错误信息 } // https://ripperhe.gitee.io/bob/#/plugin/api/http interface Http { public static request<T = any, R = HttpResponsePromise<T>>(config: HttpRequestConfig): Promise<R>; public static get<T = any, R = HttpResponsePromise<T>>(config: HttpRequestConfig): Promise<R>; public static post<T = any, R = HttpResponsePromise<T>>(config: HttpRequestConfig): Promise<R>; } type HttpMethod = | 'get' | 'GET' | 'delete' | 'DELETE' | 'head' | 'HEAD' | 'options' | 'OPTIONS' | 'post' | 'POST' | 'put' | 'PUT'; interface HttpRequestConfig { url: string; method?: HttpMethod; header?: any; params?: any; body?: any; files?: HttpRequestFiles; handler?: (resp: HttpResponse) => void; timeout?: number; } interface HttpRequestFiles { data: DataObject; // 二进制数据 name: string; // 上传表单中的名称 filename: string; // 上传之后的文件名 'content-type': string; // 文件格式 } interface HttpResponse<T = any> { data: T; // object / string / $data 解析过后的数据 rawData: DataObject; response: HttpResponseInfo; // 请求响应信息 error: HttpResponseError; } interface HttpResponseInfo { url: string; // url MIMEType: string; // MIME 类型 expectedContentLength: number; // 长度 textEncodingName: string; // 编码 suggestedFilename: string; // 建议的文件名 statusCode: number; // HTTP 状态码 headers: any; // HTTP header } interface HttpResponseError { domain: string; code: number; userInfo: any; localizedDescription: string; // 描述 localizedFailureReason: string; // 原因 localizedRecoverySuggestion: string; // 建议 } type HttpResponsePromise<T = any> = Promise<HttpResponse<T>>; // https://ripperhe.gitee.io/bob/#/plugin/api/file interface File { read(path: string): DataObject; write(object: { data: DataObject; path: string }): boolean; delete(path: string): boolean; list(path: string): string[]; copy(object: { src: string; dst: string }): boolean; move(object: { src: string; dst: string }): boolean; mkdir(path: string): boolean; exists(path: string): boolean; isDirectory(path: string): boolean; } // https://ripperhe.gitee.io/bob/#/plugin/api/data interface Data { public static fromUTF8: (data: string) => DataObject; public static fromHex: (data: string) => DataObject; public static fromBase64: (data: string) => DataObject; public static fromByteArray(data: number[]): DataObject; public static fromData: (data: DataObject) => DataObject; public static isData: (data: any) => boolean; } interface DataObject { length: number; toUTF8(): string | undefine; toHex(useUpper?: boolean): string; toBase64(): string; toByteArray(): number[]; readUInt8(index: number): number; writeUInt8(value: number, index: number): void; subData(start: number, end: number): DataObject; appendData(data: this): this; } // https://ripperhe.gitee.io/bob/#/plugin/object/serviceerror interface ServiceError { type: ServiceErrorType; // 错误类型 message: string; // 错误描述,用于展示给用户看 addtion: string; // 附加信息,可以是任何可 json 序列化的数据类型,用于 debug } enum ServiceErrorEnum { unknown = '未知错误', param = '参数错误', unsupportLanguage = '不支持的语种', secretKey = '缺少秘钥', network = '网络异常,网络请失败', api = '服务接口异常', } type ServiceErrorType = keyof typeof ServiceErrorEnum; // https://ripperhe.gitee.io/bob/#/plugin/object/translateresult interface TranslateResult { from: Language; // 由翻译接口提供的源语种,可以与查询时的 from 不同。 to: Language; // 由翻译接口提供的目标语种,可以与查询时的 to 不同。 toParagraphs: string[]; // 译文分段拆分过后的 string 数组。 fromParagraphs?: string[]; // 原文分段拆分过后的 string 数组。 toDict?: ToDictObject; // 词典结果,见 to dict object。 fromTTS?: TTSResult; // result原文的语音合成数据。 toTTS?: TTSResult; // result译文的语音合成数据。 raw?: any; // 如果插件内部调用了某翻译接口,可将接口原始数据传回,方便定位问题。 } interface ToDictObject { phonetics: Array<PhoneticObject>; // 音标数据数组,一般英文查词会有,见 phonetic object。 parts: Array<PartObject>; // 词性词义数组,一般英文查词会有,见 part object。 exchanges?: Array<ExchangeObject>; // 其他形式数组,一般英文查词会有,见 exchange object。 relatedWordParts?: Array<RelatedWordPartObject>; // 相关的单词数组,一般中文查词会有,表示和该中文对应的英文单词有哪些,见 related word part object。 addtions?: Array<AddtionObject>; // 附加内容数组,考虑到以上字段无法覆盖所有词典内容,比如例句、记忆技巧等,可将相应数据添加到该数组,最终也会显示到翻译结果中,见 addtion object。 } interface PhoneticObject { type: 'us' | 'uk'; // 音标类型,值可以是 us 或 uk,分别对应美式音标和英式音标。 value?: string; // 音标字符串。例如 ɡʊd。 tts?: TTSResult; // result音标发音数据。 } interface PartObject { part: string; // 单词词性,例如 n.、vi.... means: string[]; // 词义 string 数组。 } interface ExchangeObject { name: string; // 形式的名字,例如 比较级、最高级... words: string[]; // 该形式对于的单词 string 数组,一般只有一个 } interface RelatedWordPartObject { part?: string; // 词性。 words: Array<RelatedWordObject>; // 相关的单词数组,见 related word object。 } interface RelatedWordObject { word: string; // 单词本身。 means?: string[]; // 词义 string 数组。 } interface AddtionObject { name: string; // 附加内容名称。 value: string; // 附加内容。 } // https://ripperhe.gitee.io/bob/#/plugin/object/ttsresult interface TTSResult { type: 'url' | 'base64'; // 数据类型,必传。 value: string; // 值,必传。 raw?: any; // 如果插件内部调用了某语音合成接口,可将接口原始数据传回,方便定位问题,可不传。 } // https://ripperhe.gitee.io/bob/#/plugin/object/ocrresult interface OcrResult { from?: Language; // 图片中的文字的主要语种,可与查询参数中传入的 from 不一致,可不传。 texts: Array<OcrText>; // 文本识别结果数组,按照段落分割,见 ocr text,必传。 raw?: any; // 如果插件内部调用了某文本识别接口,可将接口原始数据传回,方便定位问题,可不传。 } interface OcrText { text: string; } type Result = TranslateResult | OcrResult | TTSResult; } declare var $http: Bob.Http; declare var $info: Bob.Info; declare var $option: Bob.Option; declare var $log: Bob.Log; declare var $data: Bob.Data; declare var $file: Bob.File;
the_stack
import { ChangeDetectorRef, Component, ElementRef, EventEmitter, forwardRef, Input, OnChanges, OnInit, Output, Renderer2, SimpleChanges } from '@angular/core'; import { NG_VALUE_ACCESSOR } from '@angular/forms'; import { I18nService } from 'ng-devui/i18n'; import { DatePickerConfigService as DatePickerConfig } from '../date-picker.config.service'; import { SelectDateRangeChangeEventArgs, SelectDateRangeChangeReason } from '../date-range-change-event-args.model'; import { DatepickerComponent as SingleDatepickerComponent } from '../datepicker.component'; import { SimpleDate } from '../single-date-range-picker.component'; @Component({ selector: 'd-two-datepicker-single', templateUrl: '../single-date-range-picker.component.html', styleUrls: ['../single-date-range-picker.component.scss'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TwoDatepickerSingleComponent), multi: true, } ] }) export class TwoDatepickerSingleComponent extends SingleDatepickerComponent implements OnChanges, OnInit { @Input() selectedRange: Date[] = Array(2); @Input() rangePicker = false; @Input() isAuxiliary = false; @Input() currentCalendars = Array(2); @Input() whichOpen: any; @Output() hoverOnDate = new EventEmitter<any>(); @Output() rangeSelected = new EventEmitter<SelectDateRangeChangeEventArgs>(); @Output() rangeSelecting = new EventEmitter<SelectDateRangeChangeEventArgs>(); @Output() syncPickerPair = new EventEmitter<{}>(); @Output() consolidateTime = new EventEmitter<any>(); public rangeStart; public rangeEnd; public previewEnd; protected selectingRange: boolean; constructor( protected elementRef: ElementRef, protected renderer: Renderer2, protected datePickerConfig: DatePickerConfig, protected changeDetectorRef: ChangeDetectorRef, protected i18n: I18nService ) { super(elementRef, renderer, datePickerConfig, changeDetectorRef, i18n); this.setI18nText(); } ngOnInit() { [this.rangeStart, this.rangeEnd] = this.selectedRange; if (!this.isAuxiliary && !this.rangeStart) { // 主面板,未选择开始日期的情况 this.onSelectDateChanged(); this.onDisplayWeeksChange(); this.initDatePicker(); } else if (this.isAuxiliary && !this.rangeEnd) { // 副面板,未选择结束日期的情况 this.onSelectDateChanged(); this.initDatePicker(); this.onNextMonth('init'); this.selectedDate = new Date(this.currentYear, this.currentMonthIndex); } else if (!this.isAuxiliary && this.rangeStart) { // 主面板,已选择开始日期的情况 this.selectedDate = this.rangeStart; super.ngOnInit(); } else if (this.isAuxiliary && this.rangeEnd) { // 副面板,已选择结束日期的情况 const rangeStart = this.convertDate(this.rangeStart); const rangeEnd = this.convertDate(this.rangeEnd); this.currentYear = rangeEnd.getFullYear(); this.currentMonthIndex = rangeEnd.getMonth(); this.selectedDate = this.rangeEnd; super.ngOnInit(); // 处理选择的日期范围开始和结束在同一个月的情况 if (rangeStart && rangeEnd && rangeStart.getFullYear() === rangeEnd.getFullYear() && rangeStart.getMonth() === rangeEnd.getMonth()) { this.onNextMonth('init'); } this.selectedDate = new Date(this.currentYear, this.currentMonthIndex); } if (!this.selectedRange.every(curDate => !!curDate)) { this.selectingRange = true; } this.availableMonths = this.onDisplayMonthsChange(); this.notifyCalenderChange(); } /* ** @param invocation:调用时机 */ onSelectDate($event, date, invocation?: any) { if ($event.stopPropagation) { $event.stopPropagation(); } if (invocation !== 'init') { if (this.isDisabledDay(date)) { $event.preventDefault(); return; } this.selectRange(date); } } emitHoverDate($event, date) { if (this.selectingRange && date.getTime() <= this.maxDate.getTime() && date.getTime() >= this.minDate.getTime()) { this.hoverOnDate.emit(date); } } selectSingle(date) { if (date) { const ensureRange = this.ensureRangeValueOrder([this.rangeStart, this.rangeEnd]); this.rangeChange(ensureRange); } } convertDate(date) { return date ? this.dateConverter.parse(date) : null; } selectRange(date, passive = false) { if (this.whichOpen === 'start') { if (!this.rangeEnd) { this.rangeEnd = null; this.selectingRange = true; } else { this.selectingRange = false; } if (!passive) { this.rangeStart = this.convertDate(date); this.selectSingle(date); this.rangeSelecting.emit(this.rangeStart); } } else if (this.whichOpen === 'end') { if (this.rangeStart && this.rangeEnd || (!this.rangeStart && !this.rangeEnd)) { this.selectingRange = false; } else { this.selectingRange = true; if (!this.rangeStart) { this.rangeStart = null; } if (!this.rangeEnd) { this.rangeEnd = null; } } if (!passive) { this.rangeEnd = this.convertDate(date); this.selectSingle(date); this.rangeSelecting.emit(this.rangeEnd); } } } rangeChange(range) { [this.rangeStart, this.rangeEnd] = this.selectedRange = range; this.notifyValueChange(range); } writeValue(selectedRange: any): void { this.selectedRange = selectedRange; } protected notifyValueChange(selectedRange: Date[]) { this.onChange(selectedRange); this.rangeSelected.emit({ reason: SelectDateRangeChangeReason.date, selectedRange: selectedRange }); } isSelectDay(date) { let rangeSource = this.selectedRange; if (this.selectingRange) { rangeSource = [this.rangeStart || this.rangeEnd, this.previewEnd]; } if ((!Array.isArray(rangeSource))) { return; } return rangeSource.some((selectedDate) => { if (!selectedDate || !date) { return false; } return ( date.getFullYear() === selectedDate.getFullYear() && date.getMonth() === selectedDate.getMonth() && date.getDate() === selectedDate.getDate() ); }); } isBetweenDay(date) { if (Array.isArray(this.selectedRange) && this.selectedRange.every(day => !!day)) { const index = this.selectedRange.findIndex(day => { return date.getFullYear() === day.getFullYear() && date.getMonth() === day.getMonth() && date.getDate() === day.getDate(); }); return ['devui-day-start', 'devui-day-end'][index]; } else { return; } } ngOnChanges(changes: SimpleChanges) { if (changes.hasOwnProperty('selectedRange')) { [this.rangeStart, this.rangeEnd] = changes['selectedRange'].currentValue; if (this.rangeStart && this.rangeEnd) { this.selectingRange = false; } } } isInRange(date) { let rangeStart = this.rangeStart; let rangeEnd = this.rangeEnd; if (this.selectingRange) { if (rangeEnd) { rangeStart = this.previewEnd; } else if (rangeStart) { rangeEnd = this.previewEnd; } } date = (new Date(date)).getTime(); return date < Math.max((new Date(rangeStart)).getTime(), (new Date(rangeEnd)).getTime()) && date > Math.min((new Date(rangeStart)).getTime(), (new Date(rangeEnd)).getTime()); } ensureRangeValueOrder(dateRange) { if (Array.isArray(dateRange) && dateRange.length === 2 && dateRange.every(curDate => !!curDate)) { if (dateRange[0].getTime() > dateRange[1].getTime()) { if (this.whichOpen === 'start') { return [dateRange[0], null]; } else { return [null, dateRange[1]]; } } } return dateRange; } onNextMonth(invocation?: any) { if (this.hasNextMonth() || invocation === 'init') { let maxDateInRange; if (invocation === 'init') { maxDateInRange = this.selectedRange.reduce((start, end) => new Date(end) > new Date(start) ? end : start); } super.onNextMonth(maxDateInRange, 'init'); this.notifyCalenderChange(); } } hasNextMonth() { let hasNextMonth = true; // 副面板只用考虑maxDate的影响 // 主面板同时考虑maxDate和日历的影响 // minDate的影响在super.hasNextMonth()中有计算 if (!this.isAuxiliary && this.currentCalendars[0] && this.currentCalendars[1]) { hasNextMonth = this.isBeforeMoreThanOneMonth(this.currentCalendars[0], this.currentCalendars[1]); } return hasNextMonth && super.hasNextMonth(); } onPreMonth() { if (this.hasPreMonth()) { super.onPreMonth(); this.notifyCalenderChange(); } } hasPreMonth() { let hasPrevMonth = true; // 主面板只用考虑minDate的影响 // 副面板同时考虑minDate和日历的影响 // minDate的影响在super.hasPreMonth()中有计算 if (this.isAuxiliary && this.currentCalendars[0] && this.currentCalendars[1]) { hasPrevMonth = this.isAfterMoreThanOneMonth(this.currentCalendars[1], this.currentCalendars[0]); } return hasPrevMonth && super.hasPreMonth(); } hasPreYearOption() { let hasPrevYear = true; if (this.openChooseYear) { if (!this.isAuxiliary) { hasPrevYear = this.nowMinYear > this.minDate.getFullYear(); } else { hasPrevYear = this.nowMinYear > this.minDate.getFullYear() && this.isBeforeMoreThanOneYear(this.currentCalendars[0], {year: this.nowMinYear, month: this.currentCalendars[1].month}); } } else if (this.currentCalendars[0] && this.currentCalendars[1]) { // 主面板只用考虑minDate的影响 if (!this.isAuxiliary) { hasPrevYear = this.currentCalendars[0].year > this.minDate.getFullYear(); } else { // 副面板同时考虑minDate和日历的影响 hasPrevYear = this.currentCalendars[1].year > this.minDate.getFullYear() && this.isBeforeMoreThanOneYear(this.currentCalendars[0], this.currentCalendars[1]); } } return hasPrevYear; } hasNextYearOption() { let hasNextYear = true; if (this.openChooseYear) { if (this.isAuxiliary) { hasNextYear = this.nowMaxYear < this.maxDate.getFullYear(); } else { hasNextYear = this.nowMaxYear < this.maxDate.getFullYear() && this.isAfterMoreThanOneYear(this.currentCalendars[1], {year: this.nowMaxYear, month: this.currentCalendars[0].month}); } } else if (this.currentCalendars[0] && this.currentCalendars[1]) { // 副面板只用考虑maxDate的影响 if (this.isAuxiliary) { hasNextYear = this.currentCalendars[1].year < this.maxDate.getFullYear(); } else { // 主面板同时考虑maxDate和日历的影响 hasNextYear = this.currentCalendars[0].year < this.maxDate.getFullYear() && this.isAfterMoreThanOneYear(this.currentCalendars[1], this.currentCalendars[0]); } } return hasNextYear; } onPreYear() { if (!this.hasPreYearOption()) { return; } if (this.openChooseYear) { if (this.nowMinYear - this._yearNumber >= this.minDate.getFullYear()) { this.nowMaxYear = this.nowMinYear - 1; this.nowMinYear = this.nowMinYear - this._yearNumber; } else { this.nowMaxYear = this.nowMinYear - 1; this.nowMinYear = this.minDate.getFullYear(); } this.onYearRangeChange(); } else { this.onSelectYear(Number(this.currentYear) - 1); } this.notifyCalenderChange(); } onNextYear() { if (!this.hasNextYearOption()) { return; } if (this.openChooseYear) { if (this.nowMaxYear + this._yearNumber <= this.maxDate.getFullYear()) { this.nowMinYear = this.nowMaxYear + 1; this.nowMaxYear = this.nowMaxYear + this._yearNumber; } else { this.nowMinYear = this.nowMaxYear + 1; this.nowMaxYear = this.maxDate.getFullYear(); } this.onYearRangeChange(); } else { this.onSelectYear(Number(this.currentYear) + 1); } this.notifyCalenderChange(); } isBeforeMoreThanOneMonth(dateA: SimpleDate, dateB: SimpleDate) { if (dateA.year > dateB.year) { return false; } if (dateA.year === dateB.year && dateB.month <= dateA.month + 1) { return false; } // 处理A日期为B日期前一年12月同时B日期为1月的特殊情况 return !(dateB.year - dateA.year === 1 && dateA.month === 11 && dateB.month === 0); } isAfterMoreThanOneMonth(dateA: SimpleDate, dateB: SimpleDate) { if (dateA.year < dateB.year) { return false; } if (dateA.year === dateB.year && dateB.month + 1 >= dateA.month) { return false; } // 处理A日期为B日期后一年1月同时B日期为12月的特殊情况 return !(dateA.year - dateB.year === 1 && dateA.month === 0 && dateB.month === 11); } isBeforeMoreThanOneYear(dateA: SimpleDate, dateB: SimpleDate) { if (dateA.year >= dateB.year) { return false; } // 处理B日期比A日期大1年同时A日期月份大于B日期月份的情况 return !(dateB.year - dateA.year === 1 && dateA.month >= dateB.month); } isAfterMoreThanOneYear(dateA: SimpleDate, dateB: SimpleDate) { if (dateA.year <= dateB.year) { return false; } // 处理A日期比B日期大1年同时A日期月份小于B日期月份的情况 return (!(dateA.year - dateB.year === 1 && dateA.month <= dateB.month)); } isYearDisable(year: number): boolean { if (this.isAuxiliary) { // 先判定主面板是否比附面板小一年以上,是的话disabled为false; return !(this.isBeforeMoreThanOneYear(this.currentCalendars[0], { year: year + 1, month: this.currentCalendars[1].month}) || // 主附面板在同一年时,判断主附面板月是否在临界值; (this.currentCalendars[0].year === year && this.currentCalendars[0].month !== 11)); } else { return !(this.isAfterMoreThanOneYear(this.currentCalendars[1], {year: year - 1, month: this.currentCalendars[0].month}) || (this.currentCalendars[1].year === year && this.currentCalendars[1].month !== 0)); } } isMonthDisable(month: string): boolean { if (this.isAuxiliary) { return !this.isBeforeMoreThanOneMonth( this.currentCalendars[0], {year: this.currentCalendars[1].year, month: parseInt(month, 10) - 1 + 1} ); } else { return !this.isAfterMoreThanOneMonth( this.currentCalendars[1], {year: this.currentCalendars[0].year, month: parseInt(month, 10) - 1 - 1} ); } } onSelectMonth(month) { if (month.disabled || this.isMonthDisable(month.title)) { return; } this.currentMonthIndex = month.index; this.onDisplayWeeksChange(); this.openChooseMonth = false; this.isAuxiliary ? this.currentCalendars[1].month = this.currentMonthIndex : this.currentCalendars[0].month = this.currentMonthIndex; } onSelectYear(year, $event?: Event) { if ($event) { $event.stopPropagation(); } const yearDisabled = typeof year === 'object' ? year.disabled : false; const yearTitle = typeof year === 'object' ? year.title : year; if (yearDisabled || this.isYearDisable(year.title)) { return; } this.currentYear = yearTitle; this.onDisplayWeeksChange(); this.availableMonths = this.onDisplayMonthsChange(); this.openChooseYear = false; if (!$event) { this.isAuxiliary ? this.currentCalendars[1].year = this.currentYear : this.currentCalendars[0].year = this.currentYear; return; } this.openChooseMonth = true; if (this.isAuxiliary) { this.currentCalendars[1].year = this.currentYear; this.currentCalendars[1].month = 11; this.currentMonthIndex = 11; } else { this.currentCalendars[0].year = this.currentYear; this.currentCalendars[0].month = 0; this.currentMonthIndex = 0; } } protected notifyCalenderChange() { this.syncPickerPair.emit({ year: this.currentYear, month: this.currentMonthIndex }); } confirmTime() { this.consolidateTime.emit(); } protected onSelectDateChanged() { let date = this.selectedDate || new Date(); if (date.getTime() < this.minDate.getTime()) { date = this.minDate; } if (date.getTime() > this.maxDate.getTime()) { date = this.maxDate; } if (!this.isAuxiliary && this.rangeEnd && !this.rangeStart) { date = new Date(this.rangeEnd); date.setMonth(date.getMonth() - 1); } this.selectedDate = this.selectedDate || date; this.currentYear = date.getFullYear(); this.currentMonthIndex = date.getMonth(); } }
the_stack
import * as THREE from 'three' import * as v3 from 'v3js' import * as nodesVS from './shaders/nodes.vs' import * as nodesFS from './shaders/nodes.fs' import * as linesFS from './shaders/lines.fs' import * as linesVS from './shaders/lines.vs' import * as arrowsVS from './shaders/arrows.vs' import * as arrowsFS from './shaders/arrows.fs' import * as imageVS from './shaders/image.vs' import * as imageFS from './shaders/image.fs' import * as hlNodesVS from './shaders/hlNodes.vs' import * as hlNodesFS from './shaders/hlNodes.fs' import * as hlLinesVS from './shaders/hlLines.vs' import * as hlLinesFS from './shaders/hlLines.fs' import * as hlArrowsVS from './shaders/hlArrows.vs' import * as hlArrowsFS from './shaders/hlArrows.fs' import * as worker from './worker.js' import * as arrowPNG from '../assets/arrow.png' import * as nodePNG from '../assets/node.png' import mitt from 'mitt' import './index.css' window.THREE = THREE require('three/examples/js/controls/MapControls.js') type RGB = [number, number, number] interface GraphData { nodes: Array<{ id: string name?: string, scale?: number, image?: string }>, links: Array<{ source: string, target: string, color?: RGB }> } interface GraphBaseConfig { width: number, height: number, nodeSize?: number, arrowSize?: number, lineWidth?: number, showArrow?: boolean, backgroundColor?: RGB, highLightColor?: RGB, showStatTable?: boolean, roundedImage?: boolean, zoomNear?: number, zoomFar?: number, debug?: boolean } interface D3ForceData { nodes: Array<{ id: string }>, links: Array<D3Link> } interface D3Link { source: string, target: string } interface ProcessedData extends D3ForceData { nodeInfoMap: { [key: string]: { index: number, scale?: number, image?: string, name?: string, imageTexture?: THREE.Texture, imagePoint?: ShaderMesh } }, linkInfoMap: { [key: string]: { color?: RGB } }, linkBuffer: Int32Array, statTable: Array<{ source: string, count: number }> } interface Mesh { geometry: THREE.BufferGeometry, material: THREE.Material, mesh: THREE.Mesh | THREE.Points | THREE.LineSegments } interface ShaderMesh extends Mesh { material: THREE.ShaderMaterial, positions: Float32Array, scale?: Float32Array, rotates?: Float32Array, colors?: Float32Array } interface GraphPerfInfo { nodeCounts: number, linkCounts: number, layoutPastTime: number, layoutProgress: string, layoutStartTime: number, prevTickTime: number, targetTick: number, intervalTime: number, layouting: boolean } interface MouseStatus { mouseOnChart: boolean, mousePosition: THREE.Vector2 } interface ViewportRect { left: number, right: number, top: number, bottom: number } interface VisibleNode { id: string, x: number, y: number } const GRAPH_BASE_CONFIG: GraphBaseConfig = { width: 400, height: 400, nodeSize: 3000, arrowSize: 1250, lineWidth: 1, showArrow: true, backgroundColor: [0, 0, 16], highLightColor: [255, 0, 0], showStatTable: true, roundedImage: true, zoomNear: 75, zoomFar: 16000, debug: false } const GRAPH_DEFAULT_PERF_INFO: GraphPerfInfo = { nodeCounts: 0, linkCounts: 0, layoutPastTime: 0, layoutProgress: '', layoutStartTime: 0, prevTickTime: 0, targetTick: 0, intervalTime: 0, layouting: false } const textureLoader: THREE.TextureLoader = new THREE.TextureLoader() const ARROW_TEXTURE = textureLoader.load(arrowPNG) const NODE_TEXTURE = textureLoader.load(nodePNG) const BASE_HEIGHT = 500 export class D3ForceGraph { $container: HTMLElement containerRect: ClientRect data: GraphData config: GraphBaseConfig perfInfo: GraphPerfInfo processedData: ProcessedData worker: Worker targetPositionStatus: Float32Array currentPositionStatus: Float32Array cachePositionStatus: Float32Array mouseStatus: MouseStatus = { mouseOnChart: false, mousePosition: new THREE.Vector2(-9999, -9999) } rafId: number highlighted: string throttleTimer: number events: mitt.Emitter lockHighlightToken: false scene: THREE.Scene renderer: THREE.WebGLRenderer camera: THREE.PerspectiveCamera controls: any nodes: ShaderMesh = { geometry: null, positions: null, scale: null, material: null, mesh: null } lines: ShaderMesh = { geometry: null, positions: null, colors: null, material: null, mesh: null } arrows: ShaderMesh = { geometry: null, positions: null, rotates: null, material: null, mesh: null } hlLines: ShaderMesh = { geometry: null, positions: null, material: null, mesh: null } hlNodes: ShaderMesh = { geometry: null, positions: null, scale: null, material: null, mesh: null } hlArrows: ShaderMesh = { geometry: null, positions: null, rotates: null, material: null, mesh: null } hlText: Mesh = { geometry: null, material: null, mesh: null } constructor(dom: HTMLElement, data: GraphData, graphBaseConfig: GraphBaseConfig = GRAPH_BASE_CONFIG) { this.$container = dom this.data = data this.config = Object.assign({}, GRAPH_BASE_CONFIG, graphBaseConfig) this.perfInfo = GRAPH_DEFAULT_PERF_INFO this.events = new mitt() this.init() } init() { try { this.processedData = this.preProcessData() this.perfInfo.nodeCounts = this.processedData.nodes.length this.perfInfo.linkCounts = this.processedData.links.length this.prepareScene() this.prepareBasicMesh() this.installControls() this.bindEvent() this.initWorker() this.start() }catch(e) { console.log(e) } } /** * preProcessData * preprocess data * * @returns {ProcessedData} * @memberof D3ForceGraph */ preProcessData(): ProcessedData { let result: ProcessedData = { nodes: [], links: [], nodeInfoMap: {}, linkInfoMap: {}, statTable: [], linkBuffer: null } let nodeCount = 0 this.data.nodes.forEach(e => { if(!result.nodeInfoMap[e.id]) { result.nodes.push({ id: e.id }) result.nodeInfoMap[e.id] = { index: nodeCount, scale: e.scale, image: e.image, name: e.name } nodeCount++ } }) let linkCountMap: { [key: string]: number } = {} let linkBuffer: Array<number> = [] this.data.links.forEach(e => { let linkInfoKey = `${e.source}-${e.target}` if(!result.linkInfoMap[linkInfoKey]) { result.links.push({ source: e.source, target: e.target }) linkBuffer.push(result.nodeInfoMap[e.source].index, result.nodeInfoMap[e.target].index) result.linkInfoMap[linkInfoKey] = { color: e.color && e.color.map(e => e / 255) as RGB } linkCountMap[e.source] = (linkCountMap[e.source] || 0) + 1 } }) result.linkBuffer = new Int32Array(linkBuffer) result.statTable = Object.keys(linkCountMap).map(e => { return { source: e, count: linkCountMap[e] } }).sort((a, b) => { return b.count - a.count }) if(result.statTable.length > 20) { result.statTable.length = 20 } return result } prepareScene(): void { this.scene = new THREE.Scene() this.scene.background = new THREE.Color(this.config.backgroundColor[0] / 255, this.config.backgroundColor[1] / 255, this.config.backgroundColor[2] / 255) this.renderer = new THREE.WebGLRenderer({ antialias: true, logarithmicDepthBuffer: true }) this.renderer.setSize(this.config.width, this.config.height) this.renderer.setPixelRatio(window.devicePixelRatio) this.$container.appendChild(this.renderer.domElement) this.camera = new THREE.PerspectiveCamera(45, this.config.width / this.config.height, 40, 18000) this.camera.position.set(0, 0, this.getPositionZ(this.processedData.nodes.length)) this.camera.up = new THREE.Vector3(0, 0, 1) this.camera.updateProjectionMatrix() this.renderer.render(this.scene, this.camera) this.containerRect = this.$container.getBoundingClientRect() this.$container.classList.add('d3-force-graph-container') } prepareBasicMesh(): void { // 预准备节点与线,使用BufferGeometry,位置先定到-9999 // z 关系 // 高亮节点:0.0001 // 头像:0.00005 // 节点: 0 // 高亮箭头:-0.0004 // 箭头:-0.0007 // 高亮线:-0.0009 // 线:-0.001 this.perfInfo.layoutStartTime = Date.now() this.nodes.geometry = new THREE.BufferGeometry() this.nodes.positions = new Float32Array(this.perfInfo.nodeCounts * 3) this.nodes.scale = new Float32Array(this.perfInfo.nodeCounts) this.nodes.material = new THREE.ShaderMaterial({ uniforms: { texture: { type: 't', value: NODE_TEXTURE }, 'u_compensation': { value: window.devicePixelRatio * this.config.height / BASE_HEIGHT } }, vertexShader: nodesVS({ nodeSize: this.config.nodeSize.toFixed(8) }), fragmentShader: nodesFS() }) this.nodes.material.extensions.derivatives = true this.processedData.nodes.forEach((e, i) => { this.nodes.positions[i * 3] = -9999 this.nodes.positions[i * 3 + 1] = -9999 this.nodes.positions[i * 3 + 2] = 0 this.nodes.scale[i] = this.processedData.nodeInfoMap[e.id].scale || 1 }) this.nodes.geometry.addAttribute('position', new THREE.BufferAttribute(this.nodes.positions, 3)) this.nodes.geometry.addAttribute('scale', new THREE.BufferAttribute(this.nodes.scale, 1)) this.nodes.geometry.computeBoundingSphere() this.nodes.mesh = new THREE.Points(this.nodes.geometry, this.nodes.material) this.nodes.mesh.name = 'basePoints' this.scene.add(this.nodes.mesh) this.lines.geometry = new THREE.BufferGeometry() this.lines.positions = new Float32Array(this.perfInfo.linkCounts * 6) this.lines.colors = new Float32Array(this.perfInfo.linkCounts * 6) this.lines.material = new THREE.ShaderMaterial({ transparent: true, opacity: 0.6, vertexShader: linesVS(), fragmentShader: linesFS() }) this.processedData.links.forEach((e, i) => { this.lines.positions[i * 6] = -9999 this.lines.positions[i * 6 + 1] = -9999 this.lines.positions[i * 6 + 2] = -0.001 this.lines.positions[i * 6 + 3] = -9999 this.lines.positions[i * 6 + 4] = -9999 this.lines.positions[i * 6 + 5] = -0.001 if(this.processedData.linkInfoMap[`${e.source}-${e.target}`].color) { this.lines.colors[i * 6] = this.processedData.linkInfoMap[`${e.source}-${e.target}`].color[0] this.lines.colors[i * 6 + 1] = this.processedData.linkInfoMap[`${e.source}-${e.target}`].color[1] this.lines.colors[i * 6 + 2] = this.processedData.linkInfoMap[`${e.source}-${e.target}`].color[2] this.lines.colors[i * 6 + 3] = this.processedData.linkInfoMap[`${e.source}-${e.target}`].color[0] this.lines.colors[i * 6 + 4] = this.processedData.linkInfoMap[`${e.source}-${e.target}`].color[1] this.lines.colors[i * 6 + 5] = this.processedData.linkInfoMap[`${e.source}-${e.target}`].color[2] }else { this.lines.colors[i * 6] = 1 this.lines.colors[i * 6 + 1] = 1 this.lines.colors[i * 6 + 2] = 1 this.lines.colors[i * 6 + 3] = 1 this.lines.colors[i * 6 + 4] = 1 this.lines.colors[i * 6 + 5] = 1 } }) this.lines.geometry.addAttribute('position', new THREE.BufferAttribute(this.lines.positions, 3)) this.lines.geometry.addAttribute('color', new THREE.BufferAttribute(this.lines.colors, 3)) this.lines.geometry.computeBoundingSphere() this.lines.mesh = new THREE.LineSegments(this.lines.geometry, this.lines.material) this.lines.mesh.name = 'baseLines' this.scene.add(this.lines.mesh) } initWorker(): void { let blob = new Blob([worker], { type: 'text/javascript' }) this.worker = new Worker(window.URL.createObjectURL(blob)) } start(): void { let message = { type: 'start', nodes: this.perfInfo.nodeCounts, DISTANCE: this.getDistance(this.perfInfo.nodeCounts), STRENGTH: this.getStrength(this.perfInfo.nodeCounts), COL: this.getCol(this.perfInfo.nodeCounts), linksBuffer: this.processedData.linkBuffer.buffer } this.worker.postMessage(message, [message.linksBuffer]) this.worker.onmessage = (event) => { switch (event.data.type) { case('tick'): { // 每次 tick 时,记录该次 tick 时间和与上次 tick 的时间差,用于补间动画 let now = Date.now() this.perfInfo.layouting = true this.perfInfo.layoutProgress = (event.data.progress * 100).toFixed(2) this.perfInfo.layoutPastTime = now - this.perfInfo.layoutStartTime this.perfInfo.intervalTime = now - (this.perfInfo.prevTickTime || now) this.perfInfo.prevTickTime = now if(event.data.currentTick === 1) { // 第一帧不画,只记录 this.targetPositionStatus = new Float32Array(event.data.nodes) }else { // 第二帧开始画第一帧,同时启动补间 if(event.data.currentTick === 2) { this.currentPositionStatus = this.targetPositionStatus this.startRender() } this.targetPositionStatus = new Float32Array(event.data.nodes) // 缓存当前 this.currentPositionStatus if(this.currentPositionStatus) { let len = this.currentPositionStatus.length if(!this.cachePositionStatus) { this.cachePositionStatus = new Float32Array(len) } for(let i = 0; i < len; i++) { this.cachePositionStatus[i] = this.currentPositionStatus[i] } } this.perfInfo.targetTick = event.data.currentTick } this.events.emit('tick', { layoutProgress: this.perfInfo.layoutProgress }) break } case('end'): { this.targetPositionStatus = new Float32Array(event.data.nodes) this.$container.addEventListener('mousemove', this.mouseMoveHandlerBinded, false) this.$container.addEventListener('mouseout', this.mouseOutHandlerBinded, false) // 布局结束后,如果鼠标不在图像区域,就停止渲染(节能) setTimeout(() => { this.perfInfo.layouting = false if(this.config.showArrow) { this.renderArrow() } this.events.emit('end') setTimeout(() => { if(!this.mouseStatus.mouseOnChart) { this.stopRender() } }, 2000) }, 2000) break } } } } installControls(): void { this.controls = new (THREE as any).MapControls(this.camera, this.renderer.domElement) this.controls.enableDamping = true this.controls.dampingFactor = 0.25 this.controls.screenSpacePanning = false this.controls.maxPolarAngle = Math.PI / 2 } // 启动渲染 startRender(): void { if(!this.rafId) { this.rafId = requestAnimationFrame(this.render.bind(this)) } } // 停止渲染,节约性能 stopRender(): void { if(this.rafId) { cancelAnimationFrame(this.rafId) this.rafId = null } } render(): void { this.rafId = null // 限制放大缩小距离,最近75,最远16000 if(this.camera.position.z < this.config.zoomNear) { this.camera.position.set(this.camera.position.x, this.camera.position.y, this.config.zoomNear) } if(this.camera.position.z > this.config.zoomFar) { this.camera.position.set(this.camera.position.x, this.camera.position.y, this.config.zoomFar) } // 节点数大于1000时,执行补间动画 if(this.perfInfo.nodeCounts > 1000) { let now = Date.now() let stepTime = now - this.perfInfo.prevTickTime if(stepTime <= this.perfInfo.intervalTime) { for(let i = 0; i < this.currentPositionStatus.length; i++) { this.currentPositionStatus[i] = (this.targetPositionStatus[i] - this.cachePositionStatus[i]) / this.perfInfo.intervalTime * stepTime + this.cachePositionStatus[i] } this.updatePosition(this.currentPositionStatus) } }else { if(this.currentPositionStatus && this.currentPositionStatus[0] !== this.targetPositionStatus[0]) { this.currentPositionStatus = this.targetPositionStatus this.updatePosition(this.currentPositionStatus) } } this.checkFinalStatus() this.updateHighLight() if(!this.perfInfo.layouting && this.camera.position.z < 300) { // todo 智能卸载 this.loadImage() } this.renderer.render(this.scene, this.camera) this.controls && this.controls.update() this.startRender() } checkFinalStatus() { if(!this.perfInfo.layouting && this.currentPositionStatus && (this.currentPositionStatus[0] !== this.targetPositionStatus[0])){ this.currentPositionStatus = this.targetPositionStatus this.updatePosition(this.currentPositionStatus) } } renderArrow(): void { this.arrows.geometry = new THREE.BufferGeometry() this.arrows.positions = new Float32Array(this.perfInfo.linkCounts * 3) this.arrows.rotates = new Float32Array(this.perfInfo.linkCounts) this.arrows.material = new THREE.ShaderMaterial({ transparent: true, uniforms: { texture: { type: 't', value: ARROW_TEXTURE }, 'u_compensation': { value: window.devicePixelRatio * this.config.height / BASE_HEIGHT } }, vertexShader: arrowsVS({ arrowSize: this.config.arrowSize.toFixed(8) }), fragmentShader: arrowsFS() }) let vec: v3.Vector3 = new v3.Vector3(0, 1, 0) let up: v3.Vector3 = new v3.Vector3(0, 1, 0) let offsetDistance = (this.config.arrowSize + this.config.nodeSize) / 1125 this.processedData.links.forEach((e, i) => { // 计算箭头的旋转方向与偏移位置 let vecX = this.currentPositionStatus[this.processedData.nodeInfoMap[e.target].index * 2] - this.currentPositionStatus[this.processedData.nodeInfoMap[e.source].index * 2] let vecY = this.currentPositionStatus[this.processedData.nodeInfoMap[e.target].index * 2 + 1] - this.currentPositionStatus[this.processedData.nodeInfoMap[e.source].index * 2 + 1] vec.x = vecX vec.y = vecY let angle = v3.Vector3.getAngle(vec, up) let vecNorm = v3.Vector3.getNorm(vec) let offsetX = vecX * offsetDistance / vecNorm let offsetY = vecY * offsetDistance / vecNorm if(vecX < 0) { angle = 2 * Math.PI - angle } this.arrows.rotates[i] = angle this.arrows.positions[i * 3] = this.currentPositionStatus[this.processedData.nodeInfoMap[e.target].index * 2] - offsetX this.arrows.positions[i * 3 + 1] = this.currentPositionStatus[this.processedData.nodeInfoMap[e.target].index * 2 + 1] - offsetY this.arrows.positions[i * 3 + 2] = -0.0007 }) this.arrows.geometry.addAttribute('position', new THREE.BufferAttribute(this.arrows.positions, 3)) this.arrows.geometry.addAttribute('rotate', new THREE.BufferAttribute(this.arrows.rotates, 1)) this.arrows.geometry.computeBoundingSphere() this.arrows.mesh = new THREE.Points(this.arrows.geometry, this.arrows.material) this.arrows.mesh.name = 'arrows' this.scene.add(this.arrows.mesh) } // 更新节点与线的位置 updatePosition(nodesPosition: Float32Array): void { for(let i = 0; i < this.perfInfo.nodeCounts; i++) { this.nodes.positions[i * 3] = nodesPosition[i * 2] this.nodes.positions[i * 3 + 1] = nodesPosition[i * 2 + 1] } this.nodes.geometry.attributes.position = new THREE.BufferAttribute(this.nodes.positions, 3) this.nodes.geometry.attributes.position.needsUpdate = true this.nodes.geometry.computeBoundingSphere() for(let i = 0; i < this.perfInfo.linkCounts; i++) { this.lines.positions[i * 6] = nodesPosition[this.processedData.nodeInfoMap[this.processedData.links[i].source].index * 2] this.lines.positions[i * 6 + 1] = nodesPosition[this.processedData.nodeInfoMap[this.processedData.links[i].source].index * 2 + 1] this.lines.positions[i * 6 + 3] = nodesPosition[this.processedData.nodeInfoMap[this.processedData.links[i].target].index * 2] this.lines.positions[i * 6 + 4] = nodesPosition[this.processedData.nodeInfoMap[this.processedData.links[i].target].index * 2 + 1] } this.lines.geometry.attributes.position = new THREE.BufferAttribute(this.lines.positions, 3) this.lines.geometry.attributes.position.needsUpdate = true this.lines.geometry.computeBoundingSphere() } // 响应鼠标在图表上移动时的交互,指到某个节点上进行高亮 updateHighLight(): void { let normalMouse = new THREE.Vector2() normalMouse.x = this.mouseStatus.mousePosition.x * 2 / this.config.width normalMouse.y = this.mouseStatus.mousePosition.y * 2 / this.config.height let ray = new THREE.Raycaster() ray.setFromCamera(normalMouse, this.camera) ray.params.Points.threshold = 2 let intersects = ray.intersectObjects(this.scene.children).filter(e => e.object.type === 'Points' && !e.object.name.startsWith('hl')) if(intersects.length > 0) { let target = intersects[0] let id if(target.object && target.object.name === 'basePoints') { id = this.processedData.nodes[target.index].id }else if(target.object && target.object.name.startsWith('ava-')) { id = (target.object as any).nodeId } if(id) { this.highlight(id) } }else { if(!this.lockHighlightToken) { this.unhighlight() } } } loadImage(): void { // 节流 if(!this.throttleTimer) { this.throttleTimer = window.setTimeout(() => { if(!this.camera || this.camera.position.z > 300) { clearTimeout(this.throttleTimer) this.throttleTimer = null return } let nodes = this.getAllVisibleNodes() let nullc = 0 let havec = 0 for(let i = 0, len = nodes.length; i < len; i++) { let id = nodes[i].id let x = this.currentPositionStatus[this.processedData.nodeInfoMap[id].index * 2] let y = this.currentPositionStatus[this.processedData.nodeInfoMap[id].index * 2 + 1] let info = this.processedData.nodeInfoMap[id] if(!info.imageTexture) { if(info.image){ havec++ textureLoader.load(info.image, (texture) => { info.imageTexture = texture info.imageTexture.needsUpdate = true this.generateAvaPoint(info, id, x, y) }, undefined, () => { info.image = null }) }else { nullc++ } }else { this.generateAvaPoint(info, id, x, y) } } this.config.debug && console.log(`同屏节点${nodes.length}个,游客${nullc}个,自定义头像${havec}个`) clearTimeout(this.throttleTimer) this.throttleTimer = null }, 1000) } } generateAvaPoint(info: ProcessedData['nodeInfoMap']['key'], id: string, x: number, y: number): void { if(!info.imagePoint) { info.imagePoint = { geometry: null, material: null, positions: new Float32Array([x, y, 0.00005]), mesh: null } info.imagePoint.geometry = new THREE.BufferGeometry() info.imagePoint.material = new THREE.ShaderMaterial({ uniforms: { texture: { type: 't', value: info.imageTexture }, 'u_compensation': { value: window.devicePixelRatio * this.config.height / BASE_HEIGHT }, scale: { value: info.scale || 1 } }, vertexShader: imageVS({ nodeSize: (this.config.nodeSize.toFixed(8)) }), fragmentShader: imageFS() }) info.imagePoint.material.extensions.derivatives = true info.imagePoint.geometry.addAttribute('position', new THREE.BufferAttribute(info.imagePoint.positions, 3)) info.imagePoint.geometry.computeBoundingSphere() info.imagePoint.mesh = new THREE.Points(info.imagePoint.geometry, info.imagePoint.material) info.imagePoint.mesh.name = `ava-${id}` ;(info.imagePoint.mesh as any).nodeId = id } if(!this.scene.getObjectByName(`ava-${id}`)) { this.scene.add(info.imagePoint.mesh) this.config.debug && console.log('loadImage:', id) } } // 获取当前 viewport 下所以可视的节点 getAllVisibleNodes(): Array<VisibleNode> { let viewportRect = this.getViewPortRect() let result = [] for(let i = 0, len = this.perfInfo.nodeCounts; i < len; i++) { if(this.targetPositionStatus[i * 2] >= viewportRect.left && this.targetPositionStatus[i * 2] <= viewportRect.right && this.targetPositionStatus[i * 2 + 1] >= viewportRect.bottom && this.targetPositionStatus[i * 2 + 1] <= viewportRect.top) { result.push({ id: this.processedData.nodes[i].id, x: this.targetPositionStatus[i * 2], y: this.targetPositionStatus[i * 2 + 1] }) } } return result } // 根据透视投影模型,计算当前可视区域 getViewPortRect(): ViewportRect { let offsetY = this.camera.position.z * Math.tan(Math.PI / 180 * 22.5) let offsetX = offsetY * this.camera.aspect return { left: this.camera.position.x - offsetX, right: this.camera.position.x + offsetX, top: this.camera.position.y + offsetY, bottom: this.camera.position.y - offsetY } } highlight(id: string): void { if(this.highlighted !== id) { this.unhighlight() this.addHighLight(id) this.highlighted = id } } unhighlight(): void { let node = this.scene.getObjectByName('hlNodes') let line = this.scene.getObjectByName('hlLines') let text = this.scene.getObjectByName('hlText') this.scene.remove(node) this.scene.remove(line) this.scene.remove(text) if(this.config.showArrow) { let arrow = this.scene.getObjectByName('hlArrows') this.scene.remove(arrow) } this.highlighted = null this.$container.classList.remove('hl') } // 根据 id 高亮节点 addHighLight(sourceId: string): void { let sourceNode = this.processedData.nodes.find(e => e.id === sourceId) let links = this.processedData.links.filter(e => (e.source === sourceId || e.target === sourceId)) let targetNodes = links.map(e => { return e.target === sourceNode.id ? e.source : e.target }) targetNodes.push(sourceNode.id) this.hlNodes.geometry = new THREE.BufferGeometry() this.hlNodes.positions = new Float32Array(targetNodes.length * 3) this.hlNodes.scale = new Float32Array(targetNodes.length) this.hlNodes.material = new THREE.ShaderMaterial({ transparent: true, uniforms: { texture: { type: 't', value: NODE_TEXTURE }, 'u_compensation': { value: window.devicePixelRatio * this.config.height / BASE_HEIGHT } }, vertexShader: hlNodesVS({ nodeSize: (this.config.nodeSize + 25).toFixed(8) }), fragmentShader: hlNodesFS() }) this.hlNodes.material.extensions.derivatives = true targetNodes.forEach((e, i) => { this.hlNodes.positions[i * 3] = this.currentPositionStatus[this.processedData.nodeInfoMap[e].index * 2] this.hlNodes.positions[i * 3 + 1] = this.currentPositionStatus[this.processedData.nodeInfoMap[e].index * 2 + 1] this.hlNodes.positions[i * 3 + 2] = 0.0001 this.hlNodes.scale[i] = this.processedData.nodeInfoMap[e].scale || 1 }) this.hlNodes.geometry.addAttribute('position', new THREE.BufferAttribute(this.hlNodes.positions, 3)) this.hlNodes.geometry.addAttribute('scale', new THREE.BufferAttribute(this.hlNodes.scale, 1)) this.hlNodes.geometry.computeBoundingSphere() this.hlNodes.mesh = new THREE.Points(this.hlNodes.geometry, this.hlNodes.material) this.hlNodes.mesh.name = 'hlNodes' this.scene.add(this.hlNodes.mesh) this.hlLines.geometry = new THREE.BufferGeometry() this.hlLines.positions = new Float32Array(links.length * 6) this.hlLines.material = new THREE.ShaderMaterial({ opacity: 0.6, vertexShader: hlLinesVS(), fragmentShader: hlLinesFS() }) links.forEach((e, i) => { this.hlLines.positions[i * 6] = this.currentPositionStatus[this.processedData.nodeInfoMap[e.source].index * 2] this.hlLines.positions[i * 6 + 1] = this.currentPositionStatus[this.processedData.nodeInfoMap[e.source].index * 2 + 1] this.hlLines.positions[i * 6 + 2] = -0.0009 this.hlLines.positions[i * 6 + 3] = this.currentPositionStatus[this.processedData.nodeInfoMap[e.target].index * 2] this.hlLines.positions[i * 6 + 4] = this.currentPositionStatus[this.processedData.nodeInfoMap[e.target].index * 2 + 1] this.hlLines.positions[i * 6 + 5] = -0.0009 }) this.hlLines.geometry.addAttribute('position', new THREE.BufferAttribute(this.hlLines.positions, 3)) this.hlLines.geometry.computeBoundingSphere() this.hlLines.mesh = new THREE.LineSegments(this.hlLines.geometry, this.hlLines.material) this.hlLines.mesh.name = 'hlLines' this.scene.add(this.hlLines.mesh) if(this.config.showArrow) { this.hlArrows.geometry = new THREE.BufferGeometry() this.hlArrows.positions = new Float32Array(links.length * 3) this.hlArrows.rotates = new Float32Array(links.length) this.hlArrows.material = new THREE.ShaderMaterial({ uniforms: { texture: { type: 't', value: ARROW_TEXTURE }, 'u_compensation': { value: window.devicePixelRatio * this.config.height / BASE_HEIGHT } }, vertexShader: hlArrowsVS({ arrowSize: (this.config.arrowSize + 25).toFixed(8) }), fragmentShader: hlArrowsFS() }) let vec = new v3.Vector3(0, 1, 0) let up = new v3.Vector3(0, 1, 0) let offsetDistance = (this.config.arrowSize + this.config.nodeSize) / 1125 links.forEach((e, i) => { // 计算箭头的旋转方向与偏移位置 let vecX = this.currentPositionStatus[this.processedData.nodeInfoMap[e.target].index * 2] - this.currentPositionStatus[this.processedData.nodeInfoMap[e.source].index * 2] let vecY = this.currentPositionStatus[this.processedData.nodeInfoMap[e.target].index * 2 + 1] - this.currentPositionStatus[this.processedData.nodeInfoMap[e.source].index * 2 + 1] vec.x = vecX vec.y = vecY let angle = v3.Vector3.getAngle(vec, up) let vecNorm = v3.Vector3.getNorm(vec) let offsetX = vecX * offsetDistance / vecNorm let offsetY = vecY * offsetDistance / vecNorm if(vecX < 0) { angle = 2 * Math.PI - angle } this.hlArrows.rotates[i] = angle this.hlArrows.positions[i * 3] = this.currentPositionStatus[this.processedData.nodeInfoMap[e.target].index * 2] - offsetX this.hlArrows.positions[i * 3 + 1] = this.currentPositionStatus[this.processedData.nodeInfoMap[e.target].index * 2 + 1] - offsetY this.hlArrows.positions[i * 3 + 2] = -0.0004 }) this.hlArrows.geometry.addAttribute('position', new THREE.BufferAttribute(this.hlArrows.positions, 3)) this.hlArrows.geometry.addAttribute('rotate', new THREE.BufferAttribute(this.hlArrows.rotates, 1)) this.hlArrows.geometry.computeBoundingSphere() this.hlArrows.mesh = new THREE.Points(this.hlArrows.geometry, this.hlArrows.material) this.hlArrows.mesh.name = 'hlArrows' this.scene.add(this.hlArrows.mesh) } let canvas1 = document.createElement('canvas') let context1 = canvas1.getContext('2d') canvas1.width = 512 canvas1.height = 64 context1.clearRect(0, 0, canvas1.width, canvas1.height) context1.font = 'Bold 24px Arial' context1.textAlign = 'center' context1.fillStyle = 'rgb(255,255,255)' let text = sourceId.startsWith('null') ? 'null' : (this.processedData.nodeInfoMap[sourceId].name || sourceId) context1.fillText(text, canvas1.width / 2, 50) let fontTexture = new THREE.Texture(canvas1) fontTexture.needsUpdate = true this.hlText.material = new THREE.MeshBasicMaterial({ map: fontTexture, side: THREE.DoubleSide, alphaTest: 0.5 }) this.hlText.material.transparent = true this.hlText.mesh = new THREE.Mesh( new THREE.PlaneGeometry(canvas1.width, canvas1.height), this.hlText.material as THREE.MeshBasicMaterial ) this.hlText.mesh.scale.set(0.12, 0.12, 0.12) let fontMeshPosition = [this.currentPositionStatus[this.processedData.nodeInfoMap[sourceId].index * 2], this.currentPositionStatus[this.processedData.nodeInfoMap[sourceId].index * 2 + 1] - 4, 0.02] this.hlText.mesh.position.set(fontMeshPosition[0], fontMeshPosition[1], 0) this.hlText.mesh.name = 'hlText' this.scene.add(this.hlText.mesh) this.$container.classList.add('hl') } mouseMoveHandler(event: MouseEvent): void { this.mouseStatus.mouseOnChart = true this.mouseStatus.mousePosition.x = event.clientX - this.containerRect.left - this.config.width / 2 this.mouseStatus.mousePosition.y = this.config.height - event.clientY + this.containerRect.top - this.config.height / 2 } mouseOutHandler(): void { this.mouseStatus.mouseOnChart = false this.mouseStatus.mousePosition.x = -9999 this.mouseStatus.mousePosition.y = -9999 } mouseMoveHandlerBinded = this.mouseMoveHandler.bind(this) mouseOutHandlerBinded = this.mouseOutHandler.bind(this) chartMouseEnterHandler(): void { this.mouseStatus.mouseOnChart = true clearTimeout(this.throttleTimer) this.throttleTimer = null // 开启渲染 this.startRender() } chartMouseLeaveHandler(): void { this.mouseStatus.mouseOnChart = false // 关闭渲染 if(!this.perfInfo.layouting && !this.lockHighlightToken) { this.stopRender() } } chartMouseEnterHandlerBinded = this.chartMouseEnterHandler.bind(this) chartMouseLeaveHandlerBinded = this.chartMouseLeaveHandler.bind(this) // 绑定事件 bindEvent(): void { this.$container.addEventListener('mouseenter', this.chartMouseEnterHandlerBinded) this.$container.addEventListener('mouseleave', this.chartMouseLeaveHandlerBinded) } // 解绑事件 unbindEvent(): void { this.$container.removeEventListener('mouseenter', this.chartMouseEnterHandlerBinded) this.$container.removeEventListener('mouseleave', this.chartMouseLeaveHandlerBinded) this.$container.removeEventListener('mousemove', this.mouseMoveHandlerBinded) this.$container.removeEventListener('mouseout', this.mouseOutHandlerBinded) } destroy(): void { this.stopRender() this.unbindEvent() this.scene = null this.camera = null this.controls = null this.targetPositionStatus = null this.currentPositionStatus = null this.cachePositionStatus = null this.nodes = { geometry: null, positions: null, scale: null, material: null, mesh: null } this.lines = { geometry: null, positions: null, colors: null, material: null, mesh: null } this.arrows = { geometry: null, positions: null, rotates: null, material: null, mesh: null } this.hlLines = { geometry: null, positions: null, material: null, mesh: null } this.hlNodes = { geometry: null, positions: null, scale: null, material: null, mesh: null } this.hlArrows = { geometry: null, positions: null, rotates: null, material: null, mesh: null } this.hlText = { geometry: null, material: null, mesh: null } this.renderer.domElement.parentElement.removeChild(this.renderer.domElement) this.renderer = null } resize(width: number, height: number) { this.camera.aspect = width / height // todo: rerender basic mesh // this.config.width = width // this.config.height = height this.camera.updateProjectionMatrix() this.renderer.setSize(width, height) this.renderer.render(this.scene, this.camera) } // Fitting equation (Four Parameter Logistic Regression) // nodesCount: 14,969,11007,50002 // z: 500,3000,7500,16000 // nodesCount: 14,764,11007,50002 // COL: 2,2.5,3.5,5 // DISTANCE: 20,25,40,50 // STRENGTH: 3,5,8,10 getPositionZ(nodesCount: number): number { return (3.04139028390183E+16 - 150.128392537138) / (1 + Math.pow(nodesCount / 2.12316143430556E+31, -0.461309470817812)) + 150.128392537138 } getDistance(nodesCount: number): number { return (60.5026920478786 - 19.6364818002641) / (1 + Math.pow(nodesCount / 11113.7184968341, -0.705912886177758)) + 19.6364818002641 } getStrength(nodesCount: number): number { return -1 * ((15.0568640234622 - 2.43316256810301) / (1 + Math.pow(nodesCount / 19283.3978670675, -0.422985777119439)) + 2.43316256810301) } getCol(nodesCount: number): number { return (2148936082128.1 - 1.89052009608515) / (1 + Math.pow(nodesCount / 7.81339751933109E+33, -0.405575129002072)) + 1.89052009608515 } }
the_stack
| Copyright (c) 2014-2017, PhosphorJS Contributors | | Distributed under the terms of the BSD 3-Clause License. | | The full license is in the file LICENSE, distributed with this software. |----------------------------------------------------------------------------*/ import { IDisposable } from '@lumino/disposable'; import { ElementExt } from '@lumino/domutils'; import { Drag } from '@lumino/dragdrop'; import { Message } from '@lumino/messaging'; import { ISignal, Signal } from '@lumino/signaling'; import { Widget } from './widget'; /** * A widget which implements a canonical scroll bar. */ export class ScrollBar extends Widget { /** * Construct a new scroll bar. * * @param options - The options for initializing the scroll bar. */ constructor(options: ScrollBar.IOptions = {}) { super({ node: Private.createNode() }); this.addClass('lm-ScrollBar'); /* <DEPRECATED> */ this.addClass('p-ScrollBar'); /* </DEPRECATED> */ this.setFlag(Widget.Flag.DisallowLayout); // Set the orientation. this._orientation = options.orientation || 'vertical'; this.dataset['orientation'] = this._orientation; // Parse the rest of the options. if (options.maximum !== undefined) { this._maximum = Math.max(0, options.maximum); } if (options.page !== undefined) { this._page = Math.max(0, options.page); } if (options.value !== undefined) { this._value = Math.max(0, Math.min(options.value, this._maximum)); } } /** * A signal emitted when the user moves the scroll thumb. * * #### Notes * The payload is the current value of the scroll bar. */ get thumbMoved(): ISignal<this, number> { return this._thumbMoved; } /** * A signal emitted when the user clicks a step button. * * #### Notes * The payload is whether a decrease or increase is requested. */ get stepRequested(): ISignal<this, 'decrement' | 'increment'> { return this._stepRequested; } /** * A signal emitted when the user clicks the scroll track. * * #### Notes * The payload is whether a decrease or increase is requested. */ get pageRequested(): ISignal<this, 'decrement' | 'increment'> { return this._pageRequested; } /** * Get the orientation of the scroll bar. */ get orientation(): ScrollBar.Orientation { return this._orientation; } /** * Set the orientation of the scroll bar. */ set orientation(value: ScrollBar.Orientation) { // Do nothing if the orientation does not change. if (this._orientation === value) { return; } // Release the mouse before making changes. this._releaseMouse(); // Update the internal orientation. this._orientation = value; this.dataset['orientation'] = value; // Schedule an update the scroll bar. this.update(); } /** * Get the current value of the scroll bar. */ get value(): number { return this._value; } /** * Set the current value of the scroll bar. * * #### Notes * The value will be clamped to the range `[0, maximum]`. */ set value(value: number) { // Clamp the value to the allowable range. value = Math.max(0, Math.min(value, this._maximum)); // Do nothing if the value does not change. if (this._value === value) { return; } // Update the internal value. this._value = value; // Schedule an update the scroll bar. this.update(); } /** * Get the page size of the scroll bar. * * #### Notes * The page size is the amount of visible content in the scrolled * region, expressed in data units. It determines the size of the * scroll bar thumb. */ get page(): number { return this._page; } /** * Set the page size of the scroll bar. * * #### Notes * The page size will be clamped to the range `[0, Infinity]`. */ set page(value: number) { // Clamp the page size to the allowable range. value = Math.max(0, value); // Do nothing if the value does not change. if (this._page === value) { return; } // Update the internal page size. this._page = value; // Schedule an update the scroll bar. this.update(); } /** * Get the maximum value of the scroll bar. */ get maximum(): number { return this._maximum; } /** * Set the maximum value of the scroll bar. * * #### Notes * The max size will be clamped to the range `[0, Infinity]`. */ set maximum(value: number) { // Clamp the value to the allowable range. value = Math.max(0, value); // Do nothing if the value does not change. if (this._maximum === value) { return; } // Update the internal values. this._maximum = value; // Clamp the current value to the new range. this._value = Math.min(this._value, value); // Schedule an update the scroll bar. this.update(); } /** * The scroll bar decrement button node. * * #### Notes * Modifying this node directly can lead to undefined behavior. */ get decrementNode(): HTMLDivElement { return this.node.getElementsByClassName('lm-ScrollBar-button')[0] as HTMLDivElement; } /** * The scroll bar increment button node. * * #### Notes * Modifying this node directly can lead to undefined behavior. */ get incrementNode(): HTMLDivElement { return this.node.getElementsByClassName('lm-ScrollBar-button')[1] as HTMLDivElement; } /** * The scroll bar track node. * * #### Notes * Modifying this node directly can lead to undefined behavior. */ get trackNode(): HTMLDivElement { return this.node.getElementsByClassName('lm-ScrollBar-track')[0] as HTMLDivElement; } /** * The scroll bar thumb node. * * #### Notes * Modifying this node directly can lead to undefined behavior. */ get thumbNode(): HTMLDivElement { return this.node.getElementsByClassName('lm-ScrollBar-thumb')[0] as HTMLDivElement; } /** * Handle the DOM events for the scroll bar. * * @param event - The DOM event sent to the scroll bar. * * #### Notes * This method implements the DOM `EventListener` interface and is * called in response to events on the scroll bar's DOM node. * * This should not be called directly by user code. */ handleEvent(event: Event): void { switch (event.type) { case 'mousedown': this._evtMouseDown(event as MouseEvent); break; case 'mousemove': this._evtMouseMove(event as MouseEvent); break; case 'mouseup': this._evtMouseUp(event as MouseEvent); break; case 'keydown': this._evtKeyDown(event as KeyboardEvent); break; case 'contextmenu': event.preventDefault(); event.stopPropagation(); break; } } /** * A method invoked on a 'before-attach' message. */ protected onBeforeAttach(msg: Message): void { this.node.addEventListener('mousedown', this); this.update(); } /** * A method invoked on an 'after-detach' message. */ protected onAfterDetach(msg: Message): void { this.node.removeEventListener('mousedown', this); this._releaseMouse(); } /** * A method invoked on an 'update-request' message. */ protected onUpdateRequest(msg: Message): void { // Convert the value and page into percentages. let value = this._value * 100 / this._maximum; let page = this._page * 100 / (this._page + this._maximum); // Clamp the value and page to the relevant range. value = Math.max(0, Math.min(value, 100)); page = Math.max(0, Math.min(page, 100)); // Fetch the thumb style. let thumbStyle = this.thumbNode.style; // Update the thumb style for the current orientation. if (this._orientation === 'horizontal') { thumbStyle.top = ''; thumbStyle.height = ''; thumbStyle.left = `${value}%`; thumbStyle.width = `${page}%`; thumbStyle.transform = `translate(${-value}%, 0%)`; } else { thumbStyle.left = ''; thumbStyle.width = ''; thumbStyle.top = `${value}%`; thumbStyle.height = `${page}%`; thumbStyle.transform = `translate(0%, ${-value}%)`; } } /** * Handle the `'keydown'` event for the scroll bar. */ private _evtKeyDown(event: KeyboardEvent): void { // Stop all input events during drag. event.preventDefault(); event.stopPropagation(); // Ignore anything except the `Escape` key. if (event.keyCode !== 27) { return; } // Fetch the previous scroll value. let value = this._pressData ? this._pressData.value : -1; // Release the mouse. this._releaseMouse(); // Restore the old scroll value if possible. if (value !== -1) { this._moveThumb(value); } } /** * Handle the `'mousedown'` event for the scroll bar. */ private _evtMouseDown(event: MouseEvent): void { // Do nothing if it's not a left mouse press. if (event.button !== 0) { return; } // Send an activate request to the scroll bar. This can be // used by message hooks to activate something relevant. this.activate(); // Do nothing if the mouse is already captured. if (this._pressData) { return; } // Find the pressed scroll bar part. let part = Private.findPart(this, event.target as HTMLElement); // Do nothing if the part is not of interest. if (!part) { return; } // Stop the event propagation. event.preventDefault(); event.stopPropagation(); // Override the mouse cursor. let override = Drag.overrideCursor('default'); // Set up the press data. this._pressData = { part, override, delta: -1, value: -1, mouseX: event.clientX, mouseY: event.clientY }; // Add the extra event listeners. document.addEventListener('mousemove', this, true); document.addEventListener('mouseup', this, true); document.addEventListener('keydown', this, true); document.addEventListener('contextmenu', this, true); // Handle a thumb press. if (part === 'thumb') { // Fetch the thumb node. let thumbNode = this.thumbNode; // Fetch the client rect for the thumb. let thumbRect = thumbNode.getBoundingClientRect(); // Update the press data delta for the current orientation. if (this._orientation === 'horizontal') { this._pressData.delta = event.clientX - thumbRect.left; } else { this._pressData.delta = event.clientY - thumbRect.top; } // Add the active class to the thumb node. thumbNode.classList.add('lm-mod-active'); /* <DEPRECATED> */ thumbNode.classList.add('p-mod-active'); /* </DEPRECATED> */ // Store the current value in the press data. this._pressData.value = this._value; // Finished. return; } // Handle a track press. if (part === 'track') { // Fetch the client rect for the thumb. let thumbRect = this.thumbNode.getBoundingClientRect(); // Determine the direction for the page request. let dir: 'decrement' | 'increment'; if (this._orientation === 'horizontal') { dir = event.clientX < thumbRect.left ? 'decrement' : 'increment'; } else { dir = event.clientY < thumbRect.top ? 'decrement' : 'increment'; } // Start the repeat timer. this._repeatTimer = window.setTimeout(this._onRepeat, 350); // Emit the page requested signal. this._pageRequested.emit(dir); // Finished. return; } // Handle a decrement button press. if (part === 'decrement') { // Add the active class to the decrement node. this.decrementNode.classList.add('lm-mod-active'); /* <DEPRECATED> */ this.decrementNode.classList.add('p-mod-active'); /* </DEPRECATED> */ // Start the repeat timer. this._repeatTimer = window.setTimeout(this._onRepeat, 350); // Emit the step requested signal. this._stepRequested.emit('decrement'); // Finished. return; } // Handle an increment button press. if (part === 'increment') { // Add the active class to the increment node. this.incrementNode.classList.add('lm-mod-active'); /* <DEPRECATED> */ this.incrementNode.classList.add('p-mod-active'); /* </DEPRECATED> */ // Start the repeat timer. this._repeatTimer = window.setTimeout(this._onRepeat, 350); // Emit the step requested signal. this._stepRequested.emit('increment'); // Finished. return; } } /** * Handle the `'mousemove'` event for the scroll bar. */ private _evtMouseMove(event: MouseEvent): void { // Do nothing if no drag is in progress. if (!this._pressData) { return; } // Stop the event propagation. event.preventDefault(); event.stopPropagation(); // Update the mouse position. this._pressData.mouseX = event.clientX; this._pressData.mouseY = event.clientY; // Bail if the thumb is not being dragged. if (this._pressData.part !== 'thumb') { return; } // Get the client rect for the thumb and track. let thumbRect = this.thumbNode.getBoundingClientRect(); let trackRect = this.trackNode.getBoundingClientRect(); // Fetch the scroll geometry based on the orientation. let trackPos: number; let trackSpan: number; if (this._orientation === 'horizontal') { trackPos = event.clientX - trackRect.left - this._pressData.delta; trackSpan = trackRect.width - thumbRect.width; } else { trackPos = event.clientY - trackRect.top - this._pressData.delta; trackSpan = trackRect.height - thumbRect.height; } // Compute the desired value from the scroll geometry. let value = trackSpan === 0 ? 0 : trackPos * this._maximum / trackSpan; // Move the thumb to the computed value. this._moveThumb(value); } /** * Handle the `'mouseup'` event for the scroll bar. */ private _evtMouseUp(event: MouseEvent): void { // Do nothing if it's not a left mouse release. if (event.button !== 0) { return; } // Stop the event propagation. event.preventDefault(); event.stopPropagation(); // Release the mouse. this._releaseMouse(); } /** * Release the mouse and restore the node states. */ private _releaseMouse(): void { // Bail if there is no press data. if (!this._pressData) { return; } // Clear the repeat timer. clearTimeout(this._repeatTimer); this._repeatTimer = -1; // Clear the press data. this._pressData.override.dispose(); this._pressData = null; // Remove the extra event listeners. document.removeEventListener('mousemove', this, true); document.removeEventListener('mouseup', this, true); document.removeEventListener('keydown', this, true); document.removeEventListener('contextmenu', this, true); // Remove the active classes from the nodes. this.thumbNode.classList.remove('lm-mod-active'); this.decrementNode.classList.remove('lm-mod-active'); this.incrementNode.classList.remove('lm-mod-active'); /* <DEPRECATED> */ this.thumbNode.classList.remove('p-mod-active'); this.decrementNode.classList.remove('p-mod-active'); this.incrementNode.classList.remove('p-mod-active'); /* </DEPRECATED> */ } /** * Move the thumb to the specified position. */ private _moveThumb(value: number): void { // Clamp the value to the allowed range. value = Math.max(0, Math.min(value, this._maximum)); // Bail if the value does not change. if (this._value === value) { return; } // Update the internal value. this._value = value; // Schedule an update of the scroll bar. this.update(); // Emit the thumb moved signal. this._thumbMoved.emit(value); } /** * A timeout callback for repeating the mouse press. */ private _onRepeat = () => { // Clear the repeat timer id. this._repeatTimer = -1; // Bail if the mouse has been released. if (!this._pressData) { return; } // Look up the part that was pressed. let part = this._pressData.part; // Bail if the thumb was pressed. if (part === 'thumb') { return; } // Schedule the timer for another repeat. this._repeatTimer = window.setTimeout(this._onRepeat, 20); // Get the current mouse position. let mouseX = this._pressData.mouseX; let mouseY = this._pressData.mouseY; // Handle a decrement button repeat. if (part === 'decrement') { // Bail if the mouse is not over the button. if (!ElementExt.hitTest(this.decrementNode, mouseX, mouseY)) { return; } // Emit the step requested signal. this._stepRequested.emit('decrement'); // Finished. return; } // Handle an increment button repeat. if (part === 'increment') { // Bail if the mouse is not over the button. if (!ElementExt.hitTest(this.incrementNode, mouseX, mouseY)) { return; } // Emit the step requested signal. this._stepRequested.emit('increment'); // Finished. return; } // Handle a track repeat. if (part === 'track') { // Bail if the mouse is not over the track. if (!ElementExt.hitTest(this.trackNode, mouseX, mouseY)) { return; } // Fetch the thumb node. let thumbNode = this.thumbNode; // Bail if the mouse is over the thumb. if (ElementExt.hitTest(thumbNode, mouseX, mouseY)) { return; } // Fetch the client rect for the thumb. let thumbRect = thumbNode.getBoundingClientRect(); // Determine the direction for the page request. let dir: 'decrement' | 'increment'; if (this._orientation === 'horizontal') { dir = mouseX < thumbRect.left ? 'decrement' : 'increment'; } else { dir = mouseY < thumbRect.top ? 'decrement' : 'increment'; } // Emit the page requested signal. this._pageRequested.emit(dir); // Finished. return; } }; private _value = 0; private _page = 10; private _maximum = 100; private _repeatTimer = -1; private _orientation: ScrollBar.Orientation; private _pressData: Private.IPressData | null = null; private _thumbMoved = new Signal<this, number>(this); private _stepRequested = new Signal<this, 'decrement' | 'increment'>(this); private _pageRequested = new Signal<this, 'decrement' | 'increment'>(this); } /** * The namespace for the `ScrollBar` class statics. */ export namespace ScrollBar { /** * A type alias for a scroll bar orientation. */ export type Orientation = 'horizontal' | 'vertical'; /** * An options object for creating a scroll bar. */ export interface IOptions { /** * The orientation of the scroll bar. * * The default is `'vertical'`. */ orientation?: Orientation; /** * The value for the scroll bar. * * The default is `0`. */ value?: number; /** * The page size for the scroll bar. * * The default is `10`. */ page?: number; /** * The maximum value for the scroll bar. * * The default is `100`. */ maximum?: number; } } /** * The namespace for the module implementation details. */ namespace Private { /** * A type alias for the parts of a scroll bar. */ export type ScrollBarPart = 'thumb' | 'track' | 'decrement' | 'increment'; /** * An object which holds mouse press data. */ export interface IPressData { /** * The scroll bar part which was pressed. */ part: ScrollBarPart; /** * The offset of the press in thumb coordinates, or -1. */ delta: number; /** * The scroll value at the time the thumb was pressed, or -1. */ value: number; /** * The disposable which will clear the override cursor. */ override: IDisposable; /** * The current X position of the mouse. */ mouseX: number; /** * The current Y position of the mouse. */ mouseY: number; } /** * Create the DOM node for a scroll bar. */ export function createNode(): HTMLElement { let node = document.createElement('div'); let decrement = document.createElement('div'); let increment = document.createElement('div'); let track = document.createElement('div'); let thumb = document.createElement('div'); decrement.className = 'lm-ScrollBar-button'; increment.className = 'lm-ScrollBar-button'; decrement.dataset['action'] = 'decrement'; increment.dataset['action'] = 'increment'; track.className = 'lm-ScrollBar-track'; thumb.className = 'lm-ScrollBar-thumb'; /* <DEPRECATED> */ decrement.classList.add('p-ScrollBar-button'); increment.classList.add('p-ScrollBar-button'); track.classList.add('p-ScrollBar-track'); thumb.classList.add('p-ScrollBar-thumb'); /* </DEPRECATED> */ track.appendChild(thumb); node.appendChild(decrement); node.appendChild(track); node.appendChild(increment); return node; } /** * Find the scroll bar part which contains the given target. */ export function findPart(scrollBar: ScrollBar, target: HTMLElement): ScrollBarPart | null { // Test the thumb. if (scrollBar.thumbNode.contains(target)) { return 'thumb'; } // Test the track. if (scrollBar.trackNode.contains(target)) { return 'track'; } // Test the decrement button. if (scrollBar.decrementNode.contains(target)) { return 'decrement'; } // Test the increment button. if (scrollBar.incrementNode.contains(target)) { return 'increment'; } // Indicate no match. return null; } }
the_stack
* This file contains definitons for objects of which Delivery Services are * composed - including some convenience functions for the magic numbers used to * represent certain properties. */ /** * Represents the `geoLimit` field of a Delivery Service */ export const enum GeoLimit { /** * No geographic limiting is to be done. */ NONE = 0, /** * Only clients found in a Coverage Zone File may be permitted access. */ CZF_ONLY = 1, /** * Only clients found in a Coverage Zone File OR can be geo-located within a * set of country codes may be permitted access. */ CZF_AND_COUNTRY_CODES = 2 } /** * Defines the supported Geograhic IP mapping database providers and their * respective magic number identifiers. */ export const enum GeoProvider { /** The standard database used for geo-location. */ MAX_MIND = 0, /** An alternative database with dubious support. */ NEUSTAR = 1 } /** * Represents a single entry in a Delivery Service's `matchList` field. */ export interface DeliveryServiceMatch { /** A regular expression matching on something depending on the 'type'. */ pattern: string; /** * The number in the set of the expression, which has vague but incredibly * important meaning. */ setNumber: number; /** * The type of match which determines how it's used. */ type: string; } /** * Represents the allowed routing protocols and their respective magic number * identifiers. */ export const enum Protocol { /** Serve HTTP traffic only. */ HTTP = 0, /** Serve HTTPS traffic only. */ HTTPS = 1, /** Serve both HTTPS and HTTP traffic. */ HTTP_AND_HTTPS = 2, /** Redirect HTTP requests to HTTPS URLs and serve HTTPS traffic normally. */ HTTP_TO_HTTPS = 3 } /** * Converts Protocols to a textual representation. * * @param p The Protocol to convert. * @returns A string representation of 'p', or 'UNKNOWN' if 'p' was unrecognized. */ export function protocolToString(p: Protocol): string { switch (p) { case Protocol.HTTP: return "Serve only unsecured HTTP requests"; case Protocol.HTTPS: return "Serve only secured HTTPS requests"; case Protocol.HTTP_AND_HTTPS: return "Serve both unsecured HTTP requests and secured HTTPS requests"; case Protocol.HTTP_TO_HTTPS: return "Serve secured HTTPS requests normally, but redirect unsecured HTTP requests to use HTTPS"; } } /** * Represents the allowed values of the `qstringIgnore` field of a * `DeliveryService`. */ export const enum QStringHandling { /** Use the query string in the cache key and pass in upstream requests. */ USE = 0, /** * Don't use the query string in the cache key but do pass it in upstream * requests. */ IGNORE = 1, /** * Neither use the query string in the cache key nor pass it in upstream * requests. */ DROP = 2 } /** * Converts a QStringHandling to a textual representation. * * @param q The QStringHandling to convert. * @returns A string representation of 'q'. */ export function qStringHandlingToString(q: QStringHandling): string { switch (q) { case QStringHandling.USE: return "Use the query parameter string when deciding if a URL is cached, and pass it in upstream requests to the" + " Mid-tier/origin"; case QStringHandling.IGNORE: return "Do not use the query parameter string when deciding if a URL is cached, but do pass it in upstream requests to the" + " Mid-tier/origin"; case QStringHandling.DROP: return "Immediately strip URLs of their query parameter strings before checking cached objects or making upstream requests"; } } /** * Represents the allowed values of the `rangeRequestHandling` field of a * `Delivery Service`. */ export const enum RangeRequestHandling { /** Range requests will not be cached. */ NONE = 0, /** * The entire object will be fetched in the background to be cached, with * the requested range served when it becomes available. */ BACKGROUND_FETCH = 1, /** * Cache range requests like any other request. */ CACHE_RANGE_REQUESTS = 2 } /** * Converts a RangeRequestHandling to a textual representation. * * @param r The RangeRequestHandling to convert. * @returns A string representation of 'r'. */ export function rangeRequestHandlingToString(r: RangeRequestHandling): string { switch (r) { case RangeRequestHandling.NONE: return "Do not cache Range requests"; case RangeRequestHandling.BACKGROUND_FETCH: return "Use the background_fetch plugin to serve Range requests while quietly caching the entire object"; case RangeRequestHandling.CACHE_RANGE_REQUESTS: return "Use the cache_range_requests plugin to directly cache object ranges"; } } /** * Represents a single Delivery Service of arbitrary type */ export interface DeliveryService { /** Whether or not the Delivery Service is actively routed. */ active: boolean; /** Whether or not anonymization services are blocked. */ anonymousBlockingEnabled: boolean; /** The TTL of DNS responses from the Traffic Router, in seconds. */ ccrDnsTtl?: number; /** The ID of the CDN to which the Delivery Service belongs. */ cdnId: number; /** The Name of the CDN to which the Delivery Service belongs. */ cdnName?: string; /** A sample path which may be requested to ensure the origin is working. */ checkPath?: string; /** * A regular expression used to extract request path fragments for use as * keys in "consistent hashing" for routing purposes. */ consistentHashRegex?: string; /** * A set of the query parameters that are important for Traffic Router to * consider when performing "consistent hashing". */ consistentHashQueryParams?: Array<string>; /** * Whether or not to use "deep caching". */ deepCachingType?: string; /** A human-friendly name for the Delivery Service. */ displayName: string; /** An FQDN to use for DNS-routed bypass scenarios. */ dnsBypassCname?: string; /** An IPv4 address to use for DNS-routed bypass scenarios. */ dnsBypassIp?: string; /** An IPv6 address to use for DNS-routed bypass scenarios. */ dnsBypassIp6?: string; /** The TTL of DNS responses served in bypass scenarios. */ dnsBypassTtl?: number; /** The Delivery Service's DSCP. */ dscp: number; /** Extra header rewrite text used at the Edge tier. */ edgeHeaderRewrite?: string; /** * A list of the URLs which may be used to request Delivery Service content. */ exampleURLs?: Array<string>; /** * Describes limitation of content availability based on geographic * location. */ geoLimit: GeoLimit; /** * The countries from which content access is allowed in the event that * geographic limiting is taking place with a setting that allows for * specific country codes to access content. */ geoLimitCountries?: string; /** * A URL to which to re-direct users who are blocked because of * geographic-based access limiting */ geoLimitRedirectURL?: string; /** * The provider of the IP-address-to-geographic-location database. */ geoProvider: GeoProvider; /** * The globally allowed maximum megabits per second to be served for the * Delivery Service. */ globalMaxMbps?: string; /** * The globally allowed maximum transactions per second to be served for the * Delivery Service. */ globalMaxTps?: string; /** * A URL to be used in HTTP-routed bypass scenarios. */ httpBypassFqdn?: string; /** * An integral, unique identifier for the Delivery Service. */ id?: number; /** * A URL from which information about a Delivery Service may be obtained. * Historically, this has been used to link to the support ticket that * requested the Delivery Service's creation. */ infoUrl?: string; /** * The number of caches across which to spread content. */ initialDispersion?: number; /** * whether or not routing of IPv6 clients should be supported. */ ipv6RoutingEnabled: boolean; /** When the Delivery Service was last updated via the API. */ lastUpdated?: Date; /** Whether or not logging should be enabled for the Delivery Service. */ logsEnabled: boolean; /** A textual description of arbitrary length. */ longDesc: string; /** A textual description of arbitrary length. */ longDesc1?: string; /** A textual description of arbitrary length. */ longDesc2?: string; /** * A list of regular expressions for routing purposes which should not ever * be modified by hand. */ matchList?: DeliveryServiceMatch[]; /** * Sets the maximum number of answers Traffic Router may provide in a single * DNS response for this Delivery Service. */ maxDnsAnswers?: number; /** * The maximum number of connections that cache servers are allowed to open * to the Origin(s). */ maxOriginConnections?: number; /** Extra header rewrite text to be used at the Mid-tier. */ midHeaderRewrite?: string; /** The latitude that should be used when geo-location of a client fails. */ missLat: number; /** The longitude that should be used when geo-location of a client fails. */ missLong: number; /** Whether or not Multi-Site Origin is in use. */ multiSiteOrigin: boolean; /** The URL of the Origin server, which I think means nothing for MSO. */ orgServerFqdn?: string; /** A string used to shield the Origin, somehow. */ originShield?: string; /** A description of the Profile used by the Delivery Service (read-only) */ profileDescription?: string; /** An integral, unique identifer for the Profile used by the Delivery Service. */ profileId?: number; /** The name of the Profile used by the Delivery Service. */ profileName?: string; /** The protocols served by the Delivery Service. */ protocol?: Protocol; /** * How query strings ought to be handled by cache servers serving content * for this Delivery Service. */ qstringIgnore?: QStringHandling; /** * How HTTP Range requests ought to be handled by cache servers serving * content for this Delivery Service. */ rangeRequestHandling?: RangeRequestHandling; /** * some raw text to be inserted into regex_remap.config. */ regexRemap?: string; /** * Whether or not regional geo-blocking should be used. */ regionalGeoBlocking: boolean; /** some raw text to be inserted into remap.config. */ remapText?: string; /** The lowest-level DNS label used in URLs for the Delivery Service. */ routingName: string; /** * Whether or not responses from the cache servers for this Delivery * Service's content will be signed. */ signed?: boolean; /** * The algorithm used to sign responses from the cache servers for this * Delivery Service's content. */ signingAlgorithm?: string; /** * The generation of SSL key used by this Delivery Service. */ sslKeyVersion?: number; /** The name of the Tenant to whom this Delivery Service belongs. */ tenant?: string; /** * An integral, unique identifier for the Tenant to whom this Delivery * Service belongs. */ tenantId?: number; /** * HTTP headers that should be logged from client requests by Traffic * Router. */ trRequestHeaders?: string; /** * Extra HTTP headers that Traffic Router should provide in responses. */ trResponseHeaders?: string; /** The type of the Delivery Service. */ type?: string; /** The integral, unique identifier of the type of the Delivery Service. */ typeId: number; /** The second-lowest-level DNS label used in the Delivery Service's URLs. */ xmlId: string; } export const defaultDeliveryService: DeliveryService ={ active: false, anonymousBlockingEnabled: false, cdnId: -1, deepCachingType: "NEVER", displayName: "", dscp: 0, geoLimit: GeoLimit.NONE, geoProvider: GeoProvider.MAX_MIND, initialDispersion: 1, ipv6RoutingEnabled: true, logsEnabled: true, longDesc: "", missLat: 0, missLong: 0, multiSiteOrigin: false, qstringIgnore: QStringHandling.USE, rangeRequestHandling: RangeRequestHandling.NONE, regionalGeoBlocking: false, routingName: "cdn", typeId: -1, xmlId: "" }; /** * Determines if the Delivery Service is a candidate for bypassing. * * @param ds The Delivery Service to check. * @returns `true` if it can have bypass settings, `false` otherwise. */ export function bypassable(ds: DeliveryService): boolean { if (!ds.type) { return false; } switch (ds.type) { case "HTTP": case "HTTP_LIVE": case "HTTP_LIVE_NATNL": case "DNS": case "DNS_LIVE": case "DNS_LIVE_NATNL": return true; default: return false; } } /** * DSCapacity represents a response from the API to a request for the capacity * of a Delivery Service. */ export interface DSCapacity { availablePercent: number; maintenancePercent: number; utilizedPercent: number; } /** * DSHealth represents a response from the API to a request for the health of a * Delivery Service. */ export interface DSHealth { totalOnline: number; totalOffline: number; }
the_stack
import { Collapse } from '@material-ui/core'; import { autobind } from 'core-decorators'; import FocusTrap from 'focus-trap-react'; import { List, Set } from 'immutable'; import keyboardJS from 'keyboardjs'; import qs from 'query-string'; import React from 'react'; import { RouteComponentProps } from 'react-router'; import { Link } from 'react-router-dom'; import { convertServerAction, ICommentListItem, IPreselectModel, IRuleModel, ITagModel, ModelId, TagModel, } from '../../../../../models'; import { ICommentAction } from '../../../../../types'; import { AddIcon, ApproveIcon, ArticleControlIcon, CommentActionButton, CommentList, DeferIcon, HighlightIcon, RejectIcon, Scrim, ToastMessage, ToolTip, } from '../../../../components'; import { DEFAULT_DRAG_HANDLE_POS1, DEFAULT_DRAG_HANDLE_POS2, } from '../../../../config'; import { IContextInjectorProps } from '../../../../injectors/contextInjector'; import { updateArticle } from '../../../../platform/dataService'; import { approveComments, confirmCommentSummaryScore, deferComments, highlightComments, ICommentActionFunction, rejectComments, rejectCommentSummaryScore, tagCommentSummaryScores, } from '../../../../stores/commentActions'; import { ARTICLE_CATEGORY_TYPE, BASE_Z_INDEX, BOX_DEFAULT_SPACING, DARK_COLOR, GUTTER_DEFAULT_SPACING, HEADER_HEIGHT, LIGHT_PRIMARY_TEXT_COLOR, NICE_MIDDLE_BLUE, SCRIM_STYLE, SCRIM_Z_INDEX, SELECT_ELEMENT, TOOLTIP_Z_INDEX, WHITE_COLOR, } from '../../../../styles'; import { clearReturnSavedCommentRow, getReturnSavedCommentRow, partial, setReturnSavedCommentRow, } from '../../../../util'; import { getDefaultSort, putDefaultSort } from '../../../../util/savedSorts'; import { css, stylesheet } from '../../../../utilx'; import { commentDetailsPageLink, INewCommentsPathParams, INewCommentsQueryParams, newCommentsPageLink, tagSelectorLink, } from '../../../routes'; import { BatchSelector } from './components/BatchSelector'; import { getCommentIDsInRange } from './store'; const actionMap: { [key: string]: ICommentActionFunction } = { highlight: highlightComments, approve: approveComments, defer: deferComments, reject: rejectComments, tag: tagCommentSummaryScores, }; const ARROW_SIZE = 6; const TOAST_DELAY = 6000; const ACTION_PLURAL: { [key: string]: string; } = { highlight: 'highlighted', approve: 'approved', defer: 'deferred', reject: 'rejected', tag: 'tagged', }; const LOADING_COMMENTS_MESSAGING = 'Loading comments.'; const NO_COMMENTS_MESSAGING = 'No matching comments found.'; const STYLES = stylesheet({ container: { height: '100%', }, buttonContainer: { alignItems: 'center', backgroundColor: NICE_MIDDLE_BLUE, boxSizing: 'border-box', display: 'flex', justifyContent: 'space-between', padding: `0px ${GUTTER_DEFAULT_SPACING}px 0 0`, width: '100%', }, commentCount: { ...ARTICLE_CATEGORY_TYPE, color: LIGHT_PRIMARY_TEXT_COLOR, textAlign: 'left', marginLeft: `${GUTTER_DEFAULT_SPACING * 2}px`, }, moderateButtons: { display: 'flex', position: 'relative', right: `${-GUTTER_DEFAULT_SPACING}px`, }, commentActionButton: { padding: `${GUTTER_DEFAULT_SPACING}px ${GUTTER_DEFAULT_SPACING}px ${GUTTER_DEFAULT_SPACING}px 0`, }, filler: { backgroundColor: NICE_MIDDLE_BLUE, height: 0, }, actionToastCount: { display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24, lineHeight: 1.5, textIndent: 4, }, scrim: { zIndex: SCRIM_Z_INDEX, background: 'none', }, topSelectRow: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%', paddingLeft: `${GUTTER_DEFAULT_SPACING}px`, paddingRight: `${GUTTER_DEFAULT_SPACING * 2}px`, boxSizing: 'border-box', backgroundColor: NICE_MIDDLE_BLUE, height: HEADER_HEIGHT, }, dropdown: { position: 'relative', marginRight: `${GUTTER_DEFAULT_SPACING}px`, }, select: { ...SELECT_ELEMENT, paddingRight: `${(ARROW_SIZE * 2) + (BOX_DEFAULT_SPACING * 2)}px`, position: 'relative', zIndex: BASE_Z_INDEX, color: LIGHT_PRIMARY_TEXT_COLOR, ':focus': { outline: 0, borderBottom: `1px solid ${LIGHT_PRIMARY_TEXT_COLOR}`, }, }, arrow: { position: 'absolute', zIndex: BASE_Z_INDEX, right: '0px', top: '8px', borderLeft: `${ARROW_SIZE}px solid transparent`, borderRight: `${ARROW_SIZE}px solid transparent`, borderTop: `${ARROW_SIZE}px solid ${LIGHT_PRIMARY_TEXT_COLOR}`, display: 'block', height: 0, width: 0, marginLeft: `${BOX_DEFAULT_SPACING}px`, marginRight: `${BOX_DEFAULT_SPACING}px`, }, toolTipWithTagsContainer: { width: 250, }, toolTipWithTagsUl: { listStyle: 'none', margin: 0, padding: `${GUTTER_DEFAULT_SPACING}px 0`, }, toolTipWithTagsButton: { backgroundColor: 'transparent', border: 'none', borderRadius: 0, color: NICE_MIDDLE_BLUE, cursor: 'pointer', padding: '8px 20px', textAlign: 'left', width: '100%', ':hover': { backgroundColor: NICE_MIDDLE_BLUE, color: LIGHT_PRIMARY_TEXT_COLOR, }, ':focus': { backgroundColor: NICE_MIDDLE_BLUE, color: LIGHT_PRIMARY_TEXT_COLOR, outline: 0, }, }, commentsNotFoundMessaging: { padding: `${GUTTER_DEFAULT_SPACING}px 0`, marginLeft: GUTTER_DEFAULT_SPACING, }, toggleLabel: { ...ARTICLE_CATEGORY_TYPE, display: 'flex', flexDirection: 'row', alignItems: 'center', color: LIGHT_PRIMARY_TEXT_COLOR, }, }); export interface INewCommentsProps extends RouteComponentProps<INewCommentsPathParams>, IContextInjectorProps { preselects?: List<IPreselectModel>; commentScores: Array<ICommentListItem>; isLoading: boolean; selectedTag?: ITagModel; areNoneSelected?: boolean; areAllSelected: boolean; isItemChecked(id: string): boolean; tags: List<ITagModel>; rules?: List<IRuleModel>; pagingIdentifier: string; textSizes?: Map<ModelId, number>; removeCommentScore?(idsToDispatch: Array<string>): any; toggleSelectAll?(): any; toggleSingleItem({ id }: { id: string }): any; loadData(params: INewCommentsPathParams, pos1: number, pos2: number, sort: string): void; } export interface INewCommentsState { categoryId?: ModelId; articleId?: ModelId; tag?: string; defaultPos1?: number; defaultPos2?: number; defaultSort?: string; pos1?: number; pos2?: number; sort?: string; commentIds?: Array<ModelId>; isConfirmationModalVisible?: boolean; isRuleInfoVisible?: boolean; confirmationAction?: ICommentAction; actionCount?: number; actionText?: string; toastButtonLabel?: 'Undo'; toastIcon?: JSX.Element; ruleToastIcon?: JSX.Element; showCount?: boolean; isTaggingToolTipMetaVisible?: boolean; taggingToolTipMetaPosition?: { top: number; left: number; }; selectedRow?: number; articleControlOpen: boolean; rulesInCategory?: List<IRuleModel>; hideHistogram: boolean; } export class NewComments extends React.Component<INewCommentsProps, INewCommentsState> { commentActionCancelled = false; listContainerRef: any = null; state: INewCommentsState = { isConfirmationModalVisible: false, isRuleInfoVisible: false, confirmationAction: null, actionCount: 0, actionText: '', toastButtonLabel: null, toastIcon: null, ruleToastIcon: null, showCount: false, isTaggingToolTipMetaVisible: false, taggingToolTipMetaPosition: { top: 0, left: 0, }, selectedRow: null, articleControlOpen: false, hideHistogram: false, }; static getDerivedStateFromProps(props: INewCommentsProps, state: INewCommentsState) { let preselect: IPreselectModel; const params = props.match.params; const tag = params.tag; const {categoryId, articleId} = props; let defaultPos1: number; let defaultPos2: number; let defaultSort; if (tag !== state.tag || !state.defaultSort) { defaultSort = getDefaultSort(categoryId, 'new', tag); } else { defaultSort = state.defaultSort; } if (tag !== 'DATE') { if (props.preselects) { if (categoryId !== 'all' && props.selectedTag) { preselect = props.preselects.find((p) => (p.categoryId === categoryId && p.tagId === props.selectedTag.id)); } if (!preselect && categoryId !== 'all') { preselect = props.preselects.find((p) => (p.categoryId === categoryId && !p.tagId)); } if (!preselect && props.selectedTag) { preselect = props.preselects.find((p) => (!p.categoryId && p.tagId === props.selectedTag.id)); } if (!preselect) { preselect = props.preselects.find((p) => (!p.categoryId && !p.tagId)); } } defaultPos1 = preselect ? preselect.lowerThreshold : DEFAULT_DRAG_HANDLE_POS1; defaultPos2 = preselect ? preselect.upperThreshold : DEFAULT_DRAG_HANDLE_POS2; } else { defaultPos1 = 0; defaultPos2 = 1; } const query: INewCommentsQueryParams = qs.parse(props.location.search); const pos1 = query.pos1 ? Number.parseFloat(query.pos1) : defaultPos1; const pos2 = query.pos2 ? Number.parseFloat(query.pos2) : defaultPos2; const sort = query.sort || defaultSort; const commentIds = getCommentIDsInRange( props.commentScores, pos1, pos2, props.match.params.tag === 'DATE', ); let rulesInCategory: List<IRuleModel>; if (props.rules) { if (categoryId !== 'all') { rulesInCategory = props.rules.filter((r) => (r.categoryId === categoryId || !r.categoryId)) as List<IRuleModel>; } else { rulesInCategory = props.rules.filter((r) => (!r.categoryId)) as List<IRuleModel>; } } if ((categoryId !== state.categoryId) || (articleId !== state.articleId) || (tag !== state.tag) || (pos1 !== state.pos1) || (pos2 !== state.pos2) || (sort !== state.sort)) { props.loadData(params, pos1, pos2, sort); } return { categoryId, articleId, tag, commentIds, defaultPos1, defaultPos2, defaultSort, pos1, pos2, sort, rulesInCategory, }; } async componentDidUpdate(_prevProps: INewCommentsProps) { // We need to wait for commentIDsInRange to load so we can check that against the saved row const commentId = getReturnSavedCommentRow(); if ((typeof commentId !== 'undefined') && !this.props.isLoading && this.state.commentIds.length > 0 ) { // need to wait to make sure dom and other items are loaded before scrolling you down to the saved comment // Maybe we need a better has loaded thing to see if a single row has been rendered and bubble that up to here? const row = this.state.commentIds.findIndex((idInRange) => idInRange === commentId); this.setState({ selectedRow: row }); clearReturnSavedCommentRow(); } } componentDidMount() { keyboardJS.bind('escape', this.onPressEscape); } componentWillUnmount() { keyboardJS.unbind('escape', this.onPressEscape); } @autobind onPressEscape() { this.setState({ isConfirmationModalVisible: false, isRuleInfoVisible: false, isTaggingToolTipMetaVisible: false, }); } @autobind saveListContainerRef(ref: HTMLDivElement) { this.listContainerRef = ref; } @autobind async handleAssignTagsSubmit(commentId: ModelId, selectedTagIds: Set<ModelId>, rejectedTagIds: Set<ModelId>) { selectedTagIds.forEach((tagId) => { confirmCommentSummaryScore(commentId, tagId); }); rejectedTagIds.forEach((tagId) => { rejectCommentSummaryScore(commentId, tagId); }); this.dispatchConfirmedAction('reject', [commentId]); } render() { const { isArticleContext, article, commentScores, textSizes, areNoneSelected, areAllSelected, isItemChecked, tags, selectedTag, isLoading, match: { params }, pagingIdentifier, } = this.props; const { pos1, pos2, commentIds, isConfirmationModalVisible, isRuleInfoVisible, isTaggingToolTipMetaVisible, taggingToolTipMetaPosition, selectedRow, rulesInCategory, hideHistogram, } = this.state; function getLinkTarget(commentId: ModelId): string { const urlParams = { context: params.context, contextId: params.contextId, commentId: commentId, }; const query = pagingIdentifier && {pagingIdentifier}; return commentDetailsPageLink(urlParams, query); } const IS_SMALL_SCREEN = window.innerWidth < 1024; let filterSortOptions = List([ TagModel({ id: '-1', label: 'Newest', key: 'newest', color: '', }), TagModel({ id: '-2', label: 'Oldest', key: 'oldest', color: '', }), ]); switch (selectedTag && selectedTag.key) { case undefined: break; case 'DATE': break; case 'SUMMARY_SCORE': filterSortOptions = filterSortOptions .push(TagModel({ id: '-3', label: `Highest ${selectedTag && selectedTag.label}`, key: 'highest', color: '', })) .push(TagModel({ id: '-4', label: `Lowest ${selectedTag && selectedTag.label}`, key: 'lowest', color: '', })); break; default: filterSortOptions = filterSortOptions .push(TagModel({ id: '-3', label: `Most ${selectedTag && selectedTag.label}`, key: 'highest', color: '', })) .push(TagModel({ id: '-4', label: `Least ${selectedTag && selectedTag.label}`, key: 'lowest', color: '', })); } const tagLinkURL = tagSelectorLink({context: params.context, contextId: params.contextId, tag: selectedTag && selectedTag.id}); const rules = selectedTag && selectedTag.key !== 'DATE' && rulesInCategory && List<IRuleModel>(rulesInCategory.filter( (r) => r.tagId && r.tagId === selectedTag.id)); const disableAllButtons = areNoneSelected || commentScores.length <= 0; const groupBy = (selectedTag && selectedTag.key === 'DATE') ? 'date' : 'score'; const totalScoresInView = commentIds.length; let commentsMessaging: string = null; if (isLoading) { commentsMessaging = LOADING_COMMENTS_MESSAGING; } else { if (totalScoresInView === 0) { commentsMessaging = NO_COMMENTS_MESSAGING; } } const showMessaging = !!commentsMessaging; const selectedIdsCount = this.getSelectedIDs().length; const boundingRect = this.listContainerRef && this.listContainerRef.getBoundingClientRect(); const listHeightOffset = boundingRect ? boundingRect.top : 500; return ( <div {...css(STYLES.container)}> <Collapse in={!hideHistogram}> <div key="tagSelection" {...css(STYLES.topSelectRow)}> <div {...css(STYLES.dropdown)}> <Link {...css(STYLES.select)} to={tagLinkURL}> {selectedTag && selectedTag.label} </Link> <span aria-hidden="true" {...css(STYLES.arrow)} /> </div> { isArticleContext && ( <ArticleControlIcon article={article} open={this.state.articleControlOpen} clearPopups={this.closePopup} openControls={this.openPopup} saveControls={this.applyRules} whiteBackground /> )} </div> { selectedTag && ( <BatchSelector key="selector" groupBy={groupBy} rules={rules} areAutomatedRulesApplied={article && article.isAutoModerated} defaultSelectionPosition1={pos1} defaultSelectionPosition2={pos2} commentScores={commentScores} onSelectionChangeEnd={this.onBatchCommentsChangeEnd} automatedRuleToast={this.handleRemoveAutomatedRule} /> )} </Collapse> <div {...css( STYLES.filler )} /> <div {...css(STYLES.buttonContainer)}> <div {...css(STYLES.commentCount)}> { commentScores.length > 0 && ( <div> <span>{selectedIdsCount} of {commentScores.length} comments selected</span> </div> )} </div> <div {...css(STYLES.moderateButtons)}> <CommentActionButton disabled={disableAllButtons} style={IS_SMALL_SCREEN && STYLES.commentActionButton} label="Approve" onClick={partial( this.triggerActionToast, 'approve', selectedIdsCount, this.dispatchConfirmedAction, )} icon={( <ApproveIcon {...css({ fill: LIGHT_PRIMARY_TEXT_COLOR })} /> )} /> <CommentActionButton disabled={disableAllButtons} style={IS_SMALL_SCREEN && STYLES.commentActionButton} label="Reject" onClick={partial( this.triggerActionToast, 'reject', selectedIdsCount, this.dispatchConfirmedAction, )} icon={( <RejectIcon {...css({ fill: LIGHT_PRIMARY_TEXT_COLOR })} /> )} /> <CommentActionButton disabled={disableAllButtons} style={IS_SMALL_SCREEN && STYLES.commentActionButton} label="Defer" onClick={partial( this.triggerActionToast, 'defer', selectedIdsCount, this.dispatchConfirmedAction, )} icon={( <DeferIcon {...css({ fill: LIGHT_PRIMARY_TEXT_COLOR })} /> )} /> <div {...css(STYLES.dropdown)}> <CommentActionButton style={IS_SMALL_SCREEN && STYLES.commentActionButton} disabled={disableAllButtons} buttonRef={this.calculateTaggingTriggerPosition} label="Tag" onClick={this.toggleTaggingToolTip} icon={( <AddIcon {...css({ fill: LIGHT_PRIMARY_TEXT_COLOR })} /> )} /> {isTaggingToolTipMetaVisible && ( <ToolTip arrowPosition="topRight" backgroundColor={WHITE_COLOR} hasDropShadow isVisible={isTaggingToolTipMetaVisible} onDeactivate={this.toggleTaggingToolTip} position={taggingToolTipMetaPosition} size={16} width={250} zIndex={TOOLTIP_Z_INDEX} > <FocusTrap focusTrapOptions={{ clickOutsideDeactivates: true, }} > <div {...css(STYLES.toolTipWithTagsContainer)}> <ul {...css(STYLES.toolTipWithTagsUl)}> {tags && tags.map((t, i) => ( <li key={t.id}> <button onClick={partial(this.onTagButtonClick, t.id)} key={`tag-${i}`} {...css(STYLES.toolTipWithTagsButton)} > {t.label} </button> </li> ))} </ul> </div> </FocusTrap> </ToolTip> )} </div> </div> </div> {/* Table View */} <div ref={this.saveListContainerRef}> { showMessaging ? ( <p {...css(STYLES.commentsNotFoundMessaging)}>{commentsMessaging}</p> ) : ( <CommentList heightOffset={listHeightOffset} textSizes={textSizes} commentIds={commentIds} selectedTag={selectedTag} areAllSelected={areAllSelected} getLinkTarget={getLinkTarget} isItemChecked={isItemChecked} onSelectAllChange={this.onSelectAllChange} onSelectionChange={this.onSelectionChange} handleAssignTagsSubmit={this.handleAssignTagsSubmit} sortOptions={filterSortOptions} currentSort={this.state.sort} onSortChange={this.onSortChange} onCommentClick={this.saveCommentRow} scrollToRow={selectedRow} totalItems={commentIds.length} dispatchConfirmedAction={this.dispatchConfirmedAction} displayArticleTitle={!isArticleContext} onTableScroll={this.onTableScroll} /> )} </div> <Scrim key="confirmationScrim" scrimStyles={{...STYLES.scrim, ...SCRIM_STYLE.scrim}} isVisible={isConfirmationModalVisible} onBackgroundClick={this.confirmationClose} > <FocusTrap focusTrapOptions={{ clickOutsideDeactivates: true, }} > <ToastMessage icon={this.state.toastIcon} buttonLabel={this.state.toastButtonLabel} onClick={this.handleUndoClick} > <div key="toastContent"> { this.state.showCount && ( <span key="toastCount" {...css(STYLES.actionToastCount)}> {this.state.toastIcon} {this.state.actionCount} </span> )} <p key="actionText">{this.state.actionText}</p> </div> </ToastMessage> </FocusTrap> </Scrim> <Scrim key="ruleScrim" scrimStyles={{...STYLES.scrim, ...SCRIM_STYLE.scrim}} isVisible={isRuleInfoVisible} onBackgroundClick={this.onRuleInfoClose} > <FocusTrap focusTrapOptions={{ clickOutsideDeactivates: true, }} > <ToastMessage icon={this.state.ruleToastIcon}> <p>{this.state.actionText}</p> </ToastMessage> </FocusTrap> </Scrim> </div> ); } matchAction(action: ICommentAction) { let showActionIcon; if (action === 'approve') { showActionIcon = <ApproveIcon {...css({ fill: DARK_COLOR })} />; } else if (action === 'reject') { showActionIcon = <RejectIcon {...css({ fill: DARK_COLOR })} />; } else if (action === 'highlight') { showActionIcon = <HighlightIcon {...css({ fill: DARK_COLOR })} />; } else if (action === 'defer') { showActionIcon = <DeferIcon {...css({ fill: DARK_COLOR })} />; } return showActionIcon; } @autobind triggerActionToast(action: ICommentAction, count: number, callback: (action?: ICommentAction) => any) { this.setState({ isConfirmationModalVisible: true, confirmationAction: action, actionCount: count, actionText: `Comment${count > 1 ? 's' : ''} ` + ACTION_PLURAL[action], toastButtonLabel: 'Undo', toastIcon: this.matchAction(action), showCount: true, }); setTimeout(async () => { if (this.commentActionCancelled) { this.commentActionCancelled = false; this.confirmationClose(); return false; } else { this.setState({ toastButtonLabel: null, }); await callback(action); this.confirmationClose(); } }, TOAST_DELAY); } @autobind handleRemoveAutomatedRule(rule: IRuleModel) { const icon = this.matchAction(convertServerAction(rule.action)); this.setState({ isRuleInfoVisible: true, actionText: 'These comments are auto ' + rule.action, ruleToastIcon: icon, }); } @autobind calculateTaggingTriggerPosition(ref: any) { if (!ref) { return; } const buttonRect = ref.getBoundingClientRect(); this.setState({ taggingToolTipMetaPosition: { top: buttonRect.height, left: buttonRect.width - 5, }, }); } @autobind onTagButtonClick(tagId: string) { const ids = this.getSelectedIDs(); this.triggerActionToast('tag', ids.length, () => tagCommentSummaryScores(ids, tagId)); this.toggleTaggingToolTip(); } @autobind toggleTaggingToolTip() { this.setState({ isTaggingToolTipMetaVisible: !this.state.isTaggingToolTipMetaVisible, }); } @autobind async dispatchConfirmedAction(action: ICommentAction, ids?: Array<string>) { const idsToDispatch = ids || this.getSelectedIDs(); // Send event actionMap[action](idsToDispatch); // remove these from the ui because they are now 'moderated' this.props.removeCommentScore(idsToDispatch); } @autobind getSelectedIDs(): Array<string> { return this.state.commentIds .filter((commentId) => this.props.isItemChecked(commentId)); } @autobind confirmationClose() { this.setState({ isConfirmationModalVisible: false }); } @autobind onRuleInfoClose() { this.setState({ isRuleInfoVisible: false }); } @autobind handleUndoClick() { this.commentActionCancelled = true; this.confirmationClose(); } @autobind setQueryStringParam(pos1: number, pos2: number, sort: string): void { if ((pos1 === this.state.pos1) && (pos2 === this.state.pos2) && (sort === this.state.sort)) { return; } const query: INewCommentsQueryParams = {}; if (pos1 !== this.state.defaultPos1) { query.pos1 = pos1.toString(); } if (pos2 !== this.state.defaultPos2) { query.pos2 = pos2.toString(); } if (sort !== this.state.defaultSort) { query.sort = sort; } this.props.history.replace(newCommentsPageLink(this.props.match.params, query)); } @autobind saveCommentRow(commentId: string): void { setReturnSavedCommentRow(commentId); } @autobind onSortChange(event: React.FormEvent<any>) { const sort: string = (event.target as any).value; putDefaultSort(this.state.categoryId, 'new', this.state.tag, sort); this.setQueryStringParam(this.state.pos1, this.state.pos2, sort); } @autobind onBatchCommentsChangeEnd(_commentIds: Array<number>, pos1: number, pos2: number) { this.setQueryStringParam(pos1, pos2, this.state.sort); } @autobind async onSelectAllChange() { await this.props.toggleSelectAll(); } @autobind async onSelectionChange(id: string) { await this.props.toggleSingleItem({ id }); } @autobind onTableScroll(position: number) { this.setState({hideHistogram: position !== 0}); return true; } @autobind openPopup() { this.setState({articleControlOpen: true}); } @autobind closePopup() { this.setState({articleControlOpen: false}); } @autobind applyRules(isCommentingEnabled: boolean, isAutoModerated: boolean): void { this.closePopup(); updateArticle(this.props.article.id, isCommentingEnabled, isAutoModerated); } }
the_stack
import { ServiceClient, ServiceClientOptions, ServiceCallback, HttpOperationResponse, ServiceClientCredentials } from 'ms-rest'; import { AzureServiceClient, AzureServiceClientOptions } from 'ms-rest-azure'; import * as models from "./models"; import * as operations from "./operations"; export default class WebSiteManagementClient extends AzureServiceClient { /** * Initializes a new instance of the WebSiteManagementClient class. * @constructor * * @class * @param {credentials} credentials - Credentials needed for the client to connect to Azure. * * @param {string} subscriptionId - Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). * * @param {string} [baseUri] - The base URI of the service. * * @param {object} [options] - The parameter options * * @param {Array} [options.filters] - Filters to be added to the request pipeline * * @param {object} [options.requestOptions] - Options for the underlying request object * {@link https://github.com/request/request#requestoptions-callback Options doc} * * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy * * @param {string} [options.acceptLanguage] - The preferred language for the response. * * @param {number} [options.longRunningOperationRetryTimeout] - The retry timeout in seconds for Long Running Operations. Default value is 30. * * @param {boolean} [options.generateClientRequestId] - Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * */ constructor(credentials: ServiceClientCredentials, subscriptionId: string, baseUri?: string, options?: AzureServiceClientOptions); credentials: ServiceClientCredentials; subscriptionId: string; apiVersion: string; acceptLanguage: string; longRunningOperationRetryTimeout: number; generateClientRequestId: boolean; // Operation groups appServiceCertificateOrders: operations.AppServiceCertificateOrders; certificateRegistrationProvider: operations.CertificateRegistrationProvider; domains: operations.Domains; topLevelDomains: operations.TopLevelDomains; domainRegistrationProvider: operations.DomainRegistrationProvider; certificates: operations.Certificates; deletedWebApps: operations.DeletedWebApps; diagnostics: operations.Diagnostics; provider: operations.Provider; recommendations: operations.Recommendations; webApps: operations.WebApps; appServiceEnvironments: operations.AppServiceEnvironments; appServicePlans: operations.AppServicePlans; resourceHealthMetadataOperations: operations.ResourceHealthMetadataOperations; /** * @summary Gets publishing user * * Gets publishing user * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<User>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getPublishingUserWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.User>>; /** * @summary Gets publishing user * * Gets publishing user * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {User} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {User} [result] - The deserialized result object if an error did not occur. * See {@link User} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getPublishingUser(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.User>; getPublishingUser(callback: ServiceCallback<models.User>): void; getPublishingUser(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.User>): void; /** * @summary Updates publishing user * * Updates publishing user * * @param {object} userDetails Details of publishing user * * @param {string} userDetails.publishingUserName Username used for publishing. * * @param {string} [userDetails.publishingPassword] Password used for * publishing. * * @param {string} [userDetails.publishingPasswordHash] Password hash used for * publishing. * * @param {string} [userDetails.publishingPasswordHashSalt] Password hash salt * used for publishing. * * @param {string} [userDetails.scmUri] Url of SCM site. * * @param {string} [userDetails.kind] Kind of resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<User>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updatePublishingUserWithHttpOperationResponse(userDetails: models.User, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.User>>; /** * @summary Updates publishing user * * Updates publishing user * * @param {object} userDetails Details of publishing user * * @param {string} userDetails.publishingUserName Username used for publishing. * * @param {string} [userDetails.publishingPassword] Password used for * publishing. * * @param {string} [userDetails.publishingPasswordHash] Password hash used for * publishing. * * @param {string} [userDetails.publishingPasswordHashSalt] Password hash salt * used for publishing. * * @param {string} [userDetails.scmUri] Url of SCM site. * * @param {string} [userDetails.kind] Kind of resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {User} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {User} [result] - The deserialized result object if an error did not occur. * See {@link User} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ updatePublishingUser(userDetails: models.User, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.User>; updatePublishingUser(userDetails: models.User, callback: ServiceCallback<models.User>): void; updatePublishingUser(userDetails: models.User, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.User>): void; /** * @summary Gets the source controls available for Azure websites. * * Gets the source controls available for Azure websites. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SourceControlCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listSourceControlsWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SourceControlCollection>>; /** * @summary Gets the source controls available for Azure websites. * * Gets the source controls available for Azure websites. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SourceControlCollection} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SourceControlCollection} [result] - The deserialized result object if an error did not occur. * See {@link SourceControlCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listSourceControls(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SourceControlCollection>; listSourceControls(callback: ServiceCallback<models.SourceControlCollection>): void; listSourceControls(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SourceControlCollection>): void; /** * @summary Gets source control token * * Gets source control token * * @param {string} sourceControlType Type of source control * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SourceControl>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getSourceControlWithHttpOperationResponse(sourceControlType: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SourceControl>>; /** * @summary Gets source control token * * Gets source control token * * @param {string} sourceControlType Type of source control * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SourceControl} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SourceControl} [result] - The deserialized result object if an error did not occur. * See {@link SourceControl} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getSourceControl(sourceControlType: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SourceControl>; getSourceControl(sourceControlType: string, callback: ServiceCallback<models.SourceControl>): void; getSourceControl(sourceControlType: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SourceControl>): void; /** * @summary Updates source control token * * Updates source control token * * @param {string} sourceControlType Type of source control * * @param {object} requestMessage Source control token information * * @param {string} [requestMessage.token] OAuth access token. * * @param {string} [requestMessage.tokenSecret] OAuth access token secret. * * @param {string} [requestMessage.refreshToken] OAuth refresh token. * * @param {date} [requestMessage.expirationTime] OAuth token expiration. * * @param {string} [requestMessage.kind] Kind of resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SourceControl>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateSourceControlWithHttpOperationResponse(sourceControlType: string, requestMessage: models.SourceControl, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SourceControl>>; /** * @summary Updates source control token * * Updates source control token * * @param {string} sourceControlType Type of source control * * @param {object} requestMessage Source control token information * * @param {string} [requestMessage.token] OAuth access token. * * @param {string} [requestMessage.tokenSecret] OAuth access token secret. * * @param {string} [requestMessage.refreshToken] OAuth refresh token. * * @param {date} [requestMessage.expirationTime] OAuth token expiration. * * @param {string} [requestMessage.kind] Kind of resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SourceControl} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SourceControl} [result] - The deserialized result object if an error did not occur. * See {@link SourceControl} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ updateSourceControl(sourceControlType: string, requestMessage: models.SourceControl, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SourceControl>; updateSourceControl(sourceControlType: string, requestMessage: models.SourceControl, callback: ServiceCallback<models.SourceControl>): void; updateSourceControl(sourceControlType: string, requestMessage: models.SourceControl, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SourceControl>): void; /** * @summary Gets a list of meters for a given location. * * Gets a list of meters for a given location. * * @param {object} [options] Optional Parameters. * * @param {string} [options.billingLocation] Azure Location of billable * resource * * @param {string} [options.osType] App Service OS type meters used for * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BillingMeterCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listBillingMetersWithHttpOperationResponse(options?: { billingLocation? : string, osType? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.BillingMeterCollection>>; /** * @summary Gets a list of meters for a given location. * * Gets a list of meters for a given location. * * @param {object} [options] Optional Parameters. * * @param {string} [options.billingLocation] Azure Location of billable * resource * * @param {string} [options.osType] App Service OS type meters used for * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {BillingMeterCollection} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {BillingMeterCollection} [result] - The deserialized result object if an error did not occur. * See {@link BillingMeterCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listBillingMeters(options?: { billingLocation? : string, osType? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.BillingMeterCollection>; listBillingMeters(callback: ServiceCallback<models.BillingMeterCollection>): void; listBillingMeters(options: { billingLocation? : string, osType? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.BillingMeterCollection>): void; /** * @summary Check if a resource name is available. * * Check if a resource name is available. * * @param {string} name Resource name to verify. * * @param {string} type Resource type used for verification. Possible values * include: 'Site', 'Slot', 'HostingEnvironment', 'PublishingUser', * 'Microsoft.Web/sites', 'Microsoft.Web/sites/slots', * 'Microsoft.Web/hostingEnvironments', 'Microsoft.Web/publishingUsers' * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.isFqdn] Is fully qualified domain name. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResourceNameAvailability>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ checkNameAvailabilityWithHttpOperationResponse(name: string, type: string, options?: { isFqdn? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResourceNameAvailability>>; /** * @summary Check if a resource name is available. * * Check if a resource name is available. * * @param {string} name Resource name to verify. * * @param {string} type Resource type used for verification. Possible values * include: 'Site', 'Slot', 'HostingEnvironment', 'PublishingUser', * 'Microsoft.Web/sites', 'Microsoft.Web/sites/slots', * 'Microsoft.Web/hostingEnvironments', 'Microsoft.Web/publishingUsers' * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.isFqdn] Is fully qualified domain name. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResourceNameAvailability} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResourceNameAvailability} [result] - The deserialized result object if an error did not occur. * See {@link ResourceNameAvailability} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ checkNameAvailability(name: string, type: string, options?: { isFqdn? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.ResourceNameAvailability>; checkNameAvailability(name: string, type: string, callback: ServiceCallback<models.ResourceNameAvailability>): void; checkNameAvailability(name: string, type: string, options: { isFqdn? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResourceNameAvailability>): void; /** * @summary Gets list of available geo regions plus ministamps * * Gets list of available geo regions plus ministamps * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DeploymentLocations>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getSubscriptionDeploymentLocationsWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DeploymentLocations>>; /** * @summary Gets list of available geo regions plus ministamps * * Gets list of available geo regions plus ministamps * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DeploymentLocations} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DeploymentLocations} [result] - The deserialized result object if an error did not occur. * See {@link DeploymentLocations} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getSubscriptionDeploymentLocations(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DeploymentLocations>; getSubscriptionDeploymentLocations(callback: ServiceCallback<models.DeploymentLocations>): void; getSubscriptionDeploymentLocations(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DeploymentLocations>): void; /** * @summary Get a list of available geographical regions. * * Get a list of available geographical regions. * * @param {object} [options] Optional Parameters. * * @param {string} [options.sku] Name of SKU used to filter the regions. * Possible values include: 'Free', 'Shared', 'Basic', 'Standard', 'Premium', * 'Dynamic', 'Isolated', 'PremiumV2', 'ElasticPremium', 'ElasticIsolated' * * @param {boolean} [options.linuxWorkersEnabled] Specify <code>true</code> if * you want to filter to only regions that support Linux workers. * * @param {boolean} [options.xenonWorkersEnabled] Specify <code>true</code> if * you want to filter to only regions that support Xenon workers. * * @param {boolean} [options.linuxDynamicWorkersEnabled] Specify * <code>true</code> if you want to filter to only regions that support Linux * Consumption Workers. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GeoRegionCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listGeoRegionsWithHttpOperationResponse(options?: { sku? : string, linuxWorkersEnabled? : boolean, xenonWorkersEnabled? : boolean, linuxDynamicWorkersEnabled? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GeoRegionCollection>>; /** * @summary Get a list of available geographical regions. * * Get a list of available geographical regions. * * @param {object} [options] Optional Parameters. * * @param {string} [options.sku] Name of SKU used to filter the regions. * Possible values include: 'Free', 'Shared', 'Basic', 'Standard', 'Premium', * 'Dynamic', 'Isolated', 'PremiumV2', 'ElasticPremium', 'ElasticIsolated' * * @param {boolean} [options.linuxWorkersEnabled] Specify <code>true</code> if * you want to filter to only regions that support Linux workers. * * @param {boolean} [options.xenonWorkersEnabled] Specify <code>true</code> if * you want to filter to only regions that support Xenon workers. * * @param {boolean} [options.linuxDynamicWorkersEnabled] Specify * <code>true</code> if you want to filter to only regions that support Linux * Consumption Workers. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GeoRegionCollection} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GeoRegionCollection} [result] - The deserialized result object if an error did not occur. * See {@link GeoRegionCollection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listGeoRegions(options?: { sku? : string, linuxWorkersEnabled? : boolean, xenonWorkersEnabled? : boolean, linuxDynamicWorkersEnabled? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.GeoRegionCollection>; listGeoRegions(callback: ServiceCallback<models.GeoRegionCollection>): void; listGeoRegions(options: { sku? : string, linuxWorkersEnabled? : boolean, xenonWorkersEnabled? : boolean, linuxDynamicWorkersEnabled? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GeoRegionCollection>): void; /** * @summary List all apps that are assigned to a hostname. * * List all apps that are assigned to a hostname. * * @param {object} [options] Optional Parameters. * * @param {string} [options.name] Name of the object. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IdentifierCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listSiteIdentifiersAssignedToHostNameWithHttpOperationResponse(options?: { name? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IdentifierCollection>>; /** * @summary List all apps that are assigned to a hostname. * * List all apps that are assigned to a hostname. * * @param {object} [options] Optional Parameters. * * @param {string} [options.name] Name of the object. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IdentifierCollection} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IdentifierCollection} [result] - The deserialized result object if an error did not occur. * See {@link IdentifierCollection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listSiteIdentifiersAssignedToHostName(options?: { name? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.IdentifierCollection>; listSiteIdentifiersAssignedToHostName(callback: ServiceCallback<models.IdentifierCollection>): void; listSiteIdentifiersAssignedToHostName(options: { name? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IdentifierCollection>): void; /** * @summary List all premier add-on offers. * * List all premier add-on offers. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PremierAddOnOfferCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listPremierAddOnOffersWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PremierAddOnOfferCollection>>; /** * @summary List all premier add-on offers. * * List all premier add-on offers. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PremierAddOnOfferCollection} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PremierAddOnOfferCollection} [result] - The deserialized result object if an error did not occur. * See {@link PremierAddOnOfferCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listPremierAddOnOffers(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PremierAddOnOfferCollection>; listPremierAddOnOffers(callback: ServiceCallback<models.PremierAddOnOfferCollection>): void; listPremierAddOnOffers(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PremierAddOnOfferCollection>): void; /** * @summary List all SKUs. * * List all SKUs. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SkuInfos>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listSkusWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SkuInfos>>; /** * @summary List all SKUs. * * List all SKUs. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SkuInfos} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SkuInfos} [result] - The deserialized result object if an error did not occur. * See {@link SkuInfos} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listSkus(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SkuInfos>; listSkus(callback: ServiceCallback<models.SkuInfos>): void; listSkus(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SkuInfos>): void; /** * @summary Verifies if this VNET is compatible with an App Service Environment * by analyzing the Network Security Group rules. * * Verifies if this VNET is compatible with an App Service Environment by * analyzing the Network Security Group rules. * * @param {object} parameters VNET information * * @param {string} [parameters.vnetResourceGroup] The Resource Group of the * VNET to be validated * * @param {string} [parameters.vnetName] The name of the VNET to be validated * * @param {string} [parameters.vnetSubnetName] The subnet name to be validated * * @param {string} [parameters.kind] Kind of resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<VnetValidationFailureDetails>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ verifyHostingEnvironmentVnetWithHttpOperationResponse(parameters: models.VnetParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VnetValidationFailureDetails>>; /** * @summary Verifies if this VNET is compatible with an App Service Environment * by analyzing the Network Security Group rules. * * Verifies if this VNET is compatible with an App Service Environment by * analyzing the Network Security Group rules. * * @param {object} parameters VNET information * * @param {string} [parameters.vnetResourceGroup] The Resource Group of the * VNET to be validated * * @param {string} [parameters.vnetName] The name of the VNET to be validated * * @param {string} [parameters.vnetSubnetName] The subnet name to be validated * * @param {string} [parameters.kind] Kind of resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {VnetValidationFailureDetails} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {VnetValidationFailureDetails} [result] - The deserialized result object if an error did not occur. * See {@link VnetValidationFailureDetails} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ verifyHostingEnvironmentVnet(parameters: models.VnetParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VnetValidationFailureDetails>; verifyHostingEnvironmentVnet(parameters: models.VnetParameters, callback: ServiceCallback<models.VnetValidationFailureDetails>): void; verifyHostingEnvironmentVnet(parameters: models.VnetParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VnetValidationFailureDetails>): void; /** * @summary Move resources between resource groups. * * Move resources between resource groups. * * @param {string} resourceGroupName Name of the resource group to which the * resource belongs. * * @param {object} moveResourceEnvelope Object that represents the resource to * move. * * @param {string} [moveResourceEnvelope.targetResourceGroup] * * @param {array} [moveResourceEnvelope.resources] * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ moveWithHttpOperationResponse(resourceGroupName: string, moveResourceEnvelope: models.CsmMoveResourceEnvelope, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Move resources between resource groups. * * Move resources between resource groups. * * @param {string} resourceGroupName Name of the resource group to which the * resource belongs. * * @param {object} moveResourceEnvelope Object that represents the resource to * move. * * @param {string} [moveResourceEnvelope.targetResourceGroup] * * @param {array} [moveResourceEnvelope.resources] * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ move(resourceGroupName: string, moveResourceEnvelope: models.CsmMoveResourceEnvelope, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; move(resourceGroupName: string, moveResourceEnvelope: models.CsmMoveResourceEnvelope, callback: ServiceCallback<void>): void; move(resourceGroupName: string, moveResourceEnvelope: models.CsmMoveResourceEnvelope, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Validate if a resource can be created. * * Validate if a resource can be created. * * @param {string} resourceGroupName Name of the resource group to which the * resource belongs. * * @param {object} validateRequest Request with the resources to validate. * * @param {string} validateRequest.name Resource name to verify. * * @param {string} validateRequest.type Resource type used for verification. * Possible values include: 'ServerFarm', 'Site' * * @param {string} validateRequest.location Expected location of the resource. * * @param {string} [validateRequest.serverFarmId] ARM resource ID of an App * Service plan that would host the app. * * @param {string} [validateRequest.skuName] Name of the target SKU for the App * Service plan. * * @param {boolean} [validateRequest.needLinuxWorkers] <code>true</code> if App * Service plan is for Linux workers; otherwise, <code>false</code>. * * @param {boolean} [validateRequest.isSpot] <code>true</code> if App Service * plan is for Spot instances; otherwise, <code>false</code>. * * @param {number} [validateRequest.capacity] Target capacity of the App * Service plan (number of VM's). * * @param {string} [validateRequest.hostingEnvironment] Name of App Service * Environment where app or App Service plan should be created. * * @param {boolean} [validateRequest.isXenon] <code>true</code> if App Service * plan is running as a windows container * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ValidateResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ validateWithHttpOperationResponse(resourceGroupName: string, validateRequest: models.ValidateRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ValidateResponse>>; /** * @summary Validate if a resource can be created. * * Validate if a resource can be created. * * @param {string} resourceGroupName Name of the resource group to which the * resource belongs. * * @param {object} validateRequest Request with the resources to validate. * * @param {string} validateRequest.name Resource name to verify. * * @param {string} validateRequest.type Resource type used for verification. * Possible values include: 'ServerFarm', 'Site' * * @param {string} validateRequest.location Expected location of the resource. * * @param {string} [validateRequest.serverFarmId] ARM resource ID of an App * Service plan that would host the app. * * @param {string} [validateRequest.skuName] Name of the target SKU for the App * Service plan. * * @param {boolean} [validateRequest.needLinuxWorkers] <code>true</code> if App * Service plan is for Linux workers; otherwise, <code>false</code>. * * @param {boolean} [validateRequest.isSpot] <code>true</code> if App Service * plan is for Spot instances; otherwise, <code>false</code>. * * @param {number} [validateRequest.capacity] Target capacity of the App * Service plan (number of VM's). * * @param {string} [validateRequest.hostingEnvironment] Name of App Service * Environment where app or App Service plan should be created. * * @param {boolean} [validateRequest.isXenon] <code>true</code> if App Service * plan is running as a windows container * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ValidateResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ValidateResponse} [result] - The deserialized result object if an error did not occur. * See {@link ValidateResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ validate(resourceGroupName: string, validateRequest: models.ValidateRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ValidateResponse>; validate(resourceGroupName: string, validateRequest: models.ValidateRequest, callback: ServiceCallback<models.ValidateResponse>): void; validate(resourceGroupName: string, validateRequest: models.ValidateRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ValidateResponse>): void; /** * @summary Validate whether a resource can be moved. * * Validate whether a resource can be moved. * * @param {string} resourceGroupName Name of the resource group to which the * resource belongs. * * @param {object} moveResourceEnvelope Object that represents the resource to * move. * * @param {string} [moveResourceEnvelope.targetResourceGroup] * * @param {array} [moveResourceEnvelope.resources] * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ validateMoveWithHttpOperationResponse(resourceGroupName: string, moveResourceEnvelope: models.CsmMoveResourceEnvelope, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Validate whether a resource can be moved. * * Validate whether a resource can be moved. * * @param {string} resourceGroupName Name of the resource group to which the * resource belongs. * * @param {object} moveResourceEnvelope Object that represents the resource to * move. * * @param {string} [moveResourceEnvelope.targetResourceGroup] * * @param {array} [moveResourceEnvelope.resources] * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ validateMove(resourceGroupName: string, moveResourceEnvelope: models.CsmMoveResourceEnvelope, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; validateMove(resourceGroupName: string, moveResourceEnvelope: models.CsmMoveResourceEnvelope, callback: ServiceCallback<void>): void; validateMove(resourceGroupName: string, moveResourceEnvelope: models.CsmMoveResourceEnvelope, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Gets the source controls available for Azure websites. * * Gets the source controls available for Azure websites. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SourceControlCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listSourceControlsNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SourceControlCollection>>; /** * @summary Gets the source controls available for Azure websites. * * Gets the source controls available for Azure websites. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SourceControlCollection} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SourceControlCollection} [result] - The deserialized result object if an error did not occur. * See {@link SourceControlCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listSourceControlsNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SourceControlCollection>; listSourceControlsNext(nextPageLink: string, callback: ServiceCallback<models.SourceControlCollection>): void; listSourceControlsNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SourceControlCollection>): void; /** * @summary Gets a list of meters for a given location. * * Gets a list of meters for a given location. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BillingMeterCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listBillingMetersNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.BillingMeterCollection>>; /** * @summary Gets a list of meters for a given location. * * Gets a list of meters for a given location. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {BillingMeterCollection} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {BillingMeterCollection} [result] - The deserialized result object if an error did not occur. * See {@link BillingMeterCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listBillingMetersNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.BillingMeterCollection>; listBillingMetersNext(nextPageLink: string, callback: ServiceCallback<models.BillingMeterCollection>): void; listBillingMetersNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.BillingMeterCollection>): void; /** * @summary Get a list of available geographical regions. * * Get a list of available geographical regions. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GeoRegionCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listGeoRegionsNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GeoRegionCollection>>; /** * @summary Get a list of available geographical regions. * * Get a list of available geographical regions. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GeoRegionCollection} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GeoRegionCollection} [result] - The deserialized result object if an error did not occur. * See {@link GeoRegionCollection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listGeoRegionsNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.GeoRegionCollection>; listGeoRegionsNext(nextPageLink: string, callback: ServiceCallback<models.GeoRegionCollection>): void; listGeoRegionsNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GeoRegionCollection>): void; /** * @summary List all apps that are assigned to a hostname. * * List all apps that are assigned to a hostname. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IdentifierCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listSiteIdentifiersAssignedToHostNameNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IdentifierCollection>>; /** * @summary List all apps that are assigned to a hostname. * * List all apps that are assigned to a hostname. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IdentifierCollection} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IdentifierCollection} [result] - The deserialized result object if an error did not occur. * See {@link IdentifierCollection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listSiteIdentifiersAssignedToHostNameNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IdentifierCollection>; listSiteIdentifiersAssignedToHostNameNext(nextPageLink: string, callback: ServiceCallback<models.IdentifierCollection>): void; listSiteIdentifiersAssignedToHostNameNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IdentifierCollection>): void; /** * @summary List all premier add-on offers. * * List all premier add-on offers. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PremierAddOnOfferCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listPremierAddOnOffersNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PremierAddOnOfferCollection>>; /** * @summary List all premier add-on offers. * * List all premier add-on offers. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PremierAddOnOfferCollection} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PremierAddOnOfferCollection} [result] - The deserialized result object if an error did not occur. * See {@link PremierAddOnOfferCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listPremierAddOnOffersNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PremierAddOnOfferCollection>; listPremierAddOnOffersNext(nextPageLink: string, callback: ServiceCallback<models.PremierAddOnOfferCollection>): void; listPremierAddOnOffersNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PremierAddOnOfferCollection>): void; } export { WebSiteManagementClient, models as WebSiteManagementModels };
the_stack
import { Div, Scroll, TextNode, Hybrid, _CVD } from 'ftr'; import { Mynavpage } from './public'; const resolve = require.resolve; const icon_str = ` \ue900 \ue901 \ue902 \ue903 \ue904 \ue905 \ue906 \ue907 \ue908 \ue909 \ue90a \ue90b \ue90c \ue90d \ue90e \ue90f \ue910 \ue911 \ue912 \ue913 \ue914 \ue915 \ue916 \ue917 \ue918 \ue919 \ue91a \ue91b \ue91c \ue91d \ue91e \ue91f \ue920 \ue921 \ue922 \ue923 \ue924 \ue925 \ue926 \ue927 \ue928 \ue929 \ue92a \ue92b \ue92c \ue92d \ue92e \ue92f \ue930 \ue931 \ue932 \ue933 \ue934 \ue935 \ue936 \ue937 \ue938 \ue939 \ue93a \ue93b \ue93c \ue93d \ue93e \ue93f \ue940 \ue941 \ue942 \ue943 \ue944 \ue945 \ue946 \ue947 \ue948 \ue949 \ue94a \ue94b \ue94c \ue94d \ue94e \ue94f \ue950 \ue951 \ue952 \ue953 \ue954 \ue955 \ue956 \ue957 \ue958 \ue959 \ue95a \ue95b \ue95c \ue95d \ue95e \ue95f \ue960 \ue961 \ue962 \ue963 \ue964 \ue965 \ue966 \ue967 \ue968 \ue969 \ue96a \ue96b \ue96c \ue96d \ue96e \ue96f \ue970 \ue971 \ue972 \ue973 \ue974 \ue975 \ue976 \ue977 \ue978 \ue979 \ue97a \ue97b \ue97c \ue97d \ue97e \ue97f \ue980 \ue981 \ue982 \ue983 \ue984 \ue985 \ue986 \ue987 \ue988 \ue989 \ue98a \ue98b \ue98c \ue98d \ue98e \ue98f \ue990 \ue991 \ue992 \ue993 \ue994 \ue995 \ue996 \ue997 \ue998 \ue999 \ue99a \ue99b \ue99c \ue99d \ue99e \ue99f \ue9a0 \ue9a1 \ue9a2 \ue9a3 \ue9a4 \ue9a5 \ue9a6 \ue9a7 \ue9a8 \ue9a9 \ue9aa \ue9ab \ue9ac \ue9ad \ue9ae \ue9af \ue9b0 \ue9b1 \ue9b2 \ue9b3 \ue9b4 \ue9b5 \ue9b6 \ue9b7 \ue9b8 \ue9b9 \ue9ba \ue9bb \ue9bc \ue9bd \ue9be \ue9bf \ue9c0 \ue9c1 \ue9c2 \ue9c3 \ue9c4 \ue9c5 \ue9c6 \ue9c7 \ue9c8 \ue9c9 \ue9ca \ue9cb \ue9cc \ue9cd \ue9ce \ue9cf \ue9d0 \ue9d1 \ue9d2 \ue9d3 \ue9d4 \ue9d5 \ue9d6 \ue9d7 \ue9d8 \ue9d9 \ue9da \ue9db \ue9dc \ue9dd \ue9de \ue9df \ue9e0 \ue9e1 \ue9e2 \ue9e3 \ue9e4 \ue9e5 \ue9e6 \ue9e7 \ue9e8 \ue9e9 \ue9ea \ue9eb \ue9ec \ue9ed \ue9ee \ue9ef \ue9f0 \ue9f1 \ue9f2 \ue9f3 \ue9f4 \ue9f5 \ue9f6 \ue9f7 \ue9f8 \ue9f9 \ue9fa \ue9fb \ue9fc \ue9fd \ue9fe \ue9ff \uea00 \uea01 \uea02 \uea03 \uea04 \uea05 \uea06 \uea07 \uea08 \uea09 \uea0a \uea0b \uea0c \uea0d \uea0e \uea0f \uea10 \uea11 \uea12 \uea13 \uea14 \uea15 \uea16 \uea17 \uea18 \uea19 \uea1a \uea1b \uea1c \uea1d \uea1e \uea1f \uea20 \uea21 \uea22 \uea23 \uea24 \uea25 \uea26 \uea27 \uea28 \uea29 \uea2a \uea2b \uea2c \uea2d \uea2e \uea2f \uea30 \uea31 \uea32 \uea33 \uea34 \uea35 \uea36 \uea37 \uea38 \uea39 \uea3a \uea3b \uea3c \uea3d \uea3e \uea3f \uea40 \uea41 \uea42 \uea43 \uea44 \uea45 \uea46 \uea47 \uea48 \uea49 \uea4a \uea4b \uea4c \uea4d \uea4e \uea4f \uea50 \uea51 \uea52 \uea53 \uea54 \uea55 \uea56 \uea57 \uea58 \uea59 \uea5a \uea5b \uea5c \uea5d \uea5e \uea5f \uea60 \uea61 \uea62 \uea63 \uea64 \uea65 \uea66 \uea67 \uea68 \uea69 \uea6a \uea6b \uea6c \uea6d \uea6e \uea6f \uea70 \uea71 \uea72 \uea73 \uea74 \uea75 \uea76 \uea77 \uea78 \uea79 \uea7a \uea7b \uea7c \uea7d \uea7e \uea7f \uea80 \uea81 \uea82 \uea83 \uea84 \uea85 \uea86 \uea87 \uea88 \uea89 \uea8a \uea8b \uea8c \uea8d \uea8e \uea8f \uea90 \uea91 \uea92 \uea93 \uea94 \uea95 \uea96 \uea97 \uea98 \uea99 \uea9a \uea9b \uea9c \uea9d \uea9e \uea9f \ueaa0 \ueaa1 \ueaa2 \ueaa3 \ueaa4 \ueaa5 \ueaa6 \ueaa7 \ueaa8 \ueaa9 \ueaaa \ueaab \ueaac \ueaad \ueaae \ueaaf \ueab0 \ueab1 \ueab2 \ueab3 \ueab4 \ueab5 \ueab6 \ueab7 \ueab8 \ueab9 \ueaba \ueabb \ueabc \ueabd \ueabe \ueabf \ueac0 \ueac1 \ueac2 \ueac3 \ueac4 \ueac5 \ueac6 \ueac7 \ueac8 \ueac9 \ueaca \ueacb \ueacc \ueacd \ueace \ueacf \uead0 \uead1 \uead2 \uead3 \uead4 \uead5 \uead6 \uead7 \uead8 \uead9 \ueada \ueadb \ueadc \ueadd \ueade \ueadf \ueae0 \ueae1 \ueae2 \ueae3 \ueae4 \ueae5 \ueae6 \ueae7 \ueae8 \ueae9 \ueaea \ueaeb \ueaec \ueaed \ueaee \ueaef \ueaf0 \ueaf1 \ueaf2 \ueaf3 \ueaf4 \ueaf5 \ueaf6 \ueaf7 \ueaf8 \ueaf9 \ueafa \ueafb \ueafc \ueafd \ueafe \ueaff \ueb00 \ueb01 \ueb02 \ueb03 \ueb04 \ueb05 \ueb06 \ueb07 \ueb08 \ueb09 \ueb0a \ueb0b \ueb0c \ueb0d \ueb0e \ueb0f \ueb10 \ueb11 \ueb12 \ueb13 \ueb14 \ueb15 \ueb16 \ueb17 \ueb18 \ueb19 \ueb1a \ueb1b \ueb1c \ueb1d \ueb1e \ueb1f \ueb20 \ueb21 \ueb22 \ueb23 \ueb24 \ueb25 \ueb26 \ueb27 \ueb28 \ueb29 \ueb2a \ueb2b \ueb2c \ueb2d \ueb2e \ueb2f \ueb30 \ueb31 \ueb32 \ueb33 \ueb34 \ueb35 \ueb36 \ueb37 \ueb38 \ueb39 \ueb3a \ueb3b \ueb3c \ueb3d \ueb3e \ueb3f \ueb40 \ueb41 \ueb42 \ueb43 \ueb44 \ueb45 \ueb46 \ueb47 \ueb48 \ueb49 \ueb4a \ueb4b \ueb4c \ueb4d \ueb4e \ueb4f \ueb50 \ueb51 \ueb52 \ueb53 \ueb54 \ueb55 \ueb56 \ueb57 \ueb58 \ueb59 \ueb5a \ueb5b \ueb5c \ueb5d \ueb5e \ueb5f \ueb60 \ueb61 \ueb62 \ueb63 \ueb64 \ueb65 \ueb66 \ueb67 \ueb68 \ueb69 \ueb6a \ueb6b \ueb6c \ueb6d \ueb6e \ueb6f \ueb70 \ueb71 \ueb72 \ueb73 \ueb74 \ueb75 \ueb76 \ueb77 \ueb78 \ueb79 \ueb7a \ueb7b \ueb7c \ueb7d \ueb7e \ueb7f \ueb80 \ueb81 \ueb82 \ueb83 \ueb84 \ueb85 \ueb86 \ueb87 \ueb88 \ueb89 \ueb8a \ueb8b \ueb8c \ueb8d \ueb8e \ueb8f \ueb90 \ueb91 \ueb92 \ueb93 \ueb94 \ueb95 \ueb96 \ueb97 \ueb98 \ueb99 \ueb9a \ueb9b \ueb9c \ueb9d \ueb9e \ueb9f \ueba0 \ueba1 \ueba2 \ueba3 \ueba4 \ueba5 \ueba6 \ueba7 \ueba8 \ueba9 \uebaa \uebab \uebac \uebad \uebae \uebaf \uebb0 \uebb1 \uebb2 \uebb3 \uebb4 \uebb5 \uebb6 \uebb7 \uebb8 \uebb9 \uebba \uebbb \uebbc \uebbd \uebbe \uebbf \uebc0 \uebc1 \uebc2 \uebc3 \uebc4 \uebc5 \uebc6 \uebc7 \uebc8 \uebc9 \uebca \uebcb \uebcc \uebcd \uebce \uebcf \uebd0 \uebd1 \uebd2 \uebd3 \uebd4 \uebd5 \uebd6 \uebd7 \uebd8 \uebd9 \uebda \uebdb \uebdc \uebdd \uebde \uebdf \uebe0 \uebe1 \uebe2 \uebe3 \uebe4 \uebe5 \uebe6 \uebe7 \uebe8 \uebe9 \uebea \uebeb \uebec \uebed \uebee \uebef \uebf0 \uebf1 \uebf2 \uebf3 \uebf4 \uebf5 \uebf6 \uebf7 \uebf8 \uebf9 \uebfa \uebfb \uebfc \uebfd \uebfe \uebff \uec00 \uec01 \uec02 \uec03 \uec04 \uec05 \uec06 \uec07 \uec08 \uec09 \uec0a \uec0b \uec0c \uec0d \uec0e \uec0f \uec10 \uec11 \uec12 \uec13 \uec14 \uec15 \uec16 \uec17 \uec18 \uec19 \uec1a \uec1b \uec1c \uec1d \uec1e \uec1f \uec20 \uec21 \uec22 \uec23 \uec24 \uec25 \uec26 \uec27 \uec28 \uec29 \uec2a \uec2b \uec2c \uec2d \uec2e \uec2f \uec30 \uec31 \uec32 \uec33 \uec34 \uec35 \uec36 \uec37 \uec38 \uec39 \uec3a \uec3b \uec3c \uec3d \uec3e \uec3f \uec40 \uec41 \uec42 \uec43 \uec44 \uec45 \uec46 \uec47 \uec48 \uec49 \uec4a \uec4b \uec4c \uec4d \uec4e \uec4f \uec50 \uec51 \uec52 \uec53 \uec54 \uec55 \uec56 \uec57 \uec58 \uec59 \uec5a \uec5b \uec5c \uec5d \uec5e \uec5f \uec60 \uec61 \uec62 \uec63 \uec64 \uec65 \uec66 \uec67 \uec68 \uec69 \uec6a \uec6b \uec6c \uec6d \uec6e \uec6f \uec70 \uec71 \uec72 \uec73 \uec74 \uec75 \uec76 \uec77 \uec78 \uec79 \uec7a \uec7b \uec7c \uec7d \uec7e \uec7f \uec80 \uec81 \uec82 \uec83 \uec84 \uec85 \uec86 \uec87 \uec88 \uec89 \uec8a \uec8b \uec8c \uec8d \uec8e \uec8f \uec90 \uec91 \uec92 \uec93 \uec94 \uec95 \uec96 \uec97 \uec98 \uec99 \uec9a \uec9b \uec9c \uec9d \uec9e \uec9f \ueca0 \ueca1 \ueca2 \ueca3 \ueca4 \ueca5 \ueca6 \ueca7 \ueca8 \ueca9 \uecaa \uecab \uecac \uecad \uecae \uecaf \uecb0 \uecb1 \uecb2 \uecb3 \uecb4 \uecb5 \uecb6 \uecb7 \uecb8 \uecb9 \uecba \uecbb \uecbc \uecbd \uecbe \uecbf \uecc0 \uecc1 \uecc2 \uecc3 \uecc4 \uecc5 \uecc6 \uecc7 \uecc8 \uecc9 \uecca \ueccb \ueccc \ueccd \uecce \ueccf \uecd0 \uecd1 \uecd2 \uecd3 \uecd4 \uecd5 \uecd6 \uecd7 \uecd8 \uecd9 \uecda \uecdb \uecdc \uecdd \uecde \uecdf \uece0 \uece1 \uece2 \uece3 \uece4 \uece5 \uece6 \uece7 \uece8 \uece9 \uecea \ueceb \uecec \ueced \uecee \uecef \uecf0 \uecf1 \uecf2 \uecf3 \uecf4 \uecf5 \uecf6 \uecf7 \uecf8 \uecf9 \uecfa \uecfb \uecfc \uecfd \uecfe \uecff \ued00 \ued01 \ued02 \ued03 \ued04 \ued05 \ued06 \ued07 \ued08 \ued09 \ued0a \ued0b \ued0c \ued0d \ued0e \ued0f \ued10 \ued11 \ued12 \ued13 \ued14 \ued15 \ued16 \ued17 \ued18 \ued19 \ued1a \ued1b \ued1c \ued1d \ued1e \ued1f \ued20 \ued21 \ued22 \ued23 \ued24 \ued25 \ued26 \ued27 \ued28 \ued29 \ued2a \ued2b \ued2c \ued2d \ued2e \ued2f \ued30 \ued31 \ued32 \ued33 \ued34 \ued35 \ued36 \ued37 \ued38 \ued39 \ued3a \ued3b \ued3c \ued3d \ued3e \ued3f \ued40 \ued41 \ued42 \ued43 \ued44 \ued45 \ued46 \ued47 \ued48 \ued49 \ued4a \ued4b \ued4c \ued4d \ued4e \ued4f \ued50 \ued51 \ued52 \ued53 \ued54 \ued55 \ued56 \ued57 \ued58 \ued59 \ued5a \ued5b \ued5c \ued5d \ued5e \ued5f \ued60 \ued61 \ued62 \ued63 \ued64 \ued65 \ued66 \ued67 \ued68 \ued69 \ued6a \ued6b \ued6c \ued6d \ued6e \ued6f \ued70 \ued71 \ued72 \ued73 \ued74 \ued75 \ued76 \ued77 \ued78 \ued79 \ued7a \ued7b \ued7c \ued7d \ued7e \ued7f \ued80 \ued81 \ued82 \ued83 \ued84 \ued85 \ued86 \ued87 \ued88 \ued89 \ued8a \ued8b \ued8c \ued8d \ued8e \ued8f \ued90 \ued91 \ued92 \ued93 \ued94 \ued95 \ued96 \ued97 \ued98 \ued99 \ued9a \ued9b \ued9c \ued9d \ued9e \ued9f \ueda0 \ueda1 \ueda2 \ueda3 \ueda4 \ueda5 \ueda6 \ueda7 \ueda8 \ueda9 \uedaa \uedab \uedac \uedad \uedae \uedaf \uedb0 \uedb1 \uedb2 \uedb3 \uedb4 \uedb5 \uedb6 \uedb7 \uedb8 \uedb9 \uedba \uedbb \uedbc \uedbd \uedbe \uedbf \uedc0 \uedc1 \uedc2 \uedc3 \uedc4 \uedc5 \uedc6 \uedc7 \uedc8 \uedc9 \uedca \uedcb \uedcc \uedcd \uedce \uedcf \uedd0 \uedd1 \uedd2 \uedd3 \uedd4 \uedd5 \uedd6 \uedd7 \uedd8 \uedd9 \uedda \ueddb \ueddc \ueddd \uedde \ueddf \uede0 \uede1 \uede2 \uede3 \uede4 \uede5 \uede6 \uede7 \uede8 \uede9 \uedea \uedeb \uedec \ueded \uedee \uedef \uedf0 \uedf1 \uedf2 \uedf3 \uedf4 \uedf5 \uedf6 \uedf7 \uedf8 \uedf9 \uedfa \uedfb \uedfc \uedfd \uedfe \uedff \uee00 \uee01 \uee02 \uee03 \uee04 \uee05 \uee06 \uee07 \uee08 \uee09 \uee0a \uee0b \uee0c \uee0d \uee0e \uee0f \uee10 \uee11 \uee12 \uee13 \uee14 \uee15 \uee16 \uee17 \uee18 \uee19 \uee1a \uee1b \uee1c \uee1d \uee1e \uee1f \uee20 \uee21 \uee22 \uee23 \uee24 \uee25 \uee26 \uee27 \uee28 \uee29 \uee2a \uee2b \uee2c \uee2d \uee2e \uee2f \uee30 \uee31 \uee32 \uee33 \uee34 \uee35 \uee36 \uee37 \uee38 \uee39 \uee3a \uee3b \uee3c \uee3d \uee3e \uee3f \uee40 \uee41 \uee42 \uee43 \uee44 \uee45 \uee46 \uee47 \uee48 \uee49 \uee4a \uee4b \uee4c \uee4d \uee4e \uee4f \uee50 \uee51 \uee52 \uee53 \uee54 \uee55 \uee56 \uee57 \uee58 \uee59 \uee5a \uee5b \uee5c \uee5d \uee5e \uee5f \uee60 \uee61 \uee62 \uee63 \uee64 \uee65 \uee66 \uee67 \uee68 \uee69 \uee6a \uee6b \uee6c \uee6d \uee6e \uee6f \uee70 \uee71 \uee72 \uee73 \uee74 \uee75 \uee76 \uee77 \uee78 \uee79 \uee7a \uee7b \uee7c \uee7d \uee7e \uee7f \uee80 \uee81 \uee82 \uee83 \uee84 \uee85 \uee86 \uee87 \uee88 \uee89 \uee8a \uee8b \uee8c \uee8d \uee8e \uee8f \uee90 \uee91 \uee92 \uee93 \uee94 \uee95 \uee96 \uee97 \uee98 \uee99 \uee9a \uee9b \uee9c \uee9d \uee9e \uee9f \ueea0 \ueea1 \ueea2 \ueea3 \ueea4 \ueea5 \ueea6 \ueea7 \ueea8 \ueea9 \ueeaa \ueeab \ueeac \ueead \ueeae \ueeaf \ueeb0 \ueeb1 \ueeb2 \ueeb3 \ueeb4 \ueeb5 \ueeb6 \ueeb7 \ueeb8 \ueeb9 \ueeba \ueebb \ueebc \ueebd \ueebe \ueebf \ueec0 \ueec1 \ueec2 \ueec3 \ueec4 \ueec5 \ueec6 \ueec7 \ueec8 \ueec9 \ueeca \ueecb \ueecc \ueecd \ueece \ueecf \ueed0 \ueed1 \ueed2 \ueed3 \ueed4 \ueed5 \ueed6 \ueed7 \ueed8 \ueed9 \ueeda \ueedb \ueedc \ueedd \ueede \ueedf \ueee0 \ueee1 \ueee2 \ueee3 \ueee4 \ueee5 \ueee6 \ueee7 \ueee8 \ueee9 \ueeea \ueeeb \ueeec \ueeed \ueeee \ueeef \ueef0 \ueef1 \ueef2 \ueef3 \ueef4 \ueef5 \ueef6 \ueef7 \ueef8 \ueef9 \ueefa \ueefb \ueefc \ueefd \ueefe \ueeff \uef00 \uef01 \uef02 \uef03 \uef04 \uef05 \uef06 \uef07 \uef08 \uef09 \uef0a \uef0b \uef0c \uef0d \uef0e \uef0f \uef10 \uef11 \uef12 \uef13 \uef14 \uef15 \uef16 \uef17 \uef18 \uef19 \uef1a \uef1b \uef1c \uef1d \uef1e \uef1f \uef20 \uef21 \uef22 \uef23 \uef24 \uef25 \uef26 \uef27 \uef28 \uef29 \uef2a \uef2b \uef2c \uef2d \uef2e \uef2f \uef30 \uef31 \uef32 \uef33 \uef34 \uef35 \uef36 \uef37 \uef38 \uef39 \uef3a \uef3b \uef3c \uef3d \uef3e \uef3f \uef40 \uef41 \uef42 \uef43 \uef44 \uef45 \uef46 \uef47 \uef48 \uef49 `; class Controller extends Mynavpage { source = resolve(__filename); render() { return super.render( <Scroll width="full" height="full" bounceLock={0}> <Div margin={10} width="full"> { Array.from({length: icon_str.length}).map((e,i)=>{ var unicode = icon_str.charCodeAt(i); if (unicode > 255) { return ( <Hybrid marginBottom={10} textAlign="center" width="25%"> <TextNode textSize={28} textFamily="icomoon-ultimate" value={icon_str[i]} /> <TextNode textColor="#555" value={` ${unicode.toString(16)}`} /> </Hybrid> ); } }).filter(e=>e) } </Div> </Scroll> ); } } export default ()=>( <Controller title="Icons" /> );
the_stack