text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { Nes } from "./nes"; import { BitHelper } from "./bithelper"; import { Mirroring } from "./cartridge"; export class Memory { public ram: Uint8Array; public saveRam: Uint8Array; nes: Nes; inputCounter = 0; //controller 1 input //for performance //amazingly accessing this.nes.cartridge.prgBanks is slower than //this.prgBanksCopy seemingly because it needs to access a seperate object prgBanksCount = 0; chrBanksCount = 0; mapper = 0; prgDataLength = 0; prgData:Uint8Array; //Mapper variables prgMode = 0; prgBankSwitchable = 0; //index of prg bank that is switchable prgBank0offset = 0; //used to calculate offset into prg data based on current bank prgBank1offset = 0; prgBank2offset = 0; //used in mmc3 mapper prgBank3offset = 0; chrMode = 0; chrBank0 = 0; //which chr bank 0 is using chrBank1 = 0; //which chr bank 1 is using mapperShiftRegister = 0; //it takes 5 writes for MMC1, each right loads into this shift register mapperWriteCount = 0; //keeps track to know when the 5th write has occurred //MMC3 mmc3BankSelect = 0; mmc3PrgMode = 0; mmc3ChrA12 = 0; irqEnabled = false; irqCounter = 0; irqCounterReset = 0; irqReloadRequested = false; constructor(nes: Nes) { this.nes = nes; //currently covers the entire addressable rangle //however only 2k will come from ram //the rest gets routed based on mappers, cartridge, etc.. // this.ram = new Uint8Array(64 * 1024); this.ram = new Uint8Array(0xFFFF); //64 kb (large just to support sample program) this.saveRam = new Uint8Array(0x8000); //TEMPORARY - need to optimize } read(address: number): number { //Cartridge if (address >= 0x4020 && address <= 0xFFFF) { //this is the most common read function in the app //make sure to keep it LEAN if (this.mapper == 0) { let real_address = address - 0x8000; //MAPPER 0 //https://wiki.nesdev.com/w/index.php/NROM //handle 16kb rom vs 32kb rom if (this.prgBanksCount == 1) { //mirror second half of prg data if (real_address >= 16384) { real_address -= 16384 } } return this.prgData[real_address]; } else if (this.mapper == 1) { //MAPPER 1 if (address >= 0x8000) { let real_address = address - 0x8000; //BANK0 if (real_address < 16384) { real_address += this.prgBank0offset; } //BANK1 else { real_address += this.prgBank1offset; } //guard against going over length //example: palamedes game if (real_address>=this.prgDataLength) { real_address = real_address % this.prgData.length; } return this.prgData[real_address]; } else { //Save RAM return this.saveRam[address]; } } else if (this.mapper == 2) { let real_address = address - 0x8000; //BANK0 if (real_address < 16384) { real_address += this.prgBank0offset; } //BANK1 else { real_address += this.prgBank1offset; } return this.prgData[real_address]; } else if (this.mapper == 3) { let real_address = address - 0x8000; //handle 16kb rom vs 32kb rom if (this.prgBanksCount == 1) { //mirror second half of prg data if (real_address >= 16384) { real_address -= 16384 } } return this.prgData[real_address]; } else if (this.mapper == 4) { if (address >= 0x8000) { let real_address = address - 0x8000; //BANK0 if (real_address < 8192) { real_address += this.prgBank0offset; } //BANK1 else if (real_address < 16384) { real_address += this.prgBank1offset; } //BANK2 else if (real_address < 24576) { real_address += this.prgBank2offset; } //BANK3 else { real_address += this.prgBank3offset; } return this.prgData[real_address]; } else { //Save RAM return this.saveRam[address]; } } else if (this.mapper == 7) { let real_address = address - 0x8000; real_address += this.prgBank0offset return this.prgData[real_address]; } else if (this.mapper == -1) { //SAMPLEPROGRAM return this.ram[address]; } else { //catch all for other mappers for now let real_address = address - 0x8000; return this.prgData[real_address]; } } else { let real_address = this.mapAddress(address); //PPU if (address >= 0x2000 && address < 0x4000) { return this.nes.ppu.readRegister(real_address); } //APU else if (address >= 0x4000 && address <= 0x400F) { //does it ever read from APU? } //Controller else if (address >= 0x4016 && address < 0x4017) { //Controller 1 if (address == 0x4016) { if (this.inputCounter < 9) { this.inputCounter++; if (this.inputCounter == 1) return this.nes.inputController.Key_Action_A ? 65 : 64; //A if (this.inputCounter == 2) return this.nes.inputController.Key_Action_B ? 65 : 64; //B if (this.inputCounter == 3) return this.nes.inputController.Key_Action_Select ? 65 : 64; //Select if (this.inputCounter == 4) return this.nes.inputController.Key_Action_Start ? 65 : 64; //Start if (this.inputCounter == 5) return this.nes.inputController.Key_Up ? 65 : 64; //Up if (this.inputCounter == 6) return this.nes.inputController.Key_Down ? 65 : 64; //Down if (this.inputCounter == 7) return this.nes.inputController.Key_Left ? 65 : 64; //Left if (this.inputCounter == 8) return this.nes.inputController.Key_Right ? 65 : 64; //Right return 0; } } else return this.ram[real_address]; } else return this.ram[real_address]; } } write(address: number, value: number) { var real_address = this.mapAddress(address); //Cartridge if (address >= 0x4020 && address <= 0xFFFF) { if (address >= 0x8000) { //Mapper 1 if (this.mapper == 1) { //REFERENCE //https://wiki.nesdev.com/w/index.php/MMC1 //if bit 7 is set, clear the mapper shiftRegister if (BitHelper.getBit(value, 7)) { this.mapperShiftRegister = 0; this.mapperWriteCount = 0; //reset it to it's initial state this.applyMapper1(0x8000, 0xc); } else //write to the shift register { this.mapperShiftRegister = this.mapperShiftRegister | (BitHelper.getBit(value, 0) << this.mapperWriteCount); this.mapperWriteCount++; if (this.mapperWriteCount == 5) { //fifth write, now apply to mapper this.applyMapper1(address, this.mapperShiftRegister); this.mapperShiftRegister = 0; this.mapperWriteCount = 0; } } } //Mapper 2 else if (this.mapper == 2) { this.prgBank0offset = value * 16384; } //Mapper 3 else if (this.mapper == 3) { // https://wiki.nesdev.com/w/index.php/CNROM //8kb chr rom bank switchable let chrBank = value & 0x3;//first 2 bits for (let i = 0; i < 8 * 1024; i++) { this.nes.cartridge.chrData[i] = this.nes.cartridge.chrDataAll[i + (8 * 1024 * chrBank)]; } } //Mapper 4 else if (this.mapper == 4) { //https://wiki.nesdev.com/w/index.php/MMC3 this.applyMapper3(address, value); } //Mapper 7 else if (this.mapper == 7) { //TODO mirroring // let mirroring = BitHelper.getBit(value,4); // if (mirroring!=0) // { // let debug=1; // } value = value & 7; this.prgBank0offset = value * 32768; } else if (this.mapper == -1) { //SAMPLEPROGRAM this.ram[address] = value; } } else //Save RAM { if (address>=this.saveRam.length || address<0) console.log('saveram out of range'); this.saveRam[address] = value; } } //PPU else if (address >= 0x2000 && address < 0x4000) { this.nes.ppu.writeRegister(real_address, value); } //APU else if (address >= 0x4000 && address <= 0x4013) { this.nes.apu.writeRegister(address, value); } //APU additional registers else if (address == 0x4015 || address == 0x4017) { this.nes.apu.writeRegister(address, value); } //OAM DMA else if (address == 0x4014) { this.nes.ppu.OAM_DMA_Copy(value); this.nes.cpu.cycles = 513; } //Controller else if (address == 0x4016) this.inputCounter = 0; else this.ram[real_address] = value; } mapAddress(address: number): number { var real_address = address; //2KB of internal ram //mirrored 4 times if (address < 0x2000) { //use modulo to simulate mirroring if (address > 0x07FF) { real_address = address % 0x0800; } } //ppu registers 0x2000-0x2007 //mirrored every 8 bytes else if (address >= 0x2000 && address < 0x4000) { if (address > 0x2008) { real_address = (address % 8) + 0x2000; } } //APU and I/O registers else if (address >= 0x4000 && address < 0x4018) { } return real_address; } //MAPPERS /* MMC1 Mapper */ applyMapper1(address: number, value: number) { if (address >= 0x8000 && address <= 0x9FFF) { //MAPPER CONTROL //set mirroring,prg mode,chr mode var mirroring = value & 0x3, prgMode = (value & 0xc) >> 2, chrMode = (value & 0x10) >> 4; if (mirroring == 2) this.nes.cartridge.mirroring = Mirroring.VERTICAL if (mirroring == 3) this.nes.cartridge.mirroring = Mirroring.HORIZONTAL; this.prgMode = prgMode; this.chrMode = chrMode; this.setPRGBanks(); } else if (address >= 0xA000 && address <= 0xBFFF) { //set chr bank 0 this.chrBank0 = value; this.setCHRBanks(); } else if (address >= 0xC000 && address <= 0xDFFF) { //set chr bank 1 this.chrBank1 = value; this.setCHRBanks(); } else if (address >= 0xE000 && address <= 0xFFFF) { //set prg bank let bank = value % 16; //only use first 4 bits, bit 5 controls prg ram this.prgBankSwitchable = bank; this.setPRGBanks(); } } setPRGBanks() { switch (this.prgMode) { case 0: this.prgBank0offset = this.prgBankSwitchable * 16384; this.prgBank1offset = (this.prgBankSwitchable) * 16384; break; case 2: this.prgBank0offset = 0; this.prgBank1offset = this.prgBankSwitchable * 16384; break; case 3: this.prgBank0offset = this.prgBankSwitchable * 16384; this.prgBank1offset = (16384 * (this.prgBanksCount - 2)); break; } } setCHRBanks() { switch (this.chrMode) { case 0: //switch all 8kb this.chrBank1 = this.chrBank0 + 1; break; case 1: //switch 2 seperate 4kb banks break; } let chrOffset0 = (4 * 1024 * this.chrBank0); let chrOffset1 = (4 * 1024 * this.chrBank1); //bank0 for (let i = 0; i < 4 * 1024; i++) { this.nes.cartridge.chrData[i] = this.nes.cartridge.chrDataAll[i + chrOffset0]; } //bank1 for (let i = 0; i < 4096; i++) { this.nes.cartridge.chrData[i + 4096] = this.nes.cartridge.chrDataAll[i + chrOffset1]; } } /* MMC3 Mapper 7 bit 0 ---- ---- CPMx xRRR ||| ||| ||| +++- Specify which bank register to update on next write to Bank Data register ||| 0: Select 2 KB CHR bank at PPU $0000-$07FF (or $1000-$17FF); ||| 1: Select 2 KB CHR bank at PPU $0800-$0FFF (or $1800-$1FFF); ||| 2: Select 1 KB CHR bank at PPU $1000-$13FF (or $0000-$03FF); ||| 3: Select 1 KB CHR bank at PPU $1400-$17FF (or $0400-$07FF); ||| 4: Select 1 KB CHR bank at PPU $1800-$1BFF (or $0800-$0BFF); ||| 5: Select 1 KB CHR bank at PPU $1C00-$1FFF (or $0C00-$0FFF); ||| 6: Select 8 KB PRG ROM bank at $8000-$9FFF (or $C000-$DFFF); ||| 7: Select 8 KB PRG ROM bank at $A000-$BFFF ||+------- Nothing on the MMC3, see MMC6 |+-------- PRG ROM bank mode (0: $8000-$9FFF swappable, | $C000-$DFFF fixed to second-last bank; | 1: $C000-$DFFF swappable, | $8000-$9FFF fixed to second-last bank) +--------- CHR A12 inversion (0: two 2 KB banks at $0000-$0FFF, four 1 KB banks at $1000-$1FFF; 1: two 2 KB banks at $1000-$1FFF, four 1 KB banks at $0000-$0FFF) */ applyMapper3(address: number, value: number) { let odd = address % 2 != 0; if (address >= 0x8000 && address <= 0x9FFF) { if (odd) { //set banks //otherwise batman doesn't work //was not clear from nesdev at all if (this.mmc3BankSelect == 0){ // 0: Select 2 KB CHR bank at PPU $0000-$07FF (or $1000-$17FF); let destinationOffset = 0; let sourceOffset = value*1024; if (this.mmc3ChrA12==1) destinationOffset += 0x1000; for (let i = 0; i < 0x800; i++) { this.nes.cartridge.chrData[i+destinationOffset] = this.nes.cartridge.chrDataAll[i + sourceOffset]; } }else if (this.mmc3BankSelect == 1){ // 1: Select 2 KB CHR bank at PPU $0800-$0FFF (or $1800-$1FFF); let destinationOffset = 0x800; let sourceOffset = value*1024; if (this.mmc3ChrA12==1) destinationOffset += 0x1000; for (let i = 0; i < 0x800; i++) { this.nes.cartridge.chrData[i+destinationOffset] = this.nes.cartridge.chrDataAll[i + sourceOffset]; } } else if (this.mmc3BankSelect==2){ // 2: Select 1 KB CHR bank at PPU $1000-$13FF (or $0000-$03FF) let destinationOffset = 0x1000; let sourceOffset = value*1024; if (this.mmc3ChrA12==1) destinationOffset -= 0x1000; for (let i = 0; i < 0x400; i++) { this.nes.cartridge.chrData[i+destinationOffset] = this.nes.cartridge.chrDataAll[i + sourceOffset]; } } else if (this.mmc3BankSelect==3){ // 3: Select 1 KB CHR bank at PPU $1400-$17FF (or $0400-$07FF); let destinationOffset = 0x1400; let sourceOffset = value*1024; if (this.mmc3ChrA12==1) destinationOffset -= 0x1000; for (let i = 0; i < 0x400; i++) { this.nes.cartridge.chrData[i+destinationOffset] = this.nes.cartridge.chrDataAll[i + sourceOffset]; } } else if (this.mmc3BankSelect==4){ // 4: Select 1 KB CHR bank at PPU $1800-$1BFF (or $0800-$0BFF); let destinationOffset = 0x1800; let sourceOffset = value*1024; if (this.mmc3ChrA12==1) destinationOffset -= 0x1000; for (let i = 0; i < 0x400; i++) { this.nes.cartridge.chrData[i+destinationOffset] = this.nes.cartridge.chrDataAll[i + sourceOffset]; } } else if (this.mmc3BankSelect==5){ // 5: Select 1 KB CHR bank at PPU $1C00-$1FFF (or $0C00-$0FFF); let destinationOffset = 0x1C00; let sourceOffset = value*1024; if (this.mmc3ChrA12==1) destinationOffset -= 0x1000; for (let i = 0; i < 0x400; i++) { this.nes.cartridge.chrData[i+destinationOffset] = this.nes.cartridge.chrDataAll[i + sourceOffset]; } } else if (this.mmc3BankSelect == 6) { // this.prgBank0offset = 8192 * Math.floor(value / 2) % this.nes.memory.prgBanksCount; // this.prgBank0offset = 8192 * (value & ( (this.prgBanksCount*2) - 1 )); value = value & ((this.prgBanksCount*2) - 1); if (this.mmc3PrgMode == 0) this.prgBank0offset = 8192 * value; else this.prgBank2offset = 8192 * (value-2); }else if (this.mmc3BankSelect == 7) { // this.prgBank1offset = 8192 * Math.floor(value / 2) % this.nes.memory.prgBanksCount; // this.prgBank1offset = 8192 * (value & ( (this.prgBanksCount*2) - 1 )); value = value & ((this.prgBanksCount*2) - 1); this.prgBank1offset = (8192 * (value-1)); } //this was hell to debug // if (this.prgBank0offset==81920 && this.readyLogger==false) // { // this.readyLogger = true; // console.log('ready logger'); // } // if (this.readyLogger && this.prgBank0offset==0) // { // this.nes.cpu.startLogging = true; // } // console.log('bank 10'); // if (this.prgBank1offset==8192) // let bank0 = (this.prgBank0offset/8192); // let bank1 = (this.prgBank1offset/8192); // console.log('Bank0: ' + bank0 + ' Bank1: ' + bank1); // this.nes.cpu.startLogging = true; // { // this.prgBank0offset = this.prgBank0offset = 8192 * 29 // } // if (bank0==30) } else { //set bank mode this.mmc3BankSelect = value & 7; //right 3 bits this.mmc3PrgMode = BitHelper.getBit(value, 6); this.mmc3ChrA12 = BitHelper.getBit(value, 7); if (this.mmc3PrgMode == 0) { // $8000-$9FFF swappable // $C000-$DFFF fixed to second-last bank this.prgBank2offset = (16384 * (this.prgBanksCount - 2)); } else { // $C000-$DFFF swappable // $8000-$9FFF fixed to second-last bank // this.prgBank0offset = (16384 * (this.prgBanksCount - 2)); this.prgBank0offset = (16384 * (this.prgBanksCount - 1)); // this.prgBank0offset = (8192*(this.prgBanksCount*2))-(8192*2); } } } else if (address >= 0xA000 && address <= 0xBFFF) { if (odd) { //set ram project } else { //set mirroring let mirroring = BitHelper.getBit(value,0); if (mirroring==0) this.nes.cartridge.mirroring = Mirroring.VERTICAL; else this.nes.cartridge.mirroring = Mirroring.HORIZONTAL; } } else if (address >= 0xC000 && address <= 0xDFFF) { if ( odd ) { this.reloadIRQ(); } else { this.irqLatch( value ); } } else if (address >= 0xE000 && address <= 0xFFFF) { if (odd) this.enableIRQ(); else this.disableIRQ(); } } reloadIRQ() { this.irqReloadRequested = true; } irqLatch( value:number ) { this.irqCounterReset = value; } enableIRQ( ) { this.irqEnabled = true; } disableIRQ( ) { this.irqEnabled = false; } clockScanlineCounter() { if( this.irqReloadRequested || !this.irqCounter ) { this.irqCounter = this.irqCounterReset; this.irqReloadRequested = false; } else { this.irqCounter--; if ( !this.irqCounter && this.irqEnabled ) { //doesn't work in super mario bros 3 if (!this.nes.isSmb3) this.nes.cpu.irqRequest(); } } } }
the_stack
import { StyledTemplateLanguageService } from 'typescript-styled-plugin/lib/api'; import { Logger, TemplateContext, TemplateLanguageService } from 'typescript-template-language-service-decorator'; import * as ts from 'typescript/lib/tsserverlibrary'; import { FoldingRange, LanguageService as HtmlLanguageService } from 'vscode-html-languageservice'; import * as vscode from 'vscode-languageserver-types'; import { Configuration } from './configuration'; import { getDocumentRegions } from './embeddedSupport'; import { VirtualDocumentProvider } from './virtual-document-provider'; const emptyCompletionList: vscode.CompletionList = { isIncomplete: false, items: [], }; interface HtmlCachedCompletionList { type: 'html'; value: vscode.CompletionList; } interface StyledCachedCompletionList { type: 'styled'; value: ts.CompletionInfo; } class CompletionsCache { private _cachedCompletionsFile?: string; private _cachedCompletionsPosition?: ts.LineAndCharacter; private _cachedCompletionsContent?: string; private _completions?: HtmlCachedCompletionList | StyledCachedCompletionList; public getCached( context: TemplateContext, position: ts.LineAndCharacter ): HtmlCachedCompletionList | StyledCachedCompletionList | undefined { if (this._completions && context.fileName === this._cachedCompletionsFile && this._cachedCompletionsPosition && arePositionsEqual(position, this._cachedCompletionsPosition) && context.text === this._cachedCompletionsContent ) { return this._completions; } return undefined; } public updateCached( context: TemplateContext, position: ts.LineAndCharacter, completions: HtmlCachedCompletionList | StyledCachedCompletionList ) { this._cachedCompletionsFile = context.fileName; this._cachedCompletionsPosition = position; this._cachedCompletionsContent = context.text; this._completions = completions; } } export default class HtmlTemplateLanguageService implements TemplateLanguageService { private _completionsCache = new CompletionsCache(); constructor( private readonly typescript: typeof ts, private readonly configuration: Configuration, private readonly virtualDocumentProvider: VirtualDocumentProvider, private readonly htmlLanguageService: HtmlLanguageService, private readonly styledLanguageService: StyledTemplateLanguageService, _logger: Logger ) { } public getCompletionsAtPosition( context: TemplateContext, position: ts.LineAndCharacter ): ts.CompletionInfo { const entry = this.getCompletionItems(context, position); if (entry.type === 'styled') { return entry.value; } return translateCompletionItemsToCompletionInfo(this.typescript, context, entry.value); } public getCompletionEntryDetails?( context: TemplateContext, position: ts.LineAndCharacter, name: string ): ts.CompletionEntryDetails { const entry = this.getCompletionItems(context, position); if (entry.type === 'styled') { return this.styledLanguageService.getCompletionEntryDetails!(context, position, name); } const item = entry.value.items.find(x => x.label === name); if (!item) { return { name, kind: this.typescript.ScriptElementKind.unknown, kindModifiers: '', tags: [], displayParts: toDisplayParts(name), documentation: [], }; } return translateCompletionItemsToCompletionEntryDetails(this.typescript, item); } public getQuickInfoAtPosition( context: TemplateContext, position: ts.LineAndCharacter ): ts.QuickInfo | undefined { const document = this.virtualDocumentProvider.createVirtualDocument(context); const documentRegions = getDocumentRegions(this.htmlLanguageService, document); const languageId = documentRegions.getLanguageAtPosition(position); switch (languageId) { case 'html': const htmlDoc = this.htmlLanguageService.parseHTMLDocument(document); const hover = this.htmlLanguageService.doHover(document, position, htmlDoc); return hover ? this.translateHover(hover, position, context) : undefined; case 'css': return this.styledLanguageService.getQuickInfoAtPosition(context, position); } return undefined; } public getFormattingEditsForRange( context: TemplateContext, start: number, end: number, settings: ts.EditorSettings ): ts.TextChange[] { if (!this.configuration.format.enabled) { return []; } // Disable formatting for blocks that contain a style tag // // Formatting styled blocks gets complex since we want to preserve interpolations inside the output // but we can't format content with `{` property. // The best fix would be to add `style` to `contentUnformatted` but // https://github.com/Microsoft/vscode-html-languageservice/issues/29 is causing problems and I'm not sure how // to work around it well if (context.text.match(/<style/g)) { return []; } const document = this.virtualDocumentProvider.createVirtualDocument(context); // Make sure we don't get rid of leading newline const leading = context.text.match(/^\s*\n/); if (leading) { start += leading[0].length; } // or any trailing newlines const trailing = context.text.match(/\n\s*$/); if (trailing) { end -= trailing[0].length; } if (end <= start) { return []; } const range = this.toVsRange(context, start, end); const edits = this.htmlLanguageService.format(document, range, { tabSize: settings.tabSize, insertSpaces: !!settings.convertTabsToSpaces, wrapLineLength: 120, unformatted: '', contentUnformatted: 'pre,code,textarea', indentInnerHtml: false, preserveNewLines: true, maxPreserveNewLines: undefined, indentHandlebars: false, endWithNewline: false, extraLiners: 'head, body, /html', wrapAttributes: 'auto', }); return edits.map(vsedit => toTsTextChange(context, vsedit)); } public getSignatureHelpItemsAtPosition( _context: TemplateContext, _position: ts.LineAndCharacter ): ts.SignatureHelpItems | undefined { // Html does not support sig help return undefined; } public getOutliningSpans( context: TemplateContext ): ts.OutliningSpan[] { const document = this.virtualDocumentProvider.createVirtualDocument(context); const ranges = this.htmlLanguageService.getFoldingRanges(document); return ranges.map(range => this.translateOutliningSpan(context, range)); } public getSemanticDiagnostics( context: TemplateContext ): ts.Diagnostic[] { return this.styledLanguageService.getSemanticDiagnostics(context); } public getSupportedCodeFixes(): number[] { return this.styledLanguageService.getSupportedCodeFixes(); } public getCodeFixesAtPosition( context: TemplateContext, start: number, end: number, errorCodes: number[], format: ts.FormatCodeSettings ): ts.CodeAction[] { return this.styledLanguageService.getCodeFixesAtPosition(context, start, end, errorCodes, format); } public getReferencesAtPosition( context: TemplateContext, position: ts.LineAndCharacter ): ts.ReferenceEntry[] | undefined { const document = this.virtualDocumentProvider.createVirtualDocument(context); const htmlDoc = this.htmlLanguageService.parseHTMLDocument(document); const highlights = this.htmlLanguageService.findDocumentHighlights(document, position, htmlDoc); return highlights.map(highlight => ({ fileName: context.fileName, textSpan: toTsSpan(context, highlight.range), } as ts.ReferenceEntry)); } public getJsxClosingTagAtPosition( context: TemplateContext, position: ts.LineAndCharacter ): ts.JsxClosingTagInfo | undefined { const document = this.virtualDocumentProvider.createVirtualDocument(context); const htmlDocument = this.htmlLanguageService.parseHTMLDocument(document); const tagComplete = this.htmlLanguageService.doTagComplete(document, position, htmlDocument); if (!tagComplete) { return undefined; } // Html returns completions with snippet placeholders. Strip these out. return { newText: tagComplete.replace(/\$\d/g, ''), }; } private toVsRange( context: TemplateContext, start: number, end: number ): vscode.Range { return { start: context.toPosition(start), end: context.toPosition(end), }; } private getCompletionItems( context: TemplateContext, position: ts.LineAndCharacter ): HtmlCachedCompletionList | StyledCachedCompletionList { const cached = this._completionsCache.getCached(context, position); if (cached) { return cached; } const document = this.virtualDocumentProvider.createVirtualDocument(context); const documentRegions = getDocumentRegions(this.htmlLanguageService, document); const languageId = documentRegions.getLanguageAtPosition(position); switch (languageId) { case 'html': { const htmlDoc = this.htmlLanguageService.parseHTMLDocument(document); const htmlCompletions: HtmlCachedCompletionList = { type: 'html', value: this.htmlLanguageService.doComplete(document, position, htmlDoc) || emptyCompletionList, }; this._completionsCache.updateCached(context, position, htmlCompletions); return htmlCompletions; } case 'css': { const styledCompletions: StyledCachedCompletionList = { type: 'styled', value: this.styledLanguageService.getCompletionsAtPosition(context, position), }; this._completionsCache.updateCached(context, position, styledCompletions); return styledCompletions; } } const completions: HtmlCachedCompletionList = { type: 'html', value: emptyCompletionList, }; this._completionsCache.updateCached(context, position, completions); return completions; } private translateHover( hover: vscode.Hover, position: ts.LineAndCharacter, context: TemplateContext ): ts.QuickInfo { const header: ts.SymbolDisplayPart[] = []; const docs: ts.SymbolDisplayPart[] = []; const convertPart = (hoverContents: typeof hover.contents) => { if (typeof hoverContents === 'string') { docs.push({ kind: 'unknown', text: hoverContents }); } else if (Array.isArray(hoverContents)) { hoverContents.forEach(convertPart); } else { header.push({ kind: 'unknown', text: hoverContents.value }); } }; convertPart(hover.contents); const start = context.toOffset(hover.range ? hover.range.start : position); return { kind: this.typescript.ScriptElementKind.string, kindModifiers: '', textSpan: { start, length: hover.range ? context.toOffset(hover.range.end) - start : 1, }, displayParts: header, documentation: docs, tags: [], }; } private translateOutliningSpan( context: TemplateContext, range: FoldingRange ): ts.OutliningSpan { const startOffset = context.toOffset({ line: range.startLine, character: range.startCharacter || 0 }); const endOffset = context.toOffset({ line: range.endLine, character: range.endCharacter || 0 }); const span = { start: startOffset, length: endOffset - startOffset, }; return { autoCollapse: false, kind: this.typescript.OutliningSpanKind.Code, bannerText: '', textSpan: span, hintSpan: span, }; } } function translateCompletionItemsToCompletionInfo( typescript: typeof ts, context: TemplateContext, items: vscode.CompletionList ): ts.CompletionInfo { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: items.items.map(x => translateCompetionEntry(typescript, context, x)), }; } function translateCompletionItemsToCompletionEntryDetails( typescript: typeof ts, item: vscode.CompletionItem ): ts.CompletionEntryDetails { return { name: item.label, kindModifiers: 'declare', kind: item.kind ? translateionCompletionItemKind(typescript, item.kind) : typescript.ScriptElementKind.unknown, displayParts: toDisplayParts(item.detail), documentation: toDisplayParts(item.documentation), tags: [], }; } function translateCompetionEntry( typescript: typeof ts, context: TemplateContext, vsItem: vscode.CompletionItem ): ts.CompletionEntry { const kind = vsItem.kind ? translateionCompletionItemKind(typescript, vsItem.kind) : typescript.ScriptElementKind.unknown; const entry: ts.CompletionEntry = { name: vsItem.label, kind, sortText: '0', }; if (vsItem.textEdit) { entry.insertText = vsItem.textEdit.newText; entry.replacementSpan = toTsSpan(context, vsItem.textEdit.range); } return entry; } function translateionCompletionItemKind( typescript: typeof ts, kind: vscode.CompletionItemKind ): ts.ScriptElementKind { switch (kind) { case vscode.CompletionItemKind.Method: return typescript.ScriptElementKind.memberFunctionElement; case vscode.CompletionItemKind.Function: return typescript.ScriptElementKind.functionElement; case vscode.CompletionItemKind.Constructor: return typescript.ScriptElementKind.constructorImplementationElement; case vscode.CompletionItemKind.Field: case vscode.CompletionItemKind.Variable: return typescript.ScriptElementKind.variableElement; case vscode.CompletionItemKind.Class: return typescript.ScriptElementKind.classElement; case vscode.CompletionItemKind.Interface: return typescript.ScriptElementKind.interfaceElement; case vscode.CompletionItemKind.Module: return typescript.ScriptElementKind.moduleElement; case vscode.CompletionItemKind.Property: return typescript.ScriptElementKind.memberVariableElement; case vscode.CompletionItemKind.Unit: case vscode.CompletionItemKind.Value: return typescript.ScriptElementKind.constElement; case vscode.CompletionItemKind.Enum: return typescript.ScriptElementKind.enumElement; case vscode.CompletionItemKind.Keyword: return typescript.ScriptElementKind.keyword; case vscode.CompletionItemKind.Color: return typescript.ScriptElementKind.constElement; case vscode.CompletionItemKind.Reference: return typescript.ScriptElementKind.alias; case vscode.CompletionItemKind.File: return typescript.ScriptElementKind.moduleElement; case vscode.CompletionItemKind.Snippet: case vscode.CompletionItemKind.Text: default: return typescript.ScriptElementKind.unknown; } } function toDisplayParts( text: string | vscode.MarkupContent | undefined ): ts.SymbolDisplayPart[] { if (!text) { return []; } return [{ kind: 'text', text: typeof text === 'string' ? text : text.value, }]; } function arePositionsEqual( left: ts.LineAndCharacter, right: ts.LineAndCharacter ): boolean { return left.line === right.line && left.character === right.character; } function toTsSpan( context: TemplateContext, range: vscode.Range ): ts.TextSpan { const editStart = context.toOffset(range.start); const editEnd = context.toOffset(range.end); return { start: editStart, length: editEnd - editStart, }; } function toTsTextChange( context: TemplateContext, vsedit: vscode.TextEdit ) { return { span: toTsSpan(context, vsedit.range), newText: vsedit.newText, }; }
the_stack
import { Browser, EventHandler, getComponent, isNullOrUndefined } from '@syncfusion/ej2-base'; import { Spreadsheet, FormulaBarEdit, ScrollEventArgs, isFormulaBarEdit, colWidthChanged, mouseDown, getUpdateUsingRaf } from '../index'; import { contentLoaded, spreadsheetDestroyed, onVerticalScroll, onHorizontalScroll, getScrollBarWidth, IScrollArgs } from '../common/index'; import { IOffset, onContentScroll, deInitProperties, setScrollEvent, updateScroll, selectionStatus } from '../common/index'; import { virtualContentLoaded, updateScrollValue } from '../common/index'; import { SheetModel, getRowHeight, getColumnWidth, getCellAddress, skipHiddenIdx } from '../../workbook/index'; import { DropDownButton } from '@syncfusion/ej2-splitbuttons'; /** * The `Scroll` module is used to handle scrolling behavior. * * @hidden */ export class Scroll { private parent: Spreadsheet; /** @hidden */ public offset: { left: IOffset, top: IOffset }; private topIndex: number; private leftIndex: number; private clientX: number = 0; /** @hidden */ public isKeyScroll: boolean = true; private initScrollValue: number; // For RTL mode /** @hidden */ public prevScroll: { scrollLeft: number, scrollTop: number }; /** * Constructor for the Spreadsheet scroll module. * * @param {Spreadsheet} parent - Constructor for the Spreadsheet scroll module. * @private */ constructor(parent: Spreadsheet) { this.parent = parent; this.addEventListener(); this.initProps(); } private onContentScroll(e: ScrollEventArgs): void { if (!this.parent) { return; } const target: HTMLElement = this.parent.getMainContent().parentElement; const scrollLeft: number = e.scrollLeft; const top: number = e.scrollTop || target.scrollTop; const left: number = scrollLeft && this.parent.enableRtl ? this.initScrollValue - scrollLeft : scrollLeft; let scrollArgs: IScrollArgs; let prevSize: number; if (this.parent.allowAutoFill) { const elem: Element = document.querySelector('#' + this.parent.element.id + '_autofilloptionbtn-popup'); const DDBElem: HTMLElement = document.querySelector('#' + this.parent.element.id + '_autofilloptionbtn'); if (elem) { const DDBObj: DropDownButton = getComponent(DDBElem, DropDownButton); DDBObj.toggle(); } } if (!isNullOrUndefined(scrollLeft) && this.prevScroll.scrollLeft !== left) { const scrollRight: boolean = left > this.prevScroll.scrollLeft; prevSize = this.offset.left.size; this.offset.left = this.getColOffset(left, scrollRight, e.skipHidden); if (!e.preventScroll) { this.parent.getColumnHeaderContent().scrollLeft = scrollLeft; this.parent.getMainContent().scrollLeft = scrollLeft; e.scrollLeft = scrollLeft; } scrollArgs = { cur: this.offset.left, prev: { idx: this.leftIndex, size: prevSize }, increase: scrollRight, preventScroll: e.preventScroll }; this.updateTopLeftCell(scrollRight, true); this.parent.notify(onHorizontalScroll, scrollArgs); if (!this.parent.scrollSettings.enableVirtualization && scrollRight && !this.parent.scrollSettings.isFinite) { this.updateNonVirtualCols(); } this.leftIndex = scrollArgs.prev.idx; this.prevScroll.scrollLeft = left; } if (Math.round(this.prevScroll.scrollTop) !== Math.round(top)) { if (e.skipRowVirualScroll) { this.prevScroll.scrollTop = 0; this.offset.top = { idx: 0, size: 0 }; } const scrollDown: boolean = top > this.prevScroll.scrollTop; prevSize = this.offset.top.size; this.offset.top = this.getRowOffset(top, scrollDown); scrollArgs = { cur: this.offset.top, prev: { idx: this.topIndex, size: prevSize }, increase: scrollDown, preventScroll: e.preventScroll }; this.updateTopLeftCell(scrollDown); if (e.preventScroll && this.offset.top.idx <= this.parent.getThreshold('row')) { this.offset.top = { idx: 0, size: 0 }; } else if (!e.skipRowVirualScroll) { this.parent.notify(onVerticalScroll, scrollArgs); } else { scrollArgs.prev.idx = scrollArgs.cur.idx; } if (!this.parent.scrollSettings.enableVirtualization && scrollDown && !this.parent.scrollSettings.isFinite) { this.updateNonVirtualRows(); } this.topIndex = scrollArgs.prev.idx; this.prevScroll.scrollTop = top; } const isEdit: boolean = false; const args: FormulaBarEdit = {isEdit: isEdit}; this.parent.notify(isFormulaBarEdit, args); if (args.isEdit) { const textArea: HTMLTextAreaElement = this.parent.element.querySelector('.e-formula-bar'); textArea.focus(); } this.isKeyScroll = true; } private updateScrollValue(args: { scrollLeft?: number, scrollTop?: number }): void { if (args.scrollLeft !== undefined) { this.prevScroll.scrollLeft = args.scrollLeft + (this.prevScroll.scrollLeft - this.offset.left.size); this.offset.left.size = args.scrollLeft; } if (args.scrollTop !== undefined) { this.prevScroll.scrollTop = args.scrollTop + (this.prevScroll.scrollTop - this.offset.top.size); this.offset.top.size = args.scrollTop; } } private updateNonVirtualRows(): void { const sheet: SheetModel = this.parent.getActiveSheet(); const threshold: number = this.parent.getThreshold('row'); if (this.offset.top.idx > sheet.rowCount - (this.parent.viewport.rowCount + threshold)) { this.parent.renderModule.refreshUI( { rowIndex: sheet.rowCount , colIndex: 0, direction: 'first', refresh: 'RowPart' }, `${getCellAddress(sheet.rowCount, 0)}:${getCellAddress(sheet.rowCount + threshold - 1, sheet.colCount - 1)}`); this.parent.setSheetPropertyOnMute(sheet, 'rowCount', sheet.rowCount + threshold); this.parent.viewport.bottomIndex = sheet.rowCount - 1; } } private updateNonVirtualCols(): void { const sheet: SheetModel = this.parent.getActiveSheet(); const threshold: number = this.parent.getThreshold('col'); if (this.offset.left.idx > sheet.colCount - (this.parent.viewport.colCount + threshold)) { this.parent.renderModule.refreshUI( { rowIndex: 0, colIndex: sheet.colCount, direction: 'first', refresh: 'ColumnPart' }, `${getCellAddress(0, sheet.colCount)}:${getCellAddress(sheet.rowCount - 1, sheet.colCount + threshold - 1)}`); this.parent.setSheetPropertyOnMute(sheet, 'colCount', sheet.colCount + threshold); this.parent.viewport.rightIndex = sheet.colCount - 1; } } private updateTopLeftCell(increase: boolean, isLeft?: boolean): void { const sheet: SheetModel = this.parent.getActiveSheet(); let top: number = this.offset.top.idx; let left: number = this.offset.left.idx; if (!increase) { const frozenRow: number = this.parent.frozenRowCount(sheet); top = skipHiddenIdx(sheet, top + frozenRow, true) - frozenRow; const frozenCol: number = this.parent.frozenColCount(sheet); left = skipHiddenIdx(sheet, left + frozenCol, true, 'columns') - frozenCol; } if (isLeft) { this.parent.updateTopLeftCell(null, left, 'row'); } else { this.parent.updateTopLeftCell(top, null, 'col'); } } private getRowOffset(scrollTop: number, scrollDown: boolean): IOffset { let temp: number = this.offset.top.size; const sheet: SheetModel = this.parent.getActiveSheet(); let i: number = scrollDown ? this.offset.top.idx + 1 : (this.offset.top.idx ? this.offset.top.idx - 1 : 0); const frozenRow: number = this.parent.frozenRowCount(sheet); const count: number = this.parent.scrollSettings.isFinite ? sheet.rowCount : Infinity; scrollTop = Math.round(scrollTop); while (i < count) { if (scrollDown) { temp += getRowHeight(sheet, i - 1 + frozenRow, true); if (Math.abs(Math.round(temp) - scrollTop) <= 1) { // <=1 -> For other resolution scrollTop value slightly various with row height return { idx: skipHiddenIdx(sheet, i + frozenRow, true) - frozenRow, size: temp }; } if (Math.round(temp) > scrollTop) { return { idx: i - 1, size: temp - getRowHeight(sheet, i - 1 + frozenRow, true) }; } i++; } else { temp -= getRowHeight(sheet, i + frozenRow, true); if (temp <= 0) { return { idx: 0, size: 0 }; } if (Math.abs(Math.round(temp) - scrollTop) <= 1) { return { idx: i, size: temp }; } if (Math.round(temp) < scrollTop) { temp += getRowHeight(sheet, i + frozenRow, true); if (Math.round(temp) > scrollTop) { return { idx: i, size: temp - getRowHeight(sheet, i + frozenRow, true) < 0 ? 0 : temp - getRowHeight(sheet, i + frozenRow, true) }; } else { return { idx: skipHiddenIdx(sheet, i + 1 + frozenRow, true) - frozenRow, size: temp }; } } i--; } } return { idx: this.offset.top.idx, size: this.offset.top.size }; } private getColOffset(scrollLeft: number, increase: boolean, skipHidden: boolean): IOffset { let temp: number = this.offset.left.size; const sheet: SheetModel = this.parent.getActiveSheet(); let i: number = increase ? this.offset.left.idx + 1 : (this.offset.left.idx ? this.offset.left.idx - 1 : 0); const frozenCol: number = this.parent.frozenColCount(sheet); const count: number = this.parent.scrollSettings.isFinite ? sheet.colCount : Infinity; while (i < count) { if (increase) { temp += getColumnWidth(sheet, i - 1 + frozenCol, skipHidden, true); if (Math.abs(Math.round(temp) - scrollLeft) <= 1) { return { idx: skipHiddenIdx(sheet, i + frozenCol, true, 'columns') - frozenCol, size: temp }; } if (Math.round(temp) > scrollLeft) { return { idx: i - 1, size: temp - getColumnWidth(sheet, i - 1 + frozenCol, skipHidden, true) }; } i++; } else { temp -= getColumnWidth(sheet, i + frozenCol, skipHidden, true); if (temp <= 0) { return { idx: 0, size: 0 }; } if (Math.abs(Math.round(temp) - scrollLeft) <= 1) { return { idx: i, size: temp }; } if (Math.round(temp) < scrollLeft) { temp += getColumnWidth(sheet, i + frozenCol, skipHidden, true); if (Math.round(temp) > scrollLeft) { temp = temp - getColumnWidth(sheet, i + frozenCol, skipHidden, true); return { idx: i, size: temp < 0 ? 0 : temp}; } else { return { idx: skipHiddenIdx(sheet, i + 1 + frozenCol, true, 'columns') - frozenCol, size: temp }; } } i--; } } return { idx: this.offset.left.idx, size: this.offset.left.size }; } private contentLoaded(args: { left?: number }): void { if (!this.parent.scrollSettings.enableVirtualization) { const scrollTrack: HTMLElement = this.parent.createElement('div', { className: 'e-virtualtrack' }); this.updateNonVirualScrollWidth({ scrollTrack: scrollTrack }); this.parent.getScrollElement().appendChild(scrollTrack); } if (args.left) { this.parent.getScrollElement().scrollLeft = args.left; } this.setScrollEvent(); if (this.parent.enableRtl) { this.initScrollValue = this.parent.getScrollElement().scrollLeft; } } private updateNonVirualScrollWidth(args: { scrollTrack?: HTMLElement }): void { if (!args.scrollTrack) { args.scrollTrack = this.parent.getScrollElement().getElementsByClassName('e-virtualtrack')[0] as HTMLElement; } args.scrollTrack.style.width = Math.abs(this.parent.getContentTable().getBoundingClientRect().width) + 'px'; } private onHeaderWheel(e: WheelEvent): void { e.preventDefault(); this.parent.getMainContent().parentElement.scrollTop += e.deltaY; this.parent.getScrollElement().scrollLeft += e.deltaX; } private onContentWheel(e: WheelEvent): void { if (e.deltaX !== 0) { e.preventDefault(); this.parent.getScrollElement().scrollLeft += e.deltaX; } } private scrollHandler(e: MouseEvent): void { this.onContentScroll(<ScrollEventArgs>{ scrollLeft: (e.target as Element).scrollLeft }); } private updateScroll(args: { top?: number, left?: number }): void { if (isNullOrUndefined(args.left)) { this.parent.sheetModule.contentPanel.scrollTop = args.top; } else { this.parent.getScrollElement().scrollLeft = args.left; } } private setScrollEvent(args: { set: boolean } = { set: true }): void { if (args.set) { EventHandler.add(this.parent.sheetModule.contentPanel, 'scroll', this.onContentScroll, this); EventHandler.add(this.parent.getColumnHeaderContent(), 'wheel', this.onHeaderWheel, this); EventHandler.add(this.parent.getSelectAllContent(), 'wheel', this.onHeaderWheel, this); EventHandler.add(this.parent.getMainContent(), 'wheel', this.onContentWheel, this); EventHandler.add(this.parent.getRowHeaderContent(), 'wheel', this.onContentWheel, this); EventHandler.add(this.parent.getScrollElement(), 'scroll', this.scrollHandler, this); } else { EventHandler.remove(this.parent.sheetModule.contentPanel, 'scroll', this.onContentScroll); EventHandler.remove(this.parent.getColumnHeaderContent(), 'wheel', this.onHeaderWheel); EventHandler.remove(this.parent.getSelectAllContent(), 'wheel', this.onHeaderWheel); EventHandler.remove(this.parent.getMainContent(), 'wheel', this.onContentWheel); EventHandler.remove(this.parent.getRowHeaderContent(), 'wheel', this.onContentWheel); EventHandler.remove(this.parent.getScrollElement(), 'scroll', this.scrollHandler); } } private initProps(): void { this.topIndex = 0; this.leftIndex = 0; this.prevScroll = { scrollLeft: 0, scrollTop: 0 }; this.offset = { left: { idx: 0, size: 0 }, top: { idx: 0, size: 0 } }; } /** * @hidden * * @returns {void} - To Set padding */ public setPadding(): void { this.parent.sheetModule.contentPanel.style.overflowY = 'scroll'; const scrollWidth: number = getScrollBarWidth(); if (scrollWidth > 0) { const colHeader: HTMLElement = this.parent.getColumnHeaderContent(); const cssProps: { margin: string, border: string } = this.parent.enableRtl ? { margin: 'marginLeft', border: 'borderLeftWidth' } : { margin: 'marginRight', border: 'borderRightWidth' }; colHeader.parentElement.style[cssProps.margin] = scrollWidth + 'px'; colHeader.style[cssProps.border] = '1px'; } } private setClientX(e: PointerEvent | TouchEvent): void { if (e.type === 'mousedown' || (e as PointerEvent).pointerType === 'mouse') { return; } const args: { touchSelectionStarted: boolean } = { touchSelectionStarted: false }; this.parent.notify(selectionStatus, args); if (args.touchSelectionStarted) { return; } this.clientX = this.getPointX(e); const sheetContent: HTMLElement = document.getElementById(this.parent.element.id + '_sheet'); EventHandler.add(sheetContent, Browser.isPointer ? 'pointermove' : 'touchmove', this.onTouchScroll, this); EventHandler.add(sheetContent, Browser.isPointer ? 'pointerup' : 'touchend', this.pointerUpHandler, this); } private getPointX(e: PointerEvent | TouchEvent): number { let clientX: number = 0; if ((e as TouchEvent).touches && (e as TouchEvent).touches.length) { clientX = (e as TouchEvent).touches[0].clientX; } else { clientX = (e as PointerEvent).clientX; } return clientX; } private onTouchScroll(e: PointerEvent | TouchEvent): void { if ((e as PointerEvent).pointerType === 'mouse') { return; } const clientX: number = this.getPointX(e); const diff: number = this.clientX - clientX; const scroller: Element = this.parent.element.getElementsByClassName('e-scroller')[0]; if ((diff > 10 || diff < -10) && scroller.scrollLeft + diff >= 0) { e.preventDefault(); this.clientX = clientX; getUpdateUsingRaf((): void => { scroller.scrollLeft += diff; }); } } private pointerUpHandler(): void { const sheetContent: HTMLElement = document.getElementById(this.parent.element.id + '_sheet'); EventHandler.remove(sheetContent, Browser.isPointer ? 'pointermove' : 'touchmove', this.onTouchScroll); EventHandler.remove(sheetContent, Browser.isPointer ? 'pointerup' : 'touchend', this.pointerUpHandler); } private addEventListener(): void { this.parent.on(contentLoaded, this.contentLoaded, this); this.parent.on(onContentScroll, this.onContentScroll, this); this.parent.on(updateScroll, this.updateScroll, this); this.parent.on(deInitProperties, this.initProps, this); this.parent.on(spreadsheetDestroyed, this.destroy, this); this.parent.on(setScrollEvent, this.setScrollEvent, this); this.parent.on(mouseDown, this.setClientX, this); this.parent.on(updateScrollValue, this.updateScrollValue, this); if (!this.parent.scrollSettings.enableVirtualization) { this.parent.on(virtualContentLoaded, this.updateNonVirualScrollWidth, this); this.parent.on(colWidthChanged, this.updateNonVirualScrollWidth, this); } } private destroy(): void { this.removeEventListener(); this.parent = null; } private removeEventListener(): void { this.parent.off(contentLoaded, this.contentLoaded); this.parent.off(onContentScroll, this.onContentScroll); this.parent.off(updateScroll, this.updateScroll); this.parent.off(deInitProperties, this.initProps); this.parent.off(spreadsheetDestroyed, this.destroy); this.parent.off(setScrollEvent, this.setScrollEvent); this.parent.off(mouseDown, this.setClientX); this.parent.off(updateScrollValue, this.updateScrollValue); if (!this.parent.scrollSettings.enableVirtualization) { this.parent.off(virtualContentLoaded, this.updateNonVirualScrollWidth); this.parent.off(colWidthChanged, this.updateNonVirualScrollWidth); } } }
the_stack
* 该文件为脚本自动生成文件,请勿随意修改。如需修改请联系 PMC * */ import { CalendarController } from '../calendar'; import { ButtonProps } from '../button'; import { FormErrorMessage } from '../form'; import { TNode } from '../common'; export interface GlobalConfigProvider { /** * 警告全局配置 */ alert?: AlertConfig; /** * 锚点全局配置 */ anchor?: AnchorConfig; /** * 动画效果控制,`ripple` 指波纹动画, `expand` 指展开动画,`fade` 指渐变动画。默认为 `{ include: ['ripple','expand','fade'], exclude: [] }` */ animation?: Partial<Record<'include' | 'exclude', Array<AnimationType>>>; /** * 日历组件全局配置 */ calendar?: CalendarConfig; /** * 级联选择器全局配置 */ cascader?: CascaderConfig; /** * CSS 类名前缀 * @default t */ classPrefix?: string; /** * 颜色选择器全局配置 */ colorPicker?: ColorPickerConfig; /** * 日期选择器全局配置 */ datePicker?: DatePickerConfig; /** * 对话框全局配置 */ dialog?: DialogConfig; /** * 抽屉全局配置 */ drawer?: DrawerConfig; /** * 表单组件全局配置 */ form?: FormConfig; /** * 输入框组件全局配置 */ input?: InputConfig; /** * 列表组件全局配置 */ list?: ListConfig; /** * 分页组件全局配置 */ pagination?: PaginationConfig; /** * 气泡确认框全局配置 */ popconfirm?: PopconfirmConfig; /** * 选择器组件全局配置 */ select?: SelectConfig; /** * 步骤条组件全局配置 */ steps?: StepsConfig; /** * 表格组件全局配置 */ table?: TableConfig; /** * 标签全局配置 */ tag?: TagConfig; /** * 时间选择器全局配置 */ timePicker?: TimePickerConfig; /** * 穿梭框全局配置 */ transfer?: TransferConfig; /** * 树组件全局配置 */ tree?: TreeConfig; /** * 树选择器组件全局配置 */ treeSelect?: TreeSelectConfig; /** * 上传组件全局配置 */ upload?: UploadConfig; } export interface TreeSelectConfig { /** * 语言配置,“暂无数据”描述文本 * @default '' */ empty?: string; /** * 语言配置,“加载中”描述文本 * @default '' */ loadingText?: string; /** * 语言配置,“请选择”占位符描述文本 * @default '' */ placeholder?: string; } export interface InputConfig { /** * 语言配置,“请输入”占位符描述文本 * @default '' */ placeholder?: string; } export interface CalendarConfig { /** * 语言配置,月份描述文本,示例:'一月,二月,三月,四月,五月,六月,七月,八月,九月,十月,十一月,十二月' * @default '' */ cellMonth?: string; /** * 日历右上角控制器按钮配置 */ controllerConfig?: CalendarController; /** * 当日期数字小于 10 时,是否使用 '0' 填充 * @default true */ fillWithZero?: boolean; /** * 第一天从星期几开始 * @default 1 */ firstDayOfWeek?: number; /** * 语言配置,“隐藏周末”描述文本 * @default '' */ hideWeekend?: string; /** * 语言配置,模式切换时的“月”描述文本 * @default '' */ monthRadio?: string; /** * 语言配置,"月"选择描述文本。示例:`'{month} 月'` * @default '' */ monthSelection?: string; /** * 语言配置,“显示周末”描述文本 * @default '' */ showWeekend?: string; /** * 语言配置,“本月”描述文本 * @default '' */ thisMonth?: string; /** * 语言配置,“今天”描述文本 * @default '' */ today?: string; /** * 语言配置,星期描述文本,示例:`'周一,周二,周三,周四,周五,周六,周日'` * @default '' */ week?: string; /** * 语言配置,模式切换时的“年”描述文本 * @default '' */ yearRadio?: string; /** * 语言配置,“年”选择描述文本,示例:`'{year} 年'` * @default '' */ yearSelection?: string; } export interface CascaderConfig { /** * 语言配置,“暂无数据”描述文本 * @default '' */ empty?: string; /** * 语言配置,“加载中”描述文本 * @default '' */ loadingText?: string; /** * 语言配置,“请选择”占位描述文本 * @default '' */ placeholder?: string; } export interface ColorPickerConfig { /** * 语言配置,“确定清空最近使用的颜色吗?”清空颜色确认文案 * @default '' */ clearConfirmText?: string; /** * 语言配置,“最近使用颜色” 区域标题文本 * @default '' */ recentColorTitle?: string; /** * 语言配置,"系统预设颜色" 区域标题文本 * @default '' */ swatchColorTitle?: string; } export interface AnchorConfig { /** * 语言配置,“链接复制成功”描述文本 * @default '' */ copySuccessText?: string; /** * 语言配置,“复制链接” 描述文本 * @default '' */ copyText?: string; } export interface AlertConfig { /** * 语言配置,“收起”描述文本 * @default '' */ collapseText?: string; /** * 语言配置,“展开更多”描述文本 * @default '' */ expandText?: string; } export interface DatePickerConfig { /** * 语言配置,“确定” 描述文本 * @default '' */ confirm?: string; /** * 语言配置,“日” 描述文本 * @default '' */ dayAriaLabel?: string; /** * 日期方向,'ltr' 表示从左往右 * @default 'ltr' */ direction?: string; /** * 第一天从星期几开始 * @default 7 */ firstDayOfWeek?: number; /** * 日期格式化规则 * @default 'YYYY-MM-DD' */ format?: string; /** * 语言配置,“月” 描述文本 * @default '' */ monthAriaLabel?: string; /** * 星期文本描述,默认值:['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'] */ months?: string[]; /** * 语言配置,“下个十年” 描述文本 * @default '' */ nextDecade?: string; /** * 语言配置,“下个月” 描述文本 * @default '' */ nextMonth?: string; /** * 语言配置,“下一年” 描述文本 * @default '' */ nextYear?: string; /** * 语言配置,“此刻” 描述文本 * @default '' */ now?: string; /** * 占位符文本提示,默认值:`{ date: '请选择日期', month: '请选择月份', year: '请选择年份' }` */ placeholder?: { date?: string; month?: string; year?: string }; /** * 语言配置,“上个十年” 描述文本 * @default '' */ preDecade?: string; /** * 语言配置,“上个月” 描述文本 * @default '' */ preMonth?: string; /** * 【暂不支持,讨论确认中】预设快捷日期选择,示例:`{ '元旦': '2021-01-01', '昨天': dayjs().subtract(1, 'day').format('YYYY-MM-DD'), '特定日期': () => ['2021-02-01'] }` */ presets?: ConfigPresetDate; /** * 语言配置,“上一年” 描述文本 * @default '' */ preYear?: string; /** * 语言配置,“ 至 ” 范围分隔符描述文本,示例:' ~ ' * @default '' */ rangeSeparator?: string; /** * 语言配置,“选择日期” 描述文本 * @default '' */ selectDate?: string; /** * 语言配置,“选择时间” 描述文本 * @default '' */ selectTime?: string; /** * 语言配置,“周” 描述文本 * @default '' */ weekAbbreviation?: string; /** * 星期文本描述,默认值:['日', '一', '二', '三', '四', '五', '六'] */ weekdays?: string[]; /** * 语言配置,“年” 描述文本 * @default '' */ yearAriaLabel?: string; } export interface DialogConfig { /** * 取消按钮风格 */ cancel?: string | ButtonProps; /** * 确认按钮风格 */ confirm?: string | ButtonProps; /** * 确认按钮主题色,即 Dialog 的 `theme` 和 确认按钮的 `theme` 映射关系。示例:{ danger: 'danger' } */ confirmBtnTheme?: { default: string; info: string; warning: string; danger: string; success: string }; } export interface DrawerConfig { /** * 语言配置,“取消”描述文本 * @default '' */ cancel?: string | ButtonProps; /** * 语言配置,“确认”描述文本 * @default '' */ confirm?: string | ButtonProps; } export interface FormConfig { /** * 表单错误信息配置,示例:`{ idcard: '请输入正确的身份证号码', max: '字符长度不能超过 ${max}' }` */ errorMessage?: FormErrorMessage; /** * 是否显示必填符号(*),默认显示 * @default true */ requiredMark?: boolean; } export interface UploadConfigFileList { /** * 语言配置,“文件名” 描述文本 * @default '' */ fileNameText?: string; /** * 语言配置,“上传日期” 描述文本 * @default '' */ fileOperationDateText?: string; /** * 语言配置,“操作” 描述文本 * @default '' */ fileOperationText?: string; /** * 语言配置,“文件尺寸” 描述文本 * @default '' */ fileSizeText?: string; /** * 语言配置,“状态” 描述文本 * @default '' */ fileStatusText?: string; } export interface ListConfig { /** * 语言配置,'点击加载更多' 描述文本 * @default '' */ loadingMoreText?: string; /** * 语言配置,'正在加载中,请稍后' 描述文本 * @default '' */ loadingText?: string; } export interface PaginationConfig { /** * 语言配置,每页条数文本,示例:`'{size} 条/页'` * @default '' */ itemsPerPage?: string; /** * 语言配置,页码跳转文本,示例:'跳至' * @default '' */ jumpTo?: string; /** * 语言配置,“页”描述文本 * @default '' */ page?: string; /** * 语言配置,数据总条数文本,示例:`'共 {total} 项数据'` * @default '' */ total?: string; } export interface PopconfirmConfig { /** * 语言配置,“取消”描述文本 */ cancel?: string | ButtonProps; /** * 语言配置,“确定”描述文本 */ confirm?: string | ButtonProps; /** * 确认按钮主题色,即 Popconfirm 的 `theme` 和 确认按钮的 `theme` 映射关系。示例:{ danger: 'danger' } */ confirmBtnTheme?: { default: string; warning: string; danger: string }; } export interface TableConfig { /** * 语言配置,“取消” 描述文本 * @default '' */ cancelText?: string; /** * 语言配置,过滤功能中,“清空筛选” 描述文本 * @default '' */ clearFilterResultButtonText?: string; /** * 语言配置,列配置功能中,“列配置” 按钮描述文本 * @default '' */ columnConfigButtonText?: string; /** * 语言配置,“请选择需要在表格中显示的数据列” 描述文本,列配置功能中弹框顶部描述 * @default '' */ columnConfigDescriptionText?: string; /** * 语言配置,“表格列配置” 描述文本,列配置功能中弹框的标题 * @default '' */ columnConfigTitleText?: string; /** * 语言配置,“确认” 描述文本 * @default '' */ confirmText?: string; /** * 语言配置,“暂无数据” 描述文本 */ empty?: string | TNode; /** * 展开和收起图标(配置传入收起图标即可),如果没有配置,会使用组件内置的默认图标 */ expandIcon?: TNode; /** * 过滤图标,如果没有配置,会使用组件内置的默认图标 */ filterIcon?: TNode; /** * 隐藏排序文本提示 * @default false */ hideSortTips?: boolean; /** * 语言配置,“点击加载更多” 描述文本 * @default '' */ loadingMoreText?: string; /** * 语言配置,“正在加载中,请稍后” 描述文本 * @default '' */ loadingText?: string; /** * 语言配置,“重置” 描述文本 * @default '' */ resetText?: string; /** * 语言配置,过滤功能中,过滤条件和结果描述文本,示例:'搜索“{result}”,找到 {count} 条结果' * @default '' */ searchResultText?: string; /** * 语言配置,'全选' 描述文本 * @default '' */ selectAllText?: string; /** * 语言配置,'点击升序' 描述文本 * @default '' */ sortAscendingOperationText?: string; /** * 语言配置,'点击取消排序' 描述文本 * @default '' */ sortCancelOperationText?: string; /** * 语言配置,'点击降序' 描述文本 * @default '' */ sortDescendingOperationText?: string; /** * 排序图标(配置传入降序图标即可),如果没有配置,会使用组件内置的默认图标 */ sortIcon?: TNode; /** * 树形结构,展开和折叠图标。如果没有配置,会使用组件内置的默认图标 */ treeExpandAndFoldIcon?: TNode<{ type: 'expand' | 'fold' }>; } export interface StepsConfig { /** * 错误步骤图标,【注意】使用渲染函数输出图标组件 */ errorIcon?: TNode; } export interface SelectConfig { /** * 清除图标,【注意】使用渲染函数输出图标组件 */ clearIcon?: TNode; /** * 语言配置,“暂无数据”描述文本 * @default '' */ empty?: string; /** * 语言配置,“加载中”描述文本 * @default '' */ loadingText?: string; /** * 语言配置,“请选择”占位符描述文本 * @default '' */ placeholder?: string; } export interface TagConfig { /** * 关闭图标,【注意】使用渲染函数输出图标组件 */ closeIcon?: TNode; } export interface TimePickerConfig { /** * 语言配置,“上午”描述文本 * @default '' */ anteMeridiem?: string; /** * 语言配置,“确定”描述文本 * @default '' */ confirm?: string; /** * 语言配置,“此刻”描述文本 * @default '' */ now?: string; /** * 语言配置,"请选择时间"占位符描述文本 * @default '' */ placeholder?: string; /** * 语言配置,“下午”描述文本 * @default '' */ postMeridiem?: string; } export interface TransferConfig { /** * 语言配置,“暂无数据”空数据描述文本 * @default '' */ empty?: string; /** * 语言配置,“请输入关键词搜索”占位符描述文本 * @default '' */ placeholder?: string; /** * 语言配置,穿梭框标题描述文本,示例:“{checked} / {total} 项” * @default '' */ title?: string; } export interface TreeConfig { /** * 语言配置,“暂无数据”描述文本 * @default '' */ empty?: string; /** * 目录层级图标,传入收起状态图标即可。【注意】使用渲染函数输出图标组件 */ folderIcon?: TNode; } export interface UploadConfig { /** * 语言配置,“取消上传” 描述文本 * @default '' */ cancelUploadText?: string; /** * 语言配置,拖拽相关。示例:{ dragDropText: '释放图标', draggingText: '拖拽到此区域', clickAndDragText: '点击上方“选择文件”或将文件拖到此区域' } */ dragger?: UploadConfigDragger; /** * 语言配置,文件信息相关。示例:{ fileNameText: '文件名', fileSizeText: '文件尺寸', fileStatusText: '状态', fileOperationText: '操作', fileOperationDateText: '上传日期' } */ file?: UploadConfigFileList; /** * 语言配置,上传进度相关。示例:{ uploadText: '上传中', waitingText: '待上传', 'failText': '上传失败', successText: '上传成功' } */ progress?: UploadConfigProgress; /** * 语言配置,文件大小超出限制时提醒文本。示例:`'文件大小不能超过 {sizeLimit}'` * @default '' */ sizeLimitMessage?: string; /** * 语言配置,上传功能触发文案。示例:{ image: '点击上传图片', normal: '点击上传', fileInput: '选择文件',reupload: '重新上传',fileInput: '删除' } */ triggerUploadText?: UploadTriggerUploadText; } export interface UploadConfigDragger { /** * 语言配置,“ 点击上方“选择文件”或将文件拖到此区域 ” 描述文本 * @default '' */ clickAndDragText?: string; /** * 语言配置,“释放图标” 描述文本 * @default '' */ dragDropText?: string; /** * 语言配置,'拖拽到此区域' 描述文本 * @default '' */ draggingText?: string; } export interface UploadConfigProgress { /** * 语言配置,“上传失败”文本描述 * @default '' */ failText?: string; /** * 语言配置,“上传成功”文本描述 * @default '' */ successText?: string; /** * 语言配置,“上传中”文本描述 * @default '' */ uploadingText?: string; /** * 语言配置,“待上传”文本描述 * @default '' */ waitingText?: string; } export type AnimationType = 'ripple' | 'expand' | 'fade'; export interface ConfigPresetDate { [name: string]: DateConfigValue | (() => DateConfigValue); } export type DateConfigValue = string | Date | Array<DateConfigValue>; export interface UploadTriggerUploadText { image?: string; normal?: string; fileInput?: string; reupload?: string; continueUpload: string; delete?: string; }
the_stack
import { Application, Channel, ChannelType, Component, GuildMember, integer, Internal, MessageInteraction, Reaction, snowflake, Sticker, StickerItem, timestamp, User } from '.' /** https://discord.com/developers/docs/resources/channel#message-object-message-structure */ export interface Message { /** id of the message */ id: snowflake /** id of the channel the message was sent in */ channel_id: snowflake /** id of the guild the message was sent in */ guild_id?: snowflake /** the author of this message (not guaranteed to be a valid user, see below) */ author: User /** member properties for this message's author */ member?: Partial<GuildMember> /** contents of the message */ content: string /** when this message was sent */ timestamp: timestamp /** when this message was edited (or null if never) */ edited_timestamp?: timestamp /** whether this was a TTS message */ tts: boolean /** whether this message mentions everyone */ mention_everyone: boolean /** users specifically mentioned in the message */ mentions: User[] /** roles specifically mentioned in this message */ mention_roles: snowflake[] /** channels specifically mentioned in this message */ mention_channels?: ChannelMention[] /** any attached files */ attachments: Attachment[] /** any embedded content */ embeds: Embed[] /** reactions to the message */ reactions?: Reaction[] /** used for validating a message was sent */ nonce?: integer | string /** whether this message is pinned */ pinned: boolean /** if the message is generated by a webhook, this is the webhook's id */ webhook_id?: snowflake /** type of message */ type: integer /** sent with Rich Presence-related chat embeds */ activity?: MessageActivity /** sent with Rich Presence-related chat embeds */ application?: Partial<Application> /** if the message is a response to an Interaction, this is the id of the interaction's application */ application_id?: snowflake /** data showing the source of a crosspost, channel follow add, pin, or reply message */ message_reference?: MessageReference /** message flags combined as a bitfield */ flags?: integer /** the message associated with the message_reference */ referenced_message?: Message /** sent if the message is a response to an Interaction */ interaction?: MessageInteraction /** the thread that was started from this message, includes thread member object */ thread?: Channel /** sent if the message contains components like buttons, action rows, or other interactive components */ components?: Component[] /** sent if the message contains stickers */ sticker_items?: StickerItem[] /** Deprecated the stickers sent with the message */ stickers?: Sticker[] } /** https://discord.com/developers/docs/resources/channel#message-object-message-types */ export enum MessageType { DEFAULT = 0, RECIPIENT_ADD = 1, RECIPIENT_REMOVE = 2, CALL = 3, CHANNEL_NAME_CHANGE = 4, CHANNEL_ICON_CHANGE = 5, CHANNEL_PINNED_MESSAGE = 6, GUILD_MEMBER_JOIN = 7, USER_PREMIUM_GUILD_SUBSCRIPTION = 8, USER_PREMIUM_GUILD_SUBSCRIPTION_TIER_1 = 9, USER_PREMIUM_GUILD_SUBSCRIPTION_TIER_2 = 10, USER_PREMIUM_GUILD_SUBSCRIPTION_TIER_3 = 11, CHANNEL_FOLLOW_ADD = 12, GUILD_DISCOVERY_DISQUALIFIED = 14, GUILD_DISCOVERY_REQUALIFIED = 15, GUILD_DISCOVERY_GRACE_PERIOD_INITIAL_WARNING = 16, GUILD_DISCOVERY_GRACE_PERIOD_FINAL_WARNING = 17, THREAD_CREATED = 18, REPLY = 19, CHAT_INPUT_COMMAND = 20, THREAD_STARTER_MESSAGE = 21, GUILD_INVITE_REMINDER = 22, CONTEXT_MENU_COMMAND = 23, } /** https://discord.com/developers/docs/resources/channel#message-object-message-activity-structure */ export interface MessageActivity { /** type of message activity */ type: integer /** party_id from a Rich Presence event */ party_id?: string } /** https://discord.com/developers/docs/resources/channel#message-object-message-activity-types */ export enum MessageActivityType { JOIN = 1, SPECTATE = 2, LISTEN = 3, JOIN_REQUEST = 5, } /** https://discord.com/developers/docs/resources/channel#message-object-message-flags */ export enum MessageFlag { /** this message has been published to subscribed channels (via Channel Following) */ CROSSPOSTED = 1 << 0, /** this message originated from a message in another channel (via Channel Following) */ IS_CROSSPOST = 1 << 1, /** do not include any embeds when serializing this message */ SUPPRESS_EMBEDS = 1 << 2, /** the source message for this crosspost has been deleted (via Channel Following) */ SOURCE_MESSAGE_DELETED = 1 << 3, /** this message came from the urgent message system */ URGENT = 1 << 4, /** this message has an associated thread, with the same id as the message */ HAS_THREAD = 1 << 5, /** this message is only visible to the user who invoked the Interaction */ EPHEMERAL = 1 << 6, /** this message is an Interaction Response and the bot is "thinking" */ LOADING = 1 << 7, } /** https://discord.com/developers/docs/resources/channel#message-reference-object-message-reference-structure */ export interface MessageReference { /** id of the originating message */ message_id?: snowflake /** id of the originating message's channel */ channel_id?: snowflake /** id of the originating message's guild */ guild_id?: snowflake /** when sending, whether to error if the referenced message doesn't exist instead of sending as a normal (non-reply) message, default true */ fail_if_not_exists?: boolean } /** https://discord.com/developers/docs/resources/channel#embed-object-embed-structure */ export interface Embed { /** title of embed */ title?: string /** type of embed (always "rich" for webhook embeds) */ type?: string /** description of embed */ description?: string /** url of embed */ url?: string /** timestamp of embed content */ timestamp?: timestamp /** color code of the embed */ color?: integer /** footer information */ footer?: EmbedFooter /** image information */ image?: EmbedImage /** thumbnail information */ thumbnail?: EmbedThumbnail /** video information */ video?: EmbedVideo /** provider information */ provider?: EmbedProvider /** author information */ author?: EmbedAuthor /** fields information */ fields?: EmbedField[] } /** https://discord.com/developers/docs/resources/channel#embed-object-embed-thumbnail-structure */ export interface EmbedThumbnail { /** source url of thumbnail (only supports http(s) and attachments) */ url: string /** a proxied url of the thumbnail */ proxy_url?: string /** height of thumbnail */ height?: integer /** width of thumbnail */ width?: integer } /** https://discord.com/developers/docs/resources/channel#embed-object-embed-video-structure */ export interface EmbedVideo { /** source url of video */ url?: string /** a proxied url of the video */ proxy_url?: string /** height of video */ height?: integer /** width of video */ width?: integer } /** https://discord.com/developers/docs/resources/channel#embed-object-embed-image-structure */ export interface EmbedImage { /** source url of image (only supports http(s) and attachments) */ url: string /** a proxied url of the image */ proxy_url?: string /** height of image */ height?: integer /** width of image */ width?: integer } /** https://discord.com/developers/docs/resources/channel#embed-object-embed-provider-structure */ export interface EmbedProvider { /** name of provider */ name?: string /** url of provider */ url?: string } /** https://discord.com/developers/docs/resources/channel#embed-object-embed-author-structure */ export interface EmbedAuthor { /** name of author */ name: string /** url of author */ url?: string /** url of author icon (only supports http(s) and attachments) */ icon_url?: string /** a proxied url of author icon */ proxy_icon_url?: string } /** https://discord.com/developers/docs/resources/channel#embed-object-embed-footer-structure */ export interface EmbedFooter { /** footer text */ text: string /** url of footer icon (only supports http(s) and attachments) */ icon_url?: string /** a proxied url of footer icon */ proxy_icon_url?: string } /** https://discord.com/developers/docs/resources/channel#embed-object-embed-field-structure */ export interface EmbedField { /** name of the field */ name: string /** value of the field */ value: string /** whether or not this field should display inline */ inline?: boolean } /** https://discord.com/developers/docs/resources/channel#attachment-object-attachment-structure */ export interface Attachment { /** attachment id */ id: snowflake /** name of file attached */ filename: string /** the attachment's media type */ content_type?: string /** size of file in bytes */ size: integer /** source url of file */ url: string /** a proxied url of file */ proxy_url: string /** height of file (if image) */ height?: integer /** width of file (if image) */ width?: integer /** whether this attachment is ephemeral */ ephemeral?: boolean } /** https://discord.com/developers/docs/resources/channel#channel-mention-object-channel-mention-structure */ export interface ChannelMention { /** id of the channel */ id: snowflake /** id of the guild containing the channel */ guild_id: snowflake /** the type of channel */ type: ChannelType /** the name of the channel */ name: string } export interface MessageCreateEvent extends Message {} export interface MessageUpdateEvent extends Message {} /** https://discord.com/developers/docs/topics/gateway#message-delete-message-delete-event-fields */ export interface MessageDeleteEvent { /** the id of the message */ id: snowflake /** the id of the channel */ channel_id: snowflake /** the id of the guild */ guild_id?: snowflake } /** https://discord.com/developers/docs/topics/gateway#message-delete-bulk-message-delete-bulk-event-fields */ export interface MessageDeleteBulkEvent { /** the ids of the messages */ ids: snowflake[] /** the id of the channel */ channel_id: snowflake /** the id of the guild */ guild_id?: snowflake } declare module './gateway' { interface GatewayEvents { /** message was created */ MESSAGE_CREATE: MessageCreateEvent /** message was edited */ MESSAGE_UPDATE: MessageUpdateEvent /** message was deleted */ MESSAGE_DELETE: MessageDeleteEvent /** multiple messages were deleted at once */ MESSAGE_DELETE_BULK: MessageDeleteBulkEvent } } declare module './internal' { interface Internal { /** https://discord.com/developers/docs/resources/channel#get-channel-messages */ getChannelMessages(channel_id: snowflake): Promise<Message[]> /** https://discord.com/developers/docs/resources/channel#get-channel-message */ getChannelMessage(channel_id: snowflake, message_id: snowflake): Promise<Message> /** https://discord.com/developers/docs/resources/channel#create-message */ createMessage(channel_id: snowflake, data: Partial<Message>): Promise<Message> /** https://discord.com/developers/docs/resources/channel#crosspost-message */ crosspostMessage(channel_id: snowflake, message_id: snowflake): Promise<Message> /** https://discord.com/developers/docs/resources/channel#edit-message */ editMessage(channel_id: snowflake, message_id: snowflake, data: Partial<Message>): Promise<Message> /** https://discord.com/developers/docs/resources/channel#delete-message */ deleteMessage(channel_id: snowflake, message_id: snowflake): Promise<void> /** https://discord.com/developers/docs/resources/channel#bulk-delete-messages */ bulkDeleteMessages(channel_id: snowflake, message_ids: snowflake[]): Promise<void> } } Internal.define({ '/channels/{channel.id}/messages': { GET: 'getChannelMessages', POST: 'createMessage', }, '/channels/{channel.id}/messages/{message.id}': { GET: 'getChannelMessage', PATCH: 'editMessage', DELETE: 'deleteMessage', }, '/channels/{channel.id}/messages/{message.id}/crosspost': { POST: 'crosspostMessage', }, '/channels/{channel.id}/messages/bulk-delete': { POST: 'bulkDeleteMessages', }, })
the_stack
import { Component, Prop, Watch } from 'vue-property-decorator'; import { State } from 'vuex-class'; import { arrayIndexBy } from '../../../../utils/array'; import { Api } from '../../../api/api.service'; import { Device } from '../../../device/device.service'; import { Environment } from '../../../environment/environment.service'; import AppExpand from '../../../expand/expand.vue'; import { currency } from '../../../filters/currency'; import { AppFocusWhen } from '../../../form-vue/focus-when.directive'; import AppForm from '../../../form-vue/form'; import { BaseForm, FormOnInit, FormOnSubmit, FormOnSubmitError, FormOnSubmitSuccess, } from '../../../form-vue/form.service'; import { Geo, Region } from '../../../geo/geo.service'; import { Growls } from '../../../growls/growls.service'; import { HistoryTick } from '../../../history-tick/history-tick-service'; import AppLoadingFade from '../../../loading/fade/fade.vue'; import AppLoading from '../../../loading/loading.vue'; import { Navigate } from '../../../navigate/navigate.service'; import { OrderPayment } from '../../../order/payment/payment.model'; import AppPopper from '../../../popper/popper.vue'; import { Screen } from '../../../screen/screen-service'; import { Sellable } from '../../../sellable/sellable.model'; import { AppStore } from '../../../store/app-store'; import { AppTooltip } from '../../../tooltip/tooltip-directive'; import { User } from '../../../user/user.model'; import { GameBuild } from '../../build/build.model'; import { Game } from '../../game.model'; import { GamePackage } from '../package.model'; type CheckoutType = 'cc-stripe' | 'paypal' | 'wallet'; @Component({ components: { AppLoading, AppLoadingFade, AppExpand, AppPopper, }, directives: { AppTooltip, AppFocusWhen, }, filters: { currency, }, }) export default class FormGamePackagePayment extends BaseForm<any> implements FormOnInit, FormOnSubmit, FormOnSubmitSuccess, FormOnSubmitError { @Prop(Game) game!: Game; @Prop(GamePackage) package!: GamePackage; @Prop(GameBuild) build?: GameBuild; @Prop(Sellable) sellable!: Sellable; @Prop(String) partnerKey?: string; @Prop(User) partner?: User; @Prop(String) operation!: 'download' | 'play'; @State app!: AppStore; $refs!: { form: AppForm; }; warnOnDiscard = false; isLoaded = false; isLoadingMethods = true; isProcessing = false; checkoutType: CheckoutType = 'cc-stripe'; checkoutStep = 'primary'; cards: any[] = []; cardsTax = {}; addresses: any[] = []; calculatedAddressTax = false; addressTaxAmount = 0; countries = Geo.getCountries(); regions: Region[] | null = null; walletBalance = 0; walletTax = 0; minOrderAmount = 50; readonly Screen = Screen; get isNameYourPrice() { return this.sellable.type === 'pwyw'; } get isPlaying() { return this.operation === 'play'; } get isDownloading() { return this.operation === 'download' && !GJ_IS_CLIENT; } get isInstalling() { return this.operation === 'download' && GJ_IS_CLIENT; } get pricing() { return this.sellable.pricings[0]; } get _minOrderAmount() { return this.sellable.type === 'paid' ? this.pricing.amount / 100 : this.minOrderAmount / 100; } get formattedAmount() { return currency(this.pricing.amount); } get minOrderMessage() { return this.$gettextInterpolate( `Because of payment processing fees, we are not able to sell this game for less than %{ amount }. You can click the link below to grab the download for free, though!`, { amount: currency(this.minOrderAmount) } ); } get hasSufficientWalletFunds() { if (!this.formModel.amount || this.formModel.amount <= 0) { return true; } // When we're filling in the address, pull that tax. // Otherwise, when we're on the main page, check the wallet tax amount for their saved address. const taxAmount = this.checkoutStep === 'address' ? this.addressTaxAmount : this.walletTax; const sellableAmount = this.pricing.amount; const currentAmount = this.formModel.amount * 100; // The formModel amount is a decimal. // Paid games have to be more than the amount of the game base price. if ( this.sellable.type === Sellable.TYPE_PAID && this.walletBalance < sellableAmount + taxAmount ) { return false; } // All games have to be more than they've entered into the box. if (this.walletBalance < currentAmount + taxAmount) { return false; } return true; } onInit() { // If they don't have a default pricing amount set for this sellable, // just do $1. this.setField('amount', this.pricing.amount ? this.pricing.amount / 100 : 1); this.setField('country', 'us'); this.load(); } @Watch('formModel.country') onCountryChange() { this.regions = Geo.getRegions(this.formModel.country) || null; if (this.regions) { this.setField('region', this.regions[0].code); // Default to first. } else { this.setField('region', ''); } this.getAddressTax(); } @Watch('formModel.region') onTaxFieldsChange() { this.getAddressTax(); } @Watch('formModel.amount') onAmountChange() { this.isLoadingMethods = true; this.load(); } async load() { const response = await Api.sendRequest( '/web/checkout/methods?amount=' + this.formModel.amount * 100, null, { detach: true } ); this.isLoadingMethods = false; this.isLoaded = true; this.minOrderAmount = response.minOrderAmount || 50; if (response && response.cards && response.cards.length) { this.cards = response.cards; this.cardsTax = arrayIndexBy<any>(response.cardsTax, 'id'); } if (response && response.billingAddresses && response.billingAddresses.length) { this.addresses = response.billingAddresses; } if (response && response.walletBalance && response.walletBalance > 0) { this.walletBalance = response.walletBalance; this.walletTax = response.walletTax; } } addMoney(amount: number) { let curAmount: number = typeof this.formModel.amount === 'string' ? parseFloat(this.formModel.amount) : this.formModel.amount; if (!curAmount) { curAmount = amount; } else { curAmount += amount; curAmount = parseFloat(curAmount.toFixed(2)); } this.setField('amount', curAmount); } collectAddress(checkoutType: CheckoutType) { if (this.addresses.length) { if (checkoutType === 'paypal') { this.checkoutPaypal(); this.$refs.form.submit(); return; } else if (checkoutType === 'wallet') { this.checkoutWallet(); return; } } this.checkoutStep = 'address'; this.checkoutType = checkoutType; this.calculatedAddressTax = false; this.addressTaxAmount = 0; this.getAddressTax(); } async getAddressTax() { this.calculatedAddressTax = false; if (!this.formModel.country || !this.formModel.region) { return; } const data = { amount: this.formModel.amount * 100, country: this.formModel.country, region: this.formModel.region, }; const response = await Api.sendRequest('/web/checkout/taxes', data, { detach: true, }); this.calculatedAddressTax = true; this.addressTaxAmount = response.amount; } checkoutCard() { this.checkoutType = 'cc-stripe'; } checkoutPaypal() { this.checkoutType = 'paypal'; } startOver() { this.checkoutStep = 'primary'; } checkoutSavedCard(card: any) { const data: any = { payment_method: 'cc-stripe', sellable_id: this.sellable.id, pricing_id: this.pricing.id, amount: this.formModel.amount * 100, }; return this.doCheckout(data, { payment_source: card.id }); } checkoutWallet() { const data: any = { payment_method: 'wallet', sellable_id: this.sellable.id, pricing_id: this.pricing.id, amount: this.formModel.amount * 100, }; if (this.addresses.length) { data.address_id = this.addresses[0].id; } else { data.country = this.formModel.country; data.street1 = this.formModel.street1; data.region = this.formModel.region; data.postcode = this.formModel.postcode; } return this.doCheckout(data, { wallet: true }); } /** * This is for checkouts outside the normal form submit flow. * We need to manually handle processing and errors. */ private async doCheckout(setupData: any, chargeData: any) { if (this.isLoadingMethods || this.isProcessing) { return; } this.isProcessing = true; setupData['source'] = HistoryTick.getSource('Game', this.package.game_id) || null; setupData['os'] = Device.os(); setupData['arch'] = Device.arch(); setupData['ref'] = this.partnerKey || null; try { let response = await Api.sendRequest('/web/checkout/setup-order', setupData, { detach: true, }); if (response.success === false) { throw response; } response = await Api.sendRequest( '/web/checkout/charge/' + response.cart.id, chargeData, { detach: true, } ); if (response.success === false) { throw response; } // Notify that we've bought this package. this.$emit('bought'); } catch (_e) { this.isProcessing = false; // This should always succeed, so let's throw a generic message if it fails. Growls.error({ sticky: true, message: this.$gettext('There was a problem processing your payment method.'), }); } } onSubmit() { this.isProcessing = true; const data: any = { payment_method: this.checkoutType, sellable_id: this.sellable.id, pricing_id: this.pricing.id, amount: this.formModel.amount * 100, country: this.formModel.country, street1: this.formModel.street1, region: this.formModel.region, postcode: this.formModel.postcode, }; if (!this.app.user) { data.email_address = this.formModel.email_address; } if (this.addresses.length) { data.address_id = this.addresses[0].id; } data['source'] = HistoryTick.getSource('Game', this.package.game_id) || null; data['os'] = Device.os(); data['arch'] = Device.arch(); data['ref'] = this.partnerKey || null; return Api.sendRequest('/web/checkout/setup-order', data, { detach: true }); } onSubmitSuccess(response: any) { if (GJ_IS_CLIENT) { // Our checkout can be done in client. if (this.checkoutType === OrderPayment.METHOD_CC_STRIPE) { Navigate.goto(Environment.checkoutBaseUrl + '/checkout/' + response.cart.id); } else { // Otherwise we have to open in browser. Navigate.gotoExternal(response.redirectUrl); } } else { // For site we have to replace the URL completely since we are switching to https. Navigate.goto(response.redirectUrl); } } onSubmitError() { this.isProcessing = false; } }
the_stack
import { URL } from 'url'; import anyTest, { TestInterface } from 'ava'; import * as proxyquire from 'proxyquire'; import * as sinon from 'sinon'; import { ConnectorConfig, UserConfig } from '@hint/utils'; import { AnalyzerError, HintResources, IFetchOptions, IFormatter, FormatterOptions } from '../../src/lib/types'; import { AnalyzerErrorStatus } from '../../src/lib/enums/error-status'; import { Problem } from '@hint/utils-types'; type Logger = { warn: () => void; }; type Configuration = { connector: ConnectorConfig; fromConfig: () => Configuration; getFilenameForDirectory: (directory: string) => string; loadConfigFile: (filePath: string) => UserConfig; validateConnectorConfig: () => boolean; validateHintsConfig: () => { invalid: string[]; valid: string[] }; }; type ResourceLoader = { loadResources: () => HintResources; }; type FS = { cwd: () => string; isFile: () => boolean; }; type AnalyzerContext = { configuration: { Configuration: Configuration }; fs: FS; logger: Logger; resourceLoader: ResourceLoader; sandbox: sinon.SinonSandbox; }; const test = anyTest as TestInterface<AnalyzerContext>; const loadScript = (context: AnalyzerContext) => { const engine = { close() { }, executeOn(url: URL, options?: IFetchOptions): Promise<Problem[]> { return Promise.resolve([]); }, on(eventName: string, listener: () => {}) { }, prependAny() { } }; const engineWrapper = { Engine: function Engine() { return engine; } }; const script = proxyquire('../../src/lib/analyzer', { './config': context.configuration, './engine': engineWrapper, './utils/resource-loader': context.resourceLoader, '@hint/utils': { logger: context.logger }, '@hint/utils-fs': { cwd: context.fs.cwd, isFile: context.fs.isFile } }); return { Analyzer: script.Analyzer, engine }; }; test.beforeEach((t) => { t.context.configuration = { Configuration: { connector: { name: 'chrome' }, fromConfig() { return {} as any; }, getFilenameForDirectory(directory: string): string { return ''; }, loadConfigFile(filePath: string): UserConfig { return {}; }, validateConnectorConfig(): boolean { return true; }, validateHintsConfig() { return {} as any; } } }; t.context.logger = { warn() { } }; t.context.resourceLoader = { loadResources: () => { return {} as any; } }; t.context.fs = { cwd() { return ''; }, isFile() { return false; } }; t.context.sandbox = sinon.createSandbox(); }); test(`If userConfig not defined, it should return an error with the status 'ConfigurationError'`, (t) => { const { Analyzer } = loadScript(t.context); const error = t.throws<AnalyzerError>(() => { Analyzer.create(); }); t.is(error.status, AnalyzerErrorStatus.ConfigurationError); }); test(`If there is an error loading the configuration, it should return an error with the status 'ConfigurationError'`, (t) => { const { Analyzer } = loadScript(t.context); const sandbox = t.context.sandbox; const fromConfigStub = sandbox.stub(t.context.configuration.Configuration, 'fromConfig').throws(new Error()); const error = t.throws<AnalyzerError>(() => { Analyzer.create({}); }); t.true(fromConfigStub.calledOnce); t.is(error.status, AnalyzerErrorStatus.ConfigurationError); }); test(`If there is any missing or incompatible resource, it should return an error with the status 'ResourceError'`, (t) => { const { Analyzer } = loadScript(t.context); const sandbox = t.context.sandbox; const fromConfigStub = sandbox.stub(t.context.configuration.Configuration, 'fromConfig').returns(t.context.configuration.Configuration); const resourceLoaderStub = sandbox.stub(t.context.resourceLoader, 'loadResources').returns({ connector: null, formatters: [], hints: [], incompatible: ['hint1'], missing: ['hint2'], parsers: [] }); const error = t.throws<AnalyzerError>(() => { Analyzer.create({}); }); t.true(resourceLoaderStub.calledOnce); t.true(fromConfigStub.calledOnce); t.is(error.status, AnalyzerErrorStatus.ResourceError); }); test(`If the connector is not configured correctly, it should return an error with the status 'ConnectorError'`, (t) => { const { Analyzer } = loadScript(t.context); const sandbox = t.context.sandbox; const fromConfigStub = sandbox.stub(t.context.configuration.Configuration, 'fromConfig').returns(t.context.configuration.Configuration); const resourceLoaderStub = sandbox.stub(t.context.resourceLoader, 'loadResources').returns({ connector: null, formatters: [], hints: [], incompatible: [], missing: [], parsers: [] }); const validateConnectorConfigStub = sandbox.stub(t.context.configuration.Configuration, 'validateConnectorConfig').returns(false); const error = t.throws<AnalyzerError>(() => { Analyzer.create({}); }); t.true(validateConnectorConfigStub.calledOnce); t.true(resourceLoaderStub.calledOnce); t.true(fromConfigStub.calledOnce); t.is(error.status, AnalyzerErrorStatus.ConnectorError); }); test(`If there is any invalid hint, it should return an error with the status 'HintError'`, (t) => { const { Analyzer } = loadScript(t.context); const sandbox = t.context.sandbox; const fromConfigStub = sandbox.stub(t.context.configuration.Configuration, 'fromConfig').returns(t.context.configuration.Configuration); const resourceLoaderStub = sandbox.stub(t.context.resourceLoader, 'loadResources').returns({ connector: null, formatters: [], hints: [], incompatible: [], missing: [], parsers: [] }); const validateHintsConfigStub = sandbox.stub(t.context.configuration.Configuration, 'validateHintsConfig').returns({ invalid: ['hint1', 'hint2'], valid: [] }); const error = t.throws<AnalyzerError>(() => { Analyzer.create({}); }); t.true(validateHintsConfigStub.calledOnce); t.true(resourceLoaderStub.calledOnce); t.true(fromConfigStub.calledOnce); t.is(error.status, AnalyzerErrorStatus.HintError); }); test('If everything is valid, it will create an instance of the class Analyzer', (t) => { const { Analyzer } = loadScript(t.context); const sandbox = t.context.sandbox; const fromConfigStub = sandbox.stub(t.context.configuration.Configuration, 'fromConfig').returns(t.context.configuration.Configuration); const resourceLoaderStub = sandbox.stub(t.context.resourceLoader, 'loadResources').returns({ connector: null, formatters: [], hints: [], incompatible: [], missing: [], parsers: [] }); const validateHintsConfigStub = sandbox.stub(t.context.configuration.Configuration, 'validateHintsConfig').returns({ invalid: [], valid: [] }); Analyzer.create({}); t.true(validateHintsConfigStub.calledOnce); t.true(resourceLoaderStub.calledOnce); t.true(fromConfigStub.calledOnce); }); test('If the target is an string, it will analyze the url', async (t) => { const sandbox = t.context.sandbox; const { Analyzer, engine } = loadScript(t.context); const engineExecuteOnStub = sandbox.stub(engine, 'executeOn').resolves([]); const engineCloseStub = sandbox.stub(engine, 'close').resolves(); /* * Analyzer constructor is private, but for testing it * is easy if we call the constructor direcly. */ const webhint = new Analyzer({}, {}, []); await webhint.analyze('https://example.com/'); t.true(engineExecuteOnStub.calledOnce); t.true(engineCloseStub.calledOnce); t.is(engineExecuteOnStub.args[0][0].href, 'https://example.com/'); }); test('If the target is an URL, it will analyze it', async (t) => { const sandbox = t.context.sandbox; const { Analyzer, engine } = loadScript(t.context); const engineExecuteOnStub = sandbox.stub(engine, 'executeOn').resolves([]); const engineCloseStub = sandbox.stub(engine, 'close').resolves(); const webhint = new Analyzer({}, {}, []); await webhint.analyze(new URL('https://example.com/')); t.true(engineExecuteOnStub.calledOnce); t.true(engineCloseStub.calledOnce); t.is(engineExecuteOnStub.args[0][0].href, 'https://example.com/'); }); test('.close() will close the engine', async (t) => { const sandbox = t.context.sandbox; const { Analyzer, engine } = loadScript(t.context); const engineExecuteOnStub = sandbox.stub(engine, 'executeOn').resolves([]); const engineCloseStub = sandbox.stub(engine, 'close').resolves(); const webhint = new Analyzer({}, {}, []); await webhint.analyze(new URL('https://example.com/')); await webhint.close(); t.true(engineExecuteOnStub.calledOnce); /* * Engine close will be called twice, one when the analysis finish * and one more time when we call close. * `close` is meant to be called when there is an unhandled exception * otherwise `analyze` is going to capture the exception and call * to `engince.close()`. */ t.true(engineCloseStub.calledTwice); t.is(engineExecuteOnStub.args[0][0].href, 'https://example.com/'); }); test('If the target is a Target with a string url, it will analyze it', async (t) => { const sandbox = t.context.sandbox; const { Analyzer, engine } = loadScript(t.context); const engineExecuteOnStub = sandbox.stub(engine, 'executeOn').resolves([]); const engineCloseStub = sandbox.stub(engine, 'close').resolves(); const webhint = new Analyzer({}, {}, []); await webhint.analyze({ url: 'https://example.com/' }); t.true(engineExecuteOnStub.calledOnce); t.true(engineCloseStub.calledOnce); t.is(engineExecuteOnStub.args[0][0].href, 'https://example.com/'); }); test('If the target is a Target with a URL, it will analyze it', async (t) => { const sandbox = t.context.sandbox; const { Analyzer, engine } = loadScript(t.context); const engineExecuteOnStub = sandbox.stub(engine, 'executeOn').resolves([]); const engineCloseStub = sandbox.stub(engine, 'close').resolves(); const webhint = new Analyzer({}, {}, []); await webhint.analyze({ url: new URL('https://example.com/') }); t.true(engineExecuteOnStub.calledOnce); t.true(engineCloseStub.calledOnce); t.is(engineExecuteOnStub.args[0][0].href, 'https://example.com/'); }); test('If the target is an Array of strings, it will analyze all of them', async (t) => { const sandbox = t.context.sandbox; const { Analyzer, engine } = loadScript(t.context); const engineExecuteOnStub = sandbox.stub(engine, 'executeOn').resolves([]); const engineCloseStub = sandbox.stub(engine, 'close').resolves(); const webhint = new Analyzer({}, {}, []); await webhint.analyze(['https://example.com/', 'https://example2.com/', 'https://example3.com/']); t.true(engineExecuteOnStub.calledThrice); t.true(engineCloseStub.calledThrice); t.is(engineExecuteOnStub.args[0][0].href, 'https://example.com/'); t.is(engineExecuteOnStub.args[1][0].href, 'https://example2.com/'); t.is(engineExecuteOnStub.args[2][0].href, 'https://example3.com/'); }); test('If the target is an Array of URLs, it will analyze all of them', async (t) => { const sandbox = t.context.sandbox; const { Analyzer, engine } = loadScript(t.context); const engineExecuteOnStub = sandbox.stub(engine, 'executeOn').resolves([]); const engineCloseStub = sandbox.stub(engine, 'close').resolves(); const webhint = new Analyzer({}, {}, []); await webhint.analyze([new URL('https://example.com/'), new URL('https://example2.com/'), new URL('https://example3.com/')]); t.true(engineExecuteOnStub.calledThrice); t.true(engineCloseStub.calledThrice); t.is(engineExecuteOnStub.args[0][0].href, 'https://example.com/'); t.is(engineExecuteOnStub.args[1][0].href, 'https://example2.com/'); t.is(engineExecuteOnStub.args[2][0].href, 'https://example3.com/'); }); test('If the target is an Array of Targets, it will analyze all of them', async (t) => { const sandbox = t.context.sandbox; const { Analyzer, engine } = loadScript(t.context); const engineExecuteOnStub = sandbox.stub(engine, 'executeOn').resolves([]); const engineCloseStub = sandbox.stub(engine, 'close').resolves(); const webhint = new Analyzer({}, {}, []); await webhint.analyze([{ url: new URL('https://example.com/') }, { url: 'https://example2.com/' }, { url: new URL('https://example3.com/') }]); t.true(engineExecuteOnStub.calledThrice); t.true(engineCloseStub.calledThrice); t.is(engineExecuteOnStub.args[0][0].href, 'https://example.com/'); t.is(engineExecuteOnStub.args[1][0].href, 'https://example2.com/'); t.is(engineExecuteOnStub.args[2][0].href, 'https://example3.com/'); }); test('If the target is an Array of strings, URLs and Targets, it will analyze all of them', async (t) => { const sandbox = t.context.sandbox; const { Analyzer, engine } = loadScript(t.context); const engineExecuteOnStub = sandbox.stub(engine, 'executeOn').resolves([]); const engineCloseStub = sandbox.stub(engine, 'close').resolves(); const webhint = new Analyzer({}, {}, []); await webhint.analyze([{ url: new URL('https://example.com/') }, 'https://example2.com/', new URL('https://example3.com/')]); t.true(engineExecuteOnStub.calledThrice); t.true(engineCloseStub.calledThrice); t.is(engineExecuteOnStub.args[0][0].href, 'https://example.com/'); t.is(engineExecuteOnStub.args[1][0].href, 'https://example2.com/'); t.is(engineExecuteOnStub.args[2][0].href, 'https://example3.com/'); }); test('If options includes an updateCallback, it will call to engine.prependAny', async (t) => { const sandbox = t.context.sandbox; const { Analyzer, engine } = loadScript(t.context); sandbox.stub(engine, 'executeOn').resolves([]); sandbox.stub(engine, 'close').resolves(); const enginePrependAnySpy = sandbox.spy(engine, 'prependAny'); const webhint = new Analyzer({}, {}, []); await webhint.analyze('https://example.com/', { updateCallback: () => { } }); t.true(enginePrependAnySpy.calledOnce); }); test(`If the option watch was configured in the connector, the analyzer will subscribe to the event 'print' in the engine`, async (t) => { const sandbox = t.context.sandbox; const { Analyzer, engine } = loadScript(t.context); sandbox.stub(engine, 'executeOn').resolves([]); sandbox.stub(engine, 'close').resolves(); const engineOnSpy = sandbox.spy(engine, 'on'); const webhint = new Analyzer({ connector: { options: { watch: true } } }, {}, []); await webhint.analyze('https://example.com/'); t.true(engineOnSpy.calledOnce); t.is(engineOnSpy.args[0][0], 'print'); }); test(`If target.content is defined and the connector is not the local connector, it should return an exception`, async (t) => { const sandbox = t.context.sandbox; const { Analyzer, engine } = loadScript(t.context); const engineExecuteOnSpy = sandbox.spy(engine, 'executeOn'); const engineCloseSpy = sandbox.spy(engine, 'close'); const webhint = new Analyzer({ connector: { name: 'notLocal' } }, {}, []); const error: AnalyzerError = await t.throwsAsync(async () => { await webhint.analyze({ content: '<html></html>', url: 'https://example.com/' }); }); t.false(engineCloseSpy.called); t.false(engineExecuteOnSpy.called); t.is(error.status, AnalyzerErrorStatus.AnalyzeError); }); test('If options includes a targetStartCallback, it will be call before engine.executeOn', async (t) => { const sandbox = t.context.sandbox; const { Analyzer, engine } = loadScript(t.context); const options = { targetStartCallback() { } }; sandbox.stub(engine, 'close').resolves(); const engineExecuteOnStub = sandbox.stub(engine, 'executeOn').resolves([]); const targetStartCallbackStub = sandbox.stub(options, 'targetStartCallback').resolves(); const webhint = new Analyzer({}, {}, []); await webhint.analyze('https://example.com/', options); t.true(targetStartCallbackStub.calledOnce); t.true(targetStartCallbackStub.calledBefore(engineExecuteOnStub)); }); test('If options includes a targetEndCallback, it will be call after engine.executeOn', async (t) => { const sandbox = t.context.sandbox; const { Analyzer, engine } = loadScript(t.context); const options = { targetEndCallback() { } }; sandbox.stub(engine, 'close').resolves(); const engineExecuteOnStub = sandbox.stub(engine, 'executeOn').resolves([]); const targetEndCallbackStub = sandbox.stub(options, 'targetEndCallback').resolves(); const webhint = new Analyzer({}, {}, []); await webhint.analyze('https://example.com/', options); t.true(targetEndCallbackStub.calledOnce); t.true(targetEndCallbackStub.calledAfter(engineExecuteOnStub)); }); test('If engine.executeOn throws an exception, it should close the engine', async (t) => { const sandbox = t.context.sandbox; const { Analyzer, engine } = loadScript(t.context); sandbox.stub(engine, 'executeOn').throws(new Error()); const engineCloseStub = sandbox.stub(engine, 'close').resolves(); const webhint = new Analyzer({}, {}, []); try { await webhint.analyze('https://example.com/'); } catch { // do nothing. } t.true(engineCloseStub.calledOnce); }); test('If the option watch was configured in the connector, and the connector is not the local connector, it should print a warning message.', async (t) => { const sandbox = t.context.sandbox; const { Analyzer, engine } = loadScript(t.context); sandbox.stub(engine, 'executeOn').resolves([]); sandbox.stub(engine, 'close').resolves(); const loggerWarn = sandbox.spy(t.context.logger, 'warn'); const webhint = new Analyzer({ connector: { options: { watch: true } } }, {}, []); await webhint.analyze('https://example.com/'); t.true(loggerWarn.calledOnce); }); test('format should call to all the formatters', async (t) => { const sandbox = t.context.sandbox; class FakeFormatter implements IFormatter { public constructor() { } public format(problems: Problem[]) { } } const formatter = new FakeFormatter(); const { Analyzer, engine } = loadScript(t.context); const formatterFormatStub = sandbox.stub(formatter, 'format').resolves(); sandbox.stub(engine, 'executeOn').resolves([]); sandbox.stub(engine, 'close').resolves(); const webhint = new Analyzer({}, {}, [formatter]); await webhint.format([]); t.true(formatterFormatStub.calledOnce); }); test('format should call to formatters using the Analyzer resources, if no resources provided as options', async (t) => { const sandbox = t.context.sandbox; class FakeFormatter implements IFormatter { public constructor() { } public format(problems: Problem[], options: FormatterOptions) { } } const formatter = new FakeFormatter(); const { Analyzer, engine } = loadScript(t.context); const formatterFormatStub = sandbox.stub(formatter, 'format').resolves(); sandbox.stub(engine, 'executeOn').resolves([]); sandbox.stub(engine, 'close').resolves(); const resources: HintResources = { connector: null, formatters: [], hints: [], incompatible: [], missing: [], parsers: [] }; const webhint = new Analyzer({}, resources, [formatter]); await webhint.format([]); t.true(formatterFormatStub.calledWithMatch([], { resources })); }); test('resources should returns all the resources', (t) => { const sandbox = t.context.sandbox; const { Analyzer, engine } = loadScript(t.context); sandbox.stub(engine, 'executeOn').resolves([]); sandbox.stub(engine, 'close').resolves(); const resources = {}; const webhint = new Analyzer({}, resources, []); t.is(webhint.resources, resources); }); test('If config is not defined, it should get the config file from the directory process.cwd()', (t) => { const sandbox = t.context.sandbox; const cwd = 'currentDirectory'; sandbox.stub(t.context.fs, 'cwd').returns(cwd); sandbox.stub(t.context.fs, 'isFile').returns(false); const getFilenameForDirectorySpy = sandbox.spy(t.context.configuration.Configuration, 'getFilenameForDirectory'); const { Analyzer } = loadScript(t.context); Analyzer.getUserConfig(); t.is(getFilenameForDirectorySpy.args[0][0], cwd); }); test('If we pass a file, getUserConfig should use it to get the configuration.', (t) => { const sandbox = t.context.sandbox; const userConfig: UserConfig = {}; sandbox.stub(t.context.fs, 'isFile').returns(true); const getFilenameForDirectorySpy = sandbox.spy(t.context.configuration.Configuration, 'getFilenameForDirectory'); const loadConfigFileStub = sandbox.stub(t.context.configuration.Configuration, 'loadConfigFile').returns(userConfig); const file = 'file/path'; const { Analyzer } = loadScript(t.context); const result = Analyzer.getUserConfig(file); t.false(getFilenameForDirectorySpy.called); t.true(loadConfigFileStub.calledOnce); t.is(result, userConfig); }); test('If load a config fails, it returns null', (t) => { const sandbox = t.context.sandbox; sandbox.stub(t.context.fs, 'isFile').returns(false); const getFilenameForDirectoryStub = sandbox.stub(t.context.configuration.Configuration, 'getFilenameForDirectory').returns('file/path'); const loadConfigFileStub = sandbox.stub(t.context.configuration.Configuration, 'loadConfigFile').throws(new Error()); const { Analyzer } = loadScript(t.context); const result = Analyzer.getUserConfig(); t.true(getFilenameForDirectoryStub.calledOnce); t.true(loadConfigFileStub.calledOnce); t.is(result, null); });
the_stack
import type { HighlightOptions, PrettyFormatOptions, } from '@roots/bud-support' import { bind, format, highlight, lodash, } from '@roots/bud-support' import {Container} from '@roots/container' import { Api, Build, Compiler, Configuration, Dashboard, Dependencies, Env, Extension, Hooks, Mode, Server, Services, } from '../' import * as Cache from '../Cache' import {Extensions} from '../Extensions' import {Logger} from '../Logger' import * as Project from '../Project' import {lifecycle} from './lifecycle' import * as methods from './methods' import * as parser from './parser' const {isFunction, omit} = lodash /** * Base {@link Framework} class * * @public */ export abstract class Framework { /** * Concrete implementation of the {@link Framework} * * @internal @virtual */ public abstract implementation: Constructor /** * Framework name * * @remarks * The name of the parent compiler is used as a base when sourcing configuration files. * So, in an implementation that uses the name `app`, the Framework will be sourcing * `app.config.js`, `app.development.config.js`, etc. * * @public */ public get name(): string { return ( this.store?.get('name') ?? this.options.config.name ?? 'bud' ) } public set name(name: string) { this.store.set('name', name) } /** * Compilation mode * * @remarks * Either `production` or `development`. Unlike webpack, there is no 'none' mode. * * @defaultValue 'production' */ public get mode(): Mode { return this.store.get('mode') } public set mode(mode: Mode) { this.store.set('mode', mode) } /** * Parent {@link Framework} instance * * @remarks * Is `null` if the current instance is the parent instance. * * @defaultValue null */ public root: Framework | null = this /** * True when current instance is the parent instance * * @readonly */ public get isRoot(): boolean { return this.root.name === this.name } /** * True when current instance is a child instance * * @readonly */ public get isChild(): boolean { return this.root.name !== this.name } /** * {@link @roots/container#Container} of child {@link Framework} instances * * @remarks * Is `null` if the current instance is a child instance. * * @defaultValue null */ public children: Container<Record<string, Framework>> = null /** * True when {@link Framework} has children * * @readonly */ public get hasChildren(): boolean { return this.children?.getEntries().length > 0 } /** * Framework services * * @remarks * Can be set directly on the child instance or passed as a property in the {@link Options}. * * @public */ public services: Services /** * Macros for assisting with common config tasks * * @public */ public api: Api /** * Build service * * @public */ public build: Build.Interface /** * Determines cache validity and generates cache keys. * * @public */ public cache: Cache.Interface /** * Compiles {@link @roots/bud-framework#Build | Build} configuration and stats/errors/progress reporting. * * @public */ public compiler: Compiler /** * Presents build progress, stats and errors from {@link Compiler} and {@link Server} * over the CLI. * * @public */ public dashboard: Dashboard /** * Utilities for interfacing with user package manager software * * @public */ public dependencies: Dependencies /** * Project information and peer dependency management utilities * * @public */ public project: Project.Interface /** * .env container * * @public */ public env: Env /** * Container service for {@link Framework} extensions. * * @remarks * Extensions can be defined as a {@link Module}, which is more generic. * * They can also be defined as a {@link WebpackPlugin} which is a {@link Module} * specifically yielding a {@link WebpackPluginInstance}. * * When adding a {@link Module} or {@link Plugin} to the container * with {@link Extensions.add} it is cast to the {@link Extension} type. * * @public */ public extensions: Extensions /** * Service allowing for fitering {@link Framework} values through callbacks. * * @example Add a new entry to the `webpack.externals` configuration: * ```ts * hooks.on( * 'build/externals', * externals => ({ * ...externals, * $: 'jquery', * }) * ) * ``` * * @example Change the `webpack.output.filename` format: * ```ts * hooks.on( * 'build.output.filename', * () => '[name].[hash:4]', * ) * ``` * * @public */ public hooks: Hooks /** * Logging service * * @public */ public logger: Logger /** * Development server and browser devtools * * @public */ public _server: Server.Interface public get server(): Server.Interface { return this.root._server } public set server(server: Server.Interface) { this.root._server = server } /** * Container service for holding configuration values * * @public */ public store: Container /** * True when {@link Framework.mode} is `production` * * @public */ public get isProduction(): boolean { return this.mode === 'production' } /** * True when {@link Framework.mode} is `development` * * @public */ public get isDevelopment(): boolean { return this.mode === 'development' } /** * True if ts-node has been invoked * * @public */ public usingTsNode: boolean = false /** * Initially received options * * @public */ public options: Options /** * Class constructor * * @param options - {@link Framework.Options | Framework constructor options} * * @public */ public constructor(options: Options) { this.options = options this.logger = new Logger(this) this.store = this.container(options.config) if (!options.childOf) { this.children = this.container() this.root = this } else { this.root = options.childOf } this.lifecycle = lifecycle.bind(this) this.services = options.services Object.entries(methods).map(([key, method]) => { if (!isFunction(method)) { this.error( `framework ctor`, `method "${key}" is not a function`, ) } this[key] = method.bind(this) }) } /** * @internal */ public lifecycle: lifecycle = lifecycle.bind(this) /** * Access a value which may or may not be a function. * * @remarks * If a value is a function **access** will call that function and return the result. * * If the value is not a function **access** will return its value. * * @example * ```js * const isAFunction = (option) => `option value: ${option}` * const isAValue = 'option value: true' * * access(isAFunction, true) // => `option value: true` * access(isAValue) // => `option value: true` * ``` * * @public */ public maybeCall: methods.maybeCall = methods.maybeCall.bind(this) /** * Gracefully shutdown {@link Framework} and registered {@link @roots/bud-framework#Service | Service instances} * * @example * ```js * bud.close() * ``` * * @public */ public close: methods.close = methods.close.bind(this) /** * Create a new {@link Container} instance * * @example * ```js * const myContainer = bud.container({key: methods.'value'}) * * myContainer.get('key') // returns 'value' * ``` * * @public */ public container: methods.container = methods.container.bind(this) /** * Returns a {@link Framework | Framework instance} from the {@link Framework.children} container * * @remarks * An optional {@link tap} function can be provided to configure the {@link Framework} instance. * * @example * ```js * const name = 'plugin' * const tapFn = plugin => plugin.entry('main', 'main.js') * * bud.get(name, tapFn) * ``` * * @public */ public get: methods.get = methods.get.bind(this) /** * Instantiate a child instance and add to {@link Framework.children} container * * @remarks * **make** takes two parameters: * * - The **name** of the new compiler * - An optional callback to use for configuring the compiler. * * @example * ```js * bud.make('scripts', child => child.entry('app', 'app.js')) * ``` * * @public */ public make: methods.make = methods.make.bind(this) /** * Returns a {@link Locations} value as an absolute path * * @public */ public path: methods.path = methods.path.bind(this) /** * Pipe a value through an array of functions. The return value of each callback is used as input for the next. * * @remarks * If no value is provided the value is assumed to be the {@link Framework} itself * * {@link sequence} is a non-mutational version of this method. * * @example * ```js * app.pipe( * [ * value => value + 1, * value => value + 1, * ], * 1, // initial value * ) // resulting value is 3 * ``` * * @public */ public pipe: methods.pipe = methods.pipe.bind(this) /** * Set a {@link @roots/bud-framework#Location | Location} value * * @remarks * The {@link Location.project} should be an absolute path. * All other directories should be relative (src, dist, etc.) * @see {@link Locations} * * @example * ```js * bud.setPath('src', 'custom/src') * ``` * * @param this - {@link Framework} * @param args - path parts * * @public */ public setPath: methods.setPath = methods.setPath.bind(this) /** * Run a value through an array of syncronous, non-mutational functions. * * @remarks * Unlike {@link pipe} the value returned from each function is ignored. * * @public */ public sequence: methods.sequence = methods.sequence.bind(this) /** * Execute a callback * * @remarks * Callback is provided {@link Framework | the Framework instance} as a parameter. * * @example * ```js * bud.tap(bud => { * // do something with bud * }) * ``` * * @example * Lexical scope is bound to Framework where applicable, so it * is possible to reference the Framework using `this`. * * ```js * bud.tap(function () { * // do something with this * }) * ``` * * @public */ public tap: methods.tap = methods.tap.bind(this) /** * Executes a function if a given test is `true`. * * @remarks * - The first parameter is the conditional check. * - The second parameter is the function to run if `true`. * - The third parameter is optional; executed if the conditional is not `true`. * * @example * Only produce a vendor bundle when running in `production` {@link Mode}: * * ```js * bud.when(bud.isProduction, () => bud.vendor()) * ``` * * @example * Use `eval` sourcemap in development mode and `hidden-source-map` in production: * * ```js * bud.when( * bud.isDevelopment, * () => bud.devtool('eval'), * () => bud.devtool('hidden-source-map'), * ) * ``` * * @public */ public when: methods.when = methods.when.bind(this) /** * Bind method to {@link Framework | Framework instance} * * @public */ public bindMethod: methods.bindMethod = methods.bindMethod.bind(this) /** * Adds a class as a property of the Framework * * @public */ public mixin: typeof methods.mixin /** * Read and write json files * * @public */ public json: typeof parser.json = parser.json /** * Read and write yaml files * * @public */ public yml: typeof parser.yml = parser.yml /** * Read and write typescript files * * @public */ public ts: typeof parser.ts = { read: parser.ts.read.bind(this), } /** * Log a message * * @public * @decorator `@bind` */ @bind public log(...messages: any[]) { this.logger?.instance && this.logger.instance .scope(...this.logger.context) .log(...messages) return this } /** * Log an `info` level message * * @public * @decorator `@bind` */ @bind public info(...messages: any[]) { this.logger?.instance && this.logger.instance .scope(...this.logger.context) .info(...messages) return this } /** * Log a `success` level message * * @public * @decorator `@bind` */ @bind public success(...messages: any[]) { this.logger?.instance && this.logger.instance .scope(...this.logger.context) .success(...messages) return this } /** * Log a `warning` level message * * @public * @decorator `@bind` */ @bind public warn(...messages: any[]) { this.logger?.instance && this.logger.instance .scope(...this.logger.context) .warn(...messages) return this } /** * Log a `warning` level message * * @public * @decorator `@bind` */ @bind public time(...messages: any[]) { this.logger?.instance && this.logger.instance .scope(...this.logger.context) .time(...messages) return this } /** * Log a `warning` level message * * @public * @decorator `@bind` */ @bind public await(...messages: any[]) { this.logger?.instance && this.logger.instance .scope(...this.logger.context) .await(...messages) return this } /** * Log a `warning` level message * * @public * @decorator `@bind` */ @bind public complete(...messages: any[]) { this.logger.instance .scope(...this.logger.context) .complete(...messages) return this } /** * Log a `warning` level message * * @public * @decorator `@bind` */ @bind public timeEnd(...messages: any[]) { this.logger.instance .scope(...this.logger.context) .timeEnd(...messages) return this } /** * Log and display a debug message. * * @remarks * This error is fatal and will kill the process * * @public * @decorator `@bind` */ @bind public debug(...messages: any[]) { // eslint-disable-next-line no-console process.stdout.write( `${highlight( format(messages, { callToJSON: false, maxDepth: 8, printFunctionName: false, escapeString: false, min: this.options.config.cli.flags['log.min'], }), )}`, ) process.exit(1) } /** * Log and display an error. * * @remarks * This error is fatal and will kill the process * * @public * @decorator `@bind` */ @bind public error(...messages: any[]) { this.logger.instance .scope(...this.logger.context) .error(...messages) return this } @bind public dump( obj: any, options?: PrettyFormatOptions & HighlightOptions & {prefix: string}, ): Framework { if (this.logger.level !== 'log') return const prettyFormatOptions = omit(options, [ 'prefix', 'language', 'ignoreIllegals', ]) // eslint-disable-next-line no-console process.stdout.write( `${ options?.prefix ? `\n${options.prefix}\n` : `\n` }${highlight( format(obj, { callToJSON: false, maxDepth: 8, printFunctionName: false, escapeString: false, min: this.options.config.cli.flags['log.min'], ...prettyFormatOptions, }), { language: options?.language ?? 'typescript', ignoreIllegals: options?.ignoreIllegals ?? true, }, )}`, ) return this } } /** * Framework Constructor */ export type Constructor = new (options: Options) => Framework /* * Constructor options */ export interface Options { /** * The object providing initial configuration values. * * @remarks * It is probable that extensions and services will modify * values introduced in this object. If you are looking to simply modify * configuration values it is generally a better idea to use the * {@link @roots/bud-hooks#Hooks | Hooks class} instead. * * @public */ config?: Partial<Configuration> /** * Framework services * @public */ services?: Services /** * @internal */ childOf?: Framework /** * Extensions to be registered * * @public */ extensions?: () => Record< string, Extension.Module | Extension.CompilerPlugin > }
the_stack
import { Component, ViewChild, AfterViewInit } from '@angular/core' import { Block, FullNode, NetworkApi, NetworkClientBrowserImpl } from 'blockchain-js-core' import * as CryptoJS from 'crypto-js' import { WebSocketConnector } from 'blockchain-js-core/dist/websocket-connector' import { State } from './supply-chain/state' import * as Paint from './supply-chain/paint' import * as Blockchain from 'blockchain-js-core' const NETWORK_CLIENT_IMPL = new NetworkClientBrowserImpl.NetworkClientBrowserImpl() const STORAGE_BLOCKS = 'blocks' const STORAGE_SETTINGS = 'settings' function sleep(time: number) { return new Promise((resolve, reject) => setTimeout(resolve, time)) } @Component({ selector: 'body', templateUrl: './app.component.html', providers: [State] }) export class AppComponent { @ViewChild("mainElement") mainElement // To save encryptMessages = false encryptionKey = this.guid() otherEncryptionKeys: string[] = [] desiredNbIncomingPeers = 3 desiredNbOutgoingPeers = 3 autoSave = true autoConnectNaturalPeer = true miningDifficulty = 100 expandedUi = false selectedTab = 5 isMining = false autoMining = false autoMiningIteration = 1 accepting = new Map<string, { offerId: string; offerMessage: string }>() knownAcceptedMessages = new Set<string>() _selectedBranch = Blockchain.Block.MASTER_BRANCH get selectedBranch() { return this._selectedBranch } set selectedBranch(branch: string) { this._selectedBranch = branch } _supplyChainBranch = null get supplyChainBranch() { return this._supplyChainBranch } set supplyChainBranch(value) { if (this._supplyChainBranch == value) return this._supplyChainBranch = value this.state.smartContract.setBranch(value) } private peersSockets = new Map<FullNode.PeerInfo, { ws: NetworkApi.WebSocket, isSelfInitiated: boolean, counterpartyId: string }>() private decypherCache = new Map<string, string>() toggleFullScreen() { if (this.mainElement.nativeElement.requestFullscreen) this.mainElement.nativeElement.requestFullscreen() else if (this.mainElement.nativeElement.webkitRequestFullScreen) this.mainElement.nativeElement.webkitRequestFullScreen() } toggleExpandedUi() { this.expandedUi = !this.expandedUi } selectTab(i) { this.selectedTab = i } get incomingPeersCount() { let count = 0 this.state.fullNode.peerInfos.forEach(peer => { if (this.peersSockets.has(peer) && !this.peersSockets.get(peer).isSelfInitiated) count++ }) return count } get outgoingPeersCount() { let count = 0 this.state.fullNode.peerInfos.forEach(peer => { if (this.peersSockets.has(peer) && this.peersSockets.get(peer).isSelfInitiated) count++ }) return count } constructor(public state: State) { window.addEventListener('beforeunload', _ => { if (this.autoSave) { this.savePreferencesToLocalStorage() } }) this.state.init() Paint.setSmartProgram(this.state.smartContract) this.loadPreferencesFromLocalStorage() //this.tryLoadBlocksFromLocalStorage() this.ensureUser() if (this.autoConnectNaturalPeer) { this.connectToNaturalRemoteNode() this.connectToRemoteMiner() } setInterval(() => { if (this.autoConnectNaturalPeer) { this.connectToNaturalRemoteNode() this.connectToRemoteMiner() } }, 5000) } setPseudo(pseudo: string) { this.state.callContract(this.state.IDENTITY_REGISTRY_CONTRACT_ID, 0, 'setPseudo', this.state.user, { pseudo }) } setSummplyChainBranch(branch: string) { this.supplyChainBranch = branch } private async ensureUser() { if (this.state.user) return const id = this.guid() const keys = await Blockchain.HashTools.generateRsaKeyPair() this.state.setUserInformations(id, keys) this.savePreferencesToLocalStorage() } addEncryptionKey(newEncryptionKey: string) { if (!newEncryptionKey || !newEncryptionKey.length || this.otherEncryptionKeys.includes(newEncryptionKey)) return this.decypherCache.clear() this.otherEncryptionKeys.push(newEncryptionKey) } toList(obj) { return Object.getOwnPropertyNames(obj).map(p => obj[p]) } keysOf(obj) { return Object.keys(obj) } removeEncryptionKey(key) { this.otherEncryptionKeys = this.otherEncryptionKeys.filter(k => k != key) } decypher(message: string) { if (!message || message.length < 5) return `(invalid) ${message}` if (this.decypherCache.has(message)) return this.decypherCache.get(message) let decypheredMessage = `(crypted) ${message}` for (let key of this.otherEncryptionKeys) { let decyphered = CryptoJS.AES.decrypt(message, key).toString(CryptoJS.enc.Utf8) if (!decyphered || decyphered.length < 6) continue let check = decyphered.substr(-3) decyphered = decyphered.substr(0, decyphered.length - 3) if (check == decyphered.substr(-3)) { this.decypherCache.set(message, decyphered) decypheredMessage = decyphered break } } this.decypherCache.set(message, decypheredMessage) return decypheredMessage } async mine(message: string) { if (this.isMining || message == '' || this.miningDifficulty <= 0) return this.isMining = true try { let dataItem = { id: this.guid(), author: this.state.user.id, message, encrypted: false } if (this.encryptMessages && this.encryptionKey) { dataItem.message = dataItem.message.padStart(3, '=') this.addEncryptionKey(this.encryptionKey) dataItem.message = CryptoJS.AES.encrypt(dataItem.message + dataItem.message.substr(-3), this.encryptionKey).toString() dataItem.encrypted = true } this.state.messageSequence.addItems([dataItem]) } catch (error) { this.log(`error mining: ${JSON.stringify(error)}`) } finally { this.isMining = false } } log(message) { this.state.log(message) } toggleAutomine(minedData, automineTimer) { if (this.autoMining) { this.autoMining = false } else { this.autoMining = true let action = async () => { this.autoMining && await this.mine(`${minedData} - ${this.autoMiningIteration++}`) if (this.autoMining) setTimeout(action, automineTimer) } action() } } private remoteMinerWebSocket: NetworkApi.WebSocket private connectToRemoteMiner() { if (this.remoteMinerWebSocket) return return /* let protocol = location.protocol.startsWith('https') ? 'wss' : 'ws' let host = location.hostname let port = protocol == 'wss' ? 443 : 9091 this.remoteMinerWebSocket = NETWORK_CLIENT_IMPL.createClientWebSocket(`${protocol}://${host}:${port}/mining`) let addData = async (branch: string, data: any): Promise<boolean> => { if (!this.remoteMinerWebSocket) return false try { this.remoteMinerWebSocket.send(JSON.stringify({ branch, data })) return true } catch (error) { return false } } this.remoteMinerWebSocket.on('open', () => { console.log(`remote miner connected`) this.state.remoteMining = addData }) this.remoteMinerWebSocket.on('error', (err) => { console.log(`error with remote miner : ${err}`) this.state.remoteMining = null this.remoteMinerWebSocket.close() }) this.remoteMinerWebSocket.on('close', () => { console.log('remote miner disconnected') this.state.remoteMining = null this.remoteMinerWebSocket = null }) */ } private naturalRemoteWebSocket: NetworkApi.WebSocket private connectToNaturalRemoteNode() { if (this.naturalRemoteWebSocket) return let protocol = location.protocol.startsWith('https') ? 'wss' : 'ws' let host = location.hostname let basePath = '' console.log(location.pathname) console.log(location.pathname.lastIndexOf('/')) if (location.pathname.lastIndexOf('/') > 0) { basePath = location.pathname.substring(0, location.pathname.lastIndexOf('/')) } let port = protocol == 'wss' ? 443 : 9091 this.naturalRemoteWebSocket = NETWORK_CLIENT_IMPL.createClientWebSocket(`${protocol}://${host}:${port}${basePath}/events`) this.naturalRemoteWebSocket.on('error', (err) => { console.error(`error with natural peer : ${err}`) this.naturalRemoteWebSocket.close() }) this.naturalRemoteWebSocket.on('close', () => { console.error('natural peer disconnected') this.naturalRemoteWebSocket = null }) this.addPeerBySocket(this.naturalRemoteWebSocket, `natural-remote`, true, `natural direct peer ${host}:${port}`) } addPeer(peerHost, peerPort, peerSecure) { console.log(`add peer ${peerHost}:${peerPort}`) let ws = NETWORK_CLIENT_IMPL.createClientWebSocket(`${peerSecure ? 'wss' : 'ws'}://${peerHost}:${peerPort}/events`) this.addPeerBySocket(ws, `${peerHost}:${peerPort}`, true, `direct peer ${peerHost}:${peerPort}`) } private addPeerBySocket(ws: NetworkApi.WebSocket, counterpartyId: string, isSelfInitiated: boolean, description: string) { let peerInfo: FullNode.PeerInfo = null let connector = null ws.on('open', () => { console.log(`peer connected`) connector = new WebSocketConnector(this.state.fullNode.node, ws) peerInfo = this.state.fullNode.addPeer(connector, description) this.peersSockets.set(peerInfo, { ws, counterpartyId, isSelfInitiated }) }) ws.on('error', (err) => { console.log(`error with peer : ${err}`) ws.close() }) ws.on('close', () => { connector && connector.terminate() connector = null if (peerInfo) { this.state.fullNode.removePeer(peerInfo.id) this.peersSockets.delete(peerInfo) } console.log('peer disconnected') }) } disconnectPeer(peerInfo: FullNode.PeerInfo) { this.state.fullNode.removePeer(peerInfo.id) let ws = this.peersSockets.get(peerInfo) ws && ws.ws.close() this.peersSockets.delete(peerInfo) } guid() { //'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx' return 'xxxxxxxxxx'.replace(/[xy]/g, (c) => { let r = Math.random() * 16 | 0 let v = c == 'x' ? r : (r & 0x3 | 0x8) return v.toString(16) }) } clearStorageAndReload() { this.autoSave = false this.autoConnectNaturalPeer = false localStorage.clear() window.location.reload(true) } resetStorage() { localStorage.setItem(STORAGE_BLOCKS, JSON.stringify([])) let settings = { autoSave: false } localStorage.setItem(STORAGE_SETTINGS, JSON.stringify(settings)) } savePreferencesToLocalStorage() { let settings = { id: this.state.user && this.state.user.id, keys: this.state.user && this.state.user.keys, encryptMessages: this.encryptMessages, encryptionKey: this.encryptionKey, otherEncryptionKeys: this.otherEncryptionKeys, desiredNbIncomingPeers: this.desiredNbIncomingPeers, desiredNbOutgoingPeers: this.desiredNbOutgoingPeers, miningDifficulty: this.miningDifficulty, autoSave: this.autoSave, autoConnectNaturalPeer: this.autoConnectNaturalPeer } localStorage.setItem(STORAGE_SETTINGS, JSON.stringify(settings)) this.log(`preferences saved`) } loadPreferencesFromLocalStorage() { try { let settingsString = localStorage.getItem(STORAGE_SETTINGS) if (!settingsString || settingsString == '') return let settings = JSON.parse(settingsString) if (!settings) return if (settings.keys && settings.id) { this.state.setUserInformations(settings.id, settings.keys) } if (settings.encryptMessages) this.encryptMessages = settings.encryptMessages || false if (settings.encryptionKey) this.encryptionKey = settings.encryptionKey || this.guid() if (settings.otherEncryptionKeys && Array.isArray(this.otherEncryptionKeys)) settings.otherEncryptionKeys.forEach(element => this.otherEncryptionKeys.push(element)) if (settings.desiredNbIncomingPeers) this.desiredNbIncomingPeers = settings.desiredNbIncomingPeers || 3 if (settings.desiredNbOutgoingPeers) this.desiredNbOutgoingPeers = settings.desiredNbOutgoingPeers || 3 if (settings.miningDifficulty) this.miningDifficulty = settings.miningDifficulty if (settings.autoConnectNaturalPeer !== undefined) this.autoConnectNaturalPeer = settings.autoConnectNaturalPeer this.autoSave = !!settings.autoSave this.log(`preferences loaded`) } catch (e) { this.log(`error loading preferences ${e}`) } } }
the_stack
import * as AstNode from '../manifest-ast-types/manifest-ast-nodes.js'; import {AnnotationRef} from '../arcs-types/annotation.js'; import {assert} from '../../platform/assert-web.js'; import {IndentingStringBuilder} from '../../utils/lib-utils.js'; import {Ttl, Capabilities, Capability, Persistence, Encryption} from '../capabilities.js'; import {EntityType, FieldType, InterfaceType, NullableField, Type, Schema, ReferenceField, InlineField} from '../../types/lib-types.js'; import {FieldPathType, resolveFieldPathType} from '../field-path.js'; export enum PolicyRetentionMedium { Ram = 'Ram', Disk = 'Disk', } export enum PolicyAllowedUsageType { Any = '*', Egress = 'egress', Join = 'join', } const intendedPurposeAnnotationName = 'intendedPurpose'; const egressTypeAnnotationName = 'egressType'; const allowedRetentionAnnotationName = 'allowedRetention'; const allowedUsageAnnotationName = 'allowedUsage'; const maxAgeAnnotationName = 'maxAge'; /** * Definition of a dataflow policy. * * This class is just a thin wrapper around the Policy AST node. There's no * actual functionality other than validating the input is correct. */ export class Policy { constructor( readonly name: string, readonly targets: PolicyTarget[], readonly configs: PolicyConfig[], readonly description: string | null, readonly egressType: string | null, readonly customAnnotations: AnnotationRef[], private readonly allAnnotations: AnnotationRef[]) {} toManifestString(builder = new IndentingStringBuilder()): string { builder.push(...this.allAnnotations.map(annotation => annotation.toString())); builder.push(`policy ${this.name} {`); builder.withIndent(builder => { this.targets.forEach(target => target.toManifestString(builder)); this.configs.forEach(config => config.toManifestString(builder)); }); builder.push('}'); return builder.toString(); } static fromAstNode( node: AstNode.Policy, buildAnnotationRefs: (ref: AstNode.AnnotationRefNode[]) => AnnotationRef[], findTypeByName: (name: string) => EntityType | InterfaceType | undefined): Policy { checkNamesAreUnique(node.targets.map(target => ({name: target.schemaName}))); const targets = node.targets.map(target => PolicyTarget.fromAstNode(target, buildAnnotationRefs, findTypeByName)); checkNamesAreUnique(node.configs); const configs = node.configs.map(config => PolicyConfig.fromAstNode(config)); // Process annotations. const allAnnotations = buildAnnotationRefs(node.annotationRefs); let description: string | null = null; let egressType: string | null = null; const customAnnotations: AnnotationRef[] = []; for (const annotation of allAnnotations) { switch (annotation.name) { case intendedPurposeAnnotationName: description = this.toDescription(annotation); break; case egressTypeAnnotationName: egressType = this.toEgressType(annotation); break; default: customAnnotations.push(annotation); break; } } return new Policy(node.name, targets, configs, description, egressType, customAnnotations, allAnnotations); } private static toDescription(annotation: AnnotationRef): string { assert(annotation.name === intendedPurposeAnnotationName); return annotation.params['description'] as string; } private static toEgressType(annotation: AnnotationRef): string { assert(annotation.name === egressTypeAnnotationName); return annotation.params['type'] as string; } } export class PolicyTarget { constructor( readonly schemaName: string, readonly type: Type, readonly fields: PolicyField[], readonly retentions: {medium: PolicyRetentionMedium, encryptionRequired: boolean}[], readonly maxAge: Ttl, readonly customAnnotations: AnnotationRef[], private readonly allAnnotations: AnnotationRef[]) {} toManifestString(builder = new IndentingStringBuilder()): string { builder.push(...this.allAnnotations.map(annotation => annotation.toString())); builder.push(`from ${this.schemaName} access {`); this.fields.forEach(field => field.toManifestString(builder.withIndent())); builder.push('}'); return builder.toString(); } static fromAstNode( node: AstNode.PolicyTarget, buildAnnotationRefs: (ref: AstNode.AnnotationRefNode[]) => AnnotationRef[], findTypeByName: (name: string) => EntityType | InterfaceType | undefined): PolicyTarget { // Check type. const type = findTypeByName(node.schemaName); if (!type) { throw new Error(`Unknown type name: ${node.schemaName}.`); } // Convert fields. checkNamesAreUnique(node.fields); const fields = node.fields.map(field => PolicyField.fromAstNode(field, type, buildAnnotationRefs)); // Process annotations. const allAnnotations = buildAnnotationRefs(node.annotationRefs); let maxAge = Ttl.zero(); const retentionMediums: Set<PolicyRetentionMedium> = new Set(); const retentions: {medium: PolicyRetentionMedium, encryptionRequired: boolean}[] = []; const customAnnotations: AnnotationRef[] = []; for (const annotation of allAnnotations) { switch (annotation.name) { case allowedRetentionAnnotationName: { const retention = this.toRetention(annotation); if (retentionMediums.has(retention.medium)) { throw new Error(`@${allowedRetentionAnnotationName} has already been defined for ${retention.medium}.`); } retentionMediums.add(retention.medium); retentions.push(retention); break; } case maxAgeAnnotationName: maxAge = this.toMaxAge(annotation); break; default: customAnnotations.push(annotation); break; } } return new PolicyTarget(node.schemaName, type, fields, retentions, maxAge, customAnnotations, allAnnotations); } private static toRetention(annotation: AnnotationRef) { assert(annotation.name === allowedRetentionAnnotationName); const medium = annotation.params['medium'] as string; checkValueInEnum(medium, PolicyRetentionMedium); return { medium: medium as PolicyRetentionMedium, encryptionRequired: annotation.params['encryption'] as boolean, }; } private static toMaxAge(annotation: AnnotationRef): Ttl { assert(annotation.name === maxAgeAnnotationName); const maxAge = annotation.params['age'] as string; return Ttl.fromString(maxAge); } toCapabilities(): Capabilities[] { return this.retentions.map(retention => { const ranges: Capability[] = []; switch (retention.medium) { case PolicyRetentionMedium.Disk: ranges.push(Persistence.onDisk()); break; case PolicyRetentionMedium.Ram: ranges.push(Persistence.inMemory()); break; default: throw new Error(`Unsupported retention medium ${retention.medium}`); } ranges.push(new Encryption(retention.encryptionRequired)); ranges.push(this.maxAge); return Capabilities.create(ranges); }); } // Returns policy fields in the format of Schema fields. toSchemaFields() { return this.fields.map(f => f.toSchemaFields(this.type)) .reduce((fields, {name, field}) => ({...fields, [name]: field}), {}); } // Return the max readable schema according to this policy. getMaxReadSchema(): Schema { return new Schema(this.type.getEntitySchema().names, this.toSchemaFields()); } } export class PolicyField { constructor( readonly name: string, readonly type: FieldPathType, readonly subfields: PolicyField[], /** * The acceptable usages this field. Each (label, usage) pair defines a * usage type that is acceptable for a given redaction label. The empty * string label describes the usage for the raw data, given no redaction. */ readonly allowedUsages: {label: string, usage: PolicyAllowedUsageType}[], readonly customAnnotations: AnnotationRef[], private readonly allAnnotations: AnnotationRef[]) {} toManifestString(builder = new IndentingStringBuilder()): string { builder.push(...this.allAnnotations.map(annotation => annotation.toString())); if (this.subfields.length) { builder.push(`${this.name} {`); this.subfields.forEach(field => field.toManifestString(builder.withIndent())); builder.push('},'); } else { builder.push(`${this.name},`); } return builder.toString(); } static fromAstNode( node: AstNode.PolicyField, parentType: FieldPathType, buildAnnotationRefs: (ref: AstNode.AnnotationRefNode[]) => AnnotationRef[]): PolicyField { // Validate field name against type. const type = resolveFieldPathType([node.name], parentType); // Convert subfields. checkNamesAreUnique(node.subfields); const subfields = node.subfields.map(field => PolicyField.fromAstNode(field, type, buildAnnotationRefs)); // Process annotations. const allAnnotations = buildAnnotationRefs(node.annotationRefs); const usages: Map<string, Set<PolicyAllowedUsageType>> = new Map(); const allowedUsages: {label: string, usage: PolicyAllowedUsageType}[] = []; const customAnnotations: AnnotationRef[] = []; for (const annotation of allAnnotations) { switch (annotation.name) { case allowedUsageAnnotationName: { const allowedUsage = this.toAllowedUsage(annotation); if (!usages.has(allowedUsage.label)) { usages.set(allowedUsage.label, new Set()); } const usageTypes = usages.get(allowedUsage.label); if (usageTypes.has(allowedUsage.usage)) { throw new Error(`Usage of label '${allowedUsage.label}' for usage type '${allowedUsage.usage}' has already been allowed.`); } usageTypes.add(allowedUsage.usage); allowedUsages.push(allowedUsage); break; } default: customAnnotations.push(annotation); break; } } if (allowedUsages.length === 0) { allowedUsages.push({label: '', usage: PolicyAllowedUsageType.Any}); } return new PolicyField(node.name, type, subfields, allowedUsages, customAnnotations, allAnnotations); } private static toAllowedUsage(annotation: AnnotationRef) { assert(annotation.name === allowedUsageAnnotationName); const usageType = annotation.params['usageType'] as string; checkValueInEnum(usageType, PolicyAllowedUsageType); const label = annotation.params['label'] as string; return { usage: usageType as PolicyAllowedUsageType, label: label === 'raw' ? '' : label, }; } // Returns policy fields in the format of Schema fields. toSchemaFields(parentType: Type) { const field = parentType.getEntitySchema().fields[this.name]; return {name: this.name, field: this.toSchemaField(field)}; } private toSchemaField(field) { switch (field.kind) { case 'kotlin-primitive': case 'schema-primitive': { assert(this.subfields.length === 0); return field; } case 'schema-collection': case 'schema-ordered-list': case 'schema-nested': { return FieldType.create( {kind: field.kind, schema: this.toSchemaField(field.schema)} ); } case 'schema-reference': { return new ReferenceField( new InlineField(this.restrictedEntityType(field.getEntityType())) ); } case 'type-name': case 'schema-inline': { const entityType = field.getEntityType(); if (entityType == null) return this; return new InlineField(this.restrictedEntityType(entityType)); } case 'schema-nullable': { return new NullableField(field.getFieldType()); } // TODO(bgogul): `field-path` does not support these types yet. // case 'schema-union': // case 'schema-tuple': // return FieldType.create({ // ...field, // types: field.getFieldTypes().map(t => this.toSchemaField(t)) // }); default: { assert(`Unsupported field kind: ${field.kind}`); } } } private restrictedEntityType(entityType): EntityType { assert(entityType != null); const restrictedFields = {}; const schema = entityType.entitySchema; for (const subfield of this.subfields) { restrictedFields[subfield.name] = subfield.toSchemaField(schema.fields[subfield.name]); } return EntityType.make(schema.names, restrictedFields, schema); } } export class PolicyConfig { constructor(readonly name: string, readonly metadata: Map<string, string>) {} toManifestString(builder = new IndentingStringBuilder()): string { builder.push(`config ${this.name} {`); builder.withIndent(builder => { for (const [k, v] of this.metadata) { builder.push(`${k}: '${v}'`); } }); builder.push('}'); return builder.toString(); } static fromAstNode(node: AstNode.PolicyConfig): PolicyConfig { return new PolicyConfig(node.name, node.metadata); } } /** Checks that the given value is an element in the given enum. Throws otherwise. */ function checkValueInEnum(value: string, enumDef: {}) { const keys = Object.keys(enumDef).filter(key => typeof key === 'string'); const values = keys.map(key => enumDef[key]); if (!(values.includes(value))) { throw new Error(`Expected one of: ${values.join(', ')}. Found: ${value}.`); } } /** Checks that the given AST nodes have unique names. Throws otherwise. */ function checkNamesAreUnique(nodes: {name: string}[]) { const names: Set<string> = new Set(); for (const node of nodes) { if (names.has(node.name)) { throw new Error(`A definition for '${node.name}' already exists.`); } names.add(node.name); } }
the_stack
// Load the .env file if it exists import * as dotenv from "dotenv"; dotenv.config(); import { MetricsAdvisorKeyCredential, MetricsAdvisorClient } from "@azure/ai-metrics-advisor"; export async function main() { // You will need to set these environment variables or edit the following values const endpoint = process.env["METRICS_ADVISOR_ENDPOINT"] || "<service endpoint>"; const subscriptionKey = process.env["METRICS_ADVISOR_SUBSCRIPTION_KEY"] || "<subscription key>"; const apiKey = process.env["METRICS_ADVISOR_API_KEY"] || "<api key>"; const credential = new MetricsAdvisorKeyCredential(subscriptionKey, apiKey); const detectionConfigId = process.env["METRICS_ADVISOR_DETECTION_CONFIG_ID"] || "<detection config id>"; const incidentId = process.env["METRICS_ADVISOR_INCIDENT_ID"] || "<incident id>"; const alertConfigId = process.env["METRICS_ADVISOR_ALERT_CONFIG_ID"] || "<alert config id>"; const alertId = process.env["METRICS_ADVISOR_ALERT_ID"] || "<alert id>"; const client = new MetricsAdvisorClient(endpoint, credential); await listIncidentsForDetectionConfig(client, detectionConfigId); await listAnomaliesForDetectionConfig(client, detectionConfigId); await listAnomalyDimensionValues(client, detectionConfigId); await getRootCauses(client, detectionConfigId, incidentId); await listAlerts(client, alertConfigId); await listIncidentsForAlert(client, alertConfigId, alertId); await listAnomaliesForAlert(client, alertConfigId, alertId); } async function listAnomalyDimensionValues(client: MetricsAdvisorClient, detectionConfigId: string) { const dimensionName = "city"; console.log( `Listing anomaly dimension values for detection config ${detectionConfigId} and dimension ${dimensionName}` ); const listIterator = await client.listAnomalyDimensionValues( detectionConfigId, new Date("10/22/2020"), new Date("10/24/2020"), dimensionName ); for await (const dimensionValue of listIterator) { console.log(dimensionValue); } console.log(` by pages`); const iterator = client .listAnomalyDimensionValues( detectionConfigId, new Date("10/22/2020"), new Date("10/24/2020"), dimensionName ) .byPage({ maxPageSize: 20 }); let result = await iterator.next(); while (!result.done) { console.log(" -- Page --"); for await (const dimensionValue of result.value) { console.log(dimensionValue); } result = await iterator.next(); } } async function listIncidentsForDetectionConfig( client: MetricsAdvisorClient, detectionConfigId: string ) { console.log(`Listing incidents for detection config '${detectionConfigId}'`); console.log(" using for-await-of syntax"); const listIterator = client.listIncidentsForDetectionConfiguration( detectionConfigId, new Date("10/22/2020"), new Date("10/24/2020"), { seriesGroupKeys: [{ city: "Manila", category: "Shoes Handbags & Sunglasses" }], } ); for await (const incident of listIterator) { console.log(" Incident"); console.log(` id: ${incident.id}`); console.log(` severity: ${incident.severity}`); console.log(` status: ${incident.status}`); console.log(` root dimension key: ${incident.rootDimensionKey}`); console.log(` startTime: ${incident.startTime}`); console.log(` last occurred: ${incident.lastOccurredTime}`); console.log(` detection config id: ${incident.detectionConfigurationId}`); } console.log(` by pages`); const iterator = client .listIncidentsForDetectionConfiguration( detectionConfigId, new Date("10/22/2020"), new Date("10/24/2020") ) .byPage({ maxPageSize: 20 }); let result = await iterator.next(); while (!result.done) { console.log(" -- Page --"); for (const item of result.value) { console.log(` id: ${item.id}`); console.log(` severity: ${item.severity}`); console.log(` status: ${item.status}`); console.log(` root dimension key: ${item.rootDimensionKey}`); console.log(` startTime: ${item.startTime}`); console.log(` last occurred: ${item.lastOccurredTime}`); console.log(` detection config id: ${item.detectionConfigurationId}`); } result = await iterator.next(); } } async function listAnomaliesForDetectionConfig( client: MetricsAdvisorClient, detectionConfigId: string ) { console.log(`Listing anomalies for detection config '${detectionConfigId}'`); const listIterator = client.listAnomaliesForDetectionConfiguration( detectionConfigId, new Date("10/22/2020"), new Date("10/24/2020"), { severityFilter: { min: "Medium", max: "High" }, } ); console.log(" using for-await-of syntax"); for await (const anomaly of listIterator) { console.log(" Anomaly"); console.log(` metric id: ${anomaly.metricId}`); console.log(` detection config id: ${anomaly.detectionConfigurationId}`); console.log(` created on: ${anomaly.createdOn}`); console.log(` modified on: ${anomaly.modifiedOn}`); console.log(` severity: ${anomaly.severity}`); console.log(` status: ${anomaly.status}`); console.log(` series key: ${anomaly.seriesKey}`); } console.log(` by pages`); const iterator = client .listAnomaliesForDetectionConfiguration( detectionConfigId, new Date("10/22/2020"), new Date("10/24/2020"), { severityFilter: { min: "Medium", max: "High" }, } ) .byPage({ maxPageSize: 20 }); let result = await iterator.next(); while (!result.done) { console.log(" -- Page --"); console.log(result.value, ["timestamp", "severity", "seriesKey"]); for (const item of result.value) { console.log(` metric id: ${item.metricId}`); console.log(` detection config id: ${item.detectionConfigurationId}`); console.log(` created on: ${item.createdOn}`); console.log(` modified on: ${item.modifiedOn}`); console.log(` severity: ${item.severity}`); console.log(` status: ${item.status}`); console.log(` series key: ${item.seriesKey}`); } result = await iterator.next(); } } async function getRootCauses( client: MetricsAdvisorClient, detectionConfigId: string, incidentId: string ) { console.log("Retrieving root causes..."); const result = await client.getIncidentRootCauses(detectionConfigId, incidentId); for (const rootcause of result.rootCauses) { console.log(`Root cause`); console.log(` Trace the path for the incident root cause ${rootcause.path.join(" => ")}`); console.log(` Series key: ${rootcause.seriesKey}`); console.log(` Description: ${rootcause.description}`); console.log(` ranking score: ${rootcause.score}`); } } async function listAlerts(client: MetricsAdvisorClient, alertConfigId: string) { console.log(`Listing alerts for alert configuration '${alertConfigId}'`); console.log(" using for-await-of syntax"); const listIterator = client.listAlerts( alertConfigId, new Date("11/01/2020"), new Date("11/05/2020"), "AnomalyTime" ); for await (const alert of listIterator) { console.log(" Alert"); console.log(` id: ${alert.id}`); console.log(` timestamp: ${alert.timestamp}`); console.log(` created on: ${alert.createdOn}`); } console.log(` by pages`); const iterator = client .listAlerts(alertConfigId, new Date("11/01/2020"), new Date("11/05/2020"), "AnomalyTime") .byPage({ maxPageSize: 20 }); let result = await iterator.next(); while (!result.done) { console.log(" -- Page --"); for (const item of result.value) { console.log(` id: ${item.id}`); console.log(` timestamp: ${item.timestamp}`); console.log(` created on: ${item.createdOn}`); } result = await iterator.next(); } } async function listIncidentsForAlert( client: MetricsAdvisorClient, alertConfigId: string, alertId: string ) { console.log( `Listing incidents for alert configuration '${alertConfigId}' and alert '${alertId}'` ); console.log(" using for-await-of syntax"); const listIterator = client.listIncidentsForAlert({ alertConfigId, id: alertId }); for await (const incident of listIterator) { console.log(" Incident"); console.log(` id: ${incident.id}`); console.log(` severity: ${incident.severity}`); console.log(` status: ${incident.status}`); console.log(` root dimension key: ${incident.rootDimensionKey}`); console.log(` startTime: ${incident.startTime}`); console.log(` last occurred: ${incident.lastOccurredTime}`); console.log(` detection config id: ${incident.detectionConfigurationId}`); } console.log(` by pages`); const iterator = client .listIncidentsForAlert({ alertConfigId, id: alertId }) .byPage({ maxPageSize: 20 }); let result = await iterator.next(); while (!result.done) { console.log(" Page"); for (const item of result.value) { console.log(` id: ${item.id}`); console.log(` severity: ${item.severity}`); console.log(` status: ${item.status}`); console.log(` root dimension key: ${item.rootDimensionKey}`); console.log(` startTime: ${item.startTime}`); console.log(` last occurred: ${item.lastOccurredTime}`); console.log(` detection config id: ${item.detectionConfigurationId}`); } result = await iterator.next(); } } async function listAnomaliesForAlert( client: MetricsAdvisorClient, alertConfigId: string, alertId: string ) { console.log( `Listing anomalies for alert configuration '${alertConfigId}' and alert '${alertId}'` ); console.log(" using for-await-of syntax"); const listIterator = client.listAnomaliesForAlert({ alertConfigId, id: alertId }); for await (const anomaly of listIterator) { console.log(" Anomaly"); console.log(` timestamp: ${anomaly.timestamp}`); console.log(` dimension: ${anomaly.seriesKey}`); console.log(` status: ${anomaly.status}`); } console.log(` by pages`); const iterator = client .listAnomaliesForAlert({ alertConfigId, id: alertId }) .byPage({ maxPageSize: 20 }); let result = await iterator.next(); while (!result.done) { console.log(" -- Page --"); for (const item of result.value) { console.log(` timestamp: ${item.timestamp}`); console.log(` dimension: ${item.seriesKey}`); console.log(` status: ${item.status}`); } result = await iterator.next(); } } main() .then((_) => { console.log("Succeeded"); }) .catch((err) => { console.log("Error occurred:"); console.log(err); });
the_stack
import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer, transcode, TranscodeEncoding, constants, kMaxLength, kStringMaxLength, Blob, resolveObjectURL, } from 'node:buffer'; import { Readable, Writable } from 'node:stream'; const utf8Buffer = new Buffer('test'); const base64Buffer = new Buffer('', 'base64'); const base64UrlBuffer = new Buffer('', 'base64url'); const octets: Uint8Array = new Uint8Array(123); const octetBuffer = new Buffer(octets); const sharedBuffer = new Buffer(octets.buffer); const copiedBuffer = new Buffer(utf8Buffer); console.log(Buffer.isBuffer(octetBuffer)); console.log(Buffer.isEncoding('utf8')); console.log(Buffer.byteLength('xyz123')); console.log(Buffer.byteLength('xyz123', 'ascii')); const result1 = Buffer.concat([utf8Buffer, base64Buffer] as ReadonlyArray<Uint8Array>); const result2 = Buffer.concat([utf8Buffer, base64Buffer] as ReadonlyArray<Uint8Array>, 9999999); // Module constants { const value1: number = constants.MAX_LENGTH; const value2: number = constants.MAX_STRING_LENGTH; const value3: number = kMaxLength; const value4: number = kStringMaxLength; } // Class Methods: Buffer.swap16(), Buffer.swa32(), Buffer.swap64() { const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); buf.swap16(); buf.swap32(); buf.swap64(); } // Class Method: Buffer.from(data) { // Array const buf1: Buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72] as ReadonlyArray<number>); // Buffer const buf2: Buffer = Buffer.from(buf1, 1, 2); // String const buf3: Buffer = Buffer.from('this is a tést'); // ArrayBuffer const arrUint16: Uint16Array = new Uint16Array(2); arrUint16[0] = 5000; arrUint16[1] = 4000; const buf4: Buffer = Buffer.from(arrUint16.buffer); const arrUint8: Uint8Array = new Uint8Array(2); const buf5: Buffer = Buffer.from(arrUint8); const buf6: Buffer = Buffer.from(buf1); const sb: SharedArrayBuffer = {} as any; const buf7: Buffer = Buffer.from(sb); // $ExpectError Buffer.from({}); } // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) { const arr: Uint16Array = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; let buf: Buffer; buf = Buffer.from(arr.buffer, 1); buf = Buffer.from(arr.buffer, 0, 1); // $ExpectError Buffer.from("this is a test", 1, 1); // Ideally passing a normal Buffer would be a type error too, but it's not // since Buffer is assignable to ArrayBuffer currently } // Class Method: Buffer.from(str[, encoding]) { const buf2: Buffer = Buffer.from('7468697320697320612074c3a97374', 'hex'); /* tslint:disable-next-line no-construct */ Buffer.from(new String("DEADBEEF"), "hex"); // $ExpectError Buffer.from(buf2, 'hex'); } // Class Method: Buffer.from(object, [, byteOffset[, length]]) (Implicit coercion) { const pseudoBuf = { valueOf() { return Buffer.from([1, 2, 3]); } }; let buf: Buffer = Buffer.from(pseudoBuf); const pseudoString = { valueOf() { return "Hello"; }}; buf = Buffer.from(pseudoString); buf = Buffer.from(pseudoString, "utf-8"); // $ExpectError Buffer.from(pseudoString, 1, 2); const pseudoArrayBuf = { valueOf() { return new Uint16Array(2); } }; buf = Buffer.from(pseudoArrayBuf, 1, 1); } // Class Method: Buffer.alloc(size[, fill[, encoding]]) { const buf1: Buffer = Buffer.alloc(5); const buf2: Buffer = Buffer.alloc(5, 'a'); const buf3: Buffer = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); const buf4: Buffer = Buffer.alloc(11, 'aGVsbG8gd29ybGQ', 'base64url'); } // Class Method: Buffer.allocUnsafe(size) { const buf: Buffer = Buffer.allocUnsafe(5); } // Class Method: Buffer.allocUnsafeSlow(size) { const buf: Buffer = Buffer.allocUnsafeSlow(10); } // Class Method byteLenght { let len: number; len = Buffer.byteLength("foo"); len = Buffer.byteLength("foo", "utf8"); const b = Buffer.from("bar"); len = Buffer.byteLength(b); len = Buffer.byteLength(b, "utf16le"); const ab = new ArrayBuffer(15); len = Buffer.byteLength(ab); len = Buffer.byteLength(ab, "ascii"); const dv = new DataView(ab); len = Buffer.byteLength(dv); len = Buffer.byteLength(dv, "utf16le"); } // Class Method poolSize { let s: number; s = Buffer.poolSize; Buffer.poolSize = 4096; } // Test that TS 1.6 works with the 'as Buffer' annotation // on isBuffer. let a: Buffer | number; a = new Buffer(10); if (Buffer.isBuffer(a)) { a.writeUInt8(3, 4); } // write* methods return offsets. const b = new Buffer(16); let result: number = b.writeUInt32LE(0, 0); result = b.writeUInt16LE(0, 4); result = b.writeUInt8(0, 6); result = b.writeInt8(0, 7); result = b.writeDoubleLE(0, 8); result = b.write('asd'); result = b.write('asd', 'hex'); result = b.write('asd', 123, 'hex'); result = b.write('asd', 123, 123, 'hex'); // fill returns the input buffer. b.fill('a').fill('b'); { const buffer = new Buffer('123'); let index: number; index = buffer.indexOf("23"); index = buffer.indexOf("23", 1); index = buffer.indexOf("23", 1, "utf8"); index = buffer.indexOf(23); index = buffer.indexOf(buffer); } { const buffer = new Buffer('123'); let index: number; index = buffer.lastIndexOf("23"); index = buffer.lastIndexOf("23", 1); index = buffer.lastIndexOf("23", 1, "utf8"); index = buffer.lastIndexOf(23); index = buffer.lastIndexOf(buffer); } { const buffer = new Buffer('123'); const val: [number, number] = [1, 1]; /* comment out for --target es5 for (let entry of buffer.entries()) { val = entry; } */ } { const buffer = new Buffer('123'); let includes: boolean; includes = buffer.includes("23"); includes = buffer.includes("23", 1); includes = buffer.includes("23", 1, "utf8"); includes = buffer.includes(23); includes = buffer.includes(23, 1); includes = buffer.includes(23, 1, "utf8"); includes = buffer.includes(buffer); includes = buffer.includes(buffer, 1); includes = buffer.includes(buffer, 1, "utf8"); } { const buffer = new Buffer('123'); const val = 1; /* comment out for --target es5 for (let key of buffer.keys()) { val = key; } */ } { const buffer = new Buffer('123'); const val = 1; /* comment out for --target es5 for (let value of buffer.values()) { val = value; } */ } // Imported Buffer from buffer module works properly { const b = new ImportedBuffer('123'); b.writeUInt8(0, 6); const sb = new ImportedSlowBuffer(43); b.writeUInt8(0, 6); } // Buffer has Uint8Array's buffer field (an ArrayBuffer). { const buffer = new Buffer('123'); const octets = new Uint8Array(buffer.buffer); } // Inherited from Uint8Array but return buffer { const b = Buffer.from('asd'); let res: Buffer = b.reverse(); res = b.subarray(); res = b.subarray(1); res = b.subarray(1, 2); } // Buffer module, transcode function { transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer const source: TranscodeEncoding = 'utf8'; const target: TranscodeEncoding = 'ascii'; transcode(Buffer.from('€'), source, target); // $ExpectType Buffer } { const a = Buffer.alloc(1000); a.writeBigInt64BE(123n); a.writeBigInt64LE(123n); a.writeBigUInt64BE(123n); a.writeBigUInt64LE(123n); let b: bigint = a.readBigInt64BE(123); b = a.readBigInt64LE(123); b = a.readBigUInt64LE(123); b = a.readBigUInt64BE(123); } async () => { const blob = new Blob(['asd', Buffer.from('test'), new Blob(['dummy'])], { type: 'application/javascript', encoding: 'base64', }); blob.size; // $ExpectType number blob.type; // $ExpectType string blob.arrayBuffer(); // $ExpectType Promise<ArrayBuffer> blob.text(); // $ExpectType Promise<string> blob.slice(); // $ExpectType Blob blob.slice(1); // $ExpectType Blob blob.slice(1, 2); // $ExpectType Blob blob.slice(1, 2, 'other'); // $ExpectType Blob }; { atob(btoa('test')); // $ExpectType string } { global.atob(global.btoa('test')); // $ExpectType string } const c: NodeJS.TypedArray = new Buffer(123); { let writableFinished: boolean; const readable: Readable = new Readable({ read() { this.push('hello'); this.push('world'); this.push(null); }, }); readable.destroyed; const writable: Writable = new Writable({ write(chunk, _, cb) { cb(); }, }); readable.pipe(writable); writableFinished = writable.writableFinished; writable.destroyed; } { const obj = { valueOf() { return 'hello'; } }; Buffer.from(obj); } const buff = Buffer.from("Hello World!"); // reads buff.readInt8(); buff.readInt8(0); buff.readUInt8(); buff.readUInt8(0); buff.readUInt16BE(); buff.readUInt16BE(0); buff.readUInt32LE(); buff.readUInt32LE(0); buff.readUInt32BE(); buff.readUInt32BE(0); buff.readInt8(); buff.readInt8(0); buff.readInt16LE(); buff.readInt16LE(0); buff.readInt16BE(); buff.readInt16BE(0); buff.readInt32LE(); buff.readInt32LE(0); buff.readInt32BE(); buff.readInt32BE(0); buff.readFloatLE(); buff.readFloatLE(0); buff.readFloatBE(); buff.readFloatBE(0); buff.readDoubleLE(); buff.readDoubleBE(0); // writes buff.writeInt8(0xab); buff.writeInt8(0xab, 0); buff.writeUInt8(0xab); buff.writeUInt8(0xab, 0); buff.writeUInt16LE(0xabcd); buff.writeUInt16LE(0xabcd, 0); buff.writeUInt16BE(0xabcd); buff.writeUInt16BE(0xabcd, 0); buff.writeUInt32LE(0xabcd); buff.writeUInt32LE(0xabcd, 0); buff.writeUInt32BE(0xabcd); buff.writeUInt32BE(0xabcd, 0); buff.writeInt16LE(0xabcd); buff.writeInt16LE(0xabcd, 0); buff.writeInt16BE(0xabcd); buff.writeInt16BE(0xabcd, 0); buff.writeInt32LE(0xabcd); buff.writeInt32LE(0xabcd, 0); buff.writeInt32BE(0xabcd); buff.writeInt32BE(0xabcd, 0); buff.writeFloatLE(0xabcd); buff.writeFloatLE(0xabcd, 0); buff.writeFloatBE(0xabcd); buff.writeFloatBE(0xabcd, 0); buff.writeDoubleLE(123.123); buff.writeDoubleLE(123.123, 0); buff.writeDoubleBE(123.123); buff.writeDoubleBE(123.123, 0); { // The 'as any' is to make sure the Global DOM Blob does not clash with the // local "Blob" which comes with node. resolveObjectURL(URL.createObjectURL(new Blob(['']) as any)); // $ExpectType Blob | undefined }
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * Operations * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface Operations { /** * @summary Returns the list of available operations. * * Operation to return the list of available operations. * * @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<OperationsDiscoveryCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationsDiscoveryCollection>>; /** * @summary Returns the list of available operations. * * Operation to return the list of available operations. * * @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 {OperationsDiscoveryCollection} - 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. * * {OperationsDiscoveryCollection} [result] - The deserialized result object if an error did not occur. * See {@link OperationsDiscoveryCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationsDiscoveryCollection>; list(callback: ServiceCallback<models.OperationsDiscoveryCollection>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationsDiscoveryCollection>): void; /** * @summary Returns the list of available operations. * * Operation to return the list of available operations. * * @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<OperationsDiscoveryCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationsDiscoveryCollection>>; /** * @summary Returns the list of available operations. * * Operation to return the list of available operations. * * @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 {OperationsDiscoveryCollection} - 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. * * {OperationsDiscoveryCollection} [result] - The deserialized result object if an error did not occur. * See {@link OperationsDiscoveryCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationsDiscoveryCollection>; listNext(nextPageLink: string, callback: ServiceCallback<models.OperationsDiscoveryCollection>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationsDiscoveryCollection>): void; } /** * @class * ReplicationAlertSettings * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface ReplicationAlertSettings { /** * @summary Gets the list of configured email notification(alert) * configurations. * * Gets the list of email notification(alert) configurations for the vault. * * @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<AlertCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AlertCollection>>; /** * @summary Gets the list of configured email notification(alert) * configurations. * * Gets the list of email notification(alert) configurations for the vault. * * @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 {AlertCollection} - 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. * * {AlertCollection} [result] - The deserialized result object if an error did not occur. * See {@link AlertCollection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AlertCollection>; list(callback: ServiceCallback<models.AlertCollection>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AlertCollection>): void; /** * @summary Gets an email notification(alert) configuration. * * Gets the details of the specified email notification(alert) configuration. * * @param {string} alertSettingName The name of the email notification * configuration. * * @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<Alert>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(alertSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Alert>>; /** * @summary Gets an email notification(alert) configuration. * * Gets the details of the specified email notification(alert) configuration. * * @param {string} alertSettingName The name of the email notification * configuration. * * @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 {Alert} - 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. * * {Alert} [result] - The deserialized result object if an error did not occur. * See {@link Alert} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(alertSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Alert>; get(alertSettingName: string, callback: ServiceCallback<models.Alert>): void; get(alertSettingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Alert>): void; /** * @summary Configures email notifications for this vault. * * Create or update an email notification(alert) configuration. * * @param {string} alertSettingName The name of the email notification(alert) * configuration. * * @param {object} request The input to configure the email * notification(alert). * * @param {object} [request.properties] The properties of a configure alert * request. * * @param {string} [request.properties.sendToOwners] A value indicating whether * to send email to subscription administrator. * * @param {array} [request.properties.customEmailAddresses] The custom email * address for sending emails. * * @param {string} [request.properties.locale] The locale for the email * notification. * * @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<Alert>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(alertSettingName: string, request: models.ConfigureAlertRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Alert>>; /** * @summary Configures email notifications for this vault. * * Create or update an email notification(alert) configuration. * * @param {string} alertSettingName The name of the email notification(alert) * configuration. * * @param {object} request The input to configure the email * notification(alert). * * @param {object} [request.properties] The properties of a configure alert * request. * * @param {string} [request.properties.sendToOwners] A value indicating whether * to send email to subscription administrator. * * @param {array} [request.properties.customEmailAddresses] The custom email * address for sending emails. * * @param {string} [request.properties.locale] The locale for the email * notification. * * @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 {Alert} - 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. * * {Alert} [result] - The deserialized result object if an error did not occur. * See {@link Alert} 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. */ create(alertSettingName: string, request: models.ConfigureAlertRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Alert>; create(alertSettingName: string, request: models.ConfigureAlertRequest, callback: ServiceCallback<models.Alert>): void; create(alertSettingName: string, request: models.ConfigureAlertRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Alert>): void; /** * @summary Gets the list of configured email notification(alert) * configurations. * * Gets the list of email notification(alert) configurations for the vault. * * @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<AlertCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AlertCollection>>; /** * @summary Gets the list of configured email notification(alert) * configurations. * * Gets the list of email notification(alert) configurations for the vault. * * @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 {AlertCollection} - 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. * * {AlertCollection} [result] - The deserialized result object if an error did not occur. * See {@link AlertCollection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AlertCollection>; listNext(nextPageLink: string, callback: ServiceCallback<models.AlertCollection>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AlertCollection>): void; } /** * @class * ReplicationEvents * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface ReplicationEvents { /** * @summary Gets the list of Azure Site Recovery events. * * Gets the list of Azure Site Recovery events for the vault. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] OData filter options. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<EventCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.EventCollection>>; /** * @summary Gets the list of Azure Site Recovery events. * * Gets the list of Azure Site Recovery events for the vault. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] OData filter options. * * @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 {EventCollection} - 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. * * {EventCollection} [result] - The deserialized result object if an error did not occur. * See {@link EventCollection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.EventCollection>; list(callback: ServiceCallback<models.EventCollection>): void; list(options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.EventCollection>): void; /** * @summary Get the details of an Azure Site recovery event. * * The operation to get the details of an Azure Site recovery event. * * @param {string} eventName The name of the Azure Site Recovery event. * * @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<Event>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(eventName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Event>>; /** * @summary Get the details of an Azure Site recovery event. * * The operation to get the details of an Azure Site recovery event. * * @param {string} eventName The name of the Azure Site Recovery event. * * @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 {Event} - 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. * * {Event} [result] - The deserialized result object if an error did not occur. * See {@link Event} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(eventName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Event>; get(eventName: string, callback: ServiceCallback<models.Event>): void; get(eventName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Event>): void; /** * @summary Gets the list of Azure Site Recovery events. * * Gets the list of Azure Site Recovery events for the vault. * * @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<EventCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.EventCollection>>; /** * @summary Gets the list of Azure Site Recovery events. * * Gets the list of Azure Site Recovery events for the vault. * * @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 {EventCollection} - 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. * * {EventCollection} [result] - The deserialized result object if an error did not occur. * See {@link EventCollection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.EventCollection>; listNext(nextPageLink: string, callback: ServiceCallback<models.EventCollection>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.EventCollection>): void; } /** * @class * ReplicationFabrics * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface ReplicationFabrics { /** * @summary Gets the list of ASR fabrics * * Gets a list of the Azure Site Recovery fabrics in the vault. * * @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<FabricCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FabricCollection>>; /** * @summary Gets the list of ASR fabrics * * Gets a list of the Azure Site Recovery fabrics in the vault. * * @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 {FabricCollection} - 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. * * {FabricCollection} [result] - The deserialized result object if an error did not occur. * See {@link FabricCollection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.FabricCollection>; list(callback: ServiceCallback<models.FabricCollection>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FabricCollection>): void; /** * @summary Gets the details of an ASR fabric. * * Gets the details of an Azure Site Recovery fabric. * * @param {string} fabricName Fabric name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Fabric>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Fabric>>; /** * @summary Gets the details of an ASR fabric. * * Gets the details of an Azure Site Recovery fabric. * * @param {string} fabricName Fabric name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Fabric} - 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. * * {Fabric} [result] - The deserialized result object if an error did not occur. * See {@link Fabric} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Fabric>; get(fabricName: string, callback: ServiceCallback<models.Fabric>): void; get(fabricName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Fabric>): void; /** * @summary Creates an Azure Site Recovery fabric. * * The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V * site) * * @param {string} fabricName Name of the ASR fabric. * * @param {object} input Fabric creation input. * * @param {object} [input.properties] Fabric creation input. * * @param {object} [input.properties.customDetails] Fabric provider specific * creation input. * * @param {string} input.properties.customDetails.instanceType Polymorphic * Discriminator * * @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<Fabric>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(fabricName: string, input: models.FabricCreationInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Fabric>>; /** * @summary Creates an Azure Site Recovery fabric. * * The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V * site) * * @param {string} fabricName Name of the ASR fabric. * * @param {object} input Fabric creation input. * * @param {object} [input.properties] Fabric creation input. * * @param {object} [input.properties.customDetails] Fabric provider specific * creation input. * * @param {string} input.properties.customDetails.instanceType Polymorphic * Discriminator * * @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 {Fabric} - 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. * * {Fabric} [result] - The deserialized result object if an error did not occur. * See {@link Fabric} 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. */ create(fabricName: string, input: models.FabricCreationInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Fabric>; create(fabricName: string, input: models.FabricCreationInput, callback: ServiceCallback<models.Fabric>): void; create(fabricName: string, input: models.FabricCreationInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Fabric>): void; /** * @summary Purges the site. * * The operation to purge(force delete) an Azure Site Recovery fabric. * * @param {string} fabricName ASR fabric to purge. * * @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. */ purgeWithHttpOperationResponse(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Purges the site. * * The operation to purge(force delete) an Azure Site Recovery fabric. * * @param {string} fabricName ASR fabric to purge. * * @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. */ purge(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; purge(fabricName: string, callback: ServiceCallback<void>): void; purge(fabricName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Checks the consistency of the ASR fabric. * * The operation to perform a consistency check on the fabric. * * @param {string} fabricName Fabric name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Fabric>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ checkConsistencyWithHttpOperationResponse(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Fabric>>; /** * @summary Checks the consistency of the ASR fabric. * * The operation to perform a consistency check on the fabric. * * @param {string} fabricName Fabric name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Fabric} - 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. * * {Fabric} [result] - The deserialized result object if an error did not occur. * See {@link Fabric} 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. */ checkConsistency(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Fabric>; checkConsistency(fabricName: string, callback: ServiceCallback<models.Fabric>): void; checkConsistency(fabricName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Fabric>): void; /** * @summary Migrates the site to AAD. * * The operation to migrate an Azure Site Recovery fabric to AAD. * * @param {string} fabricName ASR fabric to migrate. * * @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. */ migrateToAadWithHttpOperationResponse(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Migrates the site to AAD. * * The operation to migrate an Azure Site Recovery fabric to AAD. * * @param {string} fabricName ASR fabric to migrate. * * @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. */ migrateToAad(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; migrateToAad(fabricName: string, callback: ServiceCallback<void>): void; migrateToAad(fabricName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Perform failover of the process server. * * The operation to move replications from a process server to another process * server. * * @param {string} fabricName The name of the fabric containing the process * server. * * @param {object} failoverProcessServerRequest The input to the failover * process server operation. * * @param {object} [failoverProcessServerRequest.properties] The properties of * the PS Failover request. * * @param {string} [failoverProcessServerRequest.properties.containerName] The * container identifier. * * @param {string} * [failoverProcessServerRequest.properties.sourceProcessServerId] The source * process server. * * @param {string} * [failoverProcessServerRequest.properties.targetProcessServerId] The new * process server. * * @param {array} [failoverProcessServerRequest.properties.vmsToMigrate] The * VMS to migrate. * * @param {string} [failoverProcessServerRequest.properties.updateType] A value * for failover type. It can be systemlevel/serverlevel * * @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<Fabric>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ reassociateGatewayWithHttpOperationResponse(fabricName: string, failoverProcessServerRequest: models.FailoverProcessServerRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Fabric>>; /** * @summary Perform failover of the process server. * * The operation to move replications from a process server to another process * server. * * @param {string} fabricName The name of the fabric containing the process * server. * * @param {object} failoverProcessServerRequest The input to the failover * process server operation. * * @param {object} [failoverProcessServerRequest.properties] The properties of * the PS Failover request. * * @param {string} [failoverProcessServerRequest.properties.containerName] The * container identifier. * * @param {string} * [failoverProcessServerRequest.properties.sourceProcessServerId] The source * process server. * * @param {string} * [failoverProcessServerRequest.properties.targetProcessServerId] The new * process server. * * @param {array} [failoverProcessServerRequest.properties.vmsToMigrate] The * VMS to migrate. * * @param {string} [failoverProcessServerRequest.properties.updateType] A value * for failover type. It can be systemlevel/serverlevel * * @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 {Fabric} - 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. * * {Fabric} [result] - The deserialized result object if an error did not occur. * See {@link Fabric} 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. */ reassociateGateway(fabricName: string, failoverProcessServerRequest: models.FailoverProcessServerRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Fabric>; reassociateGateway(fabricName: string, failoverProcessServerRequest: models.FailoverProcessServerRequest, callback: ServiceCallback<models.Fabric>): void; reassociateGateway(fabricName: string, failoverProcessServerRequest: models.FailoverProcessServerRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Fabric>): void; /** * @summary Deletes the site. * * The operation to delete or remove an Azure Site Recovery fabric. * * @param {string} fabricName ASR fabric to delete * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Deletes the site. * * The operation to delete or remove an Azure Site Recovery fabric. * * @param {string} fabricName ASR fabric to delete * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(fabricName: string, callback: ServiceCallback<void>): void; deleteMethod(fabricName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Renews certificate for the fabric. * * Renews the connection certificate for the ASR replication fabric. * * @param {string} fabricName fabric name to renew certs for. * * @param {object} renewCertificateParameter Renew certificate input. * * @param {object} [renewCertificateParameter.properties] Renew certificate * input properties. * * @param {string} [renewCertificateParameter.properties.renewCertificateType] * Renew certificate type. * * @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<Fabric>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ renewCertificateWithHttpOperationResponse(fabricName: string, renewCertificateParameter: models.RenewCertificateInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Fabric>>; /** * @summary Renews certificate for the fabric. * * Renews the connection certificate for the ASR replication fabric. * * @param {string} fabricName fabric name to renew certs for. * * @param {object} renewCertificateParameter Renew certificate input. * * @param {object} [renewCertificateParameter.properties] Renew certificate * input properties. * * @param {string} [renewCertificateParameter.properties.renewCertificateType] * Renew certificate type. * * @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 {Fabric} - 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. * * {Fabric} [result] - The deserialized result object if an error did not occur. * See {@link Fabric} 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. */ renewCertificate(fabricName: string, renewCertificateParameter: models.RenewCertificateInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Fabric>; renewCertificate(fabricName: string, renewCertificateParameter: models.RenewCertificateInput, callback: ServiceCallback<models.Fabric>): void; renewCertificate(fabricName: string, renewCertificateParameter: models.RenewCertificateInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Fabric>): void; /** * @summary Creates an Azure Site Recovery fabric. * * The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V * site) * * @param {string} fabricName Name of the ASR fabric. * * @param {object} input Fabric creation input. * * @param {object} [input.properties] Fabric creation input. * * @param {object} [input.properties.customDetails] Fabric provider specific * creation input. * * @param {string} input.properties.customDetails.instanceType Polymorphic * Discriminator * * @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<Fabric>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateWithHttpOperationResponse(fabricName: string, input: models.FabricCreationInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Fabric>>; /** * @summary Creates an Azure Site Recovery fabric. * * The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V * site) * * @param {string} fabricName Name of the ASR fabric. * * @param {object} input Fabric creation input. * * @param {object} [input.properties] Fabric creation input. * * @param {object} [input.properties.customDetails] Fabric provider specific * creation input. * * @param {string} input.properties.customDetails.instanceType Polymorphic * Discriminator * * @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 {Fabric} - 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. * * {Fabric} [result] - The deserialized result object if an error did not occur. * See {@link Fabric} 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. */ beginCreate(fabricName: string, input: models.FabricCreationInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Fabric>; beginCreate(fabricName: string, input: models.FabricCreationInput, callback: ServiceCallback<models.Fabric>): void; beginCreate(fabricName: string, input: models.FabricCreationInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Fabric>): void; /** * @summary Purges the site. * * The operation to purge(force delete) an Azure Site Recovery fabric. * * @param {string} fabricName ASR fabric to purge. * * @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. */ beginPurgeWithHttpOperationResponse(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Purges the site. * * The operation to purge(force delete) an Azure Site Recovery fabric. * * @param {string} fabricName ASR fabric to purge. * * @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. */ beginPurge(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginPurge(fabricName: string, callback: ServiceCallback<void>): void; beginPurge(fabricName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Checks the consistency of the ASR fabric. * * The operation to perform a consistency check on the fabric. * * @param {string} fabricName Fabric name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Fabric>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCheckConsistencyWithHttpOperationResponse(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Fabric>>; /** * @summary Checks the consistency of the ASR fabric. * * The operation to perform a consistency check on the fabric. * * @param {string} fabricName Fabric name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Fabric} - 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. * * {Fabric} [result] - The deserialized result object if an error did not occur. * See {@link Fabric} 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. */ beginCheckConsistency(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Fabric>; beginCheckConsistency(fabricName: string, callback: ServiceCallback<models.Fabric>): void; beginCheckConsistency(fabricName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Fabric>): void; /** * @summary Migrates the site to AAD. * * The operation to migrate an Azure Site Recovery fabric to AAD. * * @param {string} fabricName ASR fabric to migrate. * * @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. */ beginMigrateToAadWithHttpOperationResponse(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Migrates the site to AAD. * * The operation to migrate an Azure Site Recovery fabric to AAD. * * @param {string} fabricName ASR fabric to migrate. * * @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. */ beginMigrateToAad(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginMigrateToAad(fabricName: string, callback: ServiceCallback<void>): void; beginMigrateToAad(fabricName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Perform failover of the process server. * * The operation to move replications from a process server to another process * server. * * @param {string} fabricName The name of the fabric containing the process * server. * * @param {object} failoverProcessServerRequest The input to the failover * process server operation. * * @param {object} [failoverProcessServerRequest.properties] The properties of * the PS Failover request. * * @param {string} [failoverProcessServerRequest.properties.containerName] The * container identifier. * * @param {string} * [failoverProcessServerRequest.properties.sourceProcessServerId] The source * process server. * * @param {string} * [failoverProcessServerRequest.properties.targetProcessServerId] The new * process server. * * @param {array} [failoverProcessServerRequest.properties.vmsToMigrate] The * VMS to migrate. * * @param {string} [failoverProcessServerRequest.properties.updateType] A value * for failover type. It can be systemlevel/serverlevel * * @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<Fabric>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginReassociateGatewayWithHttpOperationResponse(fabricName: string, failoverProcessServerRequest: models.FailoverProcessServerRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Fabric>>; /** * @summary Perform failover of the process server. * * The operation to move replications from a process server to another process * server. * * @param {string} fabricName The name of the fabric containing the process * server. * * @param {object} failoverProcessServerRequest The input to the failover * process server operation. * * @param {object} [failoverProcessServerRequest.properties] The properties of * the PS Failover request. * * @param {string} [failoverProcessServerRequest.properties.containerName] The * container identifier. * * @param {string} * [failoverProcessServerRequest.properties.sourceProcessServerId] The source * process server. * * @param {string} * [failoverProcessServerRequest.properties.targetProcessServerId] The new * process server. * * @param {array} [failoverProcessServerRequest.properties.vmsToMigrate] The * VMS to migrate. * * @param {string} [failoverProcessServerRequest.properties.updateType] A value * for failover type. It can be systemlevel/serverlevel * * @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 {Fabric} - 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. * * {Fabric} [result] - The deserialized result object if an error did not occur. * See {@link Fabric} 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. */ beginReassociateGateway(fabricName: string, failoverProcessServerRequest: models.FailoverProcessServerRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Fabric>; beginReassociateGateway(fabricName: string, failoverProcessServerRequest: models.FailoverProcessServerRequest, callback: ServiceCallback<models.Fabric>): void; beginReassociateGateway(fabricName: string, failoverProcessServerRequest: models.FailoverProcessServerRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Fabric>): void; /** * @summary Deletes the site. * * The operation to delete or remove an Azure Site Recovery fabric. * * @param {string} fabricName ASR fabric to delete * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Deletes the site. * * The operation to delete or remove an Azure Site Recovery fabric. * * @param {string} fabricName ASR fabric to delete * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(fabricName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(fabricName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Renews certificate for the fabric. * * Renews the connection certificate for the ASR replication fabric. * * @param {string} fabricName fabric name to renew certs for. * * @param {object} renewCertificateParameter Renew certificate input. * * @param {object} [renewCertificateParameter.properties] Renew certificate * input properties. * * @param {string} [renewCertificateParameter.properties.renewCertificateType] * Renew certificate type. * * @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<Fabric>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginRenewCertificateWithHttpOperationResponse(fabricName: string, renewCertificateParameter: models.RenewCertificateInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Fabric>>; /** * @summary Renews certificate for the fabric. * * Renews the connection certificate for the ASR replication fabric. * * @param {string} fabricName fabric name to renew certs for. * * @param {object} renewCertificateParameter Renew certificate input. * * @param {object} [renewCertificateParameter.properties] Renew certificate * input properties. * * @param {string} [renewCertificateParameter.properties.renewCertificateType] * Renew certificate type. * * @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 {Fabric} - 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. * * {Fabric} [result] - The deserialized result object if an error did not occur. * See {@link Fabric} 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. */ beginRenewCertificate(fabricName: string, renewCertificateParameter: models.RenewCertificateInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Fabric>; beginRenewCertificate(fabricName: string, renewCertificateParameter: models.RenewCertificateInput, callback: ServiceCallback<models.Fabric>): void; beginRenewCertificate(fabricName: string, renewCertificateParameter: models.RenewCertificateInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Fabric>): void; /** * @summary Gets the list of ASR fabrics * * Gets a list of the Azure Site Recovery fabrics in the vault. * * @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<FabricCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FabricCollection>>; /** * @summary Gets the list of ASR fabrics * * Gets a list of the Azure Site Recovery fabrics in the vault. * * @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 {FabricCollection} - 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. * * {FabricCollection} [result] - The deserialized result object if an error did not occur. * See {@link FabricCollection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.FabricCollection>; listNext(nextPageLink: string, callback: ServiceCallback<models.FabricCollection>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FabricCollection>): void; } /** * @class * ReplicationLogicalNetworks * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface ReplicationLogicalNetworks { /** * @summary Gets the list of logical networks under a fabric. * * Lists all the logical networks of the Azure Site Recovery fabric * * @param {string} fabricName Server Id. * * @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<LogicalNetworkCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationFabricsWithHttpOperationResponse(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LogicalNetworkCollection>>; /** * @summary Gets the list of logical networks under a fabric. * * Lists all the logical networks of the Azure Site Recovery fabric * * @param {string} fabricName Server Id. * * @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 {LogicalNetworkCollection} - 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. * * {LogicalNetworkCollection} [result] - The deserialized result object if an error did not occur. * See {@link LogicalNetworkCollection} 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. */ listByReplicationFabrics(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LogicalNetworkCollection>; listByReplicationFabrics(fabricName: string, callback: ServiceCallback<models.LogicalNetworkCollection>): void; listByReplicationFabrics(fabricName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LogicalNetworkCollection>): void; /** * @summary Gets a logical network with specified server id and logical network * name. * * Gets the details of a logical network. * * @param {string} fabricName Server Id. * * @param {string} logicalNetworkName Logical network name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LogicalNetwork>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(fabricName: string, logicalNetworkName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LogicalNetwork>>; /** * @summary Gets a logical network with specified server id and logical network * name. * * Gets the details of a logical network. * * @param {string} fabricName Server Id. * * @param {string} logicalNetworkName Logical network name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LogicalNetwork} - 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. * * {LogicalNetwork} [result] - The deserialized result object if an error did not occur. * See {@link LogicalNetwork} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(fabricName: string, logicalNetworkName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LogicalNetwork>; get(fabricName: string, logicalNetworkName: string, callback: ServiceCallback<models.LogicalNetwork>): void; get(fabricName: string, logicalNetworkName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LogicalNetwork>): void; /** * @summary Gets the list of logical networks under a fabric. * * Lists all the logical networks of the Azure Site Recovery fabric * * @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<LogicalNetworkCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationFabricsNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LogicalNetworkCollection>>; /** * @summary Gets the list of logical networks under a fabric. * * Lists all the logical networks of the Azure Site Recovery fabric * * @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 {LogicalNetworkCollection} - 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. * * {LogicalNetworkCollection} [result] - The deserialized result object if an error did not occur. * See {@link LogicalNetworkCollection} 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. */ listByReplicationFabricsNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LogicalNetworkCollection>; listByReplicationFabricsNext(nextPageLink: string, callback: ServiceCallback<models.LogicalNetworkCollection>): void; listByReplicationFabricsNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LogicalNetworkCollection>): void; } /** * @class * ReplicationNetworks * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface ReplicationNetworks { /** * @summary Gets the list of networks under a fabric. * * Lists the networks available for a fabric. * * @param {string} fabricName Fabric name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NetworkCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationFabricsWithHttpOperationResponse(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkCollection>>; /** * @summary Gets the list of networks under a fabric. * * Lists the networks available for a fabric. * * @param {string} fabricName Fabric name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NetworkCollection} - 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. * * {NetworkCollection} [result] - The deserialized result object if an error did not occur. * See {@link NetworkCollection} 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. */ listByReplicationFabrics(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkCollection>; listByReplicationFabrics(fabricName: string, callback: ServiceCallback<models.NetworkCollection>): void; listByReplicationFabrics(fabricName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkCollection>): void; /** * @summary Gets a network with specified server id and network name. * * Gets the details of a network. * * @param {string} fabricName Server Id. * * @param {string} networkName Primary network name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Network>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(fabricName: string, networkName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Network>>; /** * @summary Gets a network with specified server id and network name. * * Gets the details of a network. * * @param {string} fabricName Server Id. * * @param {string} networkName Primary network name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Network} - 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. * * {Network} [result] - The deserialized result object if an error did not occur. * See {@link Network} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(fabricName: string, networkName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Network>; get(fabricName: string, networkName: string, callback: ServiceCallback<models.Network>): void; get(fabricName: string, networkName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Network>): void; /** * @summary Gets the list of networks. View-only API. * * Lists the networks available in a vault * * @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<NetworkCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkCollection>>; /** * @summary Gets the list of networks. View-only API. * * Lists the networks available in a vault * * @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 {NetworkCollection} - 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. * * {NetworkCollection} [result] - The deserialized result object if an error did not occur. * See {@link NetworkCollection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkCollection>; list(callback: ServiceCallback<models.NetworkCollection>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkCollection>): void; /** * @summary Gets the list of networks under a fabric. * * Lists the networks available for a fabric. * * @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<NetworkCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationFabricsNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkCollection>>; /** * @summary Gets the list of networks under a fabric. * * Lists the networks available for a fabric. * * @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 {NetworkCollection} - 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. * * {NetworkCollection} [result] - The deserialized result object if an error did not occur. * See {@link NetworkCollection} 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. */ listByReplicationFabricsNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkCollection>; listByReplicationFabricsNext(nextPageLink: string, callback: ServiceCallback<models.NetworkCollection>): void; listByReplicationFabricsNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkCollection>): void; /** * @summary Gets the list of networks. View-only API. * * Lists the networks available in a vault * * @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<NetworkCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkCollection>>; /** * @summary Gets the list of networks. View-only API. * * Lists the networks available in a vault * * @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 {NetworkCollection} - 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. * * {NetworkCollection} [result] - The deserialized result object if an error did not occur. * See {@link NetworkCollection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkCollection>; listNext(nextPageLink: string, callback: ServiceCallback<models.NetworkCollection>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkCollection>): void; } /** * @class * ReplicationNetworkMappings * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface ReplicationNetworkMappings { /** * @summary Gets all the network mappings under a network. * * Lists all ASR network mappings for the specified network. * * @param {string} fabricName Primary fabric name. * * @param {string} networkName Primary network name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NetworkMappingCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationNetworksWithHttpOperationResponse(fabricName: string, networkName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkMappingCollection>>; /** * @summary Gets all the network mappings under a network. * * Lists all ASR network mappings for the specified network. * * @param {string} fabricName Primary fabric name. * * @param {string} networkName Primary network name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NetworkMappingCollection} - 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. * * {NetworkMappingCollection} [result] - The deserialized result object if an error did not occur. * See {@link NetworkMappingCollection} 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. */ listByReplicationNetworks(fabricName: string, networkName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkMappingCollection>; listByReplicationNetworks(fabricName: string, networkName: string, callback: ServiceCallback<models.NetworkMappingCollection>): void; listByReplicationNetworks(fabricName: string, networkName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkMappingCollection>): void; /** * @summary Gets network mapping by name. * * Gets the details of an ASR network mapping * * @param {string} fabricName Primary fabric name. * * @param {string} networkName Primary network name. * * @param {string} networkMappingName Network mapping name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NetworkMapping>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(fabricName: string, networkName: string, networkMappingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkMapping>>; /** * @summary Gets network mapping by name. * * Gets the details of an ASR network mapping * * @param {string} fabricName Primary fabric name. * * @param {string} networkName Primary network name. * * @param {string} networkMappingName Network mapping name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NetworkMapping} - 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. * * {NetworkMapping} [result] - The deserialized result object if an error did not occur. * See {@link NetworkMapping} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(fabricName: string, networkName: string, networkMappingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkMapping>; get(fabricName: string, networkName: string, networkMappingName: string, callback: ServiceCallback<models.NetworkMapping>): void; get(fabricName: string, networkName: string, networkMappingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkMapping>): void; /** * @summary Creates network mapping. * * The operation to create an ASR network mapping. * * @param {string} fabricName Primary fabric name. * * @param {string} networkName Primary network name. * * @param {string} networkMappingName Network mapping name. * * @param {object} input Create network mapping input. * * @param {object} [input.properties] Input properties for creating network * mapping. * * @param {string} [input.properties.recoveryFabricName] Recovery fabric Name. * * @param {string} [input.properties.recoveryNetworkId] Recovery network Id. * * @param {object} [input.properties.fabricSpecificDetails] Fabric specific * input properties. * * @param {string} input.properties.fabricSpecificDetails.instanceType * Polymorphic Discriminator * * @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<NetworkMapping>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(fabricName: string, networkName: string, networkMappingName: string, input: models.CreateNetworkMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkMapping>>; /** * @summary Creates network mapping. * * The operation to create an ASR network mapping. * * @param {string} fabricName Primary fabric name. * * @param {string} networkName Primary network name. * * @param {string} networkMappingName Network mapping name. * * @param {object} input Create network mapping input. * * @param {object} [input.properties] Input properties for creating network * mapping. * * @param {string} [input.properties.recoveryFabricName] Recovery fabric Name. * * @param {string} [input.properties.recoveryNetworkId] Recovery network Id. * * @param {object} [input.properties.fabricSpecificDetails] Fabric specific * input properties. * * @param {string} input.properties.fabricSpecificDetails.instanceType * Polymorphic Discriminator * * @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 {NetworkMapping} - 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. * * {NetworkMapping} [result] - The deserialized result object if an error did not occur. * See {@link NetworkMapping} 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. */ create(fabricName: string, networkName: string, networkMappingName: string, input: models.CreateNetworkMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkMapping>; create(fabricName: string, networkName: string, networkMappingName: string, input: models.CreateNetworkMappingInput, callback: ServiceCallback<models.NetworkMapping>): void; create(fabricName: string, networkName: string, networkMappingName: string, input: models.CreateNetworkMappingInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkMapping>): void; /** * @summary Delete network mapping. * * The operation to delete a network mapping. * * @param {string} fabricName Primary fabric name. * * @param {string} networkName Primary network name. * * @param {string} networkMappingName ARM Resource Name for network mapping. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(fabricName: string, networkName: string, networkMappingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Delete network mapping. * * The operation to delete a network mapping. * * @param {string} fabricName Primary fabric name. * * @param {string} networkName Primary network name. * * @param {string} networkMappingName ARM Resource Name for network mapping. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(fabricName: string, networkName: string, networkMappingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(fabricName: string, networkName: string, networkMappingName: string, callback: ServiceCallback<void>): void; deleteMethod(fabricName: string, networkName: string, networkMappingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Updates network mapping. * * The operation to update an ASR network mapping. * * @param {string} fabricName Primary fabric name. * * @param {string} networkName Primary network name. * * @param {string} networkMappingName Network mapping name. * * @param {object} input Update network mapping input. * * @param {object} [input.properties] The input properties needed to update * network mapping. * * @param {string} [input.properties.recoveryFabricName] Recovery fabric name. * * @param {string} [input.properties.recoveryNetworkId] Recovery network Id. * * @param {object} [input.properties.fabricSpecificDetails] Fabrics specific * input network Id. * * @param {string} input.properties.fabricSpecificDetails.instanceType * Polymorphic Discriminator * * @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<NetworkMapping>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(fabricName: string, networkName: string, networkMappingName: string, input: models.UpdateNetworkMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkMapping>>; /** * @summary Updates network mapping. * * The operation to update an ASR network mapping. * * @param {string} fabricName Primary fabric name. * * @param {string} networkName Primary network name. * * @param {string} networkMappingName Network mapping name. * * @param {object} input Update network mapping input. * * @param {object} [input.properties] The input properties needed to update * network mapping. * * @param {string} [input.properties.recoveryFabricName] Recovery fabric name. * * @param {string} [input.properties.recoveryNetworkId] Recovery network Id. * * @param {object} [input.properties.fabricSpecificDetails] Fabrics specific * input network Id. * * @param {string} input.properties.fabricSpecificDetails.instanceType * Polymorphic Discriminator * * @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 {NetworkMapping} - 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. * * {NetworkMapping} [result] - The deserialized result object if an error did not occur. * See {@link NetworkMapping} 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. */ update(fabricName: string, networkName: string, networkMappingName: string, input: models.UpdateNetworkMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkMapping>; update(fabricName: string, networkName: string, networkMappingName: string, input: models.UpdateNetworkMappingInput, callback: ServiceCallback<models.NetworkMapping>): void; update(fabricName: string, networkName: string, networkMappingName: string, input: models.UpdateNetworkMappingInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkMapping>): void; /** * @summary Gets all the network mappings under a vault. * * Lists all ASR network mappings in the vault. * * @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<NetworkMappingCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkMappingCollection>>; /** * @summary Gets all the network mappings under a vault. * * Lists all ASR network mappings in the vault. * * @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 {NetworkMappingCollection} - 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. * * {NetworkMappingCollection} [result] - The deserialized result object if an error did not occur. * See {@link NetworkMappingCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkMappingCollection>; list(callback: ServiceCallback<models.NetworkMappingCollection>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkMappingCollection>): void; /** * @summary Creates network mapping. * * The operation to create an ASR network mapping. * * @param {string} fabricName Primary fabric name. * * @param {string} networkName Primary network name. * * @param {string} networkMappingName Network mapping name. * * @param {object} input Create network mapping input. * * @param {object} [input.properties] Input properties for creating network * mapping. * * @param {string} [input.properties.recoveryFabricName] Recovery fabric Name. * * @param {string} [input.properties.recoveryNetworkId] Recovery network Id. * * @param {object} [input.properties.fabricSpecificDetails] Fabric specific * input properties. * * @param {string} input.properties.fabricSpecificDetails.instanceType * Polymorphic Discriminator * * @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<NetworkMapping>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateWithHttpOperationResponse(fabricName: string, networkName: string, networkMappingName: string, input: models.CreateNetworkMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkMapping>>; /** * @summary Creates network mapping. * * The operation to create an ASR network mapping. * * @param {string} fabricName Primary fabric name. * * @param {string} networkName Primary network name. * * @param {string} networkMappingName Network mapping name. * * @param {object} input Create network mapping input. * * @param {object} [input.properties] Input properties for creating network * mapping. * * @param {string} [input.properties.recoveryFabricName] Recovery fabric Name. * * @param {string} [input.properties.recoveryNetworkId] Recovery network Id. * * @param {object} [input.properties.fabricSpecificDetails] Fabric specific * input properties. * * @param {string} input.properties.fabricSpecificDetails.instanceType * Polymorphic Discriminator * * @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 {NetworkMapping} - 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. * * {NetworkMapping} [result] - The deserialized result object if an error did not occur. * See {@link NetworkMapping} 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. */ beginCreate(fabricName: string, networkName: string, networkMappingName: string, input: models.CreateNetworkMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkMapping>; beginCreate(fabricName: string, networkName: string, networkMappingName: string, input: models.CreateNetworkMappingInput, callback: ServiceCallback<models.NetworkMapping>): void; beginCreate(fabricName: string, networkName: string, networkMappingName: string, input: models.CreateNetworkMappingInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkMapping>): void; /** * @summary Delete network mapping. * * The operation to delete a network mapping. * * @param {string} fabricName Primary fabric name. * * @param {string} networkName Primary network name. * * @param {string} networkMappingName ARM Resource Name for network mapping. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(fabricName: string, networkName: string, networkMappingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Delete network mapping. * * The operation to delete a network mapping. * * @param {string} fabricName Primary fabric name. * * @param {string} networkName Primary network name. * * @param {string} networkMappingName ARM Resource Name for network mapping. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(fabricName: string, networkName: string, networkMappingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(fabricName: string, networkName: string, networkMappingName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(fabricName: string, networkName: string, networkMappingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Updates network mapping. * * The operation to update an ASR network mapping. * * @param {string} fabricName Primary fabric name. * * @param {string} networkName Primary network name. * * @param {string} networkMappingName Network mapping name. * * @param {object} input Update network mapping input. * * @param {object} [input.properties] The input properties needed to update * network mapping. * * @param {string} [input.properties.recoveryFabricName] Recovery fabric name. * * @param {string} [input.properties.recoveryNetworkId] Recovery network Id. * * @param {object} [input.properties.fabricSpecificDetails] Fabrics specific * input network Id. * * @param {string} input.properties.fabricSpecificDetails.instanceType * Polymorphic Discriminator * * @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<NetworkMapping>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginUpdateWithHttpOperationResponse(fabricName: string, networkName: string, networkMappingName: string, input: models.UpdateNetworkMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkMapping>>; /** * @summary Updates network mapping. * * The operation to update an ASR network mapping. * * @param {string} fabricName Primary fabric name. * * @param {string} networkName Primary network name. * * @param {string} networkMappingName Network mapping name. * * @param {object} input Update network mapping input. * * @param {object} [input.properties] The input properties needed to update * network mapping. * * @param {string} [input.properties.recoveryFabricName] Recovery fabric name. * * @param {string} [input.properties.recoveryNetworkId] Recovery network Id. * * @param {object} [input.properties.fabricSpecificDetails] Fabrics specific * input network Id. * * @param {string} input.properties.fabricSpecificDetails.instanceType * Polymorphic Discriminator * * @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 {NetworkMapping} - 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. * * {NetworkMapping} [result] - The deserialized result object if an error did not occur. * See {@link NetworkMapping} 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. */ beginUpdate(fabricName: string, networkName: string, networkMappingName: string, input: models.UpdateNetworkMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkMapping>; beginUpdate(fabricName: string, networkName: string, networkMappingName: string, input: models.UpdateNetworkMappingInput, callback: ServiceCallback<models.NetworkMapping>): void; beginUpdate(fabricName: string, networkName: string, networkMappingName: string, input: models.UpdateNetworkMappingInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkMapping>): void; /** * @summary Gets all the network mappings under a network. * * Lists all ASR network mappings for the specified network. * * @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<NetworkMappingCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationNetworksNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkMappingCollection>>; /** * @summary Gets all the network mappings under a network. * * Lists all ASR network mappings for the specified network. * * @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 {NetworkMappingCollection} - 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. * * {NetworkMappingCollection} [result] - The deserialized result object if an error did not occur. * See {@link NetworkMappingCollection} 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. */ listByReplicationNetworksNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkMappingCollection>; listByReplicationNetworksNext(nextPageLink: string, callback: ServiceCallback<models.NetworkMappingCollection>): void; listByReplicationNetworksNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkMappingCollection>): void; /** * @summary Gets all the network mappings under a vault. * * Lists all ASR network mappings in the vault. * * @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<NetworkMappingCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkMappingCollection>>; /** * @summary Gets all the network mappings under a vault. * * Lists all ASR network mappings in the vault. * * @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 {NetworkMappingCollection} - 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. * * {NetworkMappingCollection} [result] - The deserialized result object if an error did not occur. * See {@link NetworkMappingCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkMappingCollection>; listNext(nextPageLink: string, callback: ServiceCallback<models.NetworkMappingCollection>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkMappingCollection>): void; } /** * @class * ReplicationProtectionContainers * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface ReplicationProtectionContainers { /** * @summary Gets the list of protection container for a fabric. * * Lists the protection containers in the specified fabric. * * @param {string} fabricName Fabric name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProtectionContainerCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationFabricsWithHttpOperationResponse(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectionContainerCollection>>; /** * @summary Gets the list of protection container for a fabric. * * Lists the protection containers in the specified fabric. * * @param {string} fabricName Fabric name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProtectionContainerCollection} - 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. * * {ProtectionContainerCollection} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainerCollection} 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. */ listByReplicationFabrics(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectionContainerCollection>; listByReplicationFabrics(fabricName: string, callback: ServiceCallback<models.ProtectionContainerCollection>): void; listByReplicationFabrics(fabricName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectionContainerCollection>): void; /** * @summary Gets the protection container details. * * Gets the details of a protection container. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProtectionContainer>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(fabricName: string, protectionContainerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectionContainer>>; /** * @summary Gets the protection container details. * * Gets the details of a protection container. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProtectionContainer} - 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. * * {ProtectionContainer} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainer} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(fabricName: string, protectionContainerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectionContainer>; get(fabricName: string, protectionContainerName: string, callback: ServiceCallback<models.ProtectionContainer>): void; get(fabricName: string, protectionContainerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectionContainer>): void; /** * @summary Create a protection container. * * Operation to create a protection container. * * @param {string} fabricName Unique fabric ARM name. * * @param {string} protectionContainerName Unique protection container ARM * name. * * @param {object} creationInput Creation input. * * @param {object} [creationInput.properties] Create protection container input * properties. * * @param {array} [creationInput.properties.providerSpecificInput] Provider * specific inputs for container creation. * * @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<ProtectionContainer>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(fabricName: string, protectionContainerName: string, creationInput: models.CreateProtectionContainerInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectionContainer>>; /** * @summary Create a protection container. * * Operation to create a protection container. * * @param {string} fabricName Unique fabric ARM name. * * @param {string} protectionContainerName Unique protection container ARM * name. * * @param {object} creationInput Creation input. * * @param {object} [creationInput.properties] Create protection container input * properties. * * @param {array} [creationInput.properties.providerSpecificInput] Provider * specific inputs for container creation. * * @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 {ProtectionContainer} - 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. * * {ProtectionContainer} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainer} 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. */ create(fabricName: string, protectionContainerName: string, creationInput: models.CreateProtectionContainerInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectionContainer>; create(fabricName: string, protectionContainerName: string, creationInput: models.CreateProtectionContainerInput, callback: ServiceCallback<models.ProtectionContainer>): void; create(fabricName: string, protectionContainerName: string, creationInput: models.CreateProtectionContainerInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectionContainer>): void; /** * @summary Adds a protectable item to the replication protection container. * * The operation to a add a protectable item to a protection container(Add * physical server.) * * @param {string} fabricName The name of the fabric. * * @param {string} protectionContainerName The name of the protection * container. * * @param {object} discoverProtectableItemRequest The request object to add a * protectable item. * * @param {object} [discoverProtectableItemRequest.properties] The properties * of a discover protectable item request. * * @param {string} [discoverProtectableItemRequest.properties.friendlyName] The * friendly name of the physical machine. * * @param {string} [discoverProtectableItemRequest.properties.ipAddress] The IP * address of the physical machine to be discovered. * * @param {string} [discoverProtectableItemRequest.properties.osType] The OS * type on the physical machine. * * @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<ProtectionContainer>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ discoverProtectableItemWithHttpOperationResponse(fabricName: string, protectionContainerName: string, discoverProtectableItemRequest: models.DiscoverProtectableItemRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectionContainer>>; /** * @summary Adds a protectable item to the replication protection container. * * The operation to a add a protectable item to a protection container(Add * physical server.) * * @param {string} fabricName The name of the fabric. * * @param {string} protectionContainerName The name of the protection * container. * * @param {object} discoverProtectableItemRequest The request object to add a * protectable item. * * @param {object} [discoverProtectableItemRequest.properties] The properties * of a discover protectable item request. * * @param {string} [discoverProtectableItemRequest.properties.friendlyName] The * friendly name of the physical machine. * * @param {string} [discoverProtectableItemRequest.properties.ipAddress] The IP * address of the physical machine to be discovered. * * @param {string} [discoverProtectableItemRequest.properties.osType] The OS * type on the physical machine. * * @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 {ProtectionContainer} - 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. * * {ProtectionContainer} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainer} 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. */ discoverProtectableItem(fabricName: string, protectionContainerName: string, discoverProtectableItemRequest: models.DiscoverProtectableItemRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectionContainer>; discoverProtectableItem(fabricName: string, protectionContainerName: string, discoverProtectableItemRequest: models.DiscoverProtectableItemRequest, callback: ServiceCallback<models.ProtectionContainer>): void; discoverProtectableItem(fabricName: string, protectionContainerName: string, discoverProtectableItemRequest: models.DiscoverProtectableItemRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectionContainer>): void; /** * @summary Removes a protection container. * * Operation to remove a protection container. * * @param {string} fabricName Unique fabric ARM name. * * @param {string} protectionContainerName Unique protection container ARM * name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(fabricName: string, protectionContainerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Removes a protection container. * * Operation to remove a protection container. * * @param {string} fabricName Unique fabric ARM name. * * @param {string} protectionContainerName Unique protection container ARM * name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(fabricName: string, protectionContainerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(fabricName: string, protectionContainerName: string, callback: ServiceCallback<void>): void; deleteMethod(fabricName: string, protectionContainerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Switches protection from one container to another or one * replication provider to another. * * Operation to switch protection from one container to another or one * replication provider to another. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {object} switchInput Switch protection input. * * @param {object} [switchInput.properties] Switch protection properties * * @param {string} [switchInput.properties.replicationProtectedItemName] The * unique replication protected item name. * * @param {object} [switchInput.properties.providerSpecificDetails] Provider * specific switch protection input. * * @param {string} switchInput.properties.providerSpecificDetails.instanceType * Polymorphic Discriminator * * @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<ProtectionContainer>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ switchProtectionWithHttpOperationResponse(fabricName: string, protectionContainerName: string, switchInput: models.SwitchProtectionInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectionContainer>>; /** * @summary Switches protection from one container to another or one * replication provider to another. * * Operation to switch protection from one container to another or one * replication provider to another. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {object} switchInput Switch protection input. * * @param {object} [switchInput.properties] Switch protection properties * * @param {string} [switchInput.properties.replicationProtectedItemName] The * unique replication protected item name. * * @param {object} [switchInput.properties.providerSpecificDetails] Provider * specific switch protection input. * * @param {string} switchInput.properties.providerSpecificDetails.instanceType * Polymorphic Discriminator * * @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 {ProtectionContainer} - 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. * * {ProtectionContainer} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainer} 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. */ switchProtection(fabricName: string, protectionContainerName: string, switchInput: models.SwitchProtectionInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectionContainer>; switchProtection(fabricName: string, protectionContainerName: string, switchInput: models.SwitchProtectionInput, callback: ServiceCallback<models.ProtectionContainer>): void; switchProtection(fabricName: string, protectionContainerName: string, switchInput: models.SwitchProtectionInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectionContainer>): void; /** * @summary Gets the list of all protection containers in a vault. * * Lists the protection containers in a vault. * * @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<ProtectionContainerCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectionContainerCollection>>; /** * @summary Gets the list of all protection containers in a vault. * * Lists the protection containers in a vault. * * @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 {ProtectionContainerCollection} - 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. * * {ProtectionContainerCollection} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainerCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectionContainerCollection>; list(callback: ServiceCallback<models.ProtectionContainerCollection>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectionContainerCollection>): void; /** * @summary Create a protection container. * * Operation to create a protection container. * * @param {string} fabricName Unique fabric ARM name. * * @param {string} protectionContainerName Unique protection container ARM * name. * * @param {object} creationInput Creation input. * * @param {object} [creationInput.properties] Create protection container input * properties. * * @param {array} [creationInput.properties.providerSpecificInput] Provider * specific inputs for container creation. * * @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<ProtectionContainer>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateWithHttpOperationResponse(fabricName: string, protectionContainerName: string, creationInput: models.CreateProtectionContainerInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectionContainer>>; /** * @summary Create a protection container. * * Operation to create a protection container. * * @param {string} fabricName Unique fabric ARM name. * * @param {string} protectionContainerName Unique protection container ARM * name. * * @param {object} creationInput Creation input. * * @param {object} [creationInput.properties] Create protection container input * properties. * * @param {array} [creationInput.properties.providerSpecificInput] Provider * specific inputs for container creation. * * @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 {ProtectionContainer} - 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. * * {ProtectionContainer} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainer} 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. */ beginCreate(fabricName: string, protectionContainerName: string, creationInput: models.CreateProtectionContainerInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectionContainer>; beginCreate(fabricName: string, protectionContainerName: string, creationInput: models.CreateProtectionContainerInput, callback: ServiceCallback<models.ProtectionContainer>): void; beginCreate(fabricName: string, protectionContainerName: string, creationInput: models.CreateProtectionContainerInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectionContainer>): void; /** * @summary Adds a protectable item to the replication protection container. * * The operation to a add a protectable item to a protection container(Add * physical server.) * * @param {string} fabricName The name of the fabric. * * @param {string} protectionContainerName The name of the protection * container. * * @param {object} discoverProtectableItemRequest The request object to add a * protectable item. * * @param {object} [discoverProtectableItemRequest.properties] The properties * of a discover protectable item request. * * @param {string} [discoverProtectableItemRequest.properties.friendlyName] The * friendly name of the physical machine. * * @param {string} [discoverProtectableItemRequest.properties.ipAddress] The IP * address of the physical machine to be discovered. * * @param {string} [discoverProtectableItemRequest.properties.osType] The OS * type on the physical machine. * * @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<ProtectionContainer>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDiscoverProtectableItemWithHttpOperationResponse(fabricName: string, protectionContainerName: string, discoverProtectableItemRequest: models.DiscoverProtectableItemRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectionContainer>>; /** * @summary Adds a protectable item to the replication protection container. * * The operation to a add a protectable item to a protection container(Add * physical server.) * * @param {string} fabricName The name of the fabric. * * @param {string} protectionContainerName The name of the protection * container. * * @param {object} discoverProtectableItemRequest The request object to add a * protectable item. * * @param {object} [discoverProtectableItemRequest.properties] The properties * of a discover protectable item request. * * @param {string} [discoverProtectableItemRequest.properties.friendlyName] The * friendly name of the physical machine. * * @param {string} [discoverProtectableItemRequest.properties.ipAddress] The IP * address of the physical machine to be discovered. * * @param {string} [discoverProtectableItemRequest.properties.osType] The OS * type on the physical machine. * * @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 {ProtectionContainer} - 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. * * {ProtectionContainer} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainer} 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. */ beginDiscoverProtectableItem(fabricName: string, protectionContainerName: string, discoverProtectableItemRequest: models.DiscoverProtectableItemRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectionContainer>; beginDiscoverProtectableItem(fabricName: string, protectionContainerName: string, discoverProtectableItemRequest: models.DiscoverProtectableItemRequest, callback: ServiceCallback<models.ProtectionContainer>): void; beginDiscoverProtectableItem(fabricName: string, protectionContainerName: string, discoverProtectableItemRequest: models.DiscoverProtectableItemRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectionContainer>): void; /** * @summary Removes a protection container. * * Operation to remove a protection container. * * @param {string} fabricName Unique fabric ARM name. * * @param {string} protectionContainerName Unique protection container ARM * name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(fabricName: string, protectionContainerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Removes a protection container. * * Operation to remove a protection container. * * @param {string} fabricName Unique fabric ARM name. * * @param {string} protectionContainerName Unique protection container ARM * name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(fabricName: string, protectionContainerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(fabricName: string, protectionContainerName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(fabricName: string, protectionContainerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Switches protection from one container to another or one * replication provider to another. * * Operation to switch protection from one container to another or one * replication provider to another. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {object} switchInput Switch protection input. * * @param {object} [switchInput.properties] Switch protection properties * * @param {string} [switchInput.properties.replicationProtectedItemName] The * unique replication protected item name. * * @param {object} [switchInput.properties.providerSpecificDetails] Provider * specific switch protection input. * * @param {string} switchInput.properties.providerSpecificDetails.instanceType * Polymorphic Discriminator * * @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<ProtectionContainer>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginSwitchProtectionWithHttpOperationResponse(fabricName: string, protectionContainerName: string, switchInput: models.SwitchProtectionInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectionContainer>>; /** * @summary Switches protection from one container to another or one * replication provider to another. * * Operation to switch protection from one container to another or one * replication provider to another. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {object} switchInput Switch protection input. * * @param {object} [switchInput.properties] Switch protection properties * * @param {string} [switchInput.properties.replicationProtectedItemName] The * unique replication protected item name. * * @param {object} [switchInput.properties.providerSpecificDetails] Provider * specific switch protection input. * * @param {string} switchInput.properties.providerSpecificDetails.instanceType * Polymorphic Discriminator * * @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 {ProtectionContainer} - 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. * * {ProtectionContainer} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainer} 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. */ beginSwitchProtection(fabricName: string, protectionContainerName: string, switchInput: models.SwitchProtectionInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectionContainer>; beginSwitchProtection(fabricName: string, protectionContainerName: string, switchInput: models.SwitchProtectionInput, callback: ServiceCallback<models.ProtectionContainer>): void; beginSwitchProtection(fabricName: string, protectionContainerName: string, switchInput: models.SwitchProtectionInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectionContainer>): void; /** * @summary Gets the list of protection container for a fabric. * * Lists the protection containers in the specified fabric. * * @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<ProtectionContainerCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationFabricsNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectionContainerCollection>>; /** * @summary Gets the list of protection container for a fabric. * * Lists the protection containers in the specified fabric. * * @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 {ProtectionContainerCollection} - 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. * * {ProtectionContainerCollection} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainerCollection} 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. */ listByReplicationFabricsNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectionContainerCollection>; listByReplicationFabricsNext(nextPageLink: string, callback: ServiceCallback<models.ProtectionContainerCollection>): void; listByReplicationFabricsNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectionContainerCollection>): void; /** * @summary Gets the list of all protection containers in a vault. * * Lists the protection containers in a vault. * * @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<ProtectionContainerCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectionContainerCollection>>; /** * @summary Gets the list of all protection containers in a vault. * * Lists the protection containers in a vault. * * @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 {ProtectionContainerCollection} - 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. * * {ProtectionContainerCollection} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainerCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectionContainerCollection>; listNext(nextPageLink: string, callback: ServiceCallback<models.ProtectionContainerCollection>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectionContainerCollection>): void; } /** * @class * ReplicationProtectableItems * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface ReplicationProtectableItems { /** * @summary Gets the list of protectable items. * * Lists the protectable items in a protection container. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] OData filter options. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProtectableItemCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationProtectionContainersWithHttpOperationResponse(fabricName: string, protectionContainerName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectableItemCollection>>; /** * @summary Gets the list of protectable items. * * Lists the protectable items in a protection container. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] OData filter options. * * @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 {ProtectableItemCollection} - 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. * * {ProtectableItemCollection} [result] - The deserialized result object if an error did not occur. * See {@link ProtectableItemCollection} 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. */ listByReplicationProtectionContainers(fabricName: string, protectionContainerName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectableItemCollection>; listByReplicationProtectionContainers(fabricName: string, protectionContainerName: string, callback: ServiceCallback<models.ProtectableItemCollection>): void; listByReplicationProtectionContainers(fabricName: string, protectionContainerName: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectableItemCollection>): void; /** * @summary Gets the details of a protectable item. * * The operation to get the details of a protectable item. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} protectableItemName Protectable item name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProtectableItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(fabricName: string, protectionContainerName: string, protectableItemName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectableItem>>; /** * @summary Gets the details of a protectable item. * * The operation to get the details of a protectable item. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} protectableItemName Protectable item name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProtectableItem} - 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. * * {ProtectableItem} [result] - The deserialized result object if an error did not occur. * See {@link ProtectableItem} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(fabricName: string, protectionContainerName: string, protectableItemName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectableItem>; get(fabricName: string, protectionContainerName: string, protectableItemName: string, callback: ServiceCallback<models.ProtectableItem>): void; get(fabricName: string, protectionContainerName: string, protectableItemName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectableItem>): void; /** * @summary Gets the list of protectable items. * * Lists the protectable items in a protection container. * * @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<ProtectableItemCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationProtectionContainersNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectableItemCollection>>; /** * @summary Gets the list of protectable items. * * Lists the protectable items in a protection container. * * @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 {ProtectableItemCollection} - 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. * * {ProtectableItemCollection} [result] - The deserialized result object if an error did not occur. * See {@link ProtectableItemCollection} 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. */ listByReplicationProtectionContainersNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectableItemCollection>; listByReplicationProtectionContainersNext(nextPageLink: string, callback: ServiceCallback<models.ProtectableItemCollection>): void; listByReplicationProtectionContainersNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectableItemCollection>): void; } /** * @class * ReplicationProtectedItems * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface ReplicationProtectedItems { /** * @summary Gets the list of Replication protected items. * * Gets the list of ASR replication protected items in the protection * container. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ReplicationProtectedItemCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationProtectionContainersWithHttpOperationResponse(fabricName: string, protectionContainerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItemCollection>>; /** * @summary Gets the list of Replication protected items. * * Gets the list of ASR replication protected items in the protection * container. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ReplicationProtectedItemCollection} - 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. * * {ReplicationProtectedItemCollection} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItemCollection} 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. */ listByReplicationProtectionContainers(fabricName: string, protectionContainerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItemCollection>; listByReplicationProtectionContainers(fabricName: string, protectionContainerName: string, callback: ServiceCallback<models.ReplicationProtectedItemCollection>): void; listByReplicationProtectionContainers(fabricName: string, protectionContainerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItemCollection>): void; /** * @summary Gets the details of a Replication protected item. * * Gets the details of an ASR replication protected item. * * @param {string} fabricName Fabric unique name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Gets the details of a Replication protected item. * * Gets the details of an ASR replication protected item. * * @param {string} fabricName Fabric unique name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; get(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, callback: ServiceCallback<models.ReplicationProtectedItem>): void; get(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Enables protection. * * The operation to create an ASR replication protected item (Enable * replication). * * @param {string} fabricName Name of the fabric. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName A name for the replication * protected item. * * @param {object} input Enable Protection Input. * * @param {object} [input.properties] Enable protection input properties. * * @param {string} [input.properties.policyId] The Policy Id. * * @param {string} [input.properties.protectableItemId] The protectable item * Id. * * @param {object} [input.properties.providerSpecificDetails] The * ReplicationProviderInput. For HyperVReplicaAzure provider, it will be * AzureEnableProtectionInput object. For San provider, it will be * SanEnableProtectionInput object. For HyperVReplicaAzure provider, it can be * null. * * @param {string} input.properties.providerSpecificDetails.instanceType * Polymorphic Discriminator * * @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<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, input: models.EnableProtectionInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Enables protection. * * The operation to create an ASR replication protected item (Enable * replication). * * @param {string} fabricName Name of the fabric. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName A name for the replication * protected item. * * @param {object} input Enable Protection Input. * * @param {object} [input.properties] Enable protection input properties. * * @param {string} [input.properties.policyId] The Policy Id. * * @param {string} [input.properties.protectableItemId] The protectable item * Id. * * @param {object} [input.properties.providerSpecificDetails] The * ReplicationProviderInput. For HyperVReplicaAzure provider, it will be * AzureEnableProtectionInput object. For San provider, it will be * SanEnableProtectionInput object. For HyperVReplicaAzure provider, it can be * null. * * @param {string} input.properties.providerSpecificDetails.instanceType * Polymorphic Discriminator * * @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 {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ create(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, input: models.EnableProtectionInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; create(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, input: models.EnableProtectionInput, callback: ServiceCallback<models.ReplicationProtectedItem>): void; create(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, input: models.EnableProtectionInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Purges protection. * * The operation to delete or purge a replication protected item. This * operation will force delete the replication protected item. Use the remove * operation on replication protected item to perform a clean disable * replication for the item. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ purgeWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Purges protection. * * The operation to delete or purge a replication protected item. This * operation will force delete the replication protected item. Use the remove * operation on replication protected item to perform a clean disable * replication for the item. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ purge(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; purge(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, callback: ServiceCallback<void>): void; purge(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Updates protection. * * The operation to update the recovery settings of an ASR replication * protected item. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} updateProtectionInput Update protection input. * * @param {object} [updateProtectionInput.properties] Update replication * protected item properties. * * @param {string} [updateProtectionInput.properties.recoveryAzureVMName] * Target azure VM name given by the user. * * @param {string} [updateProtectionInput.properties.recoveryAzureVMSize] * Target Azure Vm size. * * @param {string} * [updateProtectionInput.properties.selectedRecoveryAzureNetworkId] Target * Azure Network Id. * * @param {string} [updateProtectionInput.properties.selectedSourceNicId] The * selected source nic Id which will be used as the primary nic during * failover. * * @param {string} [updateProtectionInput.properties.enableRdpOnTargetOption] * The selected option to enable RDP\SSH on target vm after failover. String * value of {SrsDataContract.EnableRDPOnTargetOption} enum. * * @param {array} [updateProtectionInput.properties.vmNics] The list of vm nic * details. * * @param {string} [updateProtectionInput.properties.licenseType] License type. * Possible values include: 'NotSpecified', 'NoLicenseType', 'WindowsServer' * * @param {string} [updateProtectionInput.properties.recoveryAvailabilitySetId] * The target availability set id. * * @param {object} [updateProtectionInput.properties.providerSpecificDetails] * The provider specific input to update replication protected item. * * @param {string} * updateProtectionInput.properties.providerSpecificDetails.instanceType * Polymorphic Discriminator * * @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<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, updateProtectionInput: models.UpdateReplicationProtectedItemInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Updates protection. * * The operation to update the recovery settings of an ASR replication * protected item. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} updateProtectionInput Update protection input. * * @param {object} [updateProtectionInput.properties] Update replication * protected item properties. * * @param {string} [updateProtectionInput.properties.recoveryAzureVMName] * Target azure VM name given by the user. * * @param {string} [updateProtectionInput.properties.recoveryAzureVMSize] * Target Azure Vm size. * * @param {string} * [updateProtectionInput.properties.selectedRecoveryAzureNetworkId] Target * Azure Network Id. * * @param {string} [updateProtectionInput.properties.selectedSourceNicId] The * selected source nic Id which will be used as the primary nic during * failover. * * @param {string} [updateProtectionInput.properties.enableRdpOnTargetOption] * The selected option to enable RDP\SSH on target vm after failover. String * value of {SrsDataContract.EnableRDPOnTargetOption} enum. * * @param {array} [updateProtectionInput.properties.vmNics] The list of vm nic * details. * * @param {string} [updateProtectionInput.properties.licenseType] License type. * Possible values include: 'NotSpecified', 'NoLicenseType', 'WindowsServer' * * @param {string} [updateProtectionInput.properties.recoveryAvailabilitySetId] * The target availability set id. * * @param {object} [updateProtectionInput.properties.providerSpecificDetails] * The provider specific input to update replication protected item. * * @param {string} * updateProtectionInput.properties.providerSpecificDetails.instanceType * Polymorphic Discriminator * * @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 {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ update(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, updateProtectionInput: models.UpdateReplicationProtectedItemInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; update(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, updateProtectionInput: models.UpdateReplicationProtectedItemInput, callback: ServiceCallback<models.ReplicationProtectedItem>): void; update(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, updateProtectionInput: models.UpdateReplicationProtectedItemInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Change or apply recovery point. * * The operation to change the recovery point of a failed over replication * protected item. * * @param {string} fabricName The ARM fabric name. * * @param {string} protectionContainerName The protection container name. * * @param {string} replicatedProtectedItemName The replicated protected item's * name. * * @param {object} applyRecoveryPointInput The ApplyRecoveryPointInput. * * @param {object} [applyRecoveryPointInput.properties] The input properties to * apply recovery point. * * @param {string} [applyRecoveryPointInput.properties.recoveryPointId] The * recovery point Id. * * @param {object} [applyRecoveryPointInput.properties.providerSpecificDetails] * Provider specific input for applying recovery point. * * @param {string} * applyRecoveryPointInput.properties.providerSpecificDetails.instanceType * Polymorphic Discriminator * * @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<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ applyRecoveryPointWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, applyRecoveryPointInput: models.ApplyRecoveryPointInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Change or apply recovery point. * * The operation to change the recovery point of a failed over replication * protected item. * * @param {string} fabricName The ARM fabric name. * * @param {string} protectionContainerName The protection container name. * * @param {string} replicatedProtectedItemName The replicated protected item's * name. * * @param {object} applyRecoveryPointInput The ApplyRecoveryPointInput. * * @param {object} [applyRecoveryPointInput.properties] The input properties to * apply recovery point. * * @param {string} [applyRecoveryPointInput.properties.recoveryPointId] The * recovery point Id. * * @param {object} [applyRecoveryPointInput.properties.providerSpecificDetails] * Provider specific input for applying recovery point. * * @param {string} * applyRecoveryPointInput.properties.providerSpecificDetails.instanceType * Polymorphic Discriminator * * @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 {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ applyRecoveryPoint(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, applyRecoveryPointInput: models.ApplyRecoveryPointInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; applyRecoveryPoint(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, applyRecoveryPointInput: models.ApplyRecoveryPointInput, callback: ServiceCallback<models.ReplicationProtectedItem>): void; applyRecoveryPoint(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, applyRecoveryPointInput: models.ApplyRecoveryPointInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Execute commit failover * * Operation to commit the failover of the replication protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ failoverCommitWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Execute commit failover * * Operation to commit the failover of the replication protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ failoverCommit(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; failoverCommit(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, callback: ServiceCallback<models.ReplicationProtectedItem>): void; failoverCommit(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Execute planned failover * * Operation to initiate a planned failover of the replication protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} failoverInput Disable protection input. * * @param {object} [failoverInput.properties] Planned failover input properties * * @param {string} [failoverInput.properties.failoverDirection] Failover * direction. * * @param {object} [failoverInput.properties.providerSpecificDetails] Provider * specific settings * * @param {string} * failoverInput.properties.providerSpecificDetails.instanceType Polymorphic * Discriminator * * @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<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ plannedFailoverWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.PlannedFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Execute planned failover * * Operation to initiate a planned failover of the replication protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} failoverInput Disable protection input. * * @param {object} [failoverInput.properties] Planned failover input properties * * @param {string} [failoverInput.properties.failoverDirection] Failover * direction. * * @param {object} [failoverInput.properties.providerSpecificDetails] Provider * specific settings * * @param {string} * failoverInput.properties.providerSpecificDetails.instanceType Polymorphic * Discriminator * * @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 {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ plannedFailover(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.PlannedFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; plannedFailover(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.PlannedFailoverInput, callback: ServiceCallback<models.ReplicationProtectedItem>): void; plannedFailover(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.PlannedFailoverInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Disables protection. * * The operation to disable replication on a replication protected item. This * will also remove the item. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} disableProtectionInput Disable protection input. * * @param {object} [disableProtectionInput.properties] Disable protection input * properties. * * @param {string} [disableProtectionInput.properties.disableProtectionReason] * Disable protection reason. It can have values * NotSpecified/MigrationComplete. Possible values include: 'NotSpecified', * 'MigrationComplete' * * @param {object} [disableProtectionInput.properties.replicationProviderInput] * Replication provider specific input. * * @param {string} * disableProtectionInput.properties.replicationProviderInput.instanceType * Polymorphic Discriminator * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, disableProtectionInput: models.DisableProtectionInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Disables protection. * * The operation to disable replication on a replication protected item. This * will also remove the item. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} disableProtectionInput Disable protection input. * * @param {object} [disableProtectionInput.properties] Disable protection input * properties. * * @param {string} [disableProtectionInput.properties.disableProtectionReason] * Disable protection reason. It can have values * NotSpecified/MigrationComplete. Possible values include: 'NotSpecified', * 'MigrationComplete' * * @param {object} [disableProtectionInput.properties.replicationProviderInput] * Replication provider specific input. * * @param {string} * disableProtectionInput.properties.replicationProviderInput.instanceType * Polymorphic Discriminator * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, disableProtectionInput: models.DisableProtectionInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, disableProtectionInput: models.DisableProtectionInput, callback: ServiceCallback<void>): void; deleteMethod(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, disableProtectionInput: models.DisableProtectionInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Resynchronize or repair replication. * * The operation to start resynchronize/repair replication for a replication * protected item requiring resynchronization. * * @param {string} fabricName The name of the fabric. * * @param {string} protectionContainerName The name of the container. * * @param {string} replicatedProtectedItemName The name of the replication * protected item. * * @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<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ repairReplicationWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Resynchronize or repair replication. * * The operation to start resynchronize/repair replication for a replication * protected item requiring resynchronization. * * @param {string} fabricName The name of the fabric. * * @param {string} protectionContainerName The name of the container. * * @param {string} replicatedProtectedItemName The name of the replication * protected item. * * @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 {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ repairReplication(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; repairReplication(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, callback: ServiceCallback<models.ReplicationProtectedItem>): void; repairReplication(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Execute Reverse Replication\Reprotect * * Operation to reprotect or reverse replicate a failed over replication * protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} rrInput Disable protection input. * * @param {object} [rrInput.properties] Reverse replication properties * * @param {string} [rrInput.properties.failoverDirection] Failover direction. * * @param {object} [rrInput.properties.providerSpecificDetails] Provider * specific reverse replication input. * * @param {string} rrInput.properties.providerSpecificDetails.instanceType * Polymorphic Discriminator * * @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<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ reprotectWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, rrInput: models.ReverseReplicationInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Execute Reverse Replication\Reprotect * * Operation to reprotect or reverse replicate a failed over replication * protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} rrInput Disable protection input. * * @param {object} [rrInput.properties] Reverse replication properties * * @param {string} [rrInput.properties.failoverDirection] Failover direction. * * @param {object} [rrInput.properties.providerSpecificDetails] Provider * specific reverse replication input. * * @param {string} rrInput.properties.providerSpecificDetails.instanceType * Polymorphic Discriminator * * @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 {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ reprotect(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, rrInput: models.ReverseReplicationInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; reprotect(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, rrInput: models.ReverseReplicationInput, callback: ServiceCallback<models.ReplicationProtectedItem>): void; reprotect(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, rrInput: models.ReverseReplicationInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Execute test failover * * Operation to perform a test failover of the replication protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} failoverInput Test failover input. * * @param {object} [failoverInput.properties] Planned failover input properties * * @param {string} [failoverInput.properties.failoverDirection] Failover * direction. * * @param {string} [failoverInput.properties.networkType] Network type to be * used for test failover. * * @param {string} [failoverInput.properties.networkId] The id of the network * to be used for test failover * * @param {string} [failoverInput.properties.skipTestFailoverCleanup] A value * indicating whether the test failover cleanup is to be skipped. * * @param {object} [failoverInput.properties.providerSpecificDetails] Provider * specific settings * * @param {string} * failoverInput.properties.providerSpecificDetails.instanceType Polymorphic * Discriminator * * @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<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ testFailoverWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.TestFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Execute test failover * * Operation to perform a test failover of the replication protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} failoverInput Test failover input. * * @param {object} [failoverInput.properties] Planned failover input properties * * @param {string} [failoverInput.properties.failoverDirection] Failover * direction. * * @param {string} [failoverInput.properties.networkType] Network type to be * used for test failover. * * @param {string} [failoverInput.properties.networkId] The id of the network * to be used for test failover * * @param {string} [failoverInput.properties.skipTestFailoverCleanup] A value * indicating whether the test failover cleanup is to be skipped. * * @param {object} [failoverInput.properties.providerSpecificDetails] Provider * specific settings * * @param {string} * failoverInput.properties.providerSpecificDetails.instanceType Polymorphic * Discriminator * * @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 {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ testFailover(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.TestFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; testFailover(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.TestFailoverInput, callback: ServiceCallback<models.ReplicationProtectedItem>): void; testFailover(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.TestFailoverInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Execute test failover cleanup. * * Operation to clean up the test failover of a replication protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} cleanupInput Test failover cleanup input. * * @param {object} cleanupInput.properties Test failover cleanup input * properties. * * @param {string} [cleanupInput.properties.comments] Test failover cleanup * comments. * * @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<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ testFailoverCleanupWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, cleanupInput: models.TestFailoverCleanupInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Execute test failover cleanup. * * Operation to clean up the test failover of a replication protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} cleanupInput Test failover cleanup input. * * @param {object} cleanupInput.properties Test failover cleanup input * properties. * * @param {string} [cleanupInput.properties.comments] Test failover cleanup * comments. * * @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 {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ testFailoverCleanup(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, cleanupInput: models.TestFailoverCleanupInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; testFailoverCleanup(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, cleanupInput: models.TestFailoverCleanupInput, callback: ServiceCallback<models.ReplicationProtectedItem>): void; testFailoverCleanup(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, cleanupInput: models.TestFailoverCleanupInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Execute unplanned failover * * Operation to initiate a failover of the replication protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} failoverInput Disable protection input. * * @param {object} [failoverInput.properties] Planned failover input properties * * @param {string} [failoverInput.properties.failoverDirection] Failover * direction. * * @param {string} [failoverInput.properties.sourceSiteOperations] Source site * operations status * * @param {object} [failoverInput.properties.providerSpecificDetails] Provider * specific settings * * @param {string} * failoverInput.properties.providerSpecificDetails.instanceType Polymorphic * Discriminator * * @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<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ unplannedFailoverWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.UnplannedFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Execute unplanned failover * * Operation to initiate a failover of the replication protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} failoverInput Disable protection input. * * @param {object} [failoverInput.properties] Planned failover input properties * * @param {string} [failoverInput.properties.failoverDirection] Failover * direction. * * @param {string} [failoverInput.properties.sourceSiteOperations] Source site * operations status * * @param {object} [failoverInput.properties.providerSpecificDetails] Provider * specific settings * * @param {string} * failoverInput.properties.providerSpecificDetails.instanceType Polymorphic * Discriminator * * @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 {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ unplannedFailover(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.UnplannedFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; unplannedFailover(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.UnplannedFailoverInput, callback: ServiceCallback<models.ReplicationProtectedItem>): void; unplannedFailover(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.UnplannedFailoverInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Update the mobility service on a protected item. * * The operation to update(push update) the installed mobility service software * on a replication protected item to the latest available version. * * @param {string} fabricName The name of the fabric containing the protected * item. * * @param {string} protectionContainerName The name of the container containing * the protected item. * * @param {string} replicationProtectedItemName The name of the protected item * on which the agent is to be updated. * * @param {object} updateMobilityServiceRequest Request to update the mobility * service on the protected item. * * @param {object} [updateMobilityServiceRequest.properties] The properties of * the update mobility service request. * * @param {string} [updateMobilityServiceRequest.properties.runAsAccountId] The * CS run as account Id. * * @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<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateMobilityServiceWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicationProtectedItemName: string, updateMobilityServiceRequest: models.UpdateMobilityServiceRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Update the mobility service on a protected item. * * The operation to update(push update) the installed mobility service software * on a replication protected item to the latest available version. * * @param {string} fabricName The name of the fabric containing the protected * item. * * @param {string} protectionContainerName The name of the container containing * the protected item. * * @param {string} replicationProtectedItemName The name of the protected item * on which the agent is to be updated. * * @param {object} updateMobilityServiceRequest Request to update the mobility * service on the protected item. * * @param {object} [updateMobilityServiceRequest.properties] The properties of * the update mobility service request. * * @param {string} [updateMobilityServiceRequest.properties.runAsAccountId] The * CS run as account Id. * * @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 {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ updateMobilityService(fabricName: string, protectionContainerName: string, replicationProtectedItemName: string, updateMobilityServiceRequest: models.UpdateMobilityServiceRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; updateMobilityService(fabricName: string, protectionContainerName: string, replicationProtectedItemName: string, updateMobilityServiceRequest: models.UpdateMobilityServiceRequest, callback: ServiceCallback<models.ReplicationProtectedItem>): void; updateMobilityService(fabricName: string, protectionContainerName: string, replicationProtectedItemName: string, updateMobilityServiceRequest: models.UpdateMobilityServiceRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Gets the list of replication protected items. * * Gets the list of ASR replication protected items in the vault. * * @param {object} [options] Optional Parameters. * * @param {string} [options.skipToken] The pagination token. Possible values: * "FabricId" or "FabricId_CloudId" or null * * @param {string} [options.filter] OData filter options. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ReplicationProtectedItemCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { skipToken? : string, filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItemCollection>>; /** * @summary Gets the list of replication protected items. * * Gets the list of ASR replication protected items in the vault. * * @param {object} [options] Optional Parameters. * * @param {string} [options.skipToken] The pagination token. Possible values: * "FabricId" or "FabricId_CloudId" or null * * @param {string} [options.filter] OData filter options. * * @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 {ReplicationProtectedItemCollection} - 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. * * {ReplicationProtectedItemCollection} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItemCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { skipToken? : string, filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItemCollection>; list(callback: ServiceCallback<models.ReplicationProtectedItemCollection>): void; list(options: { skipToken? : string, filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItemCollection>): void; /** * @summary Enables protection. * * The operation to create an ASR replication protected item (Enable * replication). * * @param {string} fabricName Name of the fabric. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName A name for the replication * protected item. * * @param {object} input Enable Protection Input. * * @param {object} [input.properties] Enable protection input properties. * * @param {string} [input.properties.policyId] The Policy Id. * * @param {string} [input.properties.protectableItemId] The protectable item * Id. * * @param {object} [input.properties.providerSpecificDetails] The * ReplicationProviderInput. For HyperVReplicaAzure provider, it will be * AzureEnableProtectionInput object. For San provider, it will be * SanEnableProtectionInput object. For HyperVReplicaAzure provider, it can be * null. * * @param {string} input.properties.providerSpecificDetails.instanceType * Polymorphic Discriminator * * @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<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, input: models.EnableProtectionInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Enables protection. * * The operation to create an ASR replication protected item (Enable * replication). * * @param {string} fabricName Name of the fabric. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName A name for the replication * protected item. * * @param {object} input Enable Protection Input. * * @param {object} [input.properties] Enable protection input properties. * * @param {string} [input.properties.policyId] The Policy Id. * * @param {string} [input.properties.protectableItemId] The protectable item * Id. * * @param {object} [input.properties.providerSpecificDetails] The * ReplicationProviderInput. For HyperVReplicaAzure provider, it will be * AzureEnableProtectionInput object. For San provider, it will be * SanEnableProtectionInput object. For HyperVReplicaAzure provider, it can be * null. * * @param {string} input.properties.providerSpecificDetails.instanceType * Polymorphic Discriminator * * @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 {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ beginCreate(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, input: models.EnableProtectionInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; beginCreate(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, input: models.EnableProtectionInput, callback: ServiceCallback<models.ReplicationProtectedItem>): void; beginCreate(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, input: models.EnableProtectionInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Purges protection. * * The operation to delete or purge a replication protected item. This * operation will force delete the replication protected item. Use the remove * operation on replication protected item to perform a clean disable * replication for the item. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginPurgeWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Purges protection. * * The operation to delete or purge a replication protected item. This * operation will force delete the replication protected item. Use the remove * operation on replication protected item to perform a clean disable * replication for the item. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginPurge(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginPurge(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, callback: ServiceCallback<void>): void; beginPurge(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Updates protection. * * The operation to update the recovery settings of an ASR replication * protected item. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} updateProtectionInput Update protection input. * * @param {object} [updateProtectionInput.properties] Update replication * protected item properties. * * @param {string} [updateProtectionInput.properties.recoveryAzureVMName] * Target azure VM name given by the user. * * @param {string} [updateProtectionInput.properties.recoveryAzureVMSize] * Target Azure Vm size. * * @param {string} * [updateProtectionInput.properties.selectedRecoveryAzureNetworkId] Target * Azure Network Id. * * @param {string} [updateProtectionInput.properties.selectedSourceNicId] The * selected source nic Id which will be used as the primary nic during * failover. * * @param {string} [updateProtectionInput.properties.enableRdpOnTargetOption] * The selected option to enable RDP\SSH on target vm after failover. String * value of {SrsDataContract.EnableRDPOnTargetOption} enum. * * @param {array} [updateProtectionInput.properties.vmNics] The list of vm nic * details. * * @param {string} [updateProtectionInput.properties.licenseType] License type. * Possible values include: 'NotSpecified', 'NoLicenseType', 'WindowsServer' * * @param {string} [updateProtectionInput.properties.recoveryAvailabilitySetId] * The target availability set id. * * @param {object} [updateProtectionInput.properties.providerSpecificDetails] * The provider specific input to update replication protected item. * * @param {string} * updateProtectionInput.properties.providerSpecificDetails.instanceType * Polymorphic Discriminator * * @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<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginUpdateWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, updateProtectionInput: models.UpdateReplicationProtectedItemInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Updates protection. * * The operation to update the recovery settings of an ASR replication * protected item. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} updateProtectionInput Update protection input. * * @param {object} [updateProtectionInput.properties] Update replication * protected item properties. * * @param {string} [updateProtectionInput.properties.recoveryAzureVMName] * Target azure VM name given by the user. * * @param {string} [updateProtectionInput.properties.recoveryAzureVMSize] * Target Azure Vm size. * * @param {string} * [updateProtectionInput.properties.selectedRecoveryAzureNetworkId] Target * Azure Network Id. * * @param {string} [updateProtectionInput.properties.selectedSourceNicId] The * selected source nic Id which will be used as the primary nic during * failover. * * @param {string} [updateProtectionInput.properties.enableRdpOnTargetOption] * The selected option to enable RDP\SSH on target vm after failover. String * value of {SrsDataContract.EnableRDPOnTargetOption} enum. * * @param {array} [updateProtectionInput.properties.vmNics] The list of vm nic * details. * * @param {string} [updateProtectionInput.properties.licenseType] License type. * Possible values include: 'NotSpecified', 'NoLicenseType', 'WindowsServer' * * @param {string} [updateProtectionInput.properties.recoveryAvailabilitySetId] * The target availability set id. * * @param {object} [updateProtectionInput.properties.providerSpecificDetails] * The provider specific input to update replication protected item. * * @param {string} * updateProtectionInput.properties.providerSpecificDetails.instanceType * Polymorphic Discriminator * * @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 {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ beginUpdate(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, updateProtectionInput: models.UpdateReplicationProtectedItemInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; beginUpdate(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, updateProtectionInput: models.UpdateReplicationProtectedItemInput, callback: ServiceCallback<models.ReplicationProtectedItem>): void; beginUpdate(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, updateProtectionInput: models.UpdateReplicationProtectedItemInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Change or apply recovery point. * * The operation to change the recovery point of a failed over replication * protected item. * * @param {string} fabricName The ARM fabric name. * * @param {string} protectionContainerName The protection container name. * * @param {string} replicatedProtectedItemName The replicated protected item's * name. * * @param {object} applyRecoveryPointInput The ApplyRecoveryPointInput. * * @param {object} [applyRecoveryPointInput.properties] The input properties to * apply recovery point. * * @param {string} [applyRecoveryPointInput.properties.recoveryPointId] The * recovery point Id. * * @param {object} [applyRecoveryPointInput.properties.providerSpecificDetails] * Provider specific input for applying recovery point. * * @param {string} * applyRecoveryPointInput.properties.providerSpecificDetails.instanceType * Polymorphic Discriminator * * @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<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginApplyRecoveryPointWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, applyRecoveryPointInput: models.ApplyRecoveryPointInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Change or apply recovery point. * * The operation to change the recovery point of a failed over replication * protected item. * * @param {string} fabricName The ARM fabric name. * * @param {string} protectionContainerName The protection container name. * * @param {string} replicatedProtectedItemName The replicated protected item's * name. * * @param {object} applyRecoveryPointInput The ApplyRecoveryPointInput. * * @param {object} [applyRecoveryPointInput.properties] The input properties to * apply recovery point. * * @param {string} [applyRecoveryPointInput.properties.recoveryPointId] The * recovery point Id. * * @param {object} [applyRecoveryPointInput.properties.providerSpecificDetails] * Provider specific input for applying recovery point. * * @param {string} * applyRecoveryPointInput.properties.providerSpecificDetails.instanceType * Polymorphic Discriminator * * @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 {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ beginApplyRecoveryPoint(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, applyRecoveryPointInput: models.ApplyRecoveryPointInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; beginApplyRecoveryPoint(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, applyRecoveryPointInput: models.ApplyRecoveryPointInput, callback: ServiceCallback<models.ReplicationProtectedItem>): void; beginApplyRecoveryPoint(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, applyRecoveryPointInput: models.ApplyRecoveryPointInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Execute commit failover * * Operation to commit the failover of the replication protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginFailoverCommitWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Execute commit failover * * Operation to commit the failover of the replication protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ beginFailoverCommit(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; beginFailoverCommit(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, callback: ServiceCallback<models.ReplicationProtectedItem>): void; beginFailoverCommit(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Execute planned failover * * Operation to initiate a planned failover of the replication protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} failoverInput Disable protection input. * * @param {object} [failoverInput.properties] Planned failover input properties * * @param {string} [failoverInput.properties.failoverDirection] Failover * direction. * * @param {object} [failoverInput.properties.providerSpecificDetails] Provider * specific settings * * @param {string} * failoverInput.properties.providerSpecificDetails.instanceType Polymorphic * Discriminator * * @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<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginPlannedFailoverWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.PlannedFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Execute planned failover * * Operation to initiate a planned failover of the replication protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} failoverInput Disable protection input. * * @param {object} [failoverInput.properties] Planned failover input properties * * @param {string} [failoverInput.properties.failoverDirection] Failover * direction. * * @param {object} [failoverInput.properties.providerSpecificDetails] Provider * specific settings * * @param {string} * failoverInput.properties.providerSpecificDetails.instanceType Polymorphic * Discriminator * * @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 {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ beginPlannedFailover(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.PlannedFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; beginPlannedFailover(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.PlannedFailoverInput, callback: ServiceCallback<models.ReplicationProtectedItem>): void; beginPlannedFailover(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.PlannedFailoverInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Disables protection. * * The operation to disable replication on a replication protected item. This * will also remove the item. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} disableProtectionInput Disable protection input. * * @param {object} [disableProtectionInput.properties] Disable protection input * properties. * * @param {string} [disableProtectionInput.properties.disableProtectionReason] * Disable protection reason. It can have values * NotSpecified/MigrationComplete. Possible values include: 'NotSpecified', * 'MigrationComplete' * * @param {object} [disableProtectionInput.properties.replicationProviderInput] * Replication provider specific input. * * @param {string} * disableProtectionInput.properties.replicationProviderInput.instanceType * Polymorphic Discriminator * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, disableProtectionInput: models.DisableProtectionInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Disables protection. * * The operation to disable replication on a replication protected item. This * will also remove the item. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} disableProtectionInput Disable protection input. * * @param {object} [disableProtectionInput.properties] Disable protection input * properties. * * @param {string} [disableProtectionInput.properties.disableProtectionReason] * Disable protection reason. It can have values * NotSpecified/MigrationComplete. Possible values include: 'NotSpecified', * 'MigrationComplete' * * @param {object} [disableProtectionInput.properties.replicationProviderInput] * Replication provider specific input. * * @param {string} * disableProtectionInput.properties.replicationProviderInput.instanceType * Polymorphic Discriminator * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, disableProtectionInput: models.DisableProtectionInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, disableProtectionInput: models.DisableProtectionInput, callback: ServiceCallback<void>): void; beginDeleteMethod(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, disableProtectionInput: models.DisableProtectionInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Resynchronize or repair replication. * * The operation to start resynchronize/repair replication for a replication * protected item requiring resynchronization. * * @param {string} fabricName The name of the fabric. * * @param {string} protectionContainerName The name of the container. * * @param {string} replicatedProtectedItemName The name of the replication * protected item. * * @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<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginRepairReplicationWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Resynchronize or repair replication. * * The operation to start resynchronize/repair replication for a replication * protected item requiring resynchronization. * * @param {string} fabricName The name of the fabric. * * @param {string} protectionContainerName The name of the container. * * @param {string} replicatedProtectedItemName The name of the replication * protected item. * * @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 {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ beginRepairReplication(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; beginRepairReplication(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, callback: ServiceCallback<models.ReplicationProtectedItem>): void; beginRepairReplication(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Execute Reverse Replication\Reprotect * * Operation to reprotect or reverse replicate a failed over replication * protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} rrInput Disable protection input. * * @param {object} [rrInput.properties] Reverse replication properties * * @param {string} [rrInput.properties.failoverDirection] Failover direction. * * @param {object} [rrInput.properties.providerSpecificDetails] Provider * specific reverse replication input. * * @param {string} rrInput.properties.providerSpecificDetails.instanceType * Polymorphic Discriminator * * @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<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginReprotectWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, rrInput: models.ReverseReplicationInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Execute Reverse Replication\Reprotect * * Operation to reprotect or reverse replicate a failed over replication * protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} rrInput Disable protection input. * * @param {object} [rrInput.properties] Reverse replication properties * * @param {string} [rrInput.properties.failoverDirection] Failover direction. * * @param {object} [rrInput.properties.providerSpecificDetails] Provider * specific reverse replication input. * * @param {string} rrInput.properties.providerSpecificDetails.instanceType * Polymorphic Discriminator * * @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 {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ beginReprotect(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, rrInput: models.ReverseReplicationInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; beginReprotect(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, rrInput: models.ReverseReplicationInput, callback: ServiceCallback<models.ReplicationProtectedItem>): void; beginReprotect(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, rrInput: models.ReverseReplicationInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Execute test failover * * Operation to perform a test failover of the replication protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} failoverInput Test failover input. * * @param {object} [failoverInput.properties] Planned failover input properties * * @param {string} [failoverInput.properties.failoverDirection] Failover * direction. * * @param {string} [failoverInput.properties.networkType] Network type to be * used for test failover. * * @param {string} [failoverInput.properties.networkId] The id of the network * to be used for test failover * * @param {string} [failoverInput.properties.skipTestFailoverCleanup] A value * indicating whether the test failover cleanup is to be skipped. * * @param {object} [failoverInput.properties.providerSpecificDetails] Provider * specific settings * * @param {string} * failoverInput.properties.providerSpecificDetails.instanceType Polymorphic * Discriminator * * @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<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginTestFailoverWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.TestFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Execute test failover * * Operation to perform a test failover of the replication protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} failoverInput Test failover input. * * @param {object} [failoverInput.properties] Planned failover input properties * * @param {string} [failoverInput.properties.failoverDirection] Failover * direction. * * @param {string} [failoverInput.properties.networkType] Network type to be * used for test failover. * * @param {string} [failoverInput.properties.networkId] The id of the network * to be used for test failover * * @param {string} [failoverInput.properties.skipTestFailoverCleanup] A value * indicating whether the test failover cleanup is to be skipped. * * @param {object} [failoverInput.properties.providerSpecificDetails] Provider * specific settings * * @param {string} * failoverInput.properties.providerSpecificDetails.instanceType Polymorphic * Discriminator * * @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 {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ beginTestFailover(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.TestFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; beginTestFailover(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.TestFailoverInput, callback: ServiceCallback<models.ReplicationProtectedItem>): void; beginTestFailover(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.TestFailoverInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Execute test failover cleanup. * * Operation to clean up the test failover of a replication protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} cleanupInput Test failover cleanup input. * * @param {object} cleanupInput.properties Test failover cleanup input * properties. * * @param {string} [cleanupInput.properties.comments] Test failover cleanup * comments. * * @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<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginTestFailoverCleanupWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, cleanupInput: models.TestFailoverCleanupInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Execute test failover cleanup. * * Operation to clean up the test failover of a replication protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} cleanupInput Test failover cleanup input. * * @param {object} cleanupInput.properties Test failover cleanup input * properties. * * @param {string} [cleanupInput.properties.comments] Test failover cleanup * comments. * * @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 {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ beginTestFailoverCleanup(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, cleanupInput: models.TestFailoverCleanupInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; beginTestFailoverCleanup(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, cleanupInput: models.TestFailoverCleanupInput, callback: ServiceCallback<models.ReplicationProtectedItem>): void; beginTestFailoverCleanup(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, cleanupInput: models.TestFailoverCleanupInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Execute unplanned failover * * Operation to initiate a failover of the replication protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} failoverInput Disable protection input. * * @param {object} [failoverInput.properties] Planned failover input properties * * @param {string} [failoverInput.properties.failoverDirection] Failover * direction. * * @param {string} [failoverInput.properties.sourceSiteOperations] Source site * operations status * * @param {object} [failoverInput.properties.providerSpecificDetails] Provider * specific settings * * @param {string} * failoverInput.properties.providerSpecificDetails.instanceType Polymorphic * Discriminator * * @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<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginUnplannedFailoverWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.UnplannedFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Execute unplanned failover * * Operation to initiate a failover of the replication protected item. * * @param {string} fabricName Unique fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} failoverInput Disable protection input. * * @param {object} [failoverInput.properties] Planned failover input properties * * @param {string} [failoverInput.properties.failoverDirection] Failover * direction. * * @param {string} [failoverInput.properties.sourceSiteOperations] Source site * operations status * * @param {object} [failoverInput.properties.providerSpecificDetails] Provider * specific settings * * @param {string} * failoverInput.properties.providerSpecificDetails.instanceType Polymorphic * Discriminator * * @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 {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ beginUnplannedFailover(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.UnplannedFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; beginUnplannedFailover(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.UnplannedFailoverInput, callback: ServiceCallback<models.ReplicationProtectedItem>): void; beginUnplannedFailover(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, failoverInput: models.UnplannedFailoverInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Update the mobility service on a protected item. * * The operation to update(push update) the installed mobility service software * on a replication protected item to the latest available version. * * @param {string} fabricName The name of the fabric containing the protected * item. * * @param {string} protectionContainerName The name of the container containing * the protected item. * * @param {string} replicationProtectedItemName The name of the protected item * on which the agent is to be updated. * * @param {object} updateMobilityServiceRequest Request to update the mobility * service on the protected item. * * @param {object} [updateMobilityServiceRequest.properties] The properties of * the update mobility service request. * * @param {string} [updateMobilityServiceRequest.properties.runAsAccountId] The * CS run as account Id. * * @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<ReplicationProtectedItem>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginUpdateMobilityServiceWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicationProtectedItemName: string, updateMobilityServiceRequest: models.UpdateMobilityServiceRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItem>>; /** * @summary Update the mobility service on a protected item. * * The operation to update(push update) the installed mobility service software * on a replication protected item to the latest available version. * * @param {string} fabricName The name of the fabric containing the protected * item. * * @param {string} protectionContainerName The name of the container containing * the protected item. * * @param {string} replicationProtectedItemName The name of the protected item * on which the agent is to be updated. * * @param {object} updateMobilityServiceRequest Request to update the mobility * service on the protected item. * * @param {object} [updateMobilityServiceRequest.properties] The properties of * the update mobility service request. * * @param {string} [updateMobilityServiceRequest.properties.runAsAccountId] The * CS run as account Id. * * @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 {ReplicationProtectedItem} - 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. * * {ReplicationProtectedItem} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItem} 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. */ beginUpdateMobilityService(fabricName: string, protectionContainerName: string, replicationProtectedItemName: string, updateMobilityServiceRequest: models.UpdateMobilityServiceRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItem>; beginUpdateMobilityService(fabricName: string, protectionContainerName: string, replicationProtectedItemName: string, updateMobilityServiceRequest: models.UpdateMobilityServiceRequest, callback: ServiceCallback<models.ReplicationProtectedItem>): void; beginUpdateMobilityService(fabricName: string, protectionContainerName: string, replicationProtectedItemName: string, updateMobilityServiceRequest: models.UpdateMobilityServiceRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItem>): void; /** * @summary Gets the list of Replication protected items. * * Gets the list of ASR replication protected items in the protection * container. * * @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<ReplicationProtectedItemCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationProtectionContainersNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItemCollection>>; /** * @summary Gets the list of Replication protected items. * * Gets the list of ASR replication protected items in the protection * container. * * @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 {ReplicationProtectedItemCollection} - 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. * * {ReplicationProtectedItemCollection} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItemCollection} 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. */ listByReplicationProtectionContainersNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItemCollection>; listByReplicationProtectionContainersNext(nextPageLink: string, callback: ServiceCallback<models.ReplicationProtectedItemCollection>): void; listByReplicationProtectionContainersNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItemCollection>): void; /** * @summary Gets the list of replication protected items. * * Gets the list of ASR replication protected items in the vault. * * @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<ReplicationProtectedItemCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReplicationProtectedItemCollection>>; /** * @summary Gets the list of replication protected items. * * Gets the list of ASR replication protected items in the vault. * * @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 {ReplicationProtectedItemCollection} - 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. * * {ReplicationProtectedItemCollection} [result] - The deserialized result object if an error did not occur. * See {@link ReplicationProtectedItemCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReplicationProtectedItemCollection>; listNext(nextPageLink: string, callback: ServiceCallback<models.ReplicationProtectedItemCollection>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReplicationProtectedItemCollection>): void; } /** * @class * RecoveryPoints * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface RecoveryPoints { /** * @summary Get recovery points for a replication protected item. * * Lists the available recovery points for a replication protected item. * * @param {string} fabricName The fabric name. * * @param {string} protectionContainerName The protection container name. * * @param {string} replicatedProtectedItemName The replication protected item's * name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RecoveryPointCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationProtectedItemsWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPointCollection>>; /** * @summary Get recovery points for a replication protected item. * * Lists the available recovery points for a replication protected item. * * @param {string} fabricName The fabric name. * * @param {string} protectionContainerName The protection container name. * * @param {string} replicatedProtectedItemName The replication protected item's * name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RecoveryPointCollection} - 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. * * {RecoveryPointCollection} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPointCollection} 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. */ listByReplicationProtectedItems(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPointCollection>; listByReplicationProtectedItems(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, callback: ServiceCallback<models.RecoveryPointCollection>): void; listByReplicationProtectedItems(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPointCollection>): void; /** * @summary Get a recovery point. * * Get the details of specified recovery point. * * @param {string} fabricName The fabric name. * * @param {string} protectionContainerName The protection container name. * * @param {string} replicatedProtectedItemName The replication protected item's * name. * * @param {string} recoveryPointName The recovery point name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RecoveryPoint>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, recoveryPointName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPoint>>; /** * @summary Get a recovery point. * * Get the details of specified recovery point. * * @param {string} fabricName The fabric name. * * @param {string} protectionContainerName The protection container name. * * @param {string} replicatedProtectedItemName The replication protected item's * name. * * @param {string} recoveryPointName The recovery point name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RecoveryPoint} - 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. * * {RecoveryPoint} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPoint} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, recoveryPointName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPoint>; get(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, recoveryPointName: string, callback: ServiceCallback<models.RecoveryPoint>): void; get(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, recoveryPointName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPoint>): void; /** * @summary Get recovery points for a replication protected item. * * Lists the available recovery points for a replication protected item. * * @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<RecoveryPointCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationProtectedItemsNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPointCollection>>; /** * @summary Get recovery points for a replication protected item. * * Lists the available recovery points for a replication protected item. * * @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 {RecoveryPointCollection} - 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. * * {RecoveryPointCollection} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPointCollection} 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. */ listByReplicationProtectedItemsNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPointCollection>; listByReplicationProtectedItemsNext(nextPageLink: string, callback: ServiceCallback<models.RecoveryPointCollection>): void; listByReplicationProtectedItemsNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPointCollection>): void; } /** * @class * TargetComputeSizes * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface TargetComputeSizes { /** * @summary Gets the list of target compute sizes for the replication protected * item. * * Lists the available target compute sizes for a replication protected item. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<TargetComputeSizeCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationProtectedItemsWithHttpOperationResponse(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TargetComputeSizeCollection>>; /** * @summary Gets the list of target compute sizes for the replication protected * item. * * Lists the available target compute sizes for a replication protected item. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName protection container name. * * @param {string} replicatedProtectedItemName Replication protected item name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {TargetComputeSizeCollection} - 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. * * {TargetComputeSizeCollection} [result] - The deserialized result object if an error did not occur. * See {@link TargetComputeSizeCollection} 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. */ listByReplicationProtectedItems(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TargetComputeSizeCollection>; listByReplicationProtectedItems(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, callback: ServiceCallback<models.TargetComputeSizeCollection>): void; listByReplicationProtectedItems(fabricName: string, protectionContainerName: string, replicatedProtectedItemName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TargetComputeSizeCollection>): void; /** * @summary Gets the list of target compute sizes for the replication protected * item. * * Lists the available target compute sizes for a replication protected item. * * @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<TargetComputeSizeCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationProtectedItemsNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TargetComputeSizeCollection>>; /** * @summary Gets the list of target compute sizes for the replication protected * item. * * Lists the available target compute sizes for a replication protected item. * * @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 {TargetComputeSizeCollection} - 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. * * {TargetComputeSizeCollection} [result] - The deserialized result object if an error did not occur. * See {@link TargetComputeSizeCollection} 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. */ listByReplicationProtectedItemsNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TargetComputeSizeCollection>; listByReplicationProtectedItemsNext(nextPageLink: string, callback: ServiceCallback<models.TargetComputeSizeCollection>): void; listByReplicationProtectedItemsNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TargetComputeSizeCollection>): void; } /** * @class * ReplicationProtectionContainerMappings * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface ReplicationProtectionContainerMappings { /** * @summary Gets the list of protection container mappings for a protection * container. * * Lists the protection container mappings for a protection container. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProtectionContainerMappingCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationProtectionContainersWithHttpOperationResponse(fabricName: string, protectionContainerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectionContainerMappingCollection>>; /** * @summary Gets the list of protection container mappings for a protection * container. * * Lists the protection container mappings for a protection container. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProtectionContainerMappingCollection} - 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. * * {ProtectionContainerMappingCollection} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainerMappingCollection} 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. */ listByReplicationProtectionContainers(fabricName: string, protectionContainerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectionContainerMappingCollection>; listByReplicationProtectionContainers(fabricName: string, protectionContainerName: string, callback: ServiceCallback<models.ProtectionContainerMappingCollection>): void; listByReplicationProtectionContainers(fabricName: string, protectionContainerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectionContainerMappingCollection>): void; /** * @summary Gets a protection container mapping/ * * Gets the details of a protection container mapping. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} mappingName Protection Container mapping name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProtectionContainerMapping>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(fabricName: string, protectionContainerName: string, mappingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectionContainerMapping>>; /** * @summary Gets a protection container mapping/ * * Gets the details of a protection container mapping. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} mappingName Protection Container mapping name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProtectionContainerMapping} - 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. * * {ProtectionContainerMapping} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainerMapping} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(fabricName: string, protectionContainerName: string, mappingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectionContainerMapping>; get(fabricName: string, protectionContainerName: string, mappingName: string, callback: ServiceCallback<models.ProtectionContainerMapping>): void; get(fabricName: string, protectionContainerName: string, mappingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectionContainerMapping>): void; /** * @summary Create protection container mapping. * * The operation to create a protection container mapping. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} mappingName Protection container mapping name. * * @param {object} creationInput Mapping creation input. * * @param {object} [creationInput.properties] Configure protection input * properties. * * @param {string} [creationInput.properties.targetProtectionContainerId] The * target unique protection container name. * * @param {string} [creationInput.properties.policyId] Applicable policy. * * @param {object} [creationInput.properties.providerSpecificInput] Provider * specific input for pairing. * * @param {string} creationInput.properties.providerSpecificInput.instanceType * Polymorphic Discriminator * * @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<ProtectionContainerMapping>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(fabricName: string, protectionContainerName: string, mappingName: string, creationInput: models.CreateProtectionContainerMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectionContainerMapping>>; /** * @summary Create protection container mapping. * * The operation to create a protection container mapping. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} mappingName Protection container mapping name. * * @param {object} creationInput Mapping creation input. * * @param {object} [creationInput.properties] Configure protection input * properties. * * @param {string} [creationInput.properties.targetProtectionContainerId] The * target unique protection container name. * * @param {string} [creationInput.properties.policyId] Applicable policy. * * @param {object} [creationInput.properties.providerSpecificInput] Provider * specific input for pairing. * * @param {string} creationInput.properties.providerSpecificInput.instanceType * Polymorphic Discriminator * * @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 {ProtectionContainerMapping} - 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. * * {ProtectionContainerMapping} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainerMapping} 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. */ create(fabricName: string, protectionContainerName: string, mappingName: string, creationInput: models.CreateProtectionContainerMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectionContainerMapping>; create(fabricName: string, protectionContainerName: string, mappingName: string, creationInput: models.CreateProtectionContainerMappingInput, callback: ServiceCallback<models.ProtectionContainerMapping>): void; create(fabricName: string, protectionContainerName: string, mappingName: string, creationInput: models.CreateProtectionContainerMappingInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectionContainerMapping>): void; /** * @summary Purge protection container mapping. * * The operation to purge(force delete) a protection container mapping * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} mappingName Protection container mapping name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ purgeWithHttpOperationResponse(fabricName: string, protectionContainerName: string, mappingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Purge protection container mapping. * * The operation to purge(force delete) a protection container mapping * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} mappingName Protection container mapping name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ purge(fabricName: string, protectionContainerName: string, mappingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; purge(fabricName: string, protectionContainerName: string, mappingName: string, callback: ServiceCallback<void>): void; purge(fabricName: string, protectionContainerName: string, mappingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Update protection container mapping. * * The operation to update protection container mapping. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} mappingName Protection container mapping name. * * @param {object} updateInput Mapping update input. * * @param {object} [updateInput.properties] Update protection container mapping * input properties. * * @param {object} [updateInput.properties.providerSpecificInput] Provider * specific input for updating protection container mapping. * * @param {string} updateInput.properties.providerSpecificInput.instanceType * Polymorphic Discriminator * * @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<ProtectionContainerMapping>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(fabricName: string, protectionContainerName: string, mappingName: string, updateInput: models.UpdateProtectionContainerMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectionContainerMapping>>; /** * @summary Update protection container mapping. * * The operation to update protection container mapping. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} mappingName Protection container mapping name. * * @param {object} updateInput Mapping update input. * * @param {object} [updateInput.properties] Update protection container mapping * input properties. * * @param {object} [updateInput.properties.providerSpecificInput] Provider * specific input for updating protection container mapping. * * @param {string} updateInput.properties.providerSpecificInput.instanceType * Polymorphic Discriminator * * @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 {ProtectionContainerMapping} - 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. * * {ProtectionContainerMapping} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainerMapping} 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. */ update(fabricName: string, protectionContainerName: string, mappingName: string, updateInput: models.UpdateProtectionContainerMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectionContainerMapping>; update(fabricName: string, protectionContainerName: string, mappingName: string, updateInput: models.UpdateProtectionContainerMappingInput, callback: ServiceCallback<models.ProtectionContainerMapping>): void; update(fabricName: string, protectionContainerName: string, mappingName: string, updateInput: models.UpdateProtectionContainerMappingInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectionContainerMapping>): void; /** * @summary Remove protection container mapping. * * The operation to delete or remove a protection container mapping. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} mappingName Protection container mapping name. * * @param {object} removalInput Removal input. * * @param {object} [removalInput.properties] Configure protection input * properties. * * @param {object} [removalInput.properties.providerSpecificInput] Provider * specific input for unpairing. * * @param {string} [removalInput.properties.providerSpecificInput.instanceType] * The class type. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(fabricName: string, protectionContainerName: string, mappingName: string, removalInput: models.RemoveProtectionContainerMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Remove protection container mapping. * * The operation to delete or remove a protection container mapping. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} mappingName Protection container mapping name. * * @param {object} removalInput Removal input. * * @param {object} [removalInput.properties] Configure protection input * properties. * * @param {object} [removalInput.properties.providerSpecificInput] Provider * specific input for unpairing. * * @param {string} [removalInput.properties.providerSpecificInput.instanceType] * The class type. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(fabricName: string, protectionContainerName: string, mappingName: string, removalInput: models.RemoveProtectionContainerMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(fabricName: string, protectionContainerName: string, mappingName: string, removalInput: models.RemoveProtectionContainerMappingInput, callback: ServiceCallback<void>): void; deleteMethod(fabricName: string, protectionContainerName: string, mappingName: string, removalInput: models.RemoveProtectionContainerMappingInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Gets the list of all protection container mappings in a vault. * * Lists the protection container mappings in the vault. * * @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<ProtectionContainerMappingCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectionContainerMappingCollection>>; /** * @summary Gets the list of all protection container mappings in a vault. * * Lists the protection container mappings in the vault. * * @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 {ProtectionContainerMappingCollection} - 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. * * {ProtectionContainerMappingCollection} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainerMappingCollection} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectionContainerMappingCollection>; list(callback: ServiceCallback<models.ProtectionContainerMappingCollection>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectionContainerMappingCollection>): void; /** * @summary Create protection container mapping. * * The operation to create a protection container mapping. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} mappingName Protection container mapping name. * * @param {object} creationInput Mapping creation input. * * @param {object} [creationInput.properties] Configure protection input * properties. * * @param {string} [creationInput.properties.targetProtectionContainerId] The * target unique protection container name. * * @param {string} [creationInput.properties.policyId] Applicable policy. * * @param {object} [creationInput.properties.providerSpecificInput] Provider * specific input for pairing. * * @param {string} creationInput.properties.providerSpecificInput.instanceType * Polymorphic Discriminator * * @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<ProtectionContainerMapping>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateWithHttpOperationResponse(fabricName: string, protectionContainerName: string, mappingName: string, creationInput: models.CreateProtectionContainerMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectionContainerMapping>>; /** * @summary Create protection container mapping. * * The operation to create a protection container mapping. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} mappingName Protection container mapping name. * * @param {object} creationInput Mapping creation input. * * @param {object} [creationInput.properties] Configure protection input * properties. * * @param {string} [creationInput.properties.targetProtectionContainerId] The * target unique protection container name. * * @param {string} [creationInput.properties.policyId] Applicable policy. * * @param {object} [creationInput.properties.providerSpecificInput] Provider * specific input for pairing. * * @param {string} creationInput.properties.providerSpecificInput.instanceType * Polymorphic Discriminator * * @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 {ProtectionContainerMapping} - 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. * * {ProtectionContainerMapping} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainerMapping} 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. */ beginCreate(fabricName: string, protectionContainerName: string, mappingName: string, creationInput: models.CreateProtectionContainerMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectionContainerMapping>; beginCreate(fabricName: string, protectionContainerName: string, mappingName: string, creationInput: models.CreateProtectionContainerMappingInput, callback: ServiceCallback<models.ProtectionContainerMapping>): void; beginCreate(fabricName: string, protectionContainerName: string, mappingName: string, creationInput: models.CreateProtectionContainerMappingInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectionContainerMapping>): void; /** * @summary Purge protection container mapping. * * The operation to purge(force delete) a protection container mapping * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} mappingName Protection container mapping name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginPurgeWithHttpOperationResponse(fabricName: string, protectionContainerName: string, mappingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Purge protection container mapping. * * The operation to purge(force delete) a protection container mapping * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} mappingName Protection container mapping name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginPurge(fabricName: string, protectionContainerName: string, mappingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginPurge(fabricName: string, protectionContainerName: string, mappingName: string, callback: ServiceCallback<void>): void; beginPurge(fabricName: string, protectionContainerName: string, mappingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Update protection container mapping. * * The operation to update protection container mapping. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} mappingName Protection container mapping name. * * @param {object} updateInput Mapping update input. * * @param {object} [updateInput.properties] Update protection container mapping * input properties. * * @param {object} [updateInput.properties.providerSpecificInput] Provider * specific input for updating protection container mapping. * * @param {string} updateInput.properties.providerSpecificInput.instanceType * Polymorphic Discriminator * * @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<ProtectionContainerMapping>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginUpdateWithHttpOperationResponse(fabricName: string, protectionContainerName: string, mappingName: string, updateInput: models.UpdateProtectionContainerMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectionContainerMapping>>; /** * @summary Update protection container mapping. * * The operation to update protection container mapping. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} mappingName Protection container mapping name. * * @param {object} updateInput Mapping update input. * * @param {object} [updateInput.properties] Update protection container mapping * input properties. * * @param {object} [updateInput.properties.providerSpecificInput] Provider * specific input for updating protection container mapping. * * @param {string} updateInput.properties.providerSpecificInput.instanceType * Polymorphic Discriminator * * @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 {ProtectionContainerMapping} - 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. * * {ProtectionContainerMapping} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainerMapping} 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. */ beginUpdate(fabricName: string, protectionContainerName: string, mappingName: string, updateInput: models.UpdateProtectionContainerMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectionContainerMapping>; beginUpdate(fabricName: string, protectionContainerName: string, mappingName: string, updateInput: models.UpdateProtectionContainerMappingInput, callback: ServiceCallback<models.ProtectionContainerMapping>): void; beginUpdate(fabricName: string, protectionContainerName: string, mappingName: string, updateInput: models.UpdateProtectionContainerMappingInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectionContainerMapping>): void; /** * @summary Remove protection container mapping. * * The operation to delete or remove a protection container mapping. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} mappingName Protection container mapping name. * * @param {object} removalInput Removal input. * * @param {object} [removalInput.properties] Configure protection input * properties. * * @param {object} [removalInput.properties.providerSpecificInput] Provider * specific input for unpairing. * * @param {string} [removalInput.properties.providerSpecificInput.instanceType] * The class type. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(fabricName: string, protectionContainerName: string, mappingName: string, removalInput: models.RemoveProtectionContainerMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Remove protection container mapping. * * The operation to delete or remove a protection container mapping. * * @param {string} fabricName Fabric name. * * @param {string} protectionContainerName Protection container name. * * @param {string} mappingName Protection container mapping name. * * @param {object} removalInput Removal input. * * @param {object} [removalInput.properties] Configure protection input * properties. * * @param {object} [removalInput.properties.providerSpecificInput] Provider * specific input for unpairing. * * @param {string} [removalInput.properties.providerSpecificInput.instanceType] * The class type. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(fabricName: string, protectionContainerName: string, mappingName: string, removalInput: models.RemoveProtectionContainerMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(fabricName: string, protectionContainerName: string, mappingName: string, removalInput: models.RemoveProtectionContainerMappingInput, callback: ServiceCallback<void>): void; beginDeleteMethod(fabricName: string, protectionContainerName: string, mappingName: string, removalInput: models.RemoveProtectionContainerMappingInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Gets the list of protection container mappings for a protection * container. * * Lists the protection container mappings for a protection container. * * @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<ProtectionContainerMappingCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationProtectionContainersNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectionContainerMappingCollection>>; /** * @summary Gets the list of protection container mappings for a protection * container. * * Lists the protection container mappings for a protection container. * * @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 {ProtectionContainerMappingCollection} - 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. * * {ProtectionContainerMappingCollection} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainerMappingCollection} 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. */ listByReplicationProtectionContainersNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectionContainerMappingCollection>; listByReplicationProtectionContainersNext(nextPageLink: string, callback: ServiceCallback<models.ProtectionContainerMappingCollection>): void; listByReplicationProtectionContainersNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectionContainerMappingCollection>): void; /** * @summary Gets the list of all protection container mappings in a vault. * * Lists the protection container mappings in the vault. * * @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<ProtectionContainerMappingCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProtectionContainerMappingCollection>>; /** * @summary Gets the list of all protection container mappings in a vault. * * Lists the protection container mappings in the vault. * * @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 {ProtectionContainerMappingCollection} - 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. * * {ProtectionContainerMappingCollection} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainerMappingCollection} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProtectionContainerMappingCollection>; listNext(nextPageLink: string, callback: ServiceCallback<models.ProtectionContainerMappingCollection>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProtectionContainerMappingCollection>): void; } /** * @class * ReplicationRecoveryServicesProviders * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface ReplicationRecoveryServicesProviders { /** * @summary Gets the list of registered recovery services providers for the * fabric. * * Lists the registered recovery services providers for the specified fabric. * * @param {string} fabricName Fabric name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RecoveryServicesProviderCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationFabricsWithHttpOperationResponse(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryServicesProviderCollection>>; /** * @summary Gets the list of registered recovery services providers for the * fabric. * * Lists the registered recovery services providers for the specified fabric. * * @param {string} fabricName Fabric name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RecoveryServicesProviderCollection} - 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. * * {RecoveryServicesProviderCollection} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryServicesProviderCollection} 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. */ listByReplicationFabrics(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryServicesProviderCollection>; listByReplicationFabrics(fabricName: string, callback: ServiceCallback<models.RecoveryServicesProviderCollection>): void; listByReplicationFabrics(fabricName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryServicesProviderCollection>): void; /** * @summary Gets the details of a recovery services provider. * * Gets the details of registered recovery services provider. * * @param {string} fabricName Fabric name. * * @param {string} providerName Recovery services provider name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RecoveryServicesProvider>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(fabricName: string, providerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryServicesProvider>>; /** * @summary Gets the details of a recovery services provider. * * Gets the details of registered recovery services provider. * * @param {string} fabricName Fabric name. * * @param {string} providerName Recovery services provider name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RecoveryServicesProvider} - 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. * * {RecoveryServicesProvider} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryServicesProvider} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(fabricName: string, providerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryServicesProvider>; get(fabricName: string, providerName: string, callback: ServiceCallback<models.RecoveryServicesProvider>): void; get(fabricName: string, providerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryServicesProvider>): void; /** * @summary Purges recovery service provider from fabric * * The operation to purge(force delete) a recovery services provider from the * vault. * * @param {string} fabricName Fabric name. * * @param {string} providerName Recovery services provider name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ purgeWithHttpOperationResponse(fabricName: string, providerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Purges recovery service provider from fabric * * The operation to purge(force delete) a recovery services provider from the * vault. * * @param {string} fabricName Fabric name. * * @param {string} providerName Recovery services provider name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ purge(fabricName: string, providerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; purge(fabricName: string, providerName: string, callback: ServiceCallback<void>): void; purge(fabricName: string, providerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Refresh details from the recovery services provider. * * The operation to refresh the information from the recovery services * provider. * * @param {string} fabricName Fabric name. * * @param {string} providerName Recovery services provider name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RecoveryServicesProvider>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ refreshProviderWithHttpOperationResponse(fabricName: string, providerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryServicesProvider>>; /** * @summary Refresh details from the recovery services provider. * * The operation to refresh the information from the recovery services * provider. * * @param {string} fabricName Fabric name. * * @param {string} providerName Recovery services provider name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RecoveryServicesProvider} - 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. * * {RecoveryServicesProvider} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryServicesProvider} 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. */ refreshProvider(fabricName: string, providerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryServicesProvider>; refreshProvider(fabricName: string, providerName: string, callback: ServiceCallback<models.RecoveryServicesProvider>): void; refreshProvider(fabricName: string, providerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryServicesProvider>): void; /** * @summary Deletes provider from fabric. Note: Deleting provider for any * fabric other than SingleHost is unsupported. To maintain backward * compatibility for released clients the object "deleteRspInput" is used (if * the object is empty we assume that it is old client and continue the old * behavior). * * The operation to removes/delete(unregister) a recovery services provider * from the vault * * @param {string} fabricName Fabric name. * * @param {string} providerName Recovery services provider name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(fabricName: string, providerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Deletes provider from fabric. Note: Deleting provider for any * fabric other than SingleHost is unsupported. To maintain backward * compatibility for released clients the object "deleteRspInput" is used (if * the object is empty we assume that it is old client and continue the old * behavior). * * The operation to removes/delete(unregister) a recovery services provider * from the vault * * @param {string} fabricName Fabric name. * * @param {string} providerName Recovery services provider name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(fabricName: string, providerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(fabricName: string, providerName: string, callback: ServiceCallback<void>): void; deleteMethod(fabricName: string, providerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Gets the list of registered recovery services providers in the * vault. This is a view only api. * * Lists the registered recovery services providers in the vault * * @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<RecoveryServicesProviderCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryServicesProviderCollection>>; /** * @summary Gets the list of registered recovery services providers in the * vault. This is a view only api. * * Lists the registered recovery services providers in the vault * * @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 {RecoveryServicesProviderCollection} - 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. * * {RecoveryServicesProviderCollection} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryServicesProviderCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryServicesProviderCollection>; list(callback: ServiceCallback<models.RecoveryServicesProviderCollection>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryServicesProviderCollection>): void; /** * @summary Purges recovery service provider from fabric * * The operation to purge(force delete) a recovery services provider from the * vault. * * @param {string} fabricName Fabric name. * * @param {string} providerName Recovery services provider name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginPurgeWithHttpOperationResponse(fabricName: string, providerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Purges recovery service provider from fabric * * The operation to purge(force delete) a recovery services provider from the * vault. * * @param {string} fabricName Fabric name. * * @param {string} providerName Recovery services provider name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginPurge(fabricName: string, providerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginPurge(fabricName: string, providerName: string, callback: ServiceCallback<void>): void; beginPurge(fabricName: string, providerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Refresh details from the recovery services provider. * * The operation to refresh the information from the recovery services * provider. * * @param {string} fabricName Fabric name. * * @param {string} providerName Recovery services provider name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RecoveryServicesProvider>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginRefreshProviderWithHttpOperationResponse(fabricName: string, providerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryServicesProvider>>; /** * @summary Refresh details from the recovery services provider. * * The operation to refresh the information from the recovery services * provider. * * @param {string} fabricName Fabric name. * * @param {string} providerName Recovery services provider name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RecoveryServicesProvider} - 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. * * {RecoveryServicesProvider} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryServicesProvider} 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. */ beginRefreshProvider(fabricName: string, providerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryServicesProvider>; beginRefreshProvider(fabricName: string, providerName: string, callback: ServiceCallback<models.RecoveryServicesProvider>): void; beginRefreshProvider(fabricName: string, providerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryServicesProvider>): void; /** * @summary Deletes provider from fabric. Note: Deleting provider for any * fabric other than SingleHost is unsupported. To maintain backward * compatibility for released clients the object "deleteRspInput" is used (if * the object is empty we assume that it is old client and continue the old * behavior). * * The operation to removes/delete(unregister) a recovery services provider * from the vault * * @param {string} fabricName Fabric name. * * @param {string} providerName Recovery services provider name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(fabricName: string, providerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Deletes provider from fabric. Note: Deleting provider for any * fabric other than SingleHost is unsupported. To maintain backward * compatibility for released clients the object "deleteRspInput" is used (if * the object is empty we assume that it is old client and continue the old * behavior). * * The operation to removes/delete(unregister) a recovery services provider * from the vault * * @param {string} fabricName Fabric name. * * @param {string} providerName Recovery services provider name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(fabricName: string, providerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(fabricName: string, providerName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(fabricName: string, providerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Gets the list of registered recovery services providers for the * fabric. * * Lists the registered recovery services providers for the specified fabric. * * @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<RecoveryServicesProviderCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationFabricsNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryServicesProviderCollection>>; /** * @summary Gets the list of registered recovery services providers for the * fabric. * * Lists the registered recovery services providers for the specified fabric. * * @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 {RecoveryServicesProviderCollection} - 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. * * {RecoveryServicesProviderCollection} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryServicesProviderCollection} 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. */ listByReplicationFabricsNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryServicesProviderCollection>; listByReplicationFabricsNext(nextPageLink: string, callback: ServiceCallback<models.RecoveryServicesProviderCollection>): void; listByReplicationFabricsNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryServicesProviderCollection>): void; /** * @summary Gets the list of registered recovery services providers in the * vault. This is a view only api. * * Lists the registered recovery services providers in the vault * * @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<RecoveryServicesProviderCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryServicesProviderCollection>>; /** * @summary Gets the list of registered recovery services providers in the * vault. This is a view only api. * * Lists the registered recovery services providers in the vault * * @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 {RecoveryServicesProviderCollection} - 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. * * {RecoveryServicesProviderCollection} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryServicesProviderCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryServicesProviderCollection>; listNext(nextPageLink: string, callback: ServiceCallback<models.RecoveryServicesProviderCollection>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryServicesProviderCollection>): void; } /** * @class * ReplicationStorageClassifications * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface ReplicationStorageClassifications { /** * @summary Gets the list of storage classification objects under a fabric. * * Lists the storage classifications available in the specified fabric. * * @param {string} fabricName Site name of interest. * * @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<StorageClassificationCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationFabricsWithHttpOperationResponse(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.StorageClassificationCollection>>; /** * @summary Gets the list of storage classification objects under a fabric. * * Lists the storage classifications available in the specified fabric. * * @param {string} fabricName Site name of interest. * * @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 {StorageClassificationCollection} - 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. * * {StorageClassificationCollection} [result] - The deserialized result object if an error did not occur. * See {@link StorageClassificationCollection} 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. */ listByReplicationFabrics(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.StorageClassificationCollection>; listByReplicationFabrics(fabricName: string, callback: ServiceCallback<models.StorageClassificationCollection>): void; listByReplicationFabrics(fabricName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.StorageClassificationCollection>): void; /** * @summary Gets the details of a storage classification. * * Gets the details of the specified storage classification. * * @param {string} fabricName Fabric name. * * @param {string} storageClassificationName Storage classification name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<StorageClassification>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(fabricName: string, storageClassificationName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.StorageClassification>>; /** * @summary Gets the details of a storage classification. * * Gets the details of the specified storage classification. * * @param {string} fabricName Fabric name. * * @param {string} storageClassificationName Storage classification name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {StorageClassification} - 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. * * {StorageClassification} [result] - The deserialized result object if an error did not occur. * See {@link StorageClassification} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(fabricName: string, storageClassificationName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.StorageClassification>; get(fabricName: string, storageClassificationName: string, callback: ServiceCallback<models.StorageClassification>): void; get(fabricName: string, storageClassificationName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.StorageClassification>): void; /** * @summary Gets the list of storage classification objects under a vault. * * Lists the storage classifications in the vault. * * @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<StorageClassificationCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.StorageClassificationCollection>>; /** * @summary Gets the list of storage classification objects under a vault. * * Lists the storage classifications in the vault. * * @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 {StorageClassificationCollection} - 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. * * {StorageClassificationCollection} [result] - The deserialized result object if an error did not occur. * See {@link StorageClassificationCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.StorageClassificationCollection>; list(callback: ServiceCallback<models.StorageClassificationCollection>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.StorageClassificationCollection>): void; /** * @summary Gets the list of storage classification objects under a fabric. * * Lists the storage classifications available in the specified fabric. * * @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<StorageClassificationCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationFabricsNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.StorageClassificationCollection>>; /** * @summary Gets the list of storage classification objects under a fabric. * * Lists the storage classifications available in the specified fabric. * * @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 {StorageClassificationCollection} - 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. * * {StorageClassificationCollection} [result] - The deserialized result object if an error did not occur. * See {@link StorageClassificationCollection} 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. */ listByReplicationFabricsNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.StorageClassificationCollection>; listByReplicationFabricsNext(nextPageLink: string, callback: ServiceCallback<models.StorageClassificationCollection>): void; listByReplicationFabricsNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.StorageClassificationCollection>): void; /** * @summary Gets the list of storage classification objects under a vault. * * Lists the storage classifications in the vault. * * @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<StorageClassificationCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.StorageClassificationCollection>>; /** * @summary Gets the list of storage classification objects under a vault. * * Lists the storage classifications in the vault. * * @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 {StorageClassificationCollection} - 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. * * {StorageClassificationCollection} [result] - The deserialized result object if an error did not occur. * See {@link StorageClassificationCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.StorageClassificationCollection>; listNext(nextPageLink: string, callback: ServiceCallback<models.StorageClassificationCollection>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.StorageClassificationCollection>): void; } /** * @class * ReplicationStorageClassificationMappings * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface ReplicationStorageClassificationMappings { /** * @summary Gets the list of storage classification mappings objects under a * storage. * * Lists the storage classification mappings for the fabric. * * @param {string} fabricName Fabric name. * * @param {string} storageClassificationName Storage classfication name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<StorageClassificationMappingCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationStorageClassificationsWithHttpOperationResponse(fabricName: string, storageClassificationName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.StorageClassificationMappingCollection>>; /** * @summary Gets the list of storage classification mappings objects under a * storage. * * Lists the storage classification mappings for the fabric. * * @param {string} fabricName Fabric name. * * @param {string} storageClassificationName Storage classfication name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {StorageClassificationMappingCollection} - 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. * * {StorageClassificationMappingCollection} [result] - The deserialized result object if an error did not occur. * See {@link StorageClassificationMappingCollection} 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. */ listByReplicationStorageClassifications(fabricName: string, storageClassificationName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.StorageClassificationMappingCollection>; listByReplicationStorageClassifications(fabricName: string, storageClassificationName: string, callback: ServiceCallback<models.StorageClassificationMappingCollection>): void; listByReplicationStorageClassifications(fabricName: string, storageClassificationName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.StorageClassificationMappingCollection>): void; /** * @summary Gets the details of a storage classification mapping. * * Gets the details of the specified storage classification mapping. * * @param {string} fabricName Fabric name. * * @param {string} storageClassificationName Storage classification name. * * @param {string} storageClassificationMappingName Storage classification * mapping name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<StorageClassificationMapping>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.StorageClassificationMapping>>; /** * @summary Gets the details of a storage classification mapping. * * Gets the details of the specified storage classification mapping. * * @param {string} fabricName Fabric name. * * @param {string} storageClassificationName Storage classification name. * * @param {string} storageClassificationMappingName Storage classification * mapping name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {StorageClassificationMapping} - 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. * * {StorageClassificationMapping} [result] - The deserialized result object if an error did not occur. * See {@link StorageClassificationMapping} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.StorageClassificationMapping>; get(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, callback: ServiceCallback<models.StorageClassificationMapping>): void; get(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.StorageClassificationMapping>): void; /** * @summary Create storage classification mapping. * * The operation to create a storage classification mapping. * * @param {string} fabricName Fabric name. * * @param {string} storageClassificationName Storage classification name. * * @param {string} storageClassificationMappingName Storage classification * mapping name. * * @param {object} pairingInput Pairing input. * * @param {object} [pairingInput.properties] Storage mapping input properties. * * @param {string} [pairingInput.properties.targetStorageClassificationId] The * ID of the storage object. * * @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<StorageClassificationMapping>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, pairingInput: models.StorageClassificationMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.StorageClassificationMapping>>; /** * @summary Create storage classification mapping. * * The operation to create a storage classification mapping. * * @param {string} fabricName Fabric name. * * @param {string} storageClassificationName Storage classification name. * * @param {string} storageClassificationMappingName Storage classification * mapping name. * * @param {object} pairingInput Pairing input. * * @param {object} [pairingInput.properties] Storage mapping input properties. * * @param {string} [pairingInput.properties.targetStorageClassificationId] The * ID of the storage object. * * @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 {StorageClassificationMapping} - 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. * * {StorageClassificationMapping} [result] - The deserialized result object if an error did not occur. * See {@link StorageClassificationMapping} 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. */ create(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, pairingInput: models.StorageClassificationMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.StorageClassificationMapping>; create(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, pairingInput: models.StorageClassificationMappingInput, callback: ServiceCallback<models.StorageClassificationMapping>): void; create(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, pairingInput: models.StorageClassificationMappingInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.StorageClassificationMapping>): void; /** * @summary Delete a storage classification mapping. * * The operation to delete a storage classification mapping. * * @param {string} fabricName Fabric name. * * @param {string} storageClassificationName Storage classification name. * * @param {string} storageClassificationMappingName Storage classification * mapping name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Delete a storage classification mapping. * * The operation to delete a storage classification mapping. * * @param {string} fabricName Fabric name. * * @param {string} storageClassificationName Storage classification name. * * @param {string} storageClassificationMappingName Storage classification * mapping name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, callback: ServiceCallback<void>): void; deleteMethod(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Gets the list of storage classification mappings objects under a * vault. * * Lists the storage classification mappings in the vault. * * @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<StorageClassificationMappingCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.StorageClassificationMappingCollection>>; /** * @summary Gets the list of storage classification mappings objects under a * vault. * * Lists the storage classification mappings in the vault. * * @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 {StorageClassificationMappingCollection} - 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. * * {StorageClassificationMappingCollection} [result] - The deserialized result object if an error did not occur. * See {@link StorageClassificationMappingCollection} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.StorageClassificationMappingCollection>; list(callback: ServiceCallback<models.StorageClassificationMappingCollection>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.StorageClassificationMappingCollection>): void; /** * @summary Create storage classification mapping. * * The operation to create a storage classification mapping. * * @param {string} fabricName Fabric name. * * @param {string} storageClassificationName Storage classification name. * * @param {string} storageClassificationMappingName Storage classification * mapping name. * * @param {object} pairingInput Pairing input. * * @param {object} [pairingInput.properties] Storage mapping input properties. * * @param {string} [pairingInput.properties.targetStorageClassificationId] The * ID of the storage object. * * @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<StorageClassificationMapping>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateWithHttpOperationResponse(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, pairingInput: models.StorageClassificationMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.StorageClassificationMapping>>; /** * @summary Create storage classification mapping. * * The operation to create a storage classification mapping. * * @param {string} fabricName Fabric name. * * @param {string} storageClassificationName Storage classification name. * * @param {string} storageClassificationMappingName Storage classification * mapping name. * * @param {object} pairingInput Pairing input. * * @param {object} [pairingInput.properties] Storage mapping input properties. * * @param {string} [pairingInput.properties.targetStorageClassificationId] The * ID of the storage object. * * @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 {StorageClassificationMapping} - 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. * * {StorageClassificationMapping} [result] - The deserialized result object if an error did not occur. * See {@link StorageClassificationMapping} 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. */ beginCreate(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, pairingInput: models.StorageClassificationMappingInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.StorageClassificationMapping>; beginCreate(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, pairingInput: models.StorageClassificationMappingInput, callback: ServiceCallback<models.StorageClassificationMapping>): void; beginCreate(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, pairingInput: models.StorageClassificationMappingInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.StorageClassificationMapping>): void; /** * @summary Delete a storage classification mapping. * * The operation to delete a storage classification mapping. * * @param {string} fabricName Fabric name. * * @param {string} storageClassificationName Storage classification name. * * @param {string} storageClassificationMappingName Storage classification * mapping name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Delete a storage classification mapping. * * The operation to delete a storage classification mapping. * * @param {string} fabricName Fabric name. * * @param {string} storageClassificationName Storage classification name. * * @param {string} storageClassificationMappingName Storage classification * mapping name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Gets the list of storage classification mappings objects under a * storage. * * Lists the storage classification mappings for the fabric. * * @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<StorageClassificationMappingCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationStorageClassificationsNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.StorageClassificationMappingCollection>>; /** * @summary Gets the list of storage classification mappings objects under a * storage. * * Lists the storage classification mappings for the fabric. * * @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 {StorageClassificationMappingCollection} - 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. * * {StorageClassificationMappingCollection} [result] - The deserialized result object if an error did not occur. * See {@link StorageClassificationMappingCollection} 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. */ listByReplicationStorageClassificationsNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.StorageClassificationMappingCollection>; listByReplicationStorageClassificationsNext(nextPageLink: string, callback: ServiceCallback<models.StorageClassificationMappingCollection>): void; listByReplicationStorageClassificationsNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.StorageClassificationMappingCollection>): void; /** * @summary Gets the list of storage classification mappings objects under a * vault. * * Lists the storage classification mappings in the vault. * * @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<StorageClassificationMappingCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.StorageClassificationMappingCollection>>; /** * @summary Gets the list of storage classification mappings objects under a * vault. * * Lists the storage classification mappings in the vault. * * @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 {StorageClassificationMappingCollection} - 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. * * {StorageClassificationMappingCollection} [result] - The deserialized result object if an error did not occur. * See {@link StorageClassificationMappingCollection} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.StorageClassificationMappingCollection>; listNext(nextPageLink: string, callback: ServiceCallback<models.StorageClassificationMappingCollection>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.StorageClassificationMappingCollection>): void; } /** * @class * ReplicationvCenters * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface ReplicationvCenters { /** * @summary Gets the list of vCenter registered under a fabric. * * Lists the vCenter servers registered in a fabric. * * @param {string} fabricName Fabric name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<VCenterCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationFabricsWithHttpOperationResponse(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VCenterCollection>>; /** * @summary Gets the list of vCenter registered under a fabric. * * Lists the vCenter servers registered in a fabric. * * @param {string} fabricName Fabric name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {VCenterCollection} - 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. * * {VCenterCollection} [result] - The deserialized result object if an error did not occur. * See {@link VCenterCollection} 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. */ listByReplicationFabrics(fabricName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VCenterCollection>; listByReplicationFabrics(fabricName: string, callback: ServiceCallback<models.VCenterCollection>): void; listByReplicationFabrics(fabricName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VCenterCollection>): void; /** * @summary Gets the details of a vCenter. * * Gets the details of a registered vCenter server(Add vCenter server.) * * @param {string} fabricName Fabric name. * * @param {string} vCenterName vCenter name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<VCenter>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(fabricName: string, vCenterName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VCenter>>; /** * @summary Gets the details of a vCenter. * * Gets the details of a registered vCenter server(Add vCenter server.) * * @param {string} fabricName Fabric name. * * @param {string} vCenterName vCenter name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {VCenter} - 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. * * {VCenter} [result] - The deserialized result object if an error did not occur. * See {@link VCenter} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(fabricName: string, vCenterName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VCenter>; get(fabricName: string, vCenterName: string, callback: ServiceCallback<models.VCenter>): void; get(fabricName: string, vCenterName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VCenter>): void; /** * @summary Add vCenter. * * The operation to create a vCenter object.. * * @param {string} fabricName Fabric name. * * @param {string} vCenterName vCenter name. * * @param {object} addVCenterRequest The input to the add vCenter operation. * * @param {object} [addVCenterRequest.properties] The properties of an add * vCenter request. * * @param {string} [addVCenterRequest.properties.friendlyName] The friendly * name of the vCenter. * * @param {string} [addVCenterRequest.properties.ipAddress] The IP address of * the vCenter to be discovered. * * @param {string} [addVCenterRequest.properties.processServerId] The process * server Id from where the discovery is orchestrated. * * @param {string} [addVCenterRequest.properties.port] The port number for * discovery. * * @param {string} [addVCenterRequest.properties.runAsAccountId] The account Id * which has privileges to discover the vCenter. * * @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<VCenter>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(fabricName: string, vCenterName: string, addVCenterRequest: models.AddVCenterRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VCenter>>; /** * @summary Add vCenter. * * The operation to create a vCenter object.. * * @param {string} fabricName Fabric name. * * @param {string} vCenterName vCenter name. * * @param {object} addVCenterRequest The input to the add vCenter operation. * * @param {object} [addVCenterRequest.properties] The properties of an add * vCenter request. * * @param {string} [addVCenterRequest.properties.friendlyName] The friendly * name of the vCenter. * * @param {string} [addVCenterRequest.properties.ipAddress] The IP address of * the vCenter to be discovered. * * @param {string} [addVCenterRequest.properties.processServerId] The process * server Id from where the discovery is orchestrated. * * @param {string} [addVCenterRequest.properties.port] The port number for * discovery. * * @param {string} [addVCenterRequest.properties.runAsAccountId] The account Id * which has privileges to discover the vCenter. * * @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 {VCenter} - 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. * * {VCenter} [result] - The deserialized result object if an error did not occur. * See {@link VCenter} 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. */ create(fabricName: string, vCenterName: string, addVCenterRequest: models.AddVCenterRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VCenter>; create(fabricName: string, vCenterName: string, addVCenterRequest: models.AddVCenterRequest, callback: ServiceCallback<models.VCenter>): void; create(fabricName: string, vCenterName: string, addVCenterRequest: models.AddVCenterRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VCenter>): void; /** * @summary Remove vCenter operation. * * The operation to remove(unregister) a registered vCenter server from the * vault. * * @param {string} fabricName Fabric name. * * @param {string} vCenterName vCenter name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(fabricName: string, vCenterName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Remove vCenter operation. * * The operation to remove(unregister) a registered vCenter server from the * vault. * * @param {string} fabricName Fabric name. * * @param {string} vCenterName vCenter name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(fabricName: string, vCenterName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(fabricName: string, vCenterName: string, callback: ServiceCallback<void>): void; deleteMethod(fabricName: string, vCenterName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Update vCenter operation. * * The operation to update a registered vCenter. * * @param {string} fabricName Fabric name. * * @param {string} vCenterName vCeneter name * * @param {object} updateVCenterRequest The input to the update vCenter * operation. * * @param {object} [updateVCenterRequest.properties] The update VCenter Request * Properties. * * @param {string} [updateVCenterRequest.properties.friendlyName] The friendly * name of the vCenter. * * @param {string} [updateVCenterRequest.properties.ipAddress] The IP address * of the vCenter to be discovered. * * @param {string} [updateVCenterRequest.properties.processServerId] The * process server Id from where the update can be orchestrated. * * @param {string} [updateVCenterRequest.properties.port] The port number for * discovery. * * @param {string} [updateVCenterRequest.properties.runAsAccountId] The CS * account Id which has priviliges to update the vCenter. * * @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<VCenter>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(fabricName: string, vCenterName: string, updateVCenterRequest: models.UpdateVCenterRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VCenter>>; /** * @summary Update vCenter operation. * * The operation to update a registered vCenter. * * @param {string} fabricName Fabric name. * * @param {string} vCenterName vCeneter name * * @param {object} updateVCenterRequest The input to the update vCenter * operation. * * @param {object} [updateVCenterRequest.properties] The update VCenter Request * Properties. * * @param {string} [updateVCenterRequest.properties.friendlyName] The friendly * name of the vCenter. * * @param {string} [updateVCenterRequest.properties.ipAddress] The IP address * of the vCenter to be discovered. * * @param {string} [updateVCenterRequest.properties.processServerId] The * process server Id from where the update can be orchestrated. * * @param {string} [updateVCenterRequest.properties.port] The port number for * discovery. * * @param {string} [updateVCenterRequest.properties.runAsAccountId] The CS * account Id which has priviliges to update the vCenter. * * @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 {VCenter} - 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. * * {VCenter} [result] - The deserialized result object if an error did not occur. * See {@link VCenter} 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. */ update(fabricName: string, vCenterName: string, updateVCenterRequest: models.UpdateVCenterRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VCenter>; update(fabricName: string, vCenterName: string, updateVCenterRequest: models.UpdateVCenterRequest, callback: ServiceCallback<models.VCenter>): void; update(fabricName: string, vCenterName: string, updateVCenterRequest: models.UpdateVCenterRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VCenter>): void; /** * @summary Gets the list of vCenter registered under the vault. * * Lists the vCenter servers registered in the vault. * * @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<VCenterCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VCenterCollection>>; /** * @summary Gets the list of vCenter registered under the vault. * * Lists the vCenter servers registered in the vault. * * @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 {VCenterCollection} - 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. * * {VCenterCollection} [result] - The deserialized result object if an error did not occur. * See {@link VCenterCollection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VCenterCollection>; list(callback: ServiceCallback<models.VCenterCollection>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VCenterCollection>): void; /** * @summary Add vCenter. * * The operation to create a vCenter object.. * * @param {string} fabricName Fabric name. * * @param {string} vCenterName vCenter name. * * @param {object} addVCenterRequest The input to the add vCenter operation. * * @param {object} [addVCenterRequest.properties] The properties of an add * vCenter request. * * @param {string} [addVCenterRequest.properties.friendlyName] The friendly * name of the vCenter. * * @param {string} [addVCenterRequest.properties.ipAddress] The IP address of * the vCenter to be discovered. * * @param {string} [addVCenterRequest.properties.processServerId] The process * server Id from where the discovery is orchestrated. * * @param {string} [addVCenterRequest.properties.port] The port number for * discovery. * * @param {string} [addVCenterRequest.properties.runAsAccountId] The account Id * which has privileges to discover the vCenter. * * @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<VCenter>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateWithHttpOperationResponse(fabricName: string, vCenterName: string, addVCenterRequest: models.AddVCenterRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VCenter>>; /** * @summary Add vCenter. * * The operation to create a vCenter object.. * * @param {string} fabricName Fabric name. * * @param {string} vCenterName vCenter name. * * @param {object} addVCenterRequest The input to the add vCenter operation. * * @param {object} [addVCenterRequest.properties] The properties of an add * vCenter request. * * @param {string} [addVCenterRequest.properties.friendlyName] The friendly * name of the vCenter. * * @param {string} [addVCenterRequest.properties.ipAddress] The IP address of * the vCenter to be discovered. * * @param {string} [addVCenterRequest.properties.processServerId] The process * server Id from where the discovery is orchestrated. * * @param {string} [addVCenterRequest.properties.port] The port number for * discovery. * * @param {string} [addVCenterRequest.properties.runAsAccountId] The account Id * which has privileges to discover the vCenter. * * @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 {VCenter} - 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. * * {VCenter} [result] - The deserialized result object if an error did not occur. * See {@link VCenter} 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. */ beginCreate(fabricName: string, vCenterName: string, addVCenterRequest: models.AddVCenterRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VCenter>; beginCreate(fabricName: string, vCenterName: string, addVCenterRequest: models.AddVCenterRequest, callback: ServiceCallback<models.VCenter>): void; beginCreate(fabricName: string, vCenterName: string, addVCenterRequest: models.AddVCenterRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VCenter>): void; /** * @summary Remove vCenter operation. * * The operation to remove(unregister) a registered vCenter server from the * vault. * * @param {string} fabricName Fabric name. * * @param {string} vCenterName vCenter name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(fabricName: string, vCenterName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Remove vCenter operation. * * The operation to remove(unregister) a registered vCenter server from the * vault. * * @param {string} fabricName Fabric name. * * @param {string} vCenterName vCenter name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(fabricName: string, vCenterName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(fabricName: string, vCenterName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(fabricName: string, vCenterName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Update vCenter operation. * * The operation to update a registered vCenter. * * @param {string} fabricName Fabric name. * * @param {string} vCenterName vCeneter name * * @param {object} updateVCenterRequest The input to the update vCenter * operation. * * @param {object} [updateVCenterRequest.properties] The update VCenter Request * Properties. * * @param {string} [updateVCenterRequest.properties.friendlyName] The friendly * name of the vCenter. * * @param {string} [updateVCenterRequest.properties.ipAddress] The IP address * of the vCenter to be discovered. * * @param {string} [updateVCenterRequest.properties.processServerId] The * process server Id from where the update can be orchestrated. * * @param {string} [updateVCenterRequest.properties.port] The port number for * discovery. * * @param {string} [updateVCenterRequest.properties.runAsAccountId] The CS * account Id which has priviliges to update the vCenter. * * @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<VCenter>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginUpdateWithHttpOperationResponse(fabricName: string, vCenterName: string, updateVCenterRequest: models.UpdateVCenterRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VCenter>>; /** * @summary Update vCenter operation. * * The operation to update a registered vCenter. * * @param {string} fabricName Fabric name. * * @param {string} vCenterName vCeneter name * * @param {object} updateVCenterRequest The input to the update vCenter * operation. * * @param {object} [updateVCenterRequest.properties] The update VCenter Request * Properties. * * @param {string} [updateVCenterRequest.properties.friendlyName] The friendly * name of the vCenter. * * @param {string} [updateVCenterRequest.properties.ipAddress] The IP address * of the vCenter to be discovered. * * @param {string} [updateVCenterRequest.properties.processServerId] The * process server Id from where the update can be orchestrated. * * @param {string} [updateVCenterRequest.properties.port] The port number for * discovery. * * @param {string} [updateVCenterRequest.properties.runAsAccountId] The CS * account Id which has priviliges to update the vCenter. * * @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 {VCenter} - 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. * * {VCenter} [result] - The deserialized result object if an error did not occur. * See {@link VCenter} 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. */ beginUpdate(fabricName: string, vCenterName: string, updateVCenterRequest: models.UpdateVCenterRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VCenter>; beginUpdate(fabricName: string, vCenterName: string, updateVCenterRequest: models.UpdateVCenterRequest, callback: ServiceCallback<models.VCenter>): void; beginUpdate(fabricName: string, vCenterName: string, updateVCenterRequest: models.UpdateVCenterRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VCenter>): void; /** * @summary Gets the list of vCenter registered under a fabric. * * Lists the vCenter servers registered in a fabric. * * @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<VCenterCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReplicationFabricsNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VCenterCollection>>; /** * @summary Gets the list of vCenter registered under a fabric. * * Lists the vCenter servers registered in a fabric. * * @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 {VCenterCollection} - 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. * * {VCenterCollection} [result] - The deserialized result object if an error did not occur. * See {@link VCenterCollection} 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. */ listByReplicationFabricsNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VCenterCollection>; listByReplicationFabricsNext(nextPageLink: string, callback: ServiceCallback<models.VCenterCollection>): void; listByReplicationFabricsNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VCenterCollection>): void; /** * @summary Gets the list of vCenter registered under the vault. * * Lists the vCenter servers registered in the vault. * * @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<VCenterCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VCenterCollection>>; /** * @summary Gets the list of vCenter registered under the vault. * * Lists the vCenter servers registered in the vault. * * @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 {VCenterCollection} - 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. * * {VCenterCollection} [result] - The deserialized result object if an error did not occur. * See {@link VCenterCollection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VCenterCollection>; listNext(nextPageLink: string, callback: ServiceCallback<models.VCenterCollection>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VCenterCollection>): void; } /** * @class * ReplicationJobs * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface ReplicationJobs { /** * @summary Gets the list of jobs. * * Gets the list of Azure Site Recovery Jobs for the vault. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] OData filter options. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<JobCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.JobCollection>>; /** * @summary Gets the list of jobs. * * Gets the list of Azure Site Recovery Jobs for the vault. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] OData filter options. * * @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 {JobCollection} - 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. * * {JobCollection} [result] - The deserialized result object if an error did not occur. * See {@link JobCollection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.JobCollection>; list(callback: ServiceCallback<models.JobCollection>): void; list(options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.JobCollection>): void; /** * @summary Gets the job details. * * Get the details of an Azure Site Recovery job. * * @param {string} jobName Job identifier * * @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<Job>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(jobName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Job>>; /** * @summary Gets the job details. * * Get the details of an Azure Site Recovery job. * * @param {string} jobName Job identifier * * @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 {Job} - 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. * * {Job} [result] - The deserialized result object if an error did not occur. * See {@link Job} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(jobName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Job>; get(jobName: string, callback: ServiceCallback<models.Job>): void; get(jobName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Job>): void; /** * @summary Cancels the specified job. * * The operation to cancel an Azure Site Recovery job. * * @param {string} jobName Job indentifier. * * @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<Job>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ cancelWithHttpOperationResponse(jobName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Job>>; /** * @summary Cancels the specified job. * * The operation to cancel an Azure Site Recovery job. * * @param {string} jobName Job indentifier. * * @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 {Job} - 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. * * {Job} [result] - The deserialized result object if an error did not occur. * See {@link Job} 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. */ cancel(jobName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Job>; cancel(jobName: string, callback: ServiceCallback<models.Job>): void; cancel(jobName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Job>): void; /** * @summary Restarts the specified job. * * The operation to restart an Azure Site Recovery job. * * @param {string} jobName Job identifier. * * @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<Job>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ restartWithHttpOperationResponse(jobName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Job>>; /** * @summary Restarts the specified job. * * The operation to restart an Azure Site Recovery job. * * @param {string} jobName Job identifier. * * @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 {Job} - 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. * * {Job} [result] - The deserialized result object if an error did not occur. * See {@link Job} 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. */ restart(jobName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Job>; restart(jobName: string, callback: ServiceCallback<models.Job>): void; restart(jobName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Job>): void; /** * @summary Resumes the specified job. * * The operation to resume an Azure Site Recovery job * * @param {string} jobName Job identifier. * * @param {object} resumeJobParams Resume rob comments. * * @param {object} [resumeJobParams.properties] Resume job properties. * * @param {string} [resumeJobParams.properties.comments] Resume job comments. * * @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<Job>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ resumeWithHttpOperationResponse(jobName: string, resumeJobParams: models.ResumeJobParams, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Job>>; /** * @summary Resumes the specified job. * * The operation to resume an Azure Site Recovery job * * @param {string} jobName Job identifier. * * @param {object} resumeJobParams Resume rob comments. * * @param {object} [resumeJobParams.properties] Resume job properties. * * @param {string} [resumeJobParams.properties.comments] Resume job comments. * * @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 {Job} - 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. * * {Job} [result] - The deserialized result object if an error did not occur. * See {@link Job} 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. */ resume(jobName: string, resumeJobParams: models.ResumeJobParams, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Job>; resume(jobName: string, resumeJobParams: models.ResumeJobParams, callback: ServiceCallback<models.Job>): void; resume(jobName: string, resumeJobParams: models.ResumeJobParams, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Job>): void; /** * @summary Exports the details of the Azure Site Recovery jobs of the vault. * * The operation to export the details of the Azure Site Recovery jobs of the * vault. * * @param {object} jobQueryParameter job query filter. * * @param {string} [jobQueryParameter.startTime] Date time to get jobs from. * * @param {string} [jobQueryParameter.endTime] Date time to get jobs upto. * * @param {string} [jobQueryParameter.fabricId] The Id of the fabric to search * jobs under. * * @param {string} [jobQueryParameter.affectedObjectTypes] The type of objects. * * @param {string} [jobQueryParameter.jobStatus] The states of the job to be * filtered can be in. * * @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<Job>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ exportMethodWithHttpOperationResponse(jobQueryParameter: models.JobQueryParameter, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Job>>; /** * @summary Exports the details of the Azure Site Recovery jobs of the vault. * * The operation to export the details of the Azure Site Recovery jobs of the * vault. * * @param {object} jobQueryParameter job query filter. * * @param {string} [jobQueryParameter.startTime] Date time to get jobs from. * * @param {string} [jobQueryParameter.endTime] Date time to get jobs upto. * * @param {string} [jobQueryParameter.fabricId] The Id of the fabric to search * jobs under. * * @param {string} [jobQueryParameter.affectedObjectTypes] The type of objects. * * @param {string} [jobQueryParameter.jobStatus] The states of the job to be * filtered can be in. * * @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 {Job} - 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. * * {Job} [result] - The deserialized result object if an error did not occur. * See {@link Job} 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. */ exportMethod(jobQueryParameter: models.JobQueryParameter, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Job>; exportMethod(jobQueryParameter: models.JobQueryParameter, callback: ServiceCallback<models.Job>): void; exportMethod(jobQueryParameter: models.JobQueryParameter, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Job>): void; /** * @summary Cancels the specified job. * * The operation to cancel an Azure Site Recovery job. * * @param {string} jobName Job indentifier. * * @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<Job>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCancelWithHttpOperationResponse(jobName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Job>>; /** * @summary Cancels the specified job. * * The operation to cancel an Azure Site Recovery job. * * @param {string} jobName Job indentifier. * * @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 {Job} - 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. * * {Job} [result] - The deserialized result object if an error did not occur. * See {@link Job} 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. */ beginCancel(jobName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Job>; beginCancel(jobName: string, callback: ServiceCallback<models.Job>): void; beginCancel(jobName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Job>): void; /** * @summary Restarts the specified job. * * The operation to restart an Azure Site Recovery job. * * @param {string} jobName Job identifier. * * @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<Job>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginRestartWithHttpOperationResponse(jobName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Job>>; /** * @summary Restarts the specified job. * * The operation to restart an Azure Site Recovery job. * * @param {string} jobName Job identifier. * * @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 {Job} - 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. * * {Job} [result] - The deserialized result object if an error did not occur. * See {@link Job} 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. */ beginRestart(jobName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Job>; beginRestart(jobName: string, callback: ServiceCallback<models.Job>): void; beginRestart(jobName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Job>): void; /** * @summary Resumes the specified job. * * The operation to resume an Azure Site Recovery job * * @param {string} jobName Job identifier. * * @param {object} resumeJobParams Resume rob comments. * * @param {object} [resumeJobParams.properties] Resume job properties. * * @param {string} [resumeJobParams.properties.comments] Resume job comments. * * @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<Job>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginResumeWithHttpOperationResponse(jobName: string, resumeJobParams: models.ResumeJobParams, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Job>>; /** * @summary Resumes the specified job. * * The operation to resume an Azure Site Recovery job * * @param {string} jobName Job identifier. * * @param {object} resumeJobParams Resume rob comments. * * @param {object} [resumeJobParams.properties] Resume job properties. * * @param {string} [resumeJobParams.properties.comments] Resume job comments. * * @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 {Job} - 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. * * {Job} [result] - The deserialized result object if an error did not occur. * See {@link Job} 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. */ beginResume(jobName: string, resumeJobParams: models.ResumeJobParams, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Job>; beginResume(jobName: string, resumeJobParams: models.ResumeJobParams, callback: ServiceCallback<models.Job>): void; beginResume(jobName: string, resumeJobParams: models.ResumeJobParams, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Job>): void; /** * @summary Exports the details of the Azure Site Recovery jobs of the vault. * * The operation to export the details of the Azure Site Recovery jobs of the * vault. * * @param {object} jobQueryParameter job query filter. * * @param {string} [jobQueryParameter.startTime] Date time to get jobs from. * * @param {string} [jobQueryParameter.endTime] Date time to get jobs upto. * * @param {string} [jobQueryParameter.fabricId] The Id of the fabric to search * jobs under. * * @param {string} [jobQueryParameter.affectedObjectTypes] The type of objects. * * @param {string} [jobQueryParameter.jobStatus] The states of the job to be * filtered can be in. * * @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<Job>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginExportMethodWithHttpOperationResponse(jobQueryParameter: models.JobQueryParameter, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Job>>; /** * @summary Exports the details of the Azure Site Recovery jobs of the vault. * * The operation to export the details of the Azure Site Recovery jobs of the * vault. * * @param {object} jobQueryParameter job query filter. * * @param {string} [jobQueryParameter.startTime] Date time to get jobs from. * * @param {string} [jobQueryParameter.endTime] Date time to get jobs upto. * * @param {string} [jobQueryParameter.fabricId] The Id of the fabric to search * jobs under. * * @param {string} [jobQueryParameter.affectedObjectTypes] The type of objects. * * @param {string} [jobQueryParameter.jobStatus] The states of the job to be * filtered can be in. * * @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 {Job} - 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. * * {Job} [result] - The deserialized result object if an error did not occur. * See {@link Job} 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. */ beginExportMethod(jobQueryParameter: models.JobQueryParameter, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Job>; beginExportMethod(jobQueryParameter: models.JobQueryParameter, callback: ServiceCallback<models.Job>): void; beginExportMethod(jobQueryParameter: models.JobQueryParameter, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Job>): void; /** * @summary Gets the list of jobs. * * Gets the list of Azure Site Recovery Jobs for the vault. * * @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<JobCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.JobCollection>>; /** * @summary Gets the list of jobs. * * Gets the list of Azure Site Recovery Jobs for the vault. * * @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 {JobCollection} - 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. * * {JobCollection} [result] - The deserialized result object if an error did not occur. * See {@link JobCollection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.JobCollection>; listNext(nextPageLink: string, callback: ServiceCallback<models.JobCollection>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.JobCollection>): void; } /** * @class * ReplicationPolicies * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface ReplicationPolicies { /** * @summary Gets the list of replication policies * * Lists the replication policies for a vault. * * @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<PolicyCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PolicyCollection>>; /** * @summary Gets the list of replication policies * * Lists the replication policies for a vault. * * @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 {PolicyCollection} - 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. * * {PolicyCollection} [result] - The deserialized result object if an error did not occur. * See {@link PolicyCollection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PolicyCollection>; list(callback: ServiceCallback<models.PolicyCollection>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PolicyCollection>): void; /** * @summary Gets the requested policy. * * Gets the details of a replication policy. * * @param {string} policyName Replication policy name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Policy>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(policyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Policy>>; /** * @summary Gets the requested policy. * * Gets the details of a replication policy. * * @param {string} policyName Replication policy name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Policy} - 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. * * {Policy} [result] - The deserialized result object if an error did not occur. * See {@link Policy} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(policyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Policy>; get(policyName: string, callback: ServiceCallback<models.Policy>): void; get(policyName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Policy>): void; /** * @summary Creates the policy. * * The operation to create a replication policy * * @param {string} policyName Replication policy name * * @param {object} input Create policy input * * @param {object} [input.properties] Policy creation properties. * * @param {object} [input.properties.providerSpecificInput] The * ReplicationProviderSettings. * * @param {string} input.properties.providerSpecificInput.instanceType * Polymorphic Discriminator * * @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<Policy>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(policyName: string, input: models.CreatePolicyInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Policy>>; /** * @summary Creates the policy. * * The operation to create a replication policy * * @param {string} policyName Replication policy name * * @param {object} input Create policy input * * @param {object} [input.properties] Policy creation properties. * * @param {object} [input.properties.providerSpecificInput] The * ReplicationProviderSettings. * * @param {string} input.properties.providerSpecificInput.instanceType * Polymorphic Discriminator * * @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 {Policy} - 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. * * {Policy} [result] - The deserialized result object if an error did not occur. * See {@link Policy} 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. */ create(policyName: string, input: models.CreatePolicyInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Policy>; create(policyName: string, input: models.CreatePolicyInput, callback: ServiceCallback<models.Policy>): void; create(policyName: string, input: models.CreatePolicyInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Policy>): void; /** * @summary Delete the policy. * * The operation to delete a replication policy. * * @param {string} policyName Replication policy name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(policyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Delete the policy. * * The operation to delete a replication policy. * * @param {string} policyName Replication policy name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(policyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(policyName: string, callback: ServiceCallback<void>): void; deleteMethod(policyName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Updates the policy. * * The operation to update a replication policy. * * @param {string} policyName Policy Id. * * @param {object} input Update Policy Input * * @param {object} [input.properties] The ReplicationProviderSettings. * * @param {object} [input.properties.replicationProviderSettings] The * ReplicationProviderSettings. * * @param {string} input.properties.replicationProviderSettings.instanceType * Polymorphic Discriminator * * @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<Policy>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(policyName: string, input: models.UpdatePolicyInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Policy>>; /** * @summary Updates the policy. * * The operation to update a replication policy. * * @param {string} policyName Policy Id. * * @param {object} input Update Policy Input * * @param {object} [input.properties] The ReplicationProviderSettings. * * @param {object} [input.properties.replicationProviderSettings] The * ReplicationProviderSettings. * * @param {string} input.properties.replicationProviderSettings.instanceType * Polymorphic Discriminator * * @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 {Policy} - 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. * * {Policy} [result] - The deserialized result object if an error did not occur. * See {@link Policy} 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. */ update(policyName: string, input: models.UpdatePolicyInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Policy>; update(policyName: string, input: models.UpdatePolicyInput, callback: ServiceCallback<models.Policy>): void; update(policyName: string, input: models.UpdatePolicyInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Policy>): void; /** * @summary Creates the policy. * * The operation to create a replication policy * * @param {string} policyName Replication policy name * * @param {object} input Create policy input * * @param {object} [input.properties] Policy creation properties. * * @param {object} [input.properties.providerSpecificInput] The * ReplicationProviderSettings. * * @param {string} input.properties.providerSpecificInput.instanceType * Polymorphic Discriminator * * @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<Policy>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateWithHttpOperationResponse(policyName: string, input: models.CreatePolicyInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Policy>>; /** * @summary Creates the policy. * * The operation to create a replication policy * * @param {string} policyName Replication policy name * * @param {object} input Create policy input * * @param {object} [input.properties] Policy creation properties. * * @param {object} [input.properties.providerSpecificInput] The * ReplicationProviderSettings. * * @param {string} input.properties.providerSpecificInput.instanceType * Polymorphic Discriminator * * @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 {Policy} - 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. * * {Policy} [result] - The deserialized result object if an error did not occur. * See {@link Policy} 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. */ beginCreate(policyName: string, input: models.CreatePolicyInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Policy>; beginCreate(policyName: string, input: models.CreatePolicyInput, callback: ServiceCallback<models.Policy>): void; beginCreate(policyName: string, input: models.CreatePolicyInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Policy>): void; /** * @summary Delete the policy. * * The operation to delete a replication policy. * * @param {string} policyName Replication policy name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(policyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Delete the policy. * * The operation to delete a replication policy. * * @param {string} policyName Replication policy name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(policyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(policyName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(policyName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Updates the policy. * * The operation to update a replication policy. * * @param {string} policyName Policy Id. * * @param {object} input Update Policy Input * * @param {object} [input.properties] The ReplicationProviderSettings. * * @param {object} [input.properties.replicationProviderSettings] The * ReplicationProviderSettings. * * @param {string} input.properties.replicationProviderSettings.instanceType * Polymorphic Discriminator * * @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<Policy>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginUpdateWithHttpOperationResponse(policyName: string, input: models.UpdatePolicyInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Policy>>; /** * @summary Updates the policy. * * The operation to update a replication policy. * * @param {string} policyName Policy Id. * * @param {object} input Update Policy Input * * @param {object} [input.properties] The ReplicationProviderSettings. * * @param {object} [input.properties.replicationProviderSettings] The * ReplicationProviderSettings. * * @param {string} input.properties.replicationProviderSettings.instanceType * Polymorphic Discriminator * * @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 {Policy} - 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. * * {Policy} [result] - The deserialized result object if an error did not occur. * See {@link Policy} 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. */ beginUpdate(policyName: string, input: models.UpdatePolicyInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Policy>; beginUpdate(policyName: string, input: models.UpdatePolicyInput, callback: ServiceCallback<models.Policy>): void; beginUpdate(policyName: string, input: models.UpdatePolicyInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Policy>): void; /** * @summary Gets the list of replication policies * * Lists the replication policies for a vault. * * @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<PolicyCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PolicyCollection>>; /** * @summary Gets the list of replication policies * * Lists the replication policies for a vault. * * @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 {PolicyCollection} - 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. * * {PolicyCollection} [result] - The deserialized result object if an error did not occur. * See {@link PolicyCollection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PolicyCollection>; listNext(nextPageLink: string, callback: ServiceCallback<models.PolicyCollection>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PolicyCollection>): void; } /** * @class * ReplicationRecoveryPlans * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface ReplicationRecoveryPlans { /** * @summary Gets the list of recovery plans. * * Lists the recovery plans in the vault. * * @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<RecoveryPlanCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPlanCollection>>; /** * @summary Gets the list of recovery plans. * * Lists the recovery plans in the vault. * * @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 {RecoveryPlanCollection} - 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. * * {RecoveryPlanCollection} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPlanCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPlanCollection>; list(callback: ServiceCallback<models.RecoveryPlanCollection>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPlanCollection>): void; /** * @summary Gets the requested recovery plan. * * Gets the details of the recovery plan. * * @param {string} recoveryPlanName Name of the recovery plan. * * @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<RecoveryPlan>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(recoveryPlanName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPlan>>; /** * @summary Gets the requested recovery plan. * * Gets the details of the recovery plan. * * @param {string} recoveryPlanName Name of the recovery plan. * * @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 {RecoveryPlan} - 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. * * {RecoveryPlan} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPlan} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(recoveryPlanName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPlan>; get(recoveryPlanName: string, callback: ServiceCallback<models.RecoveryPlan>): void; get(recoveryPlanName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPlan>): void; /** * @summary Creates a recovery plan with the given details. * * The operation to create a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Recovery Plan creation input. * * @param {object} input.properties Recovery plan creation properties. * * @param {string} input.properties.primaryFabricId The primary fabric Id. * * @param {string} input.properties.recoveryFabricId The recovery fabric Id. * * @param {string} [input.properties.failoverDeploymentModel] The failover * deployment model. Possible values include: 'NotApplicable', 'Classic', * 'ResourceManager' * * @param {array} input.properties.groups The recovery plan groups. * * @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<RecoveryPlan>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(recoveryPlanName: string, input: models.CreateRecoveryPlanInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPlan>>; /** * @summary Creates a recovery plan with the given details. * * The operation to create a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Recovery Plan creation input. * * @param {object} input.properties Recovery plan creation properties. * * @param {string} input.properties.primaryFabricId The primary fabric Id. * * @param {string} input.properties.recoveryFabricId The recovery fabric Id. * * @param {string} [input.properties.failoverDeploymentModel] The failover * deployment model. Possible values include: 'NotApplicable', 'Classic', * 'ResourceManager' * * @param {array} input.properties.groups The recovery plan groups. * * @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 {RecoveryPlan} - 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. * * {RecoveryPlan} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPlan} 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. */ create(recoveryPlanName: string, input: models.CreateRecoveryPlanInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPlan>; create(recoveryPlanName: string, input: models.CreateRecoveryPlanInput, callback: ServiceCallback<models.RecoveryPlan>): void; create(recoveryPlanName: string, input: models.CreateRecoveryPlanInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPlan>): void; /** * @summary Deletes the specified recovery plan. * * Delete a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(recoveryPlanName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Deletes the specified recovery plan. * * Delete a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(recoveryPlanName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(recoveryPlanName: string, callback: ServiceCallback<void>): void; deleteMethod(recoveryPlanName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Updates the given recovery plan. * * The operation to update a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Update recovery plan input * * @param {object} [input.properties] Recovery plan update properties. * * @param {array} [input.properties.groups] The recovery plan groups. * * @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<RecoveryPlan>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(recoveryPlanName: string, input: models.UpdateRecoveryPlanInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPlan>>; /** * @summary Updates the given recovery plan. * * The operation to update a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Update recovery plan input * * @param {object} [input.properties] Recovery plan update properties. * * @param {array} [input.properties.groups] The recovery plan groups. * * @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 {RecoveryPlan} - 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. * * {RecoveryPlan} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPlan} 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. */ update(recoveryPlanName: string, input: models.UpdateRecoveryPlanInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPlan>; update(recoveryPlanName: string, input: models.UpdateRecoveryPlanInput, callback: ServiceCallback<models.RecoveryPlan>): void; update(recoveryPlanName: string, input: models.UpdateRecoveryPlanInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPlan>): void; /** * @summary Execute commit failover of the recovery plan. * * The operation to commit the fail over of a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RecoveryPlan>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ failoverCommitWithHttpOperationResponse(recoveryPlanName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPlan>>; /** * @summary Execute commit failover of the recovery plan. * * The operation to commit the fail over of a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RecoveryPlan} - 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. * * {RecoveryPlan} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPlan} 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. */ failoverCommit(recoveryPlanName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPlan>; failoverCommit(recoveryPlanName: string, callback: ServiceCallback<models.RecoveryPlan>): void; failoverCommit(recoveryPlanName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPlan>): void; /** * @summary Execute planned failover of the recovery plan. * * The operation to start the planned failover of a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Failover input. * * @param {object} input.properties The recovery plan planned failover input * properties. * * @param {string} input.properties.failoverDirection The failover direction. * Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary' * * @param {array} [input.properties.providerSpecificDetails] The provider * specific properties. * * @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<RecoveryPlan>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ plannedFailoverWithHttpOperationResponse(recoveryPlanName: string, input: models.RecoveryPlanPlannedFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPlan>>; /** * @summary Execute planned failover of the recovery plan. * * The operation to start the planned failover of a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Failover input. * * @param {object} input.properties The recovery plan planned failover input * properties. * * @param {string} input.properties.failoverDirection The failover direction. * Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary' * * @param {array} [input.properties.providerSpecificDetails] The provider * specific properties. * * @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 {RecoveryPlan} - 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. * * {RecoveryPlan} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPlan} 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. */ plannedFailover(recoveryPlanName: string, input: models.RecoveryPlanPlannedFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPlan>; plannedFailover(recoveryPlanName: string, input: models.RecoveryPlanPlannedFailoverInput, callback: ServiceCallback<models.RecoveryPlan>): void; plannedFailover(recoveryPlanName: string, input: models.RecoveryPlanPlannedFailoverInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPlan>): void; /** * @summary Execute reprotect of the recovery plan. * * The operation to reprotect(reverse replicate) a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RecoveryPlan>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ reprotectWithHttpOperationResponse(recoveryPlanName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPlan>>; /** * @summary Execute reprotect of the recovery plan. * * The operation to reprotect(reverse replicate) a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RecoveryPlan} - 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. * * {RecoveryPlan} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPlan} 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. */ reprotect(recoveryPlanName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPlan>; reprotect(recoveryPlanName: string, callback: ServiceCallback<models.RecoveryPlan>): void; reprotect(recoveryPlanName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPlan>): void; /** * @summary Execute test failover of the recovery plan. * * The operation to start the test failover of a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Failover input. * * @param {object} input.properties The recovery plan test failover input * properties. * * @param {string} input.properties.failoverDirection The failover direction. * Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary' * * @param {string} input.properties.networkType The network type to be used for * test failover. * * @param {string} [input.properties.networkId] The Id of the network to be * used for test failover. * * @param {string} [input.properties.skipTestFailoverCleanup] A value * indicating whether the test failover cleanup is to be skipped. * * @param {array} [input.properties.providerSpecificDetails] The provider * specific properties. * * @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<RecoveryPlan>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ testFailoverWithHttpOperationResponse(recoveryPlanName: string, input: models.RecoveryPlanTestFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPlan>>; /** * @summary Execute test failover of the recovery plan. * * The operation to start the test failover of a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Failover input. * * @param {object} input.properties The recovery plan test failover input * properties. * * @param {string} input.properties.failoverDirection The failover direction. * Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary' * * @param {string} input.properties.networkType The network type to be used for * test failover. * * @param {string} [input.properties.networkId] The Id of the network to be * used for test failover. * * @param {string} [input.properties.skipTestFailoverCleanup] A value * indicating whether the test failover cleanup is to be skipped. * * @param {array} [input.properties.providerSpecificDetails] The provider * specific properties. * * @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 {RecoveryPlan} - 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. * * {RecoveryPlan} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPlan} 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. */ testFailover(recoveryPlanName: string, input: models.RecoveryPlanTestFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPlan>; testFailover(recoveryPlanName: string, input: models.RecoveryPlanTestFailoverInput, callback: ServiceCallback<models.RecoveryPlan>): void; testFailover(recoveryPlanName: string, input: models.RecoveryPlanTestFailoverInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPlan>): void; /** * @summary Execute test failover cleanup of the recovery plan. * * The operation to cleanup test failover of a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Test failover cleanup input. * * @param {object} input.properties The recovery plan test failover cleanup * input properties. * * @param {string} [input.properties.comments] The test failover cleanup * comments. * * @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<RecoveryPlan>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ testFailoverCleanupWithHttpOperationResponse(recoveryPlanName: string, input: models.RecoveryPlanTestFailoverCleanupInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPlan>>; /** * @summary Execute test failover cleanup of the recovery plan. * * The operation to cleanup test failover of a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Test failover cleanup input. * * @param {object} input.properties The recovery plan test failover cleanup * input properties. * * @param {string} [input.properties.comments] The test failover cleanup * comments. * * @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 {RecoveryPlan} - 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. * * {RecoveryPlan} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPlan} 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. */ testFailoverCleanup(recoveryPlanName: string, input: models.RecoveryPlanTestFailoverCleanupInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPlan>; testFailoverCleanup(recoveryPlanName: string, input: models.RecoveryPlanTestFailoverCleanupInput, callback: ServiceCallback<models.RecoveryPlan>): void; testFailoverCleanup(recoveryPlanName: string, input: models.RecoveryPlanTestFailoverCleanupInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPlan>): void; /** * @summary Execute unplanned failover of the recovery plan. * * The operation to start the failover of a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Failover input. * * @param {object} input.properties The recovery plan unplanned failover input * properties. * * @param {string} input.properties.failoverDirection The failover direction. * Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary' * * @param {string} input.properties.sourceSiteOperations A value indicating * whether source site operations are required. Possible values include: * 'Required', 'NotRequired' * * @param {array} [input.properties.providerSpecificDetails] The provider * specific properties. * * @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<RecoveryPlan>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ unplannedFailoverWithHttpOperationResponse(recoveryPlanName: string, input: models.RecoveryPlanUnplannedFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPlan>>; /** * @summary Execute unplanned failover of the recovery plan. * * The operation to start the failover of a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Failover input. * * @param {object} input.properties The recovery plan unplanned failover input * properties. * * @param {string} input.properties.failoverDirection The failover direction. * Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary' * * @param {string} input.properties.sourceSiteOperations A value indicating * whether source site operations are required. Possible values include: * 'Required', 'NotRequired' * * @param {array} [input.properties.providerSpecificDetails] The provider * specific properties. * * @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 {RecoveryPlan} - 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. * * {RecoveryPlan} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPlan} 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. */ unplannedFailover(recoveryPlanName: string, input: models.RecoveryPlanUnplannedFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPlan>; unplannedFailover(recoveryPlanName: string, input: models.RecoveryPlanUnplannedFailoverInput, callback: ServiceCallback<models.RecoveryPlan>): void; unplannedFailover(recoveryPlanName: string, input: models.RecoveryPlanUnplannedFailoverInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPlan>): void; /** * @summary Creates a recovery plan with the given details. * * The operation to create a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Recovery Plan creation input. * * @param {object} input.properties Recovery plan creation properties. * * @param {string} input.properties.primaryFabricId The primary fabric Id. * * @param {string} input.properties.recoveryFabricId The recovery fabric Id. * * @param {string} [input.properties.failoverDeploymentModel] The failover * deployment model. Possible values include: 'NotApplicable', 'Classic', * 'ResourceManager' * * @param {array} input.properties.groups The recovery plan groups. * * @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<RecoveryPlan>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateWithHttpOperationResponse(recoveryPlanName: string, input: models.CreateRecoveryPlanInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPlan>>; /** * @summary Creates a recovery plan with the given details. * * The operation to create a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Recovery Plan creation input. * * @param {object} input.properties Recovery plan creation properties. * * @param {string} input.properties.primaryFabricId The primary fabric Id. * * @param {string} input.properties.recoveryFabricId The recovery fabric Id. * * @param {string} [input.properties.failoverDeploymentModel] The failover * deployment model. Possible values include: 'NotApplicable', 'Classic', * 'ResourceManager' * * @param {array} input.properties.groups The recovery plan groups. * * @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 {RecoveryPlan} - 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. * * {RecoveryPlan} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPlan} 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. */ beginCreate(recoveryPlanName: string, input: models.CreateRecoveryPlanInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPlan>; beginCreate(recoveryPlanName: string, input: models.CreateRecoveryPlanInput, callback: ServiceCallback<models.RecoveryPlan>): void; beginCreate(recoveryPlanName: string, input: models.CreateRecoveryPlanInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPlan>): void; /** * @summary Deletes the specified recovery plan. * * Delete a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(recoveryPlanName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Deletes the specified recovery plan. * * Delete a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(recoveryPlanName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(recoveryPlanName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(recoveryPlanName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Updates the given recovery plan. * * The operation to update a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Update recovery plan input * * @param {object} [input.properties] Recovery plan update properties. * * @param {array} [input.properties.groups] The recovery plan groups. * * @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<RecoveryPlan>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginUpdateWithHttpOperationResponse(recoveryPlanName: string, input: models.UpdateRecoveryPlanInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPlan>>; /** * @summary Updates the given recovery plan. * * The operation to update a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Update recovery plan input * * @param {object} [input.properties] Recovery plan update properties. * * @param {array} [input.properties.groups] The recovery plan groups. * * @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 {RecoveryPlan} - 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. * * {RecoveryPlan} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPlan} 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. */ beginUpdate(recoveryPlanName: string, input: models.UpdateRecoveryPlanInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPlan>; beginUpdate(recoveryPlanName: string, input: models.UpdateRecoveryPlanInput, callback: ServiceCallback<models.RecoveryPlan>): void; beginUpdate(recoveryPlanName: string, input: models.UpdateRecoveryPlanInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPlan>): void; /** * @summary Execute commit failover of the recovery plan. * * The operation to commit the fail over of a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RecoveryPlan>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginFailoverCommitWithHttpOperationResponse(recoveryPlanName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPlan>>; /** * @summary Execute commit failover of the recovery plan. * * The operation to commit the fail over of a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RecoveryPlan} - 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. * * {RecoveryPlan} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPlan} 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. */ beginFailoverCommit(recoveryPlanName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPlan>; beginFailoverCommit(recoveryPlanName: string, callback: ServiceCallback<models.RecoveryPlan>): void; beginFailoverCommit(recoveryPlanName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPlan>): void; /** * @summary Execute planned failover of the recovery plan. * * The operation to start the planned failover of a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Failover input. * * @param {object} input.properties The recovery plan planned failover input * properties. * * @param {string} input.properties.failoverDirection The failover direction. * Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary' * * @param {array} [input.properties.providerSpecificDetails] The provider * specific properties. * * @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<RecoveryPlan>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginPlannedFailoverWithHttpOperationResponse(recoveryPlanName: string, input: models.RecoveryPlanPlannedFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPlan>>; /** * @summary Execute planned failover of the recovery plan. * * The operation to start the planned failover of a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Failover input. * * @param {object} input.properties The recovery plan planned failover input * properties. * * @param {string} input.properties.failoverDirection The failover direction. * Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary' * * @param {array} [input.properties.providerSpecificDetails] The provider * specific properties. * * @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 {RecoveryPlan} - 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. * * {RecoveryPlan} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPlan} 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. */ beginPlannedFailover(recoveryPlanName: string, input: models.RecoveryPlanPlannedFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPlan>; beginPlannedFailover(recoveryPlanName: string, input: models.RecoveryPlanPlannedFailoverInput, callback: ServiceCallback<models.RecoveryPlan>): void; beginPlannedFailover(recoveryPlanName: string, input: models.RecoveryPlanPlannedFailoverInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPlan>): void; /** * @summary Execute reprotect of the recovery plan. * * The operation to reprotect(reverse replicate) a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RecoveryPlan>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginReprotectWithHttpOperationResponse(recoveryPlanName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPlan>>; /** * @summary Execute reprotect of the recovery plan. * * The operation to reprotect(reverse replicate) a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RecoveryPlan} - 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. * * {RecoveryPlan} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPlan} 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. */ beginReprotect(recoveryPlanName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPlan>; beginReprotect(recoveryPlanName: string, callback: ServiceCallback<models.RecoveryPlan>): void; beginReprotect(recoveryPlanName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPlan>): void; /** * @summary Execute test failover of the recovery plan. * * The operation to start the test failover of a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Failover input. * * @param {object} input.properties The recovery plan test failover input * properties. * * @param {string} input.properties.failoverDirection The failover direction. * Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary' * * @param {string} input.properties.networkType The network type to be used for * test failover. * * @param {string} [input.properties.networkId] The Id of the network to be * used for test failover. * * @param {string} [input.properties.skipTestFailoverCleanup] A value * indicating whether the test failover cleanup is to be skipped. * * @param {array} [input.properties.providerSpecificDetails] The provider * specific properties. * * @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<RecoveryPlan>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginTestFailoverWithHttpOperationResponse(recoveryPlanName: string, input: models.RecoveryPlanTestFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPlan>>; /** * @summary Execute test failover of the recovery plan. * * The operation to start the test failover of a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Failover input. * * @param {object} input.properties The recovery plan test failover input * properties. * * @param {string} input.properties.failoverDirection The failover direction. * Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary' * * @param {string} input.properties.networkType The network type to be used for * test failover. * * @param {string} [input.properties.networkId] The Id of the network to be * used for test failover. * * @param {string} [input.properties.skipTestFailoverCleanup] A value * indicating whether the test failover cleanup is to be skipped. * * @param {array} [input.properties.providerSpecificDetails] The provider * specific properties. * * @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 {RecoveryPlan} - 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. * * {RecoveryPlan} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPlan} 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. */ beginTestFailover(recoveryPlanName: string, input: models.RecoveryPlanTestFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPlan>; beginTestFailover(recoveryPlanName: string, input: models.RecoveryPlanTestFailoverInput, callback: ServiceCallback<models.RecoveryPlan>): void; beginTestFailover(recoveryPlanName: string, input: models.RecoveryPlanTestFailoverInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPlan>): void; /** * @summary Execute test failover cleanup of the recovery plan. * * The operation to cleanup test failover of a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Test failover cleanup input. * * @param {object} input.properties The recovery plan test failover cleanup * input properties. * * @param {string} [input.properties.comments] The test failover cleanup * comments. * * @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<RecoveryPlan>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginTestFailoverCleanupWithHttpOperationResponse(recoveryPlanName: string, input: models.RecoveryPlanTestFailoverCleanupInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPlan>>; /** * @summary Execute test failover cleanup of the recovery plan. * * The operation to cleanup test failover of a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Test failover cleanup input. * * @param {object} input.properties The recovery plan test failover cleanup * input properties. * * @param {string} [input.properties.comments] The test failover cleanup * comments. * * @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 {RecoveryPlan} - 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. * * {RecoveryPlan} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPlan} 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. */ beginTestFailoverCleanup(recoveryPlanName: string, input: models.RecoveryPlanTestFailoverCleanupInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPlan>; beginTestFailoverCleanup(recoveryPlanName: string, input: models.RecoveryPlanTestFailoverCleanupInput, callback: ServiceCallback<models.RecoveryPlan>): void; beginTestFailoverCleanup(recoveryPlanName: string, input: models.RecoveryPlanTestFailoverCleanupInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPlan>): void; /** * @summary Execute unplanned failover of the recovery plan. * * The operation to start the failover of a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Failover input. * * @param {object} input.properties The recovery plan unplanned failover input * properties. * * @param {string} input.properties.failoverDirection The failover direction. * Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary' * * @param {string} input.properties.sourceSiteOperations A value indicating * whether source site operations are required. Possible values include: * 'Required', 'NotRequired' * * @param {array} [input.properties.providerSpecificDetails] The provider * specific properties. * * @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<RecoveryPlan>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginUnplannedFailoverWithHttpOperationResponse(recoveryPlanName: string, input: models.RecoveryPlanUnplannedFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPlan>>; /** * @summary Execute unplanned failover of the recovery plan. * * The operation to start the failover of a recovery plan. * * @param {string} recoveryPlanName Recovery plan name. * * @param {object} input Failover input. * * @param {object} input.properties The recovery plan unplanned failover input * properties. * * @param {string} input.properties.failoverDirection The failover direction. * Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary' * * @param {string} input.properties.sourceSiteOperations A value indicating * whether source site operations are required. Possible values include: * 'Required', 'NotRequired' * * @param {array} [input.properties.providerSpecificDetails] The provider * specific properties. * * @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 {RecoveryPlan} - 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. * * {RecoveryPlan} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPlan} 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. */ beginUnplannedFailover(recoveryPlanName: string, input: models.RecoveryPlanUnplannedFailoverInput, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPlan>; beginUnplannedFailover(recoveryPlanName: string, input: models.RecoveryPlanUnplannedFailoverInput, callback: ServiceCallback<models.RecoveryPlan>): void; beginUnplannedFailover(recoveryPlanName: string, input: models.RecoveryPlanUnplannedFailoverInput, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPlan>): void; /** * @summary Gets the list of recovery plans. * * Lists the recovery plans in the vault. * * @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<RecoveryPlanCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RecoveryPlanCollection>>; /** * @summary Gets the list of recovery plans. * * Lists the recovery plans in the vault. * * @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 {RecoveryPlanCollection} - 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. * * {RecoveryPlanCollection} [result] - The deserialized result object if an error did not occur. * See {@link RecoveryPlanCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RecoveryPlanCollection>; listNext(nextPageLink: string, callback: ServiceCallback<models.RecoveryPlanCollection>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RecoveryPlanCollection>): void; } /** * @class * ReplicationVaultHealth * __NOTE__: An instance of this class is automatically created for an * instance of the SiteRecoveryManagementClient. */ export interface ReplicationVaultHealth { /** * @summary Gets the health summary for the vault. * * Gets the health details of the vault. * * @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<VaultHealthDetails>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VaultHealthDetails>>; /** * @summary Gets the health summary for the vault. * * Gets the health details of the vault. * * @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 {VaultHealthDetails} - 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. * * {VaultHealthDetails} [result] - The deserialized result object if an error did not occur. * See {@link VaultHealthDetails} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VaultHealthDetails>; get(callback: ServiceCallback<models.VaultHealthDetails>): void; get(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VaultHealthDetails>): void; /** * @summary Refreshes health summary of the vault. * * @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<VaultHealthDetails>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ refreshWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VaultHealthDetails>>; /** * @summary Refreshes health summary of the vault. * * @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 {VaultHealthDetails} - 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. * * {VaultHealthDetails} [result] - The deserialized result object if an error did not occur. * See {@link VaultHealthDetails} 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. */ refresh(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VaultHealthDetails>; refresh(callback: ServiceCallback<models.VaultHealthDetails>): void; refresh(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VaultHealthDetails>): void; /** * @summary Refreshes health summary of the vault. * * @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<VaultHealthDetails>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginRefreshWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VaultHealthDetails>>; /** * @summary Refreshes health summary of the vault. * * @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 {VaultHealthDetails} - 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. * * {VaultHealthDetails} [result] - The deserialized result object if an error did not occur. * See {@link VaultHealthDetails} 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. */ beginRefresh(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VaultHealthDetails>; beginRefresh(callback: ServiceCallback<models.VaultHealthDetails>): void; beginRefresh(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VaultHealthDetails>): void; }
the_stack
* @deprecated `kaitian-worker` was deprecated, Please use `sumi-worker` instead. */ declare module 'kaitian-worker' { export * from 'sumi-worker'; } declare module 'sumi-worker' { /** * Accessibility information which controls screen reader behavior. */ export interface AccessibilityInformation { /** * Label to be read out by a screen reader once the item has focus. */ label: string; /** * Role of the widget which defines how a screen reader interacts with it. * The role should be set in special cases when for example a tree-like element behaves like a checkbox. * If role is not specified VS Code will pick the appropriate role automatically. * More about aria roles can be found here https://w3c.github.io/aria/#widget_roles */ role?: string; } export type relativePathKind = 'http' | 'file'; export interface ExtensionContext<T> { registerExtendModuleService<S>(service: S): void; readonly componentProxy: T; /** * An array to which disposables can be added. When this * extension is deactivated the disposables will be disposed. */ readonly subscriptions: { dispose(): any }[]; /** * The absolute file path of the directory containing the extension. */ readonly extensionPath: string; /** * Get the absolute path of a resource contained in the extension. * * @param relativePath A relative path to a resource contained in the extension. * @param kind The schema of the absolute path * @return The absolute path of the resource. * * ```typescript * // from http server * // http://ide.host.com/extensions/resource/test-extension * const httpPath = context.asAbsolutePath('icon/name.svg', 'http'); * // http://ide.host.com/extensions/resource/test-extension/icon/name.svg * * // from local * const filePath = context.asAbsolutePath('icon/name.svg', 'file'); * // file:///path/to/extensions/test-extension/icon/name.svg * ``` */ asAbsolutePath(relativePath: string, kind: relativePathKind): string; } /** * Defines a port mapping used for localhost inside the webview. */ export interface WebviewPortMapping { /** * Localhost port to remap inside the webview. */ readonly webviewPort: number; /** * Destination port. The `webviewPort` is resolved to this port. */ readonly extensionHostPort: number; } /** * Content settings for a webview. */ export interface WebviewOptions { /** * Controls whether scripts are enabled in the webview content or not. * * Defaults to false (scripts-disabled). */ readonly enableScripts?: boolean; /** * Controls whether forms are enabled in the webview content or not. * * Defaults to true if {@link WebviewOptions.enableScripts scripts are enabled}. Otherwise defaults to false. * Explicitly setting this property to either true or false overrides the default. */ readonly enableForms?: boolean; /** * Controls whether command uris are enabled in webview content or not. * * Defaults to false. */ readonly enableCommandUris?: boolean; /** * Root paths from which the webview can load local (filesystem) resources using the `vscode-resource:` scheme. * * Default to the root folders of the current workspace plus the extension's install directory. * * Pass in an empty array to disallow access to any local resources. */ readonly localResourceRoots?: ReadonlyArray<Uri>; /** * Mappings of localhost ports used inside the webview. * * Port mapping allow webviews to transparently define how localhost ports are resolved. This can be used * to allow using a static localhost port inside the webview that is resolved to random port that a service is * running on. * * If a webview accesses localhost content, we recommend that you specify port mappings even if * the `webviewPort` and `extensionHostPort` ports are the same. * * *Note* that port mappings only work for `http` or `https` urls. Websocket urls (e.g. `ws://localhost:3000`) * cannot be mapped to another port. */ readonly portMapping?: ReadonlyArray<WebviewPortMapping>; } /** * A webview displays html content, like an iframe. */ export interface Webview { /** * Content settings for the webview. */ options: WebviewOptions; /** * Contents of the webview. * * Should be a complete html document. */ html: string; /** * Fired when the webview content posts a message. */ readonly onDidReceiveMessage: Event<any>; /** * Post a message to the webview content. * * Messages are only delivered if the webview is visible. * * @param message Body of the message. */ postMessage(message: any): Thenable<boolean>; } /** * Content settings for a webview panel. */ export interface WebviewPanelOptions { /** * Controls if the find widget is enabled in the panel. * * Defaults to false. */ readonly enableFindWidget?: boolean; /** * Controls if the webview panel's content (iframe) is kept around even when the panel * is no longer visible. * * Normally the webview panel's html context is created when the panel becomes visible * and destroyed when it is hidden. Extensions that have complex state * or UI can set the `retainContextWhenHidden` to make VS Code keep the webview * context around, even when the webview moves to a background tab. When a webview using * `retainContextWhenHidden` becomes hidden, its scripts and other dynamic content are suspended. * When the panel becomes visible again, the context is automatically restored * in the exact same state it was in originally. You cannot send messages to a * hidden webview, even with `retainContextWhenHidden` enabled. * * `retainContextWhenHidden` has a high memory overhead and should only be used if * your panel's context cannot be quickly saved and restored. */ readonly retainContextWhenHidden?: boolean; } /** * Value-object describing what options a terminal should use. */ export interface TerminalOptions { /** * A human-readable string which will be used to represent the terminal in the UI. */ name?: string; /** * A path to a custom shell executable to be used in the terminal. */ shellPath?: string; /** * Args for the custom shell executable. A string can be used on Windows only which allows * specifying shell args in [command-line format](https://msdn.microsoft.com/en-au/08dfcab2-eb6e-49a4-80eb-87d4076c98c6). */ shellArgs?: string[] | string; /** * A path or Uri for the current working directory to be used for the terminal. */ cwd?: string | Uri; /** * Object with environment variables that will be added to the VS Code process. */ env?: { [key: string]: string | null }; /** * Whether the terminal process environment should be exactly as provided in * `TerminalOptions.env`. When this is false (default), the environment will be based on the * window's environment and also apply configured platform settings like * `terminal.integrated.windows.env` on top. When this is true, the complete environment * must be provided as nothing will be inherited from the process or any configuration. */ strictEnv?: boolean; /** * When enabled the terminal will run the process as normal but not be surfaced to the user * until `Terminal.show` is called. The typical usage for this is when you need to run * something that may need interactivity but only want to tell the user about it when * interaction is needed. Note that the terminals will still be exposed to all extensions * as normal. */ hideFromUser?: boolean; } /** * The clipboard provides read and write access to the system's clipboard. */ export interface Clipboard { /** * Read the current clipboard contents as text. * @returns A thenable that resolves to a string. */ readText(): Thenable<string>; /** * Writes text into the clipboard. * @returns A thenable that resolves when writing happened. */ writeText(value: string): Thenable<void>; } /** * A selection range represents a part of a selection hierarchy. A selection range * may have a parent selection range that contains it. */ export class SelectionRange { /** * The [range](#Range) of this selection range. */ range: Range; /** * The parent selection range containing this range. */ parent?: SelectionRange; /** * Creates a new selection range. * * @param range The range of the selection range. * @param parent The parent of the selection range. */ constructor(range: Range, parent?: SelectionRange); } /** * A tuple of two characters, like a pair of * opening and closing brackets. */ export type CharacterPair = [string, string]; /** * The workspace symbol provider interface defines the contract between extensions and * the [symbol search](https://code.visualstudio.com/docs/editor/editingevolved#_open-symbol-by-name)-feature. */ export interface WorkspaceSymbolProvider { /** * Project-wide search for a symbol matching the given query string. * * The `query`-parameter should be interpreted in a *relaxed way* as the editor will apply its own highlighting * and scoring on the results. A good rule of thumb is to match case-insensitive and to simply check that the * characters of *query* appear in their order in a candidate symbol. Don't use prefix, substring, or similar * strict matching. * * To improve performance implementors can implement `resolveWorkspaceSymbol` and then provide symbols with partial * [location](#SymbolInformation.location)-objects, without a `range` defined. The editor will then call * `resolveWorkspaceSymbol` for selected symbols only, e.g. when opening a workspace symbol. * * @param query A query string, can be the empty string in which case all symbols should be returned. * @param token A cancellation token. * @return An array of document highlights or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined`, `null`, or an empty array. */ provideWorkspaceSymbols(query: string, token: CancellationToken): ProviderResult<SymbolInformation[]>; /** * Given a symbol fill in its [location](#SymbolInformation.location). This method is called whenever a symbol * is selected in the UI. Providers can implement this method and return incomplete symbols from * [`provideWorkspaceSymbols`](#WorkspaceSymbolProvider.provideWorkspaceSymbols) which often helps to improve * performance. * * @param symbol The symbol that is to be resolved. Guaranteed to be an instance of an object returned from an * earlier call to `provideWorkspaceSymbols`. * @param token A cancellation token. * @return The resolved symbol or a thenable that resolves to that. When no result is returned, * the given `symbol` is used. */ resolveWorkspaceSymbol?(symbol: SymbolInformation, token: CancellationToken): ProviderResult<SymbolInformation>; } /** * Describes how comments for a language work. */ export interface CommentRule { /** * The line comment token, like `// this is a comment` */ lineComment?: string; /** * The block comment character pair, like `/* block comment *&#47;` */ blockComment?: CharacterPair; } /** * Describes a rule to be evaluated when pressing Enter. */ export interface OnEnterRule { /** * This rule will only execute if the text before the cursor matches this regular expression. */ beforeText: RegExp; /** * This rule will only execute if the text after the cursor matches this regular expression. */ afterText?: RegExp; /** * The action to execute. */ action: EnterAction; } /** * Describes indentation rules for a language. */ export interface IndentationRule { /** * If a line matches this pattern, then all the lines after it should be unindented once (until another rule matches). */ decreaseIndentPattern: RegExp; /** * If a line matches this pattern, then all the lines after it should be indented once (until another rule matches). */ increaseIndentPattern: RegExp; /** * If a line matches this pattern, then **only the next line** after it should be indented once. */ indentNextLinePattern?: RegExp; /** * If a line matches this pattern, then its indentation should not be changed and it should not be evaluated against the other rules. */ unIndentedLinePattern?: RegExp; } /** * A workspace folder is one of potentially many roots opened by the editor. All workspace folders * are equal which means there is no notion of an active or master workspace folder. */ export interface WorkspaceFolder { /** * The associated uri for this workspace folder. * * *Note:* The [Uri](#Uri)-type was intentionally chosen such that future releases of the editor can support * workspace folders that are not stored on the local disk, e.g. `ftp://server/workspaces/foo`. */ readonly uri: Uri; /** * The name of this workspace folder. Defaults to * the basename of its [uri-path](#Uri.path) */ readonly name: string; /** * The ordinal number of this workspace folder. */ readonly index: number; } /** * Represents reasons why a text document is saved. */ export enum TextDocumentSaveReason { /** * Manually triggered, e.g. by the user pressing save, by starting debugging, * or by an API call. */ Manual = 1, /** * Automatic after a delay. */ AfterDelay = 2, /** * When the editor lost focus. */ FocusOut = 3, } /** * Represents the state of a window. */ export interface WindowState { /** * Whether the current window is focused. */ readonly focused: boolean; } /** * Represents a parameter of a callable-signature. A parameter can * have a label and a doc-comment. */ export class ParameterInformation { /** * The label of this signature. * * Either a string or inclusive start and exclusive end offsets within its containing * [signature label](#SignatureInformation.label). *Note*: A label of type string must be * a substring of its containing signature information's [label](#SignatureInformation.label). */ label: string | [number, number]; /** * The human-readable doc-comment of this signature. Will be shown * in the UI but can be omitted. */ documentation?: string | MarkdownString; /** * Creates a new parameter information object. * * @param label A label string or inclusive start and exclusive end offsets within its containing signature label. * @param documentation A doc string. */ constructor(label: string | [number, number], documentation?: string | MarkdownString); } /** * How a [`SignatureHelpProvider`](#SignatureHelpProvider) was triggered. */ export enum SignatureHelpTriggerKind { /** * Signature help was invoked manually by the user or by a command. */ Invoke = 1, /** * Signature help was triggered by a trigger character. */ TriggerCharacter = 2, /** * Signature help was triggered by the cursor moving or by the document content changing. */ ContentChange = 3, } /** * Additional information about the context in which a * [`SignatureHelpProvider`](#SignatureHelpProvider.provideSignatureHelp) was triggered. */ export interface SignatureHelpContext { /** * Action that caused signature help to be triggered. */ readonly triggerKind: SignatureHelpTriggerKind; /** * Character that caused signature help to be triggered. * * This is `undefined` when signature help is not triggered by typing, such as when manually invoking * signature help or when moving the cursor. */ readonly triggerCharacter?: string; /** * `true` if signature help was already showing when it was triggered. * * Retriggers occur when the signature help is already active and can be caused by actions such as * typing a trigger character, a cursor move, or document content changes. */ readonly isRetrigger: boolean; /** * The currently active [`SignatureHelp`](#SignatureHelp). * * The `activeSignatureHelp` has its [`SignatureHelp.activeSignature`] field updated based on * the user arrowing through available signatures. */ readonly activeSignatureHelp?: SignatureHelp; } /** * The signature help provider interface defines the contract between extensions and * the [parameter hints](https://code.visualstudio.com/docs/editor/intellisense)-feature. */ export interface SignatureHelpProvider { /** * Provide help for the signature at the given position and document. * * @param document The document in which the command was invoked. * @param position The position at which the command was invoked. * @param token A cancellation token. * @param context Information about how signature help was triggered. * * @return Signature help or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined` or `null`. */ provideSignatureHelp( document: TextDocument, position: Position, token: CancellationToken, context: SignatureHelpContext, ): ProviderResult<SignatureHelp>; } /** * Metadata about a registered [`SignatureHelpProvider`](#SignatureHelpProvider). */ export interface SignatureHelpProviderMetadata { /** * List of characters that trigger signature help. */ readonly triggerCharacters: ReadonlyArray<string>; /** * List of characters that re-trigger signature help. * * These trigger characters are only active when signature help is already showing. All trigger characters * are also counted as re-trigger characters. */ readonly retriggerCharacters: ReadonlyArray<string>; } /** * Represents the signature of something callable. A signature * can have a label, like a function-name, a doc-comment, and * a set of parameters. */ export class SignatureInformation { /** * The label of this signature. Will be shown in * the UI. */ label: string; /** * The human-readable doc-comment of this signature. Will be shown * in the UI but can be omitted. */ documentation?: string | MarkdownString; /** * The parameters of this signature. */ parameters: ParameterInformation[]; /** * The index of the active parameter. * * If provided, this is used in place of {@linkcode SignatureHelp.activeSignature}. */ activeParameter?: number; /** * Creates a new signature information object. * * @param label A label string. * @param documentation A doc string. */ constructor(label: string, documentation?: string | MarkdownString); } /** * Signature help represents the signature of something * callable. There can be multiple signatures but only one * active and only one active parameter. */ export class SignatureHelp { /** * One or more signatures. */ signatures: SignatureInformation[]; /** * The active signature. */ activeSignature: number; /** * The active parameter of the active signature. */ activeParameter: number; } /** * Symbol tags are extra annotations that tweak the rendering of a symbol. */ export enum SymbolTag { /** * Render a symbol as obsolete, usually using a strike-out. */ Deprecated = 1, } /** * Represents information about programming constructs like variables, classes, * interfaces etc. */ export class SymbolInformation { /** * The name of this symbol. */ name: string; /** * The name of the symbol containing this symbol. */ containerName: string; /** * The kind of this symbol. */ kind: SymbolKind; /** * Tags for this symbol. */ tags?: ReadonlyArray<SymbolTag>; /** * The location of this symbol. */ location: Location; /** * Creates a new symbol information object. * * @param name The name of the symbol. * @param kind The kind of the symbol. * @param containerName The name of the symbol containing the symbol. * @param location The location of the symbol. */ constructor(name: string, kind: SymbolKind, containerName: string, location: Location); /** * ~~Creates a new symbol information object.~~ * * @deprecated Please use the constructor taking a [location](#Location) object. * * @param name The name of the symbol. * @param kind The kind of the symbol. * @param range The range of the location of the symbol. * @param uri The resource of the location of symbol, defaults to the current document. * @param containerName The name of the symbol containing the symbol. */ constructor(name: string, kind: SymbolKind, range: Range, uri?: Uri, containerName?: string); } /** * A symbol kind. */ export enum SymbolKind { File = 0, Module = 1, Namespace = 2, Package = 3, Class = 4, Method = 5, Property = 6, Field = 7, Constructor = 8, Enum = 9, Interface = 10, Function = 11, Variable = 12, Constant = 13, String = 14, Number = 15, Boolean = 16, Array = 17, Object = 18, Key = 19, Null = 20, EnumMember = 21, Struct = 22, Event = 23, Operator = 24, TypeParameter = 25, } /** * The version of the editor. */ export const version: string; /** * In a remote window the extension kind describes if an extension * runs where the UI (window) runs or if an extension runs remotely. */ export enum ExtensionKind { /** * Extension runs where the UI runs. */ UI = 1, /** * Extension runs where the remote extension host runs. */ Workspace = 2, } export interface SelectionRangeProvider { /** * Provide selection ranges for the given positions. * * Selection ranges should be computed individually and independend for each position. The editor will merge * and deduplicate ranges but providers must return hierarchies of selection ranges so that a range * is [contained](#Range.contains) by its parent. * * @param document The document in which the command was invoked. * @param positions The positions at which the command was invoked. * @param token A cancellation token. * @return Selection ranges or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined` or `null`. */ provideSelectionRanges( document: TextDocument, positions: Position[], token: CancellationToken, ): ProviderResult<SelectionRange[]>; } /** * Contains additional information about the context in which * [completion provider](#CompletionItemProvider.provideCompletionItems) is triggered. */ export interface CompletionContext { /** * How the completion was triggered. */ readonly triggerKind: CompletionTriggerKind; /** * Character that triggered the completion item provider. * * `undefined` if provider was not triggered by a character. * * The trigger character is already in the document when the completion provider is triggered. */ readonly triggerCharacter?: string; } /** * How a [completion provider](#CompletionItemProvider) was triggered */ export enum CompletionTriggerKind { /** * Completion was triggered normally. */ Invoke = 0, /** * Completion was triggered by a trigger character. */ TriggerCharacter = 1, /** * Completion was re-triggered as current completion list is incomplete */ TriggerForIncompleteCompletions = 2, } /** * Completion item kinds. */ export enum CompletionItemKind { Text = 0, Method = 1, Function = 2, Constructor = 3, Field = 4, Variable = 5, Class = 6, Interface = 7, Module = 8, Property = 9, Unit = 10, Value = 11, Enum = 12, Keyword = 13, Snippet = 14, Color = 15, Reference = 17, File = 16, Folder = 18, EnumMember = 19, Constant = 20, Struct = 21, Event = 22, Operator = 23, TypeParameter = 24, } /** * A workspace edit is a collection of textual and files changes for * multiple resources and documents. * * Use the [applyEdit](#workspace.applyEdit)-function to apply a workspace edit. */ export class WorkspaceEdit { /** * The number of affected resources of textual or resource changes. */ readonly size: number; /** * Replace the given range with given text for the given resource. * * @param uri A resource identifier. * @param range A range. * @param newText A string. */ replace(uri: Uri, range: Range, newText: string): void; /** * Insert the given text at the given position. * * @param uri A resource identifier. * @param position A position. * @param newText A string. */ insert(uri: Uri, position: Position, newText: string): void; /** * Delete the text at the given range. * * @param uri A resource identifier. * @param range A range. */ delete(uri: Uri, range: Range): void; /** * Check if a text edit for a resource exists. * * @param uri A resource identifier. * @return `true` if the given resource will be touched by this edit. */ has(uri: Uri): boolean; /** * Set (and replace) text edits for a resource. * * @param uri A resource identifier. * @param edits An array of text edits. */ set(uri: Uri, edits: TextEdit[]): void; /** * Get the text edits for a resource. * * @param uri A resource identifier. * @return An array of text edits. */ get(uri: Uri): TextEdit[]; /** * Create a regular file. * * @param uri Uri of the new file.. * @param options Defines if an existing file should be overwritten or be * ignored. When overwrite and ignoreIfExists are both set overwrite wins. */ createFile(uri: Uri, options?: { overwrite?: boolean; ignoreIfExists?: boolean }): void; /** * Delete a file or folder. * * @param uri The uri of the file that is to be deleted. */ deleteFile(uri: Uri, options?: { recursive?: boolean; ignoreIfNotExists?: boolean }): void; /** * Rename a file or folder. * * @param oldUri The existing file. * @param newUri The new location. * @param options Defines if existing files should be overwritten or be * ignored. When overwrite and ignoreIfExists are both set overwrite wins. */ renameFile(oldUri: Uri, newUri: Uri, options?: { overwrite?: boolean; ignoreIfExists?: boolean }): void; /** * Get all text edits grouped by resource. * * @return A shallow copy of `[Uri, TextEdit[]]`-tuples. */ entries(): [Uri, TextEdit[]][]; } /** * Options for creating a [TreeView](#TreeView) */ export interface TreeViewOptions<T> { /** * A data provider that provides tree data. */ treeDataProvider: TreeDataProvider<T>; /** * Whether to show collapse all action or not. */ showCollapseAll?: boolean; /** * Whether the tree supports multi-select. When the tree supports multi-select and a command is executed from the tree, * the first argument to the command is the tree item that the command was executed on and the second argument is an * array containing all selected tree items. */ canSelectMany?: boolean; } /** * The event that is fired when an element in the [TreeView](#TreeView) is expanded or collapsed */ export interface TreeViewExpansionEvent<T> { /** * Element that is expanded or collapsed. */ readonly element: T; } /** * The event that is fired when there is a change in [tree view's selection](#TreeView.selection) */ export interface TreeViewSelectionChangeEvent<T> { /** * Selected elements. */ readonly selection: T[]; } /** * The event that is fired when there is a change in [tree view's visibility](#TreeView.visible) */ export interface TreeViewVisibilityChangeEvent { /** * `true` if the [tree view](#TreeView) is visible otherwise `false`. */ readonly visible: boolean; } /** * Represents a Tree view */ export interface TreeView<T> extends Disposable { /** * Event that is fired when an element is expanded */ readonly onDidExpandElement: Event<TreeViewExpansionEvent<T>>; /** * Event that is fired when an element is collapsed */ readonly onDidCollapseElement: Event<TreeViewExpansionEvent<T>>; /** * Currently selected elements. */ readonly selection: T[]; /** * Event that is fired when the [selection](#TreeView.selection) has changed */ readonly onDidChangeSelection: Event<TreeViewSelectionChangeEvent<T>>; /** * `true` if the [tree view](#TreeView) is visible otherwise `false`. */ readonly visible: boolean; /** * Event that is fired when [visibility](#TreeView.visible) has changed */ readonly onDidChangeVisibility: Event<TreeViewVisibilityChangeEvent>; /** * Reveals the given element in the tree view. * If the tree view is not visible then the tree view is shown and element is revealed. * * By default revealed element is selected. * In order to not to select, set the option `select` to `false`. * In order to focus, set the option `focus` to `true`. * In order to expand the revealed element, set the option `expand` to `true`. To expand recursively set `expand` to the number of levels to expand. * **NOTE:** You can expand only to 3 levels maximum. * * **NOTE:** [TreeDataProvider](#TreeDataProvider) is required to implement [getParent](#TreeDataProvider.getParent) method to access this API. */ reveal(element: T, options?: { select?: boolean; focus?: boolean; expand?: boolean | number }): Thenable<void>; } /** * Collapsible state of the tree item */ export enum TreeItemCollapsibleState { /** * Determines an item can be neither collapsed nor expanded. Implies it has no children. */ None = 0, /** * Determines an item is collapsed */ Collapsed = 1, /** * Determines an item is expanded */ Expanded = 2, } /** * Label describing the [Tree item](#TreeItem) */ export interface TreeItemLabel { /** * A human-readable string describing the [Tree item](#TreeItem). */ label: string; /** * Ranges in the label to highlight. A range is defined as a tuple of two number where the * first is the inclusive start index and the second the exclusive end index */ highlights?: [number, number][]; } /** * A data provider that provides tree data */ export interface TreeDataProvider<T> { /** * An optional event to signal that an element or root has changed. * This will trigger the view to update the changed element/root and its children recursively (if shown). * To signal that root has changed, do not pass any argument or pass `undefined` or `null`. */ onDidChangeTreeData?: Event<T | undefined | null>; /** * Get [TreeItem](#TreeItem) representation of the `element` * * @param element The element for which [TreeItem](#TreeItem) representation is asked for. * @return [TreeItem](#TreeItem) representation of the element */ getTreeItem(element: T): TreeItem | Thenable<TreeItem>; /** * Get the children of `element` or root if no element is passed. * * @param element The element from which the provider gets children. Can be `undefined`. * @return Children of `element` or root if no element is passed. */ getChildren(element?: T): ProviderResult<T[]>; /** * Optional method to return the parent of `element`. * Return `null` or `undefined` if `element` is a child of root. * * **NOTE:** This method should be implemented in order to access [reveal](#TreeView.reveal) API. * * @param element The element for which the parent has to be returned. * @return Parent of `element`. */ getParent?(element: T): ProviderResult<T>; /** * Called on hover to resolve the {@link TreeItem.tooltip TreeItem} property if it is undefined. * Called on tree item click/open to resolve the {@link TreeItem.command TreeItem} property if it is undefined. * Only properties that were undefined can be resolved in `resolveTreeItem`. * Functionality may be expanded later to include being called to resolve other missing * properties on selection and/or on open. * * Will only ever be called once per TreeItem. * * onDidChangeTreeData should not be triggered from within resolveTreeItem. * * *Note* that this function is called when tree items are already showing in the UI. * Because of that, no property that changes the presentation (label, description, etc.) * can be changed. * * @param item Undefined properties of `item` should be set then `item` should be returned. * @param element The object associated with the TreeItem. * @param token A cancellation token. * @return The resolved tree item or a thenable that resolves to such. It is OK to return the given * `item`. When no result is returned, the given `item` will be used. */ resolveTreeItem?(item: TreeItem, element: T, token: CancellationToken): ProviderResult<TreeItem>; } export class TreeItem { /** * A human-readable string describing this item. When `falsy`, it is derived from {@link TreeItem.resourceUri resourceUri}. */ label?: string | TreeItemLabel; /** * Optional id for the tree item that has to be unique across tree. The id is used to preserve the selection and expansion state of the tree item. * * If not provided, an id is generated using the tree item's label. **Note** that when labels change, ids will change and that selection and expansion state cannot be kept stable anymore. */ id?: string; /** * The icon path or [ThemeIcon](#ThemeIcon) for the tree item. * When `falsy`, [Folder Theme Icon](#ThemeIcon.Folder) is assigned, if item is collapsible otherwise [File Theme Icon](#ThemeIcon.File). * When a [ThemeIcon](#ThemeIcon) is specified, icon is derived from the current file icon theme for the specified theme icon using [resourceUri](#TreeItem.resourceUri) (if provided). */ iconPath?: string | Uri | { light: string | Uri; dark: string | Uri } | ThemeIcon; /** * A human readable string which is rendered less prominent. * When `true`, it is derived from [resourceUri](#TreeItem.resourceUri) and when `falsy`, it is not shown. */ description?: string | boolean; /** * The [uri](#Uri) of the resource representing this item. * * Will be used to derive the [label](#TreeItem.label), when it is not provided. * Will be used to derive the icon from current icon theme, when [iconPath](#TreeItem.iconPath) has [ThemeIcon](#ThemeIcon) value. */ resourceUri?: Uri; /** * The tooltip text when you hover over this item. */ tooltip?: string | undefined; /** * The [command](#Command) that should be executed when the tree item is selected. */ command?: Command; /** * [TreeItemCollapsibleState](#TreeItemCollapsibleState) of the tree item. */ collapsibleState?: TreeItemCollapsibleState; /** * Context value of the tree item. This can be used to contribute item specific actions in the tree. * For example, a tree item is given a context value as `folder`. When contributing actions to `view/item/context` * using `menus` extension point, you can specify context value for key `viewItem` in `when` expression like `viewItem == folder`. * ``` * "contributes": { * "menus": { * "view/item/context": [ * { * "command": "extension.deleteFolder", * "when": "viewItem == folder" * } * ] * } * } * ``` * This will show action `extension.deleteFolder` only for items with `contextValue` is `folder`. */ contextValue?: string; /** * Accessibility information used when screen reader interacts with this tree item. * Generally, a TreeItem has no need to set the `role` of the accessibilityInformation; * however, there are cases where a TreeItem is not displayed in a tree-like way where setting the `role` may make sense. */ accessibilityInformation?: AccessibilityInformation; /** * @param label A human-readable string describing this item * @param collapsibleState {@link TreeItemCollapsibleState} of the tree item. Default is {@link TreeItemCollapsibleState.None} */ constructor(label: string | TreeItemLabel, collapsibleState?: TreeItemCollapsibleState); /** * @param resourceUri The {@link Uri} of the resource representing this item. * @param collapsibleState {@link TreeItemCollapsibleState} of the tree item. Default is {@link TreeItemCollapsibleState.None} */ // eslint-disable-next-line @typescript-eslint/unified-signatures constructor(resourceUri: Uri, collapsibleState?: TreeItemCollapsibleState); } /** * Represents a line of text, such as a line of source code. * * TextLine objects are __immutable__. When a [document](#TextDocument) changes, * previously retrieved lines will not represent the latest state. */ export interface TextLine { /** * The zero-based line number. */ readonly lineNumber: number; /** * The text of this line without the line separator characters. */ readonly text: string; /** * The range this line covers without the line separator characters. */ readonly range: Range; /** * The range this line covers with the line separator characters. */ readonly rangeIncludingLineBreak: Range; /** * The offset of the first character which is not a whitespace character as defined * by `/\s/`. **Note** that if a line is all whitespace the length of the line is returned. */ readonly firstNonWhitespaceCharacterIndex: number; /** * Whether this line is whitespace only, shorthand * for [TextLine.firstNonWhitespaceCharacterIndex](#TextLine.firstNonWhitespaceCharacterIndex) === [TextLine.text.length](#TextLine.text). */ readonly isEmptyOrWhitespace: boolean; } /** * Represents a text document, such as a source file. Text documents have * [lines](#TextLine) and knowledge about an underlying resource like a file. */ export interface TextDocument { /** * The associated uri for this document. * * *Note* that most documents use the `file`-scheme, which means they are files on disk. However, **not** all documents are * saved on disk and therefore the `scheme` must be checked before trying to access the underlying file or siblings on disk. * * @see [FileSystemProvider](#FileSystemProvider) * @see [TextDocumentContentProvider](#TextDocumentContentProvider) */ readonly uri: Uri; /** * The file system path of the associated resource. Shorthand * notation for [TextDocument.uri.fsPath](#TextDocument.uri). Independent of the uri scheme. */ readonly fileName: string; /** * Is this document representing an untitled file which has never been saved yet. *Note* that * this does not mean the document will be saved to disk, use [`uri.scheme`](#Uri.scheme) * to figure out where a document will be [saved](#FileSystemProvider), e.g. `file`, `ftp` etc. */ readonly isUntitled: boolean; /** * The identifier of the language associated with this document. */ readonly languageId: string; /** * The version number of this document (it will strictly increase after each * change, including undo/redo). */ readonly version: number; /** * `true` if there are unpersisted changes. */ readonly isDirty: boolean; /** * `true` if the document have been closed. A closed document isn't synchronized anymore * and won't be re-used when the same resource is opened again. */ readonly isClosed: boolean; /** * Save the underlying file. * * @return A promise that will resolve to true when the file * has been saved. If the file was not dirty or the save failed, * will return false. */ save(): Thenable<boolean>; /** * The [end of line](#EndOfLine) sequence that is predominately * used in this document. */ readonly eol: EndOfLine; /** * The number of lines in this document. */ readonly lineCount: number; /** * Returns a text line denoted by the position. Note * that the returned object is *not* live and changes to the * document are not reflected. * * The position will be [adjusted](#TextDocument.validatePosition). * * @see [TextDocument.lineAt](#TextDocument.lineAt) * @param position A position. * @return A [line](#TextLine). */ lineAt(position: Position | number): TextLine; /** * Converts the position to a zero-based offset. * * The position will be [adjusted](#TextDocument.validatePosition). * * @param position A position. * @return A valid zero-based offset. */ offsetAt(position: Position): number; /** * Converts a zero-based offset to a position. * * @param offset A zero-based offset. * @return A valid [position](#Position). */ positionAt(offset: number): Position; /** * Get the text of this document. A substring can be retrieved by providing * a range. The range will be [adjusted](#TextDocument.validateRange). * * @param range Include only the text included by the range. * @return The text inside the provided range or the entire text. */ getText(range?: Range): string; /** * Get a word-range at the given position. By default words are defined by * common separators, like space, -, _, etc. In addition, per language custom * [word definitions](#LanguageConfiguration.wordPattern) can be defined. It * is also possible to provide a custom regular expression. * * * *Note 1:* A custom regular expression must not match the empty string and * if it does, it will be ignored. * * *Note 2:* A custom regular expression will fail to match multiline strings * and in the name of speed regular expressions should not match words with * spaces. Use [`TextLine.text`](#TextLine.text) for more complex, non-wordy, scenarios. * * The position will be [adjusted](#TextDocument.validatePosition). * * @param position A position. * @param regex Optional regular expression that describes what a word is. * @return A range spanning a word, or `undefined`. */ getWordRangeAtPosition(position: Position, regex?: RegExp): Range | undefined; /** * Ensure a range is completely contained in this document. * * @param range A range. * @return The given range or a new, adjusted range. */ validateRange(range: Range): Range; /** * Ensure a position is contained in the range of this document. * * @param position A position. * @return The given position or a new, adjusted position. */ validatePosition(position: Position): Position; } /** * Represents a text selection in an editor. */ export class Selection extends Range { /** * The position at which the selection starts. * This position might be before or after [active](#Selection.active). */ anchor: Position; /** * The position of the cursor. * This position might be before or after [anchor](#Selection.anchor). */ active: Position; /** * Create a selection from two positions. * * @param anchor A position. * @param active A position. */ constructor(anchor: Position, active: Position); /** * Create a selection from four coordinates. * * @param anchorLine A zero-based line value. * @param anchorCharacter A zero-based character value. * @param activeLine A zero-based line value. * @param activeCharacter A zero-based character value. */ constructor(anchorLine: number, anchorCharacter: number, activeLine: number, activeCharacter: number); /** * A selection is reversed if [active](#Selection.active).isBefore([anchor](#Selection.anchor)). */ isReversed: boolean; } /** * A complex edit that will be applied in one transaction on a TextEditor. * This holds a description of the edits and if the edits are valid (i.e. no overlapping regions, document was not changed in the meantime, etc.) * they can be applied on a [document](#TextDocument) associated with a [text editor](#TextEditor). * */ /** * A universal resource identifier representing either a file on disk * or another resource, like untitled resources. */ export class Uri { /** * Create an URI from a string, e.g. `http://www.msft.com/some/path`, * `file:///usr/home`, or `scheme:with/path`. * * *Note* that for a while uris without a `scheme` were accepted. That is not correct * as all uris should have a scheme. To avoid breakage of existing code the optional * `strict`-argument has been added. We *strongly* advise to use it, e.g. `Uri.parse('my:uri', true)` * * @see [Uri.toString](#Uri.toString) * @param value The string value of an Uri. * @param strict Throw an error when `value` is empty or when no `scheme` can be parsed. * @return A new Uri instance. */ static parse(value: string, strict?: boolean): Uri; /** * Create an URI from a file system path. The [scheme](#Uri.scheme) * will be `file`. * * The *difference* between `Uri#parse` and `Uri#file` is that the latter treats the argument * as path, not as stringified-uri. E.g. `Uri.file(path)` is *not* the same as * `Uri.parse('file://' + path)` because the path might contain characters that are * interpreted (# and ?). See the following sample: * ```ts const good = URI.file('/coding/c#/project1'); good.scheme === 'file'; good.path === '/coding/c#/project1'; good.fragment === ''; const bad = URI.parse('file://' + '/coding/c#/project1'); bad.scheme === 'file'; bad.path === '/coding/c'; // path is now broken bad.fragment === '/project1'; ``` * * @param path A file system or UNC path. * @return A new Uri instance. */ static file(path: string): Uri; /** * Use the `file` and `parse` factory functions to create new `Uri` objects. */ private constructor(scheme: string, authority: string, path: string, query: string, fragment: string); /** * Scheme is the `http` part of `http://www.msft.com/some/path?query#fragment`. * The part before the first colon. */ readonly scheme: string; /** * Authority is the `www.msft.com` part of `http://www.msft.com/some/path?query#fragment`. * The part between the first double slashes and the next slash. */ readonly authority: string; /** * Path is the `/some/path` part of `http://www.msft.com/some/path?query#fragment`. */ readonly path: string; /** * Query is the `query` part of `http://www.msft.com/some/path?query#fragment`. */ readonly query: string; /** * Fragment is the `fragment` part of `http://www.msft.com/some/path?query#fragment`. */ readonly fragment: string; /** * The string representing the corresponding file system path of this Uri. * * Will handle UNC paths and normalize windows drive letters to lower-case. Also * uses the platform specific path separator. * * * Will *not* validate the path for invalid characters and semantics. * * Will *not* look at the scheme of this Uri. * * The resulting string shall *not* be used for display purposes but * for disk operations, like `readFile` et al. * * The *difference* to the [`path`](#Uri.path)-property is the use of the platform specific * path separator and the handling of UNC paths. The sample below outlines the difference: * ```ts const u = URI.parse('file://server/c$/folder/file.txt') u.authority === 'server' u.path === '/shares/c$/file.txt' u.fsPath === '\\server\c$\folder\file.txt' ``` */ readonly fsPath: string; /** * Derive a new Uri from this Uri. * * ```ts * let file = Uri.parse('before:some/file/path'); * let other = file.with({ scheme: 'after' }); * assert.ok(other.toString() === 'after:some/file/path'); * ``` * * @param change An object that describes a change to this Uri. To unset components use `null` or * the empty string. * @return A new Uri that reflects the given change. Will return `this` Uri if the change * is not changing anything. */ with(change: { scheme?: string; authority?: string; path?: string; query?: string; fragment?: string }): Uri; /** * Returns a string representation of this Uri. The representation and normalization * of a URI depends on the scheme. * * * The resulting string can be safely used with [Uri.parse](#Uri.parse). * * The resulting string shall *not* be used for display purposes. * * *Note* that the implementation will encode _aggressive_ which often leads to unexpected, * but not incorrect, results. For instance, colons are encoded to `%3A` which might be unexpected * in file-uri. Also `&` and `=` will be encoded which might be unexpected for http-uris. For stability * reasons this cannot be changed anymore. If you suffer from too aggressive encoding you should use * the `skipEncoding`-argument: `uri.toString(true)`. * * @param skipEncoding Do not percentage-encode the result, defaults to `false`. Note that * the `#` and `?` characters occurring in the path will always be encoded. * @returns A string representation of this Uri. */ toString(skipEncoding?: boolean): string; /** * Returns a JSON representation of this Uri. * * @return An object. */ toJSON(): any; } /** * Represents a typed event. * * A function that represents an event to which you subscribe by calling it with * a listener function as argument. * * @sample `item.onDidChange(function(event) { console.log("Event happened: " + event); });` */ type Event<T> = (listener: (e: T) => any, thisArgs?: any, disposables?: Disposable[]) => Disposable; /** * An event emitter can be used to create and manage an [event](#Event) for others * to subscribe to. One emitter always owns one event. * * Use this class if you want to provide event from within your extension, for instance * inside a [TextDocumentContentProvider](#TextDocumentContentProvider) or when providing * API to other extensions. */ export class EventEmitter<T> { /** * The event listeners can subscribe to. */ event: Event<T>; /** * Notify all subscribers of the [event](#EventEmitter.event). Failure * of one or more listener will not fail this function call. * * @param data The event object. */ fire(data?: T): void; /** * Dispose this object and free resources. */ dispose(): void; } /** * A cancellation token is passed to an asynchronous or long running * operation to request cancellation, like cancelling a request * for completion items because the user continued to type. * * To get an instance of a `CancellationToken` use a * [CancellationTokenSource](#CancellationTokenSource). */ export interface CancellationToken { /** * Is `true` when the token has been cancelled, `false` otherwise. */ isCancellationRequested: boolean; /** * An [event](#Event) which fires upon cancellation. */ onCancellationRequested: Event<any>; } /** * A cancellation source creates and controls a [cancellation token](#CancellationToken). */ export class CancellationTokenSource { /** * The cancellation token of this source. */ token: CancellationToken; /** * Signal cancellation on the token. */ cancel(): void; /** * Dispose object and free resources. */ dispose(): void; } export enum TextDocumentChangeReason { /** The text change is caused by an undo operation. */ Undo = 1, /** The text change is caused by an redo operation. */ Redo = 2, } /** * An event describing a transactional [document](#TextDocument) change. */ export interface TextDocumentChangeEvent { /** * The affected document. */ readonly document: TextDocument; /** * An array of content changes. */ readonly contentChanges: ReadonlyArray<TextDocumentContentChangeEvent>; /** * The reason why the document was changed. * Is `undefined` if the reason is not known. */ readonly reason: TextDocumentChangeReason | undefined; } /** * Represents a related message and source code location for a diagnostic. This should be * used to point to code locations that cause or related to a diagnostics, e.g. when duplicating * a symbol in a scope. */ export class DiagnosticRelatedInformation { /** * The location of this related diagnostic information. */ location: Location; /** * The message of this related diagnostic information. */ message: string; /** * Creates a new related diagnostic information object. * * @param location The location. * @param message The message. */ constructor(location: Location, message: string); } /** * Additional metadata about the type of a diagnostic. */ export enum DiagnosticTag { /** * Unused or unnecessary code. * * Diagnostics with this tag are rendered faded out. The amount of fading * is controlled by the `"editorUnnecessaryCode.opacity"` theme color. For * example, `"editorUnnecessaryCode.opacity": "#000000c0"` will render the * code with 75% opacity. For high contrast themes, use the * `"editorUnnecessaryCode.border"` theme color to underline unnecessary code * instead of fading it out. */ Unnecessary = 1, Deprecated = 2, } /** * Represents the severity of diagnostics. */ export enum DiagnosticSeverity { /** * Something not allowed by the rules of a language or other means. */ Error = 0, /** * Something suspicious but allowed. */ Warning = 1, /** * Something to inform about but not a problem. */ Information = 2, /** * Something to hint to a better way of doing it, like proposing * a refactoring. */ Hint = 3, } /** * Represents a diagnostic, such as a compiler error or warning. Diagnostic objects * are only valid in the scope of a file. */ export class Diagnostic { /** * The range to which this diagnostic applies. */ range: Range; /** * The human-readable message. */ message: string; /** * The severity, default is [error](#DiagnosticSeverity.Error). */ severity: DiagnosticSeverity; /** * A human-readable string describing the source of this * diagnostic, e.g. 'typescript' or 'super lint'. */ source?: string; /** * A code or identifier for this diagnostic. * Should be used for later processing, e.g. when providing [code actions](#CodeActionContext). */ code?: string | number; /** * An array of related diagnostic information, e.g. when symbol-names within * a scope collide all definitions can be marked via this property. */ relatedInformation?: DiagnosticRelatedInformation[]; /** * Additional metadata about the diagnostic. */ tags?: DiagnosticTag[]; /** * Creates a new diagnostic object. * * @param range The range to which this diagnostic applies. * @param message The human-readable message. * @param severity The severity, default is [error](#DiagnosticSeverity.Error). */ constructor(range: Range, message: string, severity?: DiagnosticSeverity); } /** * Represents a type which can release resources, such * as event listening or a timer. */ export class Disposable { /** * Combine many disposable-likes into one. Use this method * when having objects with a dispose function which are not * instances of Disposable. * * @param disposableLikes Objects that have at least a `dispose`-function member. * @return Returns a new disposable which, upon dispose, will * dispose all provided disposables. */ static from(...disposableLikes: { dispose: () => any }[]): Disposable; /** * Creates a new Disposable calling the provided function * on dispose. * @param callOnDispose Function that disposes something. */ constructor(callOnDispose: () => void); /** * Dispose this object. */ dispose(): any; } /** * Represents an extension. * * To get an instance of an `Extension` use [getExtension](#extensions.getExtension). */ export interface Extension<T> { /** * The canonical extension identifier in the form of: `publisher.name`. */ readonly id: string; /** * The absolute file path of the directory containing this extension. */ readonly extensionPath: string; /** * `true` if the extension has been activated. */ readonly isActive: boolean; /** * The parsed contents of the extension's package.json. */ readonly packageJSON: any; /** * The extension kind describes if an extension runs where the UI runs * or if an extension runs where the remote extension host runs. The extension kind * if defined in the `package.json` file of extensions but can also be refined * via the the `remote.extensionKind`-setting. When no remote extension host exists, * the value is [`ExtensionKind.UI`](#ExtensionKind.UI). */ extensionKind: ExtensionKind; /** * The public API exported by this extension. It is an invalid action * to access this field before this extension has been activated. */ readonly exports: T; /** * Activates this extension and returns its public API. * * @return A promise that will resolve when this extension has been activated. */ activate(): Thenable<T>; } /** * A memento represents a storage utility. It can store and retrieve * values. */ export interface Memento { /** * Return a value. * * @param key A string. * @return The stored value or `undefined`. */ get<T>(key: string): T | undefined; /** * Return a value. * * @param key A string. * @param defaultValue A value that should be returned when there is no * value (`undefined`) with the given key. * @return The stored value or the defaultValue. */ get<T>(key: string, defaultValue: T): T; /** * Store a value. The value must be JSON-stringifyable. * * @param key A string. * @param value A value. MUST not contain cyclic references. */ update(key: string, value: any): Thenable<void>; /** * VS Code Proposal API, maybe remove on latest version. * #region https://github.com/microsoft/vscode/issues/87110 * * The stored keys. */ readonly keys: readonly string[]; } export interface Terminal { /** * The name of the terminal. */ readonly name: string; /** * The process ID of the shell process. */ readonly processId: Thenable<number>; /** * Send text to the terminal. The text is written to the stdin of the underlying pty process * (shell) of the terminal. * * @param text The text to send. * @param addNewLine Whether to add a new line to the text being sent, this is normally * required to run a command in the terminal. The character(s) added are \n or \r\n * depending on the platform. This defaults to `true`. */ sendText(text: string, addNewLine?: boolean): void; /** * Show the terminal panel and reveal this terminal in the UI. * * @param preserveFocus When `true` the terminal will not take focus. */ show(preserveFocus?: boolean): void; /** * Hide the terminal panel if this terminal is currently showing. */ hide(): void; /** * Dispose and free associated resources. */ dispose(): void; } /** * Represents the state of a {@link Terminal}. */ export interface TerminalState { /** * Whether the {@link Terminal} has been interacted with. Interaction means that the * terminal has sent data to the process which depending on the terminal's _mode_. By * default input is sent when a key is pressed or when a command or extension sends text, * but based on the terminal's mode it can also happen on: * * - a pointer click event * - a pointer scroll event * - a pointer move event * - terminal focus in/out * * For more information on events that can send data see "DEC Private Mode Set (DECSET)" on * https://invisible-island.net/xterm/ctlseqs/ctlseqs.html */ readonly isInteractedWith: boolean; } export interface env {} /** * A memento represents a storage utility. It can store and retrieve * values. */ export interface Memento { /** * Return a value. * * @param key A string. * @return The stored value or `undefined`. */ get<T>(key: string): T | undefined; /** * Return a value. * * @param key A string. * @param defaultValue A value that should be returned when there is no * value (`undefined`) with the given key. * @return The stored value or the defaultValue. */ get<T>(key: string, defaultValue: T): T; /** * Store a value. The value must be JSON-stringifyable. * * @param key A string. * @param value A value. MUST not contain cyclic references. */ update(key: string, value: any): Thenable<void>; } /** * A file system watcher notifies about changes to files and folders * on disk. * * To get an instance of a `FileSystemWatcher` use * [createFileSystemWatcher](#workspace.createFileSystemWatcher). */ export interface FileSystemWatcher extends Disposable { /** * true if this file system watcher has been created such that * it ignores creation file system events. */ ignoreCreateEvents: boolean; /** * true if this file system watcher has been created such that * it ignores change file system events. */ ignoreChangeEvents: boolean; /** * true if this file system watcher has been created such that * it ignores delete file system events. */ ignoreDeleteEvents: boolean; /** * An event which fires on file/folder creation. */ onDidCreate: Event<Uri>; /** * An event which fires on file/folder change. */ onDidChange: Event<Uri>; /** * An event which fires on file/folder deletion. */ onDidDelete: Event<Uri>; } /** * Enumeration of file types. The types `File` and `Directory` can also be * a symbolic links, in that use `FileType.File | FileType.SymbolicLink` and * `FileType.Directory | FileType.SymbolicLink`. */ export enum FileType { /** * The file type is unknown. */ Unknown = 0, /** * A regular file. */ File = 1, /** * A directory. */ Directory = 2, /** * A symbolic link to a file. */ SymbolicLink = 64, } /** * The `FileStat`-type represents metadata about a file */ export interface FileStat { /** * The type of the file, e.g. is a regular file, a directory, or symbolic link * to a file. */ type: FileType; /** * The creation timestamp in milliseconds elapsed since January 1, 1970 00:00:00 UTC. */ ctime: number; /** * The modification timestamp in milliseconds elapsed since January 1, 1970 00:00:00 UTC. */ mtime: number; /** * The size in bytes. */ size: number; } /** * A type that filesystem providers should use to signal errors. * * This class has factory methods for common error-cases, like `FileNotFound` when * a file or folder doesn't exist, use them like so: `throw vscode.FileSystemError.FileNotFound(someUri);` */ export class FileSystemError extends Error { /** * Create an error to signal that a file or folder wasn't found. * @param messageOrUri Message or uri. */ static FileNotFound(messageOrUri?: string | Uri): FileSystemError; /** * Create an error to signal that a file or folder already exists, e.g. when * creating but not overwriting a file. * @param messageOrUri Message or uri. */ static FileExists(messageOrUri?: string | Uri): FileSystemError; /** * Create an error to signal that a file is not a folder. * @param messageOrUri Message or uri. */ static FileNotADirectory(messageOrUri?: string | Uri): FileSystemError; /** * Create an error to signal that a file is a folder. * @param messageOrUri Message or uri. */ static FileIsADirectory(messageOrUri?: string | Uri): FileSystemError; /** * Create an error to signal that an operation lacks required permissions. * @param messageOrUri Message or uri. */ static NoPermissions(messageOrUri?: string | Uri): FileSystemError; /** * Create an error to signal that the file system is unavailable or too busy to * complete a request. * @param messageOrUri Message or uri. */ static Unavailable(messageOrUri?: string | Uri): FileSystemError; /** * Creates a new filesystem error. * * @param messageOrUri Message or uri. */ constructor(messageOrUri?: string | Uri); } /** * Enumeration of file change types. */ export enum FileChangeType { /** * The contents or metadata of a file have changed. */ Changed = 1, /** * A file has been created. */ Created = 2, /** * A file has been deleted. */ Deleted = 3, } /** * The event filesystem providers must use to signal a file change. */ export interface FileChangeEvent { /** * The type of change. */ readonly type: FileChangeType; /** * The uri of the file that has changed. */ readonly uri: Uri; } /** * The filesystem provider defines what the editor needs to read, write, discover, * and to manage files and folders. It allows extensions to serve files from remote places, * like ftp-servers, and to seamlessly integrate those into the editor. * * * *Note 1:* The filesystem provider API works with [uris](#Uri) and assumes hierarchical * paths, e.g. `foo:/my/path` is a child of `foo:/my/` and a parent of `foo:/my/path/deeper`. * * *Note 2:* There is an activation event `onFileSystem:<scheme>` that fires when a file * or folder is being accessed. * * *Note 3:* The word 'file' is often used to denote all [kinds](#FileType) of files, e.g. * folders, symbolic links, and regular files. */ export interface FileSystemProvider { /** * An event to signal that a resource has been created, changed, or deleted. This * event should fire for resources that are being [watched](#FileSystemProvider.watch) * by clients of this provider. */ readonly onDidChangeFile: Event<FileChangeEvent[]>; /** * Subscribe to events in the file or folder denoted by `uri`. * * The editor will call this function for files and folders. In the latter case, the * options differ from defaults, e.g. what files/folders to exclude from watching * and if subfolders, sub-subfolder, etc. should be watched (`recursive`). * * @param uri The uri of the file to be watched. * @param options Configures the watch. * @returns A disposable that tells the provider to stop watching the `uri`. */ watch(uri: Uri, options: { recursive: boolean; excludes: string[] }): Disposable; /** * Retrieve metadata about a file. * * Note that the metadata for symbolic links should be the metadata of the file they refer to. * Still, the [SymbolicLink](#FileType.SymbolicLink)-type must be used in addition to the actual type, e.g. * `FileType.SymbolicLink | FileType.Directory`. * * @param uri The uri of the file to retrieve metadata about. * @return The file metadata about the file. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `uri` doesn't exist. */ stat(uri: Uri): FileStat | Thenable<FileStat>; /** * Retrieve all entries of a [directory](#FileType.Directory). * * @param uri The uri of the folder. * @return An array of name/type-tuples or a thenable that resolves to such. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `uri` doesn't exist. */ readDirectory(uri: Uri): [string, FileType][] | Thenable<[string, FileType][]>; /** * Create a new directory (Note, that new files are created via `write`-calls). * * @param uri The uri of the new folder. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when the parent of `uri` doesn't exist, e.g. no mkdirp-logic required. * @throws [`FileExists`](#FileSystemError.FileExists) when `uri` already exists. * @throws [`NoPermissions`](#FileSystemError.NoPermissions) when permissions aren't sufficient. */ createDirectory(uri: Uri): void | Thenable<void>; /** * Read the entire contents of a file. * * @param uri The uri of the file. * @return An array of bytes or a thenable that resolves to such. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `uri` doesn't exist. */ readFile(uri: Uri): Uint8Array | Thenable<Uint8Array>; /** * Write data to a file, replacing its entire contents. * * @param uri The uri of the file. * @param content The new content of the file. * @param options Defines if missing files should or must be created. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `uri` doesn't exist and `create` is not set. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when the parent of `uri` doesn't exist and `create` is set, e.g. no mkdirp-logic required. * @throws [`FileExists`](#FileSystemError.FileExists) when `uri` already exists, `create` is set but `overwrite` is not set. * @throws [`NoPermissions`](#FileSystemError.NoPermissions) when permissions aren't sufficient. */ writeFile(uri: Uri, content: Uint8Array, options: { create: boolean; overwrite: boolean }): void | Thenable<void>; /** * Delete a file. * * @param uri The resource that is to be deleted. * @param options Defines if deletion of folders is recursive. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `uri` doesn't exist. * @throws [`NoPermissions`](#FileSystemError.NoPermissions) when permissions aren't sufficient. */ delete(uri: Uri, options: { recursive: boolean }): void | Thenable<void>; /** * Rename a file or folder. * * @param oldUri The existing file. * @param newUri The new location. * @param options Defines if existing files should be overwritten. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `oldUri` doesn't exist. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when parent of `newUri` doesn't exist, e.g. no mkdirp-logic required. * @throws [`FileExists`](#FileSystemError.FileExists) when `newUri` exists and when the `overwrite` option is not `true`. * @throws [`NoPermissions`](#FileSystemError.NoPermissions) when permissions aren't sufficient. */ rename(oldUri: Uri, newUri: Uri, options: { overwrite: boolean }): void | Thenable<void>; /** * Copy files or folders. Implementing this function is optional but it will speedup * the copy operation. * * @param source The existing file. * @param destination The destination location. * @param options Defines if existing files should be overwritten. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `source` doesn't exist. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when parent of `destination` doesn't exist, e.g. no mkdirp-logic required. * @throws [`FileExists`](#FileSystemError.FileExists) when `destination` exists and when the `overwrite` option is not `true`. * @throws [`NoPermissions`](#FileSystemError.NoPermissions) when permissions aren't sufficient. */ copy?(source: Uri, destination: Uri, options: { overwrite: boolean }): void | Thenable<void>; } export interface FileSystem { stat(uri: Uri): Thenable<FileStat>; readDirectory(uri: Uri): Thenable<[string, FileType][]>; createDirectory(uri: Uri): Thenable<void>; readFile(uri: Uri): Thenable<Uint8Array>; writeFile(uri: Uri, content: Uint8Array, options?: { create: boolean; overwrite: boolean }): Thenable<void>; delete(uri: Uri, options?: { recursive: boolean }): Thenable<void>; rename(source: Uri, target: Uri, options?: { overwrite: boolean }): Thenable<void>; copy(source: Uri, target: Uri, options?: { overwrite: boolean }): Thenable<void>; } /** * Represents the configuration. It is a merged view of * * - Default configuration * - Global configuration * - Workspace configuration (if available) * - Workspace folder configuration of the requested resource (if available) * * *Global configuration* comes from User Settings and shadows Defaults. * * *Workspace configuration* comes from Workspace Settings and shadows Global configuration. * * *Workspace Folder configuration* comes from `.vscode` folder under one of the [workspace folders](#workspace.workspaceFolders). * * *Note:* Workspace and Workspace Folder configurations contains `launch` and `tasks` settings. Their basename will be * part of the section identifier. The following snippets shows how to retrieve all configurations * from `launch.json`: * * ```ts * // launch.json configuration * const config = workspace.getConfiguration('launch', vscode.window.activeTextEditor.document.uri); * * // retrieve values * const values = config.get('configurations'); * ``` * * Refer to [Settings](https://code.visualstudio.com/docs/getstarted/settings) for more information. */ /** * An output channel is a container for readonly textual information. * * To get an instance of an `OutputChannel` use * [createOutputChannel](#window.createOutputChannel). */ /** * Defines a generalized way of reporting progress updates. */ export interface Progress<T> { /** * Report a progress update. * @param value A progress item, like a message and/or an * report on how much work finished */ report(value: T): void; } /** * A location in the editor at which progress information can be shown. It depends on the * location how progress is visually represented. */ export enum ProgressLocation { /** * Show progress for the source control viewlet, as overlay for the icon and as progress bar * inside the viewlet (when visible). Neither supports cancellation nor discrete progress. */ SourceControl = 1, /** * Show progress in the status bar of the editor. Neither supports cancellation nor discrete progress. */ Window = 10, /** * Show progress as notification with an optional cancel button. Supports to show infinite and discrete progress. */ Notification = 15, } /** * Value-object describing where and how progress should show. */ export interface ProgressOptions { /** * The location at which progress should show. */ location: ProgressLocation; /** * A human-readable string which will be used to describe the * operation. */ title?: string; /** * Controls if a cancel button should show to allow the user to * cancel the long running operation. Note that currently only * `ProgressLocation.Notification` is supporting to show a cancel * button. */ cancellable?: boolean; } /** * A reference to one of the workbench colors as defined in https://code.visualstudio.com/docs/getstarted/theme-color-reference. * Using a theme color is preferred over a custom color as it gives theme authors and users the possibility to change the color. */ export class ThemeColor { /** * Creates a reference to a theme color. * @param id of the color. The available colors are listed in https://code.visualstudio.com/docs/getstarted/theme-color-reference. */ constructor(id: string); } /** * A reference to a named icon. Currently, [File](#ThemeIcon.File), [Folder](#ThemeIcon.Folder), * and [ThemeIcon ids](https://code.visualstudio.com/api/references/icons-in-labels#icon-listing) are supported. * Using a theme icon is preferred over a custom icon as it gives product theme authors the possibility to change the icons. * * *Note* that theme icons can also be rendered inside labels and descriptions. Places that support theme icons spell this out * and they use the `$(<name>)`-syntax, for instance `quickPick.label = "Hello World $(globe)"`. */ export class ThemeIcon { /** * Reference to an icon representing a file. The icon is taken from the current file icon theme or a placeholder icon is used. */ static readonly File: ThemeIcon; /** * Reference to an icon representing a folder. The icon is taken from the current file icon theme or a placeholder icon is used. */ static readonly Folder: ThemeIcon; /** * The id of the icon. The available icons are listed in https://code.visualstudio.com/api/references/icons-in-labels#icon-listing. */ readonly id: string; /** * The optional ThemeColor of the icon. The color is currently only used in [TreeItem](#TreeItem). */ readonly color?: ThemeColor; /** * Creates a reference to a theme icon. * @param id id of the icon. The available icons are listed in https://code.visualstudio.com/api/references/icons-in-labels#icon-listing. * @param color optional `ThemeColor` for the icon. The color is currently only used in [TreeItem](#TreeItem). */ constructor(id: string, color?: ThemeColor); } /** * Represents theme specific rendering styles for a [text editor decoration](#TextEditorDecorationType). */ export interface ThemableDecorationRenderOptions { /** * Background color of the decoration. Use rgba() and define transparent background colors to play well with other decorations. * Alternatively a color from the color registry can be [referenced](#ThemeColor). */ backgroundColor?: string | ThemeColor; /** * CSS styling property that will be applied to text enclosed by a decoration. */ outline?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. * Better use 'outline' for setting one or more of the individual outline properties. */ outlineColor?: string | ThemeColor; /** * CSS styling property that will be applied to text enclosed by a decoration. * Better use 'outline' for setting one or more of the individual outline properties. */ outlineStyle?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. * Better use 'outline' for setting one or more of the individual outline properties. */ outlineWidth?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. */ border?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. * Better use 'border' for setting one or more of the individual border properties. */ borderColor?: string | ThemeColor; /** * CSS styling property that will be applied to text enclosed by a decoration. * Better use 'border' for setting one or more of the individual border properties. */ borderRadius?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. * Better use 'border' for setting one or more of the individual border properties. */ borderSpacing?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. * Better use 'border' for setting one or more of the individual border properties. */ borderStyle?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. * Better use 'border' for setting one or more of the individual border properties. */ borderWidth?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. */ fontStyle?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. */ fontWeight?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. */ textDecoration?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. */ cursor?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. */ color?: string | ThemeColor; /** * CSS styling property that will be applied to text enclosed by a decoration. */ opacity?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. */ letterSpacing?: string; /** * An **absolute path** or an URI to an image to be rendered in the gutter. */ gutterIconPath?: string | Uri; /** * Specifies the size of the gutter icon. * Available values are 'auto', 'contain', 'cover' and any percentage value. * For further information: https://msdn.microsoft.com/en-us/library/jj127316(v=vs.85).aspx */ gutterIconSize?: string; /** * The color of the decoration in the overview ruler. Use rgba() and define transparent colors to play well with other decorations. */ overviewRulerColor?: string | ThemeColor; /** * Defines the rendering options of the attachment that is inserted before the decorated text. */ before?: ThemableDecorationAttachmentRenderOptions; /** * Defines the rendering options of the attachment that is inserted after the decorated text. */ after?: ThemableDecorationAttachmentRenderOptions; } export interface ThemableDecorationAttachmentRenderOptions { /** * Defines a text content that is shown in the attachment. Either an icon or a text can be shown, but not both. */ contentText?: string; /** * An **absolute path** or an URI to an image to be rendered in the attachment. Either an icon * or a text can be shown, but not both. */ contentIconPath?: string | Uri; /** * CSS styling property that will be applied to the decoration attachment. */ border?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. */ borderColor?: string | ThemeColor; /** * CSS styling property that will be applied to the decoration attachment. */ fontStyle?: string; /** * CSS styling property that will be applied to the decoration attachment. */ fontWeight?: string; /** * CSS styling property that will be applied to the decoration attachment. */ textDecoration?: string; /** * CSS styling property that will be applied to the decoration attachment. */ color?: string | ThemeColor; /** * CSS styling property that will be applied to the decoration attachment. */ backgroundColor?: string | ThemeColor; /** * CSS styling property that will be applied to the decoration attachment. */ margin?: string; /** * CSS styling property that will be applied to the decoration attachment. */ width?: string; /** * CSS styling property that will be applied to the decoration attachment. */ height?: string; } /** * Represents a color in RGBA space. */ export class Color { /** * The red component of this color in the range [0-1]. */ readonly red: number; /** * The green component of this color in the range [0-1]. */ readonly green: number; /** * The blue component of this color in the range [0-1]. */ readonly blue: number; /** * The alpha component of this color in the range [0-1]. */ readonly alpha: number; /** * Creates a new color instance. * * @param red The red component. * @param green The green component. * @param blue The blue component. * @param alpha The alpha component. */ constructor(red: number, green: number, blue: number, alpha: number); } /** * Represents a color range from a document. */ export class ColorInformation { /** * The range in the document where this color appears. */ range: Range; /** * The actual color value for this color range. */ color: Color; /** * Creates a new color range. * * @param range The range the color appears in. Must not be empty. * @param color The value of the color. * @param format The format in which this color is currently formatted. */ constructor(range: Range, color: Color); } /** * A color presentation object describes how a [`color`](#Color) should be represented as text and what * edits are required to refer to it from source code. * * For some languages one color can have multiple presentations, e.g. css can represent the color red with * the constant `Red`, the hex-value `#ff0000`, or in rgba and hsla forms. In csharp other representations * apply, e.g. `System.Drawing.Color.Red`. */ export class ColorPresentation { /** * The label of this color presentation. It will be shown on the color * picker header. By default this is also the text that is inserted when selecting * this color presentation. */ label: string; /** * An [edit](#TextEdit) which is applied to a document when selecting * this presentation for the color. When `falsy` the [label](#ColorPresentation.label) * is used. */ textEdit?: TextEdit; /** * An optional array of additional [text edits](#TextEdit) that are applied when * selecting this color presentation. Edits must not overlap with the main [edit](#ColorPresentation.textEdit) nor with themselves. */ additionalTextEdits?: TextEdit[]; /** * Creates a new color presentation. * * @param label The label of this color presentation. */ constructor(label: string); } /** * The document color provider defines the contract between extensions and feature of * picking and modifying colors in the editor. */ export interface DocumentColorProvider { /** * Provide colors for the given document. * * @param document The document in which the command was invoked. * @param token A cancellation token. * @return An array of [color information](#ColorInformation) or a thenable that resolves to such. The lack of a result * can be signaled by returning `undefined`, `null`, or an empty array. */ provideDocumentColors(document: TextDocument, token: CancellationToken): ProviderResult<ColorInformation[]>; /** * Provide [representations](#ColorPresentation) for a color. * * @param color The color to show and insert. * @param context A context object with additional information * @param token A cancellation token. * @return An array of color presentations or a thenable that resolves to such. The lack of a result * can be signaled by returning `undefined`, `null`, or an empty array. */ provideColorPresentations( color: Color, context: { document: TextDocument; range: Range }, token: CancellationToken, ): ProviderResult<ColorPresentation[]>; } }
the_stack
import { FastifyInstance } from 'fastify'; import StatusCodes from 'http-status-codes'; import { Pool } from 'pg'; import { CARDANO, ASSET_NAME_LENGTH, POLICY_ID_LENGTH } from '../../../src/server/utils/constants'; import { latestBlockIdentifier, coinsWithSpecifiedTokens, coinsWithEmptyMa, allCoinsOfAddr1q8, coinsWithEmptyNameToken } from '../fixture-data'; import { setupDatabase, setupServer } from '../utils/test-utils'; const generatePayload = ( blockchain: string, network: string, address: string, currencies?: Components.Schemas.Currency[] ) => ({ // eslint-disable-next-line camelcase network_identifier: { blockchain, network }, account_identifier: { address }, currencies }); const ACCOUNT_COINS_ENDPOINT = '/account/coins'; describe('/account/coins endpoint', () => { let database: Pool; let server: FastifyInstance; beforeAll(async () => { database = setupDatabase(); server = setupServer(database); }); afterAll(async () => { await database.end(); }); test('should only consider coins till latest block', async () => { const response = await server.inject({ method: 'post', url: ACCOUNT_COINS_ENDPOINT, payload: generatePayload( CARDANO, 'mainnet', 'DdzFFzCqrhsdufpFxByLTQmktKJnTrudktaHq1nK2MAEDLXjz5kbRcr5prHi9gHb6m8pTvhgK6JbFDZA1LTiTcP6g8KuPSF1TfKP8ewp' ) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json()).toEqual({ block_identifier: latestBlockIdentifier, coins: [ { coin_identifier: { identifier: '4bcf79c0c2967986749fd0ae03f5b54a712d51b35672a3d974707c060c4d8dac:1' }, amount: { value: '10509579714', currency: { decimals: 6, symbol: 'ADA' } } }, { coin_identifier: { identifier: 'bcc57134d1bd588b00f40142f0fdc17db5f35047e3196cdf26aa7319524c0014:1' }, amount: { value: '999800000', currency: { decimals: 6, symbol: 'ADA' } } } ] }); }); test('should return empty if address doesnt exist', async () => { const response = await server.inject({ method: 'post', url: ACCOUNT_COINS_ENDPOINT, payload: generatePayload(CARDANO, 'mainnet', 'fakeAddress') }); expect(response.statusCode).toEqual(StatusCodes.INTERNAL_SERVER_ERROR); expect(response.json()).toEqual({ code: 4015, message: 'Provided address is invalid', retriable: true, details: { message: 'fakeAddress' } }); }); test('should have no coins for an account with zero balance', async () => { const response = await server.inject({ method: 'post', url: ACCOUNT_COINS_ENDPOINT, payload: generatePayload( CARDANO, 'mainnet', 'DdzFFzCqrhsszHTvbjTmYje5hehGbadkT6WgWbaqCy5XNxNttsPNF13eAjjBHYT7JaLJz2XVxiucam1EvwBRPSTiCrT4TNCBas4hfzic' ) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json()).toEqual({ block_identifier: latestBlockIdentifier, coins: [] }); }); test('should no return coins for stake accounts', async () => { const response = await server.inject({ method: 'post', url: ACCOUNT_COINS_ENDPOINT, payload: generatePayload(CARDANO, 'mainnet', 'stake1uyqq2a22arunrft3k9ehqc7yjpxtxjmvgndae80xw89mwyge9skyp') }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json()).toEqual({ block_identifier: latestBlockIdentifier, coins: [] }); }); test('should return coins with multi assets currencies', async () => { const response = await server.inject({ method: 'post', url: ACCOUNT_COINS_ENDPOINT, payload: generatePayload( CARDANO, 'mainnet', 'addr1q8a3rmnxnp986vy3tzz3vd3mdk9lmjnnw6w68uaaa8g4t4u5lddnau28pea3mdy84uls504lsc7uk9zyzmqtcxyy7jyqqjm7sg' ) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json()).toEqual({ block_identifier: latestBlockIdentifier, coins: allCoinsOfAddr1q8 }); }); test('should return coins for ma with empty name', async () => { const response = await server.inject({ method: 'post', url: ACCOUNT_COINS_ENDPOINT, payload: generatePayload( CARDANO, 'mainnet', 'addr1qx5d5d8aqn0970nl3km63za5q87fwh2alm79zwuxvh6rh9lg96s8las2lwer5psc7yr59kmafzkz2l5jz4dyxghs7pvqj24sft' ) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json()).toEqual({ block_identifier: latestBlockIdentifier, coins: coinsWithEmptyMa }); }); test('should return coins for one specified currency', async () => { const response = await server.inject({ method: 'post', url: ACCOUNT_COINS_ENDPOINT, payload: generatePayload( CARDANO, 'mainnet', 'addr1q8a3rmnxnp986vy3tzz3vd3mdk9lmjnnw6w68uaaa8g4t4u5lddnau28pea3mdy84uls504lsc7uk9zyzmqtcxyy7jyqqjm7sg', [ { decimals: 0, symbol: '46555a5a', metadata: { policyId: 'cebbcd14c5b11ca83d7ef93b02acfc0bcb372066bdee259f6cd9ae6c' } } ] ) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json()).toEqual({ block_identifier: latestBlockIdentifier, coins: [ { coin_identifier: { identifier: '038e318f0deef63f44be78a8224c06d3faae683f48eb0215a448ab13fd1eb540:0' }, amount: { value: '2000000', currency: { decimals: 6, symbol: 'ADA' } }, metadata: { '038e318f0deef63f44be78a8224c06d3faae683f48eb0215a448ab13fd1eb540:0': [ { policyId: 'cebbcd14c5b11ca83d7ef93b02acfc0bcb372066bdee259f6cd9ae6c', tokens: [ { value: '1000000', currency: { symbol: '46555a5a', decimals: 0, metadata: { policyId: 'cebbcd14c5b11ca83d7ef93b02acfc0bcb372066bdee259f6cd9ae6c' } } } ] } ] } } ] }); }); test('should return coins for multiple specified currencies', async () => { const response = await server.inject({ method: 'post', url: ACCOUNT_COINS_ENDPOINT, payload: generatePayload( CARDANO, 'mainnet', 'addr1q8a3rmnxnp986vy3tzz3vd3mdk9lmjnnw6w68uaaa8g4t4u5lddnau28pea3mdy84uls504lsc7uk9zyzmqtcxyy7jyqqjm7sg', [ { decimals: 0, symbol: '46555a5a', metadata: { policyId: 'cebbcd14c5b11ca83d7ef93b02acfc0bcb372066bdee259f6cd9ae6c' } }, { decimals: 0, symbol: '4f47', metadata: { policyId: '818c4c891e543a4d9487b6c18e8b7ed7f0f0870158c45f94e547e7b1' } } ] ) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json()).toEqual({ block_identifier: latestBlockIdentifier, coins: coinsWithSpecifiedTokens }); }); test('should return all coins when ADA is specified as currency', async () => { const response = await server.inject({ method: 'post', url: ACCOUNT_COINS_ENDPOINT, payload: generatePayload( CARDANO, 'mainnet', 'addr1q8a3rmnxnp986vy3tzz3vd3mdk9lmjnnw6w68uaaa8g4t4u5lddnau28pea3mdy84uls504lsc7uk9zyzmqtcxyy7jyqqjm7sg', [ { decimals: 6, symbol: 'ADA' } ] ) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json()).toEqual({ block_identifier: latestBlockIdentifier, coins: allCoinsOfAddr1q8 }); }); test('should return coins for multi asset currency with empty name', async () => { const response = await server.inject({ method: 'post', url: ACCOUNT_COINS_ENDPOINT, payload: generatePayload( CARDANO, 'mainnet', 'addr1qx5d5d8aqn0970nl3km63za5q87fwh2alm79zwuxvh6rh9lg96s8las2lwer5psc7yr59kmafzkz2l5jz4dyxghs7pvqj24sft', [ { decimals: 0, symbol: '\\x', metadata: { policyId: '9b9ddbada8dc9cd08509ed660d5b3a65da8f36178def7ced99fa0333' } } ] ) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json()).toEqual({ block_identifier: latestBlockIdentifier, coins: coinsWithEmptyNameToken }); }); test('should fail when querying for a currency with non hex string symbol', async () => { const invalidSymbol = 'thisIsANonHexString'; const response = await server.inject({ method: 'post', url: ACCOUNT_COINS_ENDPOINT, payload: generatePayload(CARDANO, 'mainnet', 'addr_test1vre2sc6w0zftnhselly9fd6kqqnmfmklful9zcmdh92mewszqs66y', [ { decimals: 0, symbol: invalidSymbol, metadata: { policyId: '181aace621eea2b6cb367adb5000d516fa785087bad20308c072517e' } } ]) }); expect(response.statusCode).toEqual(StatusCodes.INTERNAL_SERVER_ERROR); expect(response.json()).toEqual({ code: 4024, message: 'Invalid token name', retriable: false, details: { message: 'Given name is thisIsANonHexString' } }); }); test('should fail when querying for a currency with a symbol longer than expected', async () => { const invalidSymbol = new Array(ASSET_NAME_LENGTH + 2).join('0'); const response = await server.inject({ method: 'post', url: ACCOUNT_COINS_ENDPOINT, payload: generatePayload(CARDANO, 'mainnet', 'addr_test1vre2sc6w0zftnhselly9fd6kqqnmfmklful9zcmdh92mewszqs66y', [ { decimals: 0, symbol: invalidSymbol, metadata: { policyId: '181aace621eea2b6cb367adb5000d516fa785087bad20308c072517e' } } ]) }); expect(response.statusCode).toEqual(StatusCodes.INTERNAL_SERVER_ERROR); expect(response.json()).toEqual({ code: 4024, message: 'Invalid token name', retriable: false, details: { message: 'Given name is 00000000000000000000000000000000000000000000000000000000000000000' } }); }); test('should fail when querying for a currency with a policy id longer than expected', async () => { const invalidPolicy = new Array(POLICY_ID_LENGTH + 1).join('w'); const response = await server.inject({ method: 'post', url: ACCOUNT_COINS_ENDPOINT, payload: generatePayload(CARDANO, 'mainnet', 'addr_test1vre2sc6w0zftnhselly9fd6kqqnmfmklful9zcmdh92mewszqs66y', [ { decimals: 0, symbol: '486173414e616d65', metadata: { policyId: invalidPolicy } } ]) }); expect(response.statusCode).toEqual(StatusCodes.INTERNAL_SERVER_ERROR); expect(response.json()).toEqual({ code: 4023, message: 'Invalid policy id', retriable: false, details: { message: 'Given policy id is wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww' } }); }); test('should fail when querying for a currency with a non hex policy id', async () => { const invalidPolicy = 'thisIsANonHexString'; const response = await server.inject({ method: 'post', url: ACCOUNT_COINS_ENDPOINT, payload: generatePayload(CARDANO, 'mainnet', 'addr_test1vre2sc6w0zftnhselly9fd6kqqnmfmklful9zcmdh92mewszqs66y', [ { decimals: 0, symbol: '486173414e616d65', metadata: { policyId: invalidPolicy } } ]) }); expect(response.statusCode).toEqual(StatusCodes.INTERNAL_SERVER_ERROR); expect(response.json()).toEqual({ code: 4023, message: 'Invalid policy id', retriable: false, details: { message: 'Given policy id is thisIsANonHexString' } }); }); });
the_stack
import * as _ from 'lodash'; import { Address } from 'set-protocol-utils'; import { BigNumber } from 'bignumber.js'; import { UpdatableOracleMockContract } from 'set-protocol-oracles'; import { CoreMockContract, LinearAuctionLiquidatorContract, OracleWhiteListContract, RebalanceAuctionModuleContract, SetTokenContract, SetTokenFactoryContract, StandardTokenMockContract, TransferProxyContract, VaultContract, RebalancingSetTokenV3Contract, RebalancingSetTokenV3FactoryContract, WhiteListContract, FixedFeeCalculatorContract, } from '../contracts'; import { Blockchain } from '../blockchain'; import { ether } from '../units'; import { ONE_HOUR_IN_SECONDS } from '../constants'; import { getWeb3 } from '../web3Helper'; import { CoreHelper } from './coreHelper'; import { ERC20Helper } from './erc20Helper'; import { OracleHelper } from 'set-protocol-oracles'; import { FeeCalculatorHelper } from './feeCalculatorHelper'; import { LiquidatorHelper } from './liquidatorHelper'; import { ValuationHelper } from './valuationHelper'; const web3 = getWeb3(); const blockchain = new Blockchain(web3); export interface BaseSetConfig { set1Components?: Address[]; set2Components?: Address[]; set3Components?: Address[]; set1Units?: BigNumber[]; set2Units?: BigNumber[]; set3Units?: BigNumber[]; set1NaturalUnit?: BigNumber; set2NaturalUnit?: BigNumber; set3NaturalUnit?: BigNumber; } export interface PriceUpdate { component1Price?: BigNumber; component2Price?: BigNumber; component3Price?: BigNumber; } export interface ComponentConfig { component1Price?: BigNumber; component2Price?: BigNumber; component3Price?: BigNumber; component1Decimals?: number; component2Decimals?: number; component3Decimals?: number; } export class RebalanceTestSetup { private _contractOwnerAddress: Address; private _coreHelper: CoreHelper; private _erc20Helper: ERC20Helper; private _oracleHelper: OracleHelper; private _liquidatorHelper: LiquidatorHelper; private _valuationHelper: ValuationHelper; private _feeCalculatorHelper: FeeCalculatorHelper; public core: CoreMockContract; public transferProxy: TransferProxyContract; public vault: VaultContract; public setTokenFactory: SetTokenFactoryContract; public rebalanceAuctionModule: RebalanceAuctionModuleContract; public rebalancingFactory: RebalancingSetTokenV3FactoryContract; public rebalancingComponentWhiteList: WhiteListContract; public liquidatorWhitelist: WhiteListContract; public fixedFeeCalculator: FixedFeeCalculatorContract; public feeCalculatorWhitelist: WhiteListContract; public linearAuctionLiquidator: LinearAuctionLiquidatorContract; public component1: StandardTokenMockContract; public component2: StandardTokenMockContract; public component3: StandardTokenMockContract; public component1Price: BigNumber; public component2Price: BigNumber; public component3Price: BigNumber; public set1: SetTokenContract; public set2: SetTokenContract; public set3: SetTokenContract; public set1Components: Address[]; public set2Components: Address[]; public set3Components: Address[]; public set1Units: BigNumber[]; public set2Units: BigNumber[]; public set3Units: BigNumber[]; public set1NaturalUnit: BigNumber; public set2NaturalUnit: BigNumber; public set3NaturalUnit: BigNumber; public component1Oracle: UpdatableOracleMockContract; public component2Oracle: UpdatableOracleMockContract; public component3Oracle: UpdatableOracleMockContract; public oracleWhiteList: OracleWhiteListContract; public rebalancingSetToken: RebalancingSetTokenV3Contract; constructor( contractOwnerAddress: Address, ) { this._contractOwnerAddress = contractOwnerAddress; this._coreHelper = new CoreHelper(this._contractOwnerAddress, this._contractOwnerAddress); this._erc20Helper = new ERC20Helper(this._contractOwnerAddress); this._oracleHelper = new OracleHelper(this._contractOwnerAddress); this._feeCalculatorHelper = new FeeCalculatorHelper(this._contractOwnerAddress); this._valuationHelper = new ValuationHelper( this._contractOwnerAddress, this._coreHelper, this._erc20Helper, this._oracleHelper ); this._liquidatorHelper = new LiquidatorHelper(this._contractOwnerAddress, this._erc20Helper, this._valuationHelper); } /* ============ Deployment ============ */ public async initialize( from: Address = this._contractOwnerAddress ): Promise<void> { await this.initializeCore(); await this.initializeComponents(); await this.initializeBaseSets(); } public async initializeBaseSets(config: BaseSetConfig = {}): Promise<void> { this.set1Components = config.set1Components || [this.component1.address, this.component2.address]; this.set1Units = config.set1Units || [new BigNumber(10 ** 13), new BigNumber(1280)]; this.set1NaturalUnit = config.set1NaturalUnit || new BigNumber(10 ** 13); this.set1 = await this._coreHelper.createSetTokenAsync( this.core, this.setTokenFactory.address, this.set1Components, this.set1Units, this.set1NaturalUnit, ); this.set2Components = config.set2Components || [this.component1.address, this.component2.address]; this.set2Units = config.set2Units || [new BigNumber(10 ** 13), new BigNumber(5120)]; this.set2NaturalUnit = config.set2NaturalUnit || new BigNumber(10 ** 13); this.set2 = await this._coreHelper.createSetTokenAsync( this.core, this.setTokenFactory.address, this.set2Components, this.set2Units, this.set2NaturalUnit, ); this.set3Components = config.set3Components || [this.component1.address, this.component3.address]; this.set3Units = config.set3Units || [new BigNumber(10 ** 13), new BigNumber(5120)]; this.set3NaturalUnit = config.set3NaturalUnit || new BigNumber(10 ** 13); this.set3 = await this._coreHelper.createSetTokenAsync( this.core, this.setTokenFactory.address, this.set3Components, this.set3Units, this.set3NaturalUnit, ); } public async initializeComponents(config: ComponentConfig = {}): Promise<void> { const component1Decimals = config.component1Decimals || 18; const component2Decimals = config.component2Decimals || 6; const component3Decimals = config.component3Decimals || 8; this.component1 = await this._erc20Helper.deployTokenAsync(this._contractOwnerAddress, component1Decimals); this.component2 = await this._erc20Helper.deployTokenAsync(this._contractOwnerAddress, component2Decimals); this.component3 = await this._erc20Helper.deployTokenAsync(this._contractOwnerAddress, component3Decimals); this.component1Price = config.component1Price || ether(128); this.component2Price = config.component2Price || ether(1); this.component3Price = config.component3Price || ether(7500); this.component1Oracle = await this._oracleHelper.deployUpdatableOracleMockAsync(this.component1Price); this.component2Oracle = await this._oracleHelper.deployUpdatableOracleMockAsync(this.component2Price); this.component3Oracle = await this._oracleHelper.deployUpdatableOracleMockAsync(this.component3Price); await this.oracleWhiteList.addTokenOraclePair.sendTransactionAsync( this.component1.address, this.component1Oracle.address, ); await this.oracleWhiteList.addTokenOraclePair.sendTransactionAsync( this.component2.address, this.component2Oracle.address, ); await this.oracleWhiteList.addTokenOraclePair.sendTransactionAsync( this.component3.address, this.component3Oracle.address, ); await this._coreHelper.addTokensToWhiteList( [this.component1.address, this.component2.address, this.component3.address], this.rebalancingComponentWhiteList, ); await this._erc20Helper.approveTransfersAsync( [this.component1, this.component2, this.component3], this.transferProxy.address ); } public async initializeCore( from: Address = this._contractOwnerAddress ): Promise<void> { this.transferProxy = await this._coreHelper.deployTransferProxyAsync(); this.vault = await this._coreHelper.deployVaultAsync(); this.core = await this._coreHelper.deployCoreMockAsync(this.transferProxy, this.vault); this.setTokenFactory = await this._coreHelper.deploySetTokenFactoryAsync(this.core.address); await this._coreHelper.setDefaultStateAndAuthorizationsAsync( this.core, this.vault, this.transferProxy, this.setTokenFactory, ); this.rebalanceAuctionModule = await this._coreHelper.deployRebalanceAuctionModuleAsync(this.core, this.vault); await this._coreHelper.addModuleAsync(this.core, this.rebalanceAuctionModule.address); this.rebalancingComponentWhiteList = await this._coreHelper.deployWhiteListAsync(); this.oracleWhiteList = await this._coreHelper.deployOracleWhiteListAsync(); this.liquidatorWhitelist = await this._coreHelper.deployWhiteListAsync(); this.feeCalculatorWhitelist = await this._coreHelper.deployWhiteListAsync(); this.rebalancingFactory = await this._coreHelper.deployRebalancingSetTokenV3FactoryAsync( this.core.address, this.rebalancingComponentWhiteList.address, this.liquidatorWhitelist.address, this.feeCalculatorWhitelist.address, ); await this._coreHelper.addFactoryAsync(this.core, this.rebalancingFactory); this.fixedFeeCalculator = await this._feeCalculatorHelper.deployFixedFeeCalculatorAsync(); await this._coreHelper.addAddressToWhiteList(this.fixedFeeCalculator.address, this.feeCalculatorWhitelist); // Hardcoding values for now const auctionPeriod = ONE_HOUR_IN_SECONDS.mul(4); const rangeStart = new BigNumber(1); // 10% below fair value const rangeEnd = new BigNumber(21); // 10% above fair value const name = 'liquidator'; this.linearAuctionLiquidator = await this._liquidatorHelper.deployLinearAuctionLiquidatorAsync( this.core.address, this.oracleWhiteList.address, auctionPeriod, rangeStart, rangeEnd, name, ); await this._coreHelper.addAddressToWhiteList(this.linearAuctionLiquidator.address, this.liquidatorWhitelist); console.log( 'Core: ' + this.core.address, 'TransferProxy: ' + this.transferProxy.address, 'Vault: ' + this.vault.address, 'SetTokenFactory: ' + this.setTokenFactory.address, 'RebalanceAuctionModule: ' + this.rebalanceAuctionModule.address, 'RebalancingComponentWhiteList: ' + this.rebalancingComponentWhiteList.address, 'OracleWhiteList: ' + this.oracleWhiteList.address, 'LiquidatorWhiteList: ' + this.liquidatorWhitelist.address, 'FeeCalculatorWhiteList: ' + this.feeCalculatorWhitelist.address, 'RebalancingFactory: ' + this.rebalancingFactory.address, 'FixedFeeCalculator: ' + this.fixedFeeCalculator.address, 'LinearAuctionLiquidator: ' + this.linearAuctionLiquidator.address ); } public setRebalancingSet( rebalancingSet: RebalancingSetTokenV3Contract ): void { this.rebalancingSetToken = rebalancingSet; } public async mintRebalancingSets( rebalancingSetQuantity: BigNumber, ): Promise<void> { const rebalancingNaturalUnit = await this.rebalancingSetToken.naturalUnit.callAsync(); const currentSet = await this.rebalancingSetToken.currentSet.callAsync(); const [currentSetUnit] = await this.rebalancingSetToken.getUnits.callAsync(); const curSetNaturalUnit = await this.set1.naturalUnit.callAsync(); const currentSetRequired = rebalancingSetQuantity .mul(currentSetUnit) .div(rebalancingNaturalUnit) .div(curSetNaturalUnit).round(0, 3) .mul(curSetNaturalUnit) .mul(2); // Ensure there is enough minted for safe measure // Issue currentSetToken await this.core.issue.sendTransactionAsync( currentSet, currentSetRequired, {from: this._contractOwnerAddress } ); const currentSetERC20Instance = await this._erc20Helper.getTokenInstanceAsync(currentSet); await this._erc20Helper.approveTransfersAsync([currentSetERC20Instance], this.transferProxy.address); // Use issued currentSetToken to issue rebalancingSetToken await this.core.issue.sendTransactionAsync(this.rebalancingSetToken.address, rebalancingSetQuantity); } public async approveComponentsToAddress(toApprove: Address): Promise<void> { await this._erc20Helper.approveTransfersAsync( [this.component1, this.component2, this.component3], toApprove ); } public async jumpTimeAndUpdateOracles( timeIncrease: BigNumber, newPrices: PriceUpdate, ): Promise<void> { await blockchain.increaseTimeAsync(timeIncrease); await blockchain.mineBlockAsync(); if (newPrices.component1Price) { await this.component1Oracle.updatePrice.sendTransactionAsync(newPrices.component1Price); } if (newPrices.component2Price) { await this.component2Oracle.updatePrice.sendTransactionAsync(newPrices.component2Price); } if (newPrices.component3Price) { await this.component3Oracle.updatePrice.sendTransactionAsync(newPrices.component3Price); } } }
the_stack
import { getNodeTag, MessageOrCCLogEntry, ZWaveError, ZWaveErrorCodes, } from "@zwave-js/core"; import { MessageHeaders } from "@zwave-js/serial"; import type { JSONObject } from "@zwave-js/shared"; import { num2hex, staticExtends } from "@zwave-js/shared"; import { entries } from "alcalzone-shared/objects"; import { isCommandClassContainer } from "../commandclass/ICommandClassContainer"; import type { Driver } from "../driver/Driver"; import { isNodeQuery } from "../node/INodeQuery"; import type { ZWaveNode } from "../node/Node"; import { FunctionType, MessagePriority, MessageType } from "./Constants"; type Constructable<T extends Message> = new ( driver: Driver, options?: MessageOptions, ) => T; export interface MessageDeserializationOptions { data: Buffer; } /** * Tests whether the given message constructor options contain a buffer for deserialization */ export function gotDeserializationOptions( options: Record<any, any> | undefined, ): options is MessageDeserializationOptions { return options != undefined && Buffer.isBuffer(options.data); } export interface MessageBaseOptions { callbackId?: number; } export interface MessageCreationOptions extends MessageBaseOptions { type?: MessageType; functionType?: FunctionType; expectedResponse?: FunctionType | typeof Message | ResponsePredicate; expectedCallback?: FunctionType | typeof Message | ResponsePredicate; payload?: Buffer; } export type MessageOptions = | MessageCreationOptions | MessageDeserializationOptions; /** * Represents a Z-Wave message for communication with the serial interface */ export class Message { public constructor(protected driver: Driver, options: MessageOptions = {}) { // decide which implementation we follow if (gotDeserializationOptions(options)) { // #1: deserialize from payload const payload = options.data; // SOF, length, type, commandId and checksum must be present if (!payload.length || payload.length < 5) { throw new ZWaveError( "Could not deserialize the message because it was truncated", ZWaveErrorCodes.PacketFormat_Truncated, ); } // the packet has to start with SOF if (payload[0] !== MessageHeaders.SOF) { throw new ZWaveError( "Could not deserialize the message because it does not start with SOF", ZWaveErrorCodes.PacketFormat_Invalid, ); } // check the length again, this time with the transmitted length const messageLength = Message.getMessageLength(payload); if (payload.length < messageLength) { throw new ZWaveError( "Could not deserialize the message because it was truncated", ZWaveErrorCodes.PacketFormat_Truncated, ); } // check the checksum const expectedChecksum = computeChecksum( payload.slice(0, messageLength), ); if (payload[messageLength - 1] !== expectedChecksum) { throw new ZWaveError( "Could not deserialize the message because the checksum didn't match", ZWaveErrorCodes.PacketFormat_Checksum, ); } this.type = payload[2]; this.functionType = payload[3]; const payloadLength = messageLength - 5; this.payload = payload.slice(4, 4 + payloadLength); } else { // Try to determine the message type if (options.type == undefined) options.type = getMessageType(this); if (options.type == undefined) { throw new ZWaveError( "A message must have a given or predefined message type", ZWaveErrorCodes.Argument_Invalid, ); } this.type = options.type; if (options.functionType == undefined) options.functionType = getFunctionType(this); if (options.functionType == undefined) { throw new ZWaveError( "A message must have a given or predefined function type", ZWaveErrorCodes.Argument_Invalid, ); } this.functionType = options.functionType; // Fall back to decorated response/callback types if none is given this.expectedResponse = options.expectedResponse ?? getExpectedResponse(this); this.expectedCallback = options.expectedCallback ?? getExpectedCallback(this); this._callbackId = options.callbackId; this.payload = options.payload || Buffer.allocUnsafe(0); } } public type: MessageType; public functionType: FunctionType; public expectedResponse: | FunctionType | typeof Message | ResponsePredicate | undefined; public expectedCallback: | FunctionType | typeof Message | ResponsePredicate | undefined; public payload: Buffer; // TODO: Length limit 255 private _callbackId: number | undefined; /** * Used to map requests to responses. * * WARNING: Accessing this property will generate a new callback ID if this message had none. * If you want to compare the callback ID, use `hasCallbackId()` beforehand to check if the callback ID is already defined. */ public get callbackId(): number { if (this._callbackId == undefined) { this._callbackId = this.driver.getNextCallbackId(); } return this._callbackId; } public set callbackId(v: number) { this._callbackId = v; } /** * Tests whether this message's callback ID is defined */ public hasCallbackId(): boolean { return this._callbackId != undefined; } /** * Tests whether this message needs a callback ID to match its response */ public needsCallbackId(): boolean { return true; } /** Returns the callback timeout for this message in case the default settings do not apply. */ public getCallbackTimeout(): number | undefined { // Use default timeout by default return; } /** Serializes this message into a Buffer */ public serialize(): Buffer { const ret = Buffer.allocUnsafe(this.payload.length + 5); ret[0] = MessageHeaders.SOF; // length of the following data, including the checksum ret[1] = this.payload.length + 3; // write the remaining data ret[2] = this.type; ret[3] = this.functionType; this.payload.copy(ret, 4); // followed by the checksum ret[ret.length - 1] = computeChecksum(ret); return ret; } /** Returns the number of bytes the first message in the buffer occupies */ public static getMessageLength(data: Buffer): number { const remainingLength = data[1]; return remainingLength + 2; } /** * Checks if there's enough data in the buffer to deserialize */ public static isComplete(data?: Buffer): boolean { if (!data || !data.length || data.length < 5) return false; // not yet const messageLength = Message.getMessageLength(data); if (data.length < messageLength) return false; // not yet return true; // probably, but the checksum may be wrong } /** * Retrieves the correct constructor for the next message in the given Buffer. * It is assumed that the buffer has been checked beforehand */ public static getConstructor(data: Buffer): Constructable<Message> { return getMessageConstructor(data[2], data[3]) || Message; } /** Creates an instance of the message that is serialized in the given buffer */ public static from(driver: Driver, data: Buffer): Message { const Constructor = Message.getConstructor(data); const ret = new Constructor(driver, { data }); return ret; } /** Returns the slice of data which represents the message payload */ public static extractPayload(data: Buffer): Buffer { const messageLength = Message.getMessageLength(data); const payloadLength = messageLength - 5; return data.slice(4, 4 + payloadLength); } /** Generates a representation of this Message for the log */ public toLogEntry(): MessageOrCCLogEntry { const tags = [ this.type === MessageType.Request ? "REQ" : "RES", FunctionType[this.functionType], ]; const nodeId = this.getNodeId(); if (nodeId) tags.unshift(getNodeTag(nodeId)); return { tags, message: this.payload.length > 0 ? { payload: `0x${this.payload.toString("hex")}` } : undefined, }; } /** Generates the JSON representation of this Message */ public toJSON(): JSONObject { return this.toJSONInternal(); } private toJSONInternal(): JSONObject { const ret: JSONObject = { name: this.constructor.name, type: MessageType[this.type], functionType: FunctionType[this.functionType] || num2hex(this.functionType), }; if (this.expectedResponse != null) ret.expectedResponse = FunctionType[this.functionType]; ret.payload = this.payload.toString("hex"); return ret; } protected toJSONInherited(props: JSONObject): JSONObject { const ret = this.toJSONInternal(); delete ret.payload; for (const [key, value] of entries(props)) { if (value !== undefined) ret[key] = value; } return ret; } private testMessage( msg: Message, predicate: Message["expectedResponse"], ): boolean { if (predicate == undefined) return false; if (typeof predicate === "number") { return msg.functionType === predicate; } if (staticExtends(predicate, Message)) { // predicate is a Message constructor return msg instanceof predicate; } else { // predicate is a ResponsePredicate return predicate(this, msg); } } /** Tests whether this message expects a response from the controller */ public expectsResponse(): boolean { return !!this.expectedResponse; } /** Tests whether this message expects a callback from the controller */ public expectsCallback(): boolean { // A message expects a callback... return ( // ...when it has a callback id that is not 0 (no callback) ((this.hasCallbackId() && this.callbackId !== 0) || // or the message type does not need a callback id to match the response !this.needsCallbackId()) && // and the expected callback is defined !!this.expectedCallback ); } /** Checks if a message is an expected response for this message */ public isExpectedResponse(msg: Message): boolean { return ( msg.type === MessageType.Response && this.testMessage(msg, this.expectedResponse) ); } /** Checks if a message is an expected callback for this message */ public isExpectedCallback(msg: Message): boolean { if (msg.type !== MessageType.Request) return false; // If a received request included a callback id, enforce that the response contains the same if ( this.hasCallbackId() && (!msg.hasCallbackId() || this._callbackId !== msg._callbackId) ) { return false; } return this.testMessage(msg, this.expectedCallback); } /** Finds the ID of the target or source node in a message, if it contains that information */ public getNodeId(): number | undefined { if (isNodeQuery(this)) return this.nodeId; if (isCommandClassContainer(this) && this.command.isSinglecast()) { return this.command.nodeId; } } /** * Returns the node this message is linked to or undefined */ public getNodeUnsafe(): ZWaveNode | undefined { const nodeId = this.getNodeId(); if (nodeId != undefined) return this.driver.controller.nodes.get(nodeId); } } /** Computes the checksum for a serialized message as defined in the Z-Wave specs */ function computeChecksum(message: Buffer): number { let ret = 0xff; // exclude SOF and checksum byte from the computation for (let i = 1; i < message.length - 1; i++) { ret ^= message[i]; } return ret; } // ======================= // use decorators to link function types to message classes const METADATA_messageTypes = Symbol("messageTypes"); const METADATA_messageTypeMap = Symbol("messageTypeMap"); const METADATA_expectedResponse = Symbol("expectedResponse"); const METADATA_expectedCallback = Symbol("expectedCallback"); const METADATA_priority = Symbol("priority"); type MessageTypeMap = Map<string, Constructable<Message>>; interface MessageTypeMapEntry { messageType: MessageType; functionType: FunctionType; } function getMessageTypeMapKey( messageType: MessageType, functionType: FunctionType, ): string { return JSON.stringify({ messageType, functionType }); } export type ResponseRole = | "unexpected" // a message that does not belong to this transaction | "confirmation" // a confirmation response, e.g. controller reporting that a message was sent | "final" // a final response (leading to a resolved transaction) | "fatal_controller" // a response from the controller that leads to a rejected transaction | "fatal_node"; // a response or (lack thereof) from the node that leads to a rejected transaction/** /** * A predicate function to test if a received message matches to the sent message */ export type ResponsePredicate<TSent extends Message = Message> = ( sentMessage: TSent, receivedMessage: Message, ) => boolean; /** * Defines the message and function type associated with a Z-Wave message */ export function messageTypes( messageType: MessageType, functionType: FunctionType, ): ClassDecorator { return (messageClass) => { Reflect.defineMetadata( METADATA_messageTypes, { messageType, functionType }, messageClass, ); // also store a map in the Message metadata for lookup. const map: MessageTypeMap = (Reflect.getMetadata( METADATA_messageTypeMap, Message, ) || new Map()) as MessageTypeMap; map.set( getMessageTypeMapKey(messageType, functionType), messageClass as any as Constructable<Message>, ); Reflect.defineMetadata(METADATA_messageTypeMap, map, Message); }; } /** * Retrieves the message type defined for a Z-Wave message class */ export function getMessageType<T extends Message>( messageClass: T, ): MessageType | undefined { // get the class constructor const constr = messageClass.constructor; // retrieve the current metadata const meta = Reflect.getMetadata(METADATA_messageTypes, constr) as | MessageTypeMapEntry | undefined; return meta?.messageType; } /** * Retrieves the message type defined for a Z-Wave message class */ export function getMessageTypeStatic<T extends Constructable<Message>>( classConstructor: T, ): MessageType | undefined { // retrieve the current metadata const meta = Reflect.getMetadata( METADATA_messageTypes, classConstructor, ) as MessageTypeMapEntry | undefined; return meta?.messageType; } /** * Retrieves the function type defined for a Z-Wave message class */ export function getFunctionType<T extends Message>( messageClass: T, ): FunctionType | undefined { // get the class constructor const constr = messageClass.constructor; // retrieve the current metadata const meta = Reflect.getMetadata(METADATA_messageTypes, constr) as | MessageTypeMapEntry | undefined; return meta?.functionType; } /** * Retrieves the function type defined for a Z-Wave message class */ export function getFunctionTypeStatic<T extends Constructable<Message>>( classConstructor: T, ): FunctionType | undefined { // retrieve the current metadata const meta = Reflect.getMetadata( METADATA_messageTypes, classConstructor, ) as MessageTypeMapEntry | undefined; return meta?.functionType; } /** * Looks up the message constructor for a given message type and function type */ function getMessageConstructor( messageType: MessageType, functionType: FunctionType, ): Constructable<Message> | undefined { // Retrieve the constructor map from the Message class const functionTypeMap = Reflect.getMetadata( METADATA_messageTypeMap, Message, ) as MessageTypeMap | undefined; if (functionTypeMap != null) { return functionTypeMap.get( getMessageTypeMapKey(messageType, functionType), ); } } /** * Defines the expected response function type or message class for a Z-Wave message */ export function expectedResponse( typeOrPredicate: FunctionType | typeof Message | ResponsePredicate, ): ClassDecorator { return (messageClass) => { Reflect.defineMetadata( METADATA_expectedResponse, typeOrPredicate, messageClass, ); }; } /** * Retrieves the expected response function type or message class defined for a Z-Wave message class */ export function getExpectedResponse<T extends Message>( messageClass: T, ): FunctionType | typeof Message | ResponsePredicate | undefined { // get the class constructor const constr = messageClass.constructor; // retrieve the current metadata const ret = Reflect.getMetadata(METADATA_expectedResponse, constr) as | FunctionType | typeof Message | ResponsePredicate | undefined; return ret; } /** * Retrieves the function type defined for a Z-Wave message class */ export function getExpectedResponseStatic<T extends Constructable<Message>>( classConstructor: T, ): FunctionType | typeof Message | ResponsePredicate | undefined { // retrieve the current metadata const ret = Reflect.getMetadata( METADATA_expectedResponse, classConstructor, ) as FunctionType | typeof Message | ResponsePredicate | undefined; return ret; } /** * Defines the expected callback function type or message class for a Z-Wave message */ export function expectedCallback<TSent extends Message>( typeOrPredicate: FunctionType | typeof Message | ResponsePredicate<TSent>, ): ClassDecorator { return (messageClass) => { Reflect.defineMetadata( METADATA_expectedCallback, typeOrPredicate, messageClass, ); }; } /** * Retrieves the expected callback function type or message class defined for a Z-Wave message class */ export function getExpectedCallback<T extends Message>( messageClass: T, ): FunctionType | typeof Message | ResponsePredicate | undefined { // get the class constructor const constr = messageClass.constructor; // retrieve the current metadata const ret = Reflect.getMetadata(METADATA_expectedCallback, constr) as | FunctionType | typeof Message | ResponsePredicate | undefined; return ret; } /** * Retrieves the function type defined for a Z-Wave message class */ export function getExpectedCallbackStatic<T extends Constructable<Message>>( classConstructor: T, ): FunctionType | typeof Message | ResponsePredicate | undefined { // retrieve the current metadata const ret = Reflect.getMetadata( METADATA_expectedCallback, classConstructor, ) as FunctionType | typeof Message | ResponsePredicate | undefined; return ret; } /** * Defines the default priority associated with a Z-Wave message */ export function priority(prio: MessagePriority): ClassDecorator { return (messageClass) => { Reflect.defineMetadata(METADATA_priority, prio, messageClass); }; } /** * Retrieves the default priority defined for a Z-Wave message class */ export function getDefaultPriority<T extends Message>( messageClass: T, ): MessagePriority | undefined { // get the class constructor const constr = messageClass.constructor; // retrieve the current metadata const ret = Reflect.getMetadata(METADATA_priority, constr) as | MessagePriority | undefined; return ret; } /** * Retrieves the default priority defined for a Z-Wave message class */ export function getDefaultPriorityStatic<T extends Constructable<Message>>( classConstructor: T, ): MessagePriority | undefined { // retrieve the current metadata const ret = Reflect.getMetadata(METADATA_priority, classConstructor) as | MessagePriority | undefined; return ret; }
the_stack
import {Program} from "../src/runtime/dsl2"; import {verify} from "./util"; import * as test from "tape"; test("find a record and generate a record as a result", (assert) => { // ----------------------------------------------------- // program // ----------------------------------------------------- let prog = new Program("test"); prog.bind("simple block", ({find, record, lib}) => { find({foo: "bar"}); return [ record({zomg: "baz"}) ] }); // ----------------------------------------------------- // verification // ----------------------------------------------------- verify(assert, prog, [ [1, "foo", "bar"] ], [ [2, "zomg", "baz", 1] ]) assert.end(); }); test("> filters numbers", (assert) => { // ----------------------------------------------------- // program // ----------------------------------------------------- let prog = new Program("test"); prog.bind("simple block", ({find, record, lib}) => { let a = find(); let b = find(); a.age > b.age; return [ record({age1: a.age, age2: b.age}) ] }); // ----------------------------------------------------- // verification // ----------------------------------------------------- verify(assert, prog, [ [1, "tag", "person"], [1, "age", 7], [2, "tag", "person"], [2, "age", 41], [3, "tag", "person"], [3, "age", 3], ], [ [4, "age1", 41, 1], [4, "age2", 7, 1], [5, "age1", 41, 1], [5, "age2", 3, 1], [6, "age1", 7, 1], [6, "age2", 3, 1], ]) assert.end(); }); test("simple addition", (assert) => { // ----------------------------------------------------- // program // ----------------------------------------------------- let prog = new Program("test"); prog.bind("simple block", ({find, record, lib}) => { let a = find("person"); let b = find("person"); a.age > b.age; let result = a.age + b.age; return [ record({age1: a.age, age2: b.age, result}) ] }); // ----------------------------------------------------- // verification // ----------------------------------------------------- verify(assert, prog, [ [1, "tag", "person"], [1, "age", 7], [2, "tag", "person"], [2, "age", 41], [3, "tag", "person"], [3, "age", 3], ], [ [4, "age1", 41, 1], [4, "age2", 7, 1], [4, "result", 48, 1], [5, "age1", 41, 1], [5, "age2", 3, 1], [5, "result", 44, 1], [6, "age1", 7, 1], [6, "age2", 3, 1], [6, "result", 10, 1], ]) assert.end(); }); test("simple division", (assert) => { // ----------------------------------------------------- // program // ----------------------------------------------------- let prog = new Program("test"); prog.bind("simple block", ({find, record, lib}) => { let a = find("person"); let b = find("person"); a.age > b.age; let result = a.age / b.age; return [ record({age1: a.age, age2: b.age, result}) ] }); // ----------------------------------------------------- // verification // ----------------------------------------------------- verify(assert, prog, [ [1, "tag", "person"], [1, "age", 7], [2, "tag", "person"], [2, "age", 35], ], [ [4, "age1", 35, 1], [4, "age2", 7, 1], [4, "result", 5, 1], ]) assert.end(); }); test("static equality filters expressions", (assert) => { let prog = new Program("Automatic Teacher's Assistant"); prog.bind("Auto TA addition", ({find, record, lib}) => { let addition = find("addition"); 1 == addition.a + addition.b; return [record("success", {addition})]; }); verify(assert, prog, [ [1, "tag", "addition"], [1, "a", 7], [1, "b", 13], [2, "tag", "addition"], [2, "a", 3], [2, "b", -2], ], [ ["A", "tag", "success", 1], ["A", "addition", 2, 1] ]) assert.end(); }); test("dynamic equality filters expressions", (assert) => { let prog = new Program("Automatic Teacher's Assistant"); prog.bind("Auto TA addition", ({find, record, lib}) => { let addition = find("addition"); addition.c == addition.a + addition.b; return [record("success", {addition})]; }); verify(assert, prog, [ [1, "tag", "addition"], [1, "a", 7], [1, "b", 13], [1, "c", 1], [2, "tag", "addition"], [2, "a", 3], [2, "b", -2], [2, "c", 1], ], [ ["Z", "tag", "success", 1], ["Z", "addition", 2, 1] ]) assert.end(); }); test("simple recursion", (assert) => { // ----------------------------------------------------- // program // ----------------------------------------------------- let prog = new Program("test"); prog.bind("simple block", ({find, record, lib}) => { let {number} = find(); 9 > number; let result = number + 1; return [ record({number: result}) ] }); // ----------------------------------------------------- // verification // ----------------------------------------------------- verify(assert, prog, [ [1, "number", 1], ], [ [2, "number", 2, 1], [3, "number", 3, 2], [4, "number", 4, 3], [5, "number", 5, 4], [6, "number", 6, 5], [7, "number", 7, 6], [8, "number", 8, 7], [9, "number", 9, 8], ]); assert.end(); }); test("test addition operator", (assert) => { // ----------------------------------------------------- // program // ----------------------------------------------------- let prog = new Program("test"); prog.bind("simple block", ({find, record, lib}) => { let joof = find({foo: "bar"}); return [ joof.add("name", "JOOF") ] }); // ----------------------------------------------------- // verification // ----------------------------------------------------- verify(assert, prog, [ [1, "foo", "bar"] ], [ [1, "name", "JOOF", 1] ]) assert.end(); }); test("transitive closure", (assert) => { // ----------------------------------------------------- // program // ----------------------------------------------------- let prog = new Program("test"); prog.bind("Every edge is the beginning of a path.", ({find, record, lib}) => { let from = find(); return [ from.add("path", from.edge) ]; }); prog.bind("Jump from node to node building the path.", ({find, record, lib}) => { let from = find(); let intermediate = find(); from.edge == intermediate; let to = intermediate.path; intermediate.path; return [ from.add("path", to) ] }); // ----------------------------------------------------- // verification // ----------------------------------------------------- verify(assert, prog, [ [1, "edge", 2], [2, "edge", 1], ], [ [1, "path", 2, 1], [2, "path", 1, 1], [1, "path", 1, 2], [2, "path", 2, 2], ]) verify(assert, prog, [ [1, "edge", 2, 0, -1], ], [ [1, "path", 2, 1, -1], [1, "path", 1, 2, -1], [2, "path", 2, 2, -1], //[2, "path", 1, 3, -1], ]) verify(assert, prog, [ [1, "edge", 2, 0, 1], ], [ [1, "path", 2, 1, 1], [1, "path", 1, 2, 1], [2, "path", 2, 2, 1], //[2, "path", 1, 3, 1], ]) // verify(assert, prog, [ // [1, "edge", 2], // [2, "edge", 3], // [3, "edge", 4], // [4, "edge", 1], // ], [ // [1, "path", 2, 1], // [2, "path", 3, 1], // [3, "path", 4, 1], // [4, "path", 1, 1], // [1, "path", 3, 2], // [2, "path", 4, 2], // [3, "path", 1, 2], // [4, "path", 2, 2], // [1, "path", 4, 3], // [2, "path", 1, 3], // [3, "path", 2, 3], // [4, "path", 3, 3], // [1, "path", 1, 4], // [2, "path", 2, 4], // [3, "path", 3, 4], // [4, "path", 4, 4], // [1, "path", 2, 5], // [2, "path", 3, 5], // [3, "path", 4, 5], // [4, "path", 1, 5] // ]); // // Kick the legs out from under the cycle. // verify(assert, prog, [ // [4, "edge", 1, 0, -1] // ], [ // [4, "path", 1, 1, -1], // [4, "path", 2, 2, -1], // [3, "path", 1, 2, -1], // [2, "path", 1, 2, -1], // [1, "path", 1, 2, -1], // [4, "path", 3, 3, -1], // [3, "path", 2, 3, -1], // [2, "path", 2, 3, -1], // [1, "path", 2, 3, -1], // [4, "path", 4, 4, -1], // [4, "path", 1, 5, -1], // ]); assert.end(); }); test("removal", (assert) => { // ----------------------------------------------------- // program // ----------------------------------------------------- let prog = new Program("test"); prog.bind("simple block", ({find, record, lib}) => { find({foo: "bar"}); return [ record({zomg: "baz"}) ] }); // ----------------------------------------------------- // verification // ----------------------------------------------------- // trust, but verify(assert, prog, [ [1, "foo", "bar"] ], [ [2, "zomg", "baz", 1] ]); verify(assert, prog, [ [1, "foo", "bar", 0, -1] ], [ [2, "zomg", "baz", 1, -1] ], 1); assert.end(); }); test.skip("not", (assert) => { // ----------------------------------------------------- // program // ----------------------------------------------------- let prog = new Program("test"); prog.bind("simple block", ({find, record, lib, not}) => { let person = find({tag: "person"}); not(() => person.alive); return [ person.add("dead", "true") ] }); // ----------------------------------------------------- // verification // ----------------------------------------------------- // trust, but verify(assert, prog, [ [1, "tag", "person"] ], [ [1, "dead", "true", 1] ]); assert.end(); }); test("Nested attribute lookup", (assert) => { // ----------------------------------------------------- // program // ----------------------------------------------------- let prog = new Program("test"); prog.bind("simple block", ({find, record, lib}) => { let jeff = find({tag: "bar"}); return [ record({zomg: jeff.dog.weight}) ] }); // ----------------------------------------------------- // verification // ----------------------------------------------------- verify(assert, prog, [ [1, "tag", "bar"], [1, "dog", 2], [2, "weight", 13], ], [ [3, "zomg", 13, 1] ]) assert.end(); }); test("Basic not", (assert) => { // ----------------------------------------------------- // program // ----------------------------------------------------- let prog = new Program("test"); prog.bind("simple block", ({find, record, lib, not}) => { let person = find("person"); not(() => { person.age; }) return [ person.add("tag", "old") ] }); // ----------------------------------------------------- // verification // ----------------------------------------------------- verify(assert, prog, [ [1, "tag", "person"], ], [ [1, "tag", "old", 1] ]) verify(assert, prog, [ [1, "age", 20], ], [ [1, "tag", "old", 1, -1] ]) assert.end(); }); test("Basic aggregate", (assert) => { // ----------------------------------------------------- // program // ----------------------------------------------------- let prog = new Program("test"); prog.bind("simple block", ({find, record, lib, gather}) => { let person = find("person"); let count = gather(person).count(); return [ record("info").add("total people", count) ] }); // ----------------------------------------------------- // verification // ----------------------------------------------------- verify(assert, prog, [ [1, "tag", "person"], [2, "tag", "person"], ], [ [3, "tag", "info", 1], [3, "total people", 2, 1], ]) verify(assert, prog, [ [1, "tag", "person", 0, -1], ], [ [3, "total people", 2, 1, -1], [3, "total people", 1, 1], ]) verify(assert, prog, [ [1, "tag", "person"], [4, "tag", "person"], ], [ [3, "total people", 1, 1, -1], [3, "total people", 3, 1], ]) assert.end(); }); test("commit, remove, and recursion", (assert) => { // ----------------------------------------------------- // program // ----------------------------------------------------- let prog = new Program("test"); prog.commit("coolness", ({find, not, record, choose}) => { let click = find("click", "direct-target"); let count = find("count"); let current = count.count; 5 > current; return [ count.add("count", current + 1) ] }) prog.commit("foo", ({find}) => { let click = find("click", "direct-target"); return [ click.remove("tag", "click"), click.remove("tag", "direct-target"), ]; }) // ----------------------------------------------------- // verification // ----------------------------------------------------- verify(assert, prog, [ [1, "tag", "count"], [1, "count", 0] ], [ ]) verify(assert, prog, [ [2, "tag", "click"], [2, "tag", "direct-target"] ], [ [2, "tag", "click", 0, -1], [2, "tag", "direct-target", 0, -1], [1, "count", 1, 0], ]) verify(assert, prog, [ [3, "tag", "click"], [3, "tag", "direct-target"] ], [ [3, "tag", "click", 0, -1], [3, "tag", "direct-target", 0, -1], [1, "count", 2, 0], ]) assert.end(); }); test("Remove: free AV", (assert) => { let prog = new Program("test"); prog.commit("coolness", ({find, not, record, choose}) => { let person = find("person"); return [ person.remove() ] }) verify(assert, prog, [ [1, "tag", "person"], [1, "name", "chris"], [1, "age", 30], ], [ [1, "tag", "person", 0, -1], [1, "name", "chris", 0, -1], [1, "age", 30, 0, -1], ]) assert.end(); }); test("Reference: arbitrary refs act like records", (assert) => { let prog = new Program("test"); prog.commit("coolness", ({find, not, record, union}) => { let person = find("person"); let [thing] = union(() => { return find("person"); }, () => { return "foo"; }) return [ thing.remove() ] }) verify(assert, prog, [ [1, "tag", "person"], [1, "name", "chris"], [1, "age", 30], ["foo", "tag", "person"], ["foo", "name", "chris"], ["foo", "age", 30], ], [ [1, "tag", "person", 0, -1], [1, "name", "chris", 0, -1], [1, "age", 30, 0, -1], ["foo", "tag", "person", 0, -1], ["foo", "name", "chris", 0, -1], ["foo", "age", 30, 0, -1], ]) assert.end(); });
the_stack
import { Component, OnInit, Input, Output, EventEmitter, OnDestroy } from '@angular/core'; import { FormGroup, FormBuilder, FormArray, Validators, FormControl, AbstractControl, ValidatorFn } from '@angular/forms'; import { Observable, of } from 'rxjs'; import { map, startWith } from 'rxjs/operators'; import { Story } from '../common/models/story'; import { Intent } from '../common/models/intent'; import { Response } from '../common/models/response'; import { Entity } from '../common/models/entity'; import { IntentResponse } from '../common/models/intent_response'; import { MatDialog } from '@angular/material/dialog'; import { AddEntityValueComponent } from '../common/modals/add-entity-value/add-entity-value.component'; import { SharedDataService } from '../common/services/shared-data.service'; import { constant } from '../../environments/constants'; import { ApiService } from '../common/services/apis.service'; declare var adjustScroll: Function; @Component({ selector: 'app-manage-stories', templateUrl: './manage-stories.component.html', styleUrls: ['./manage-stories.component.scss'] }) export class ManageStoriesComponent implements OnInit, OnDestroy { story: Story; storyForm: FormGroup; intents: any; intents_text_arr: any; intentsfilteredOptions: Observable<string[]>; intentControl = new FormControl(); responses: any; responses_text_arr: any; responsesfilteredOptions: Observable<string[]>; responseControl = new FormControl(); entities: any; entities_text_arr: any; entitiesfilteredOptions: Observable<string[]>; entityControl = new FormControl(); actions: any; intent_response_entity_arr = new Array<object[]>(); intents_responses: any; intents_responses_backup: any; intents_entities_responses: any; removable = true; selectable = true; disable_response = false; show_intent_error = false; show_ir_error: boolean; on_intent_response_entity: boolean; currentStory: any; @Input() projectObjectId: string; @Input() domainObjectId: string; @Input() storyObjectId: string; @Output() saveStoryJSON = new EventEmitter<{ story_index: number, intents_responses: [{}] }>(); constructor(private fb: FormBuilder, public dialog: MatDialog, public apiService: ApiService, public sharedDataService: SharedDataService) { } ngOnInit() { const intents_responses: FormArray = new FormArray([]); this.storyForm = this.fb.group({ intents_responses: intents_responses }); // Get Everything (Actions has entire story in it) this.getActions(); this.getEntities(); this.getIntents(); this.getResponses(); this.show_ir_error = false; this.on_intent_response_entity = false; this.sharedDataService.setSharedData('activeTabIndex', '2', constant.MODULE_COMMON); } getStory() { this.apiService.requestStoryDetails(this.storyObjectId).subscribe(story_details => { if (story_details) { this.currentStory = story_details; if (this.currentStory !== undefined) { if (this.currentStory.story.length > 0) { this.story = new Story; this.story.story_name = this.currentStory.story_name; this.story.story = this.currentStory.story; this.initForm(this.story); // handles both the create and edit logic } else { this.initForm(); // handles both the create and edit logic } } } }, err => console.error('Observer got an error: ' + err), () => console.log('Observer got a complete notification')); } getActions() { this.apiService.requestActions().subscribe(actions => { if (actions) { this.actions = actions; this.convertToResponseTextArray(); this.forceReload(); } }, err => console.error('Observer got an error: ' + err), () => console.log('Observer got a complete notification')); } getIntents() { this.apiService.requestIntents(this.projectObjectId, this.domainObjectId).subscribe(intents => { if (intents) { console.log(intents); this.intents = intents; this.convertToIntentTextArray(); } }, err => console.error('Observer got an error: ' + err), () => console.log('Observer got a complete notification')); } convertToIntentTextArray() { const intents_text_arr = new Array<object>(); this.intents.forEach(function (intent) { if (intent.text_entities !== undefined) { const intent_text_entities = intent.text_entities; for (let i = 0; i < intent_text_entities.length; i++) { // tslint:disable-next-line: max-line-length intents_text_arr.push({'intent_id': intent._id.$oid, 'intent_name': intent.intent_name, 'intent_text': intent_text_entities[i].text}); } } }); this.intents_text_arr = intents_text_arr; } getResponses() { this.apiService.requestResponses(this.projectObjectId, this.domainObjectId).subscribe(responses => { if (responses) { this.responses = responses; } }, err => console.error('Observer got an error: ' + err), () => console.log('Observer got a complete notification')); } convertToResponseTextArray() { const responses_text_arr = new Array<object>(); console.log(this.responses); this.responses.forEach(function (response) { if (response.text_entities !== undefined) { const response_text_entities = response.text_entities; for (let i = 0; i < response_text_entities.length; i++) { // tslint:disable-next-line:max-line-length responses_text_arr.push({'response_id': response._id.$oid, 'response_name': response.response_name, 'response_text': response_text_entities[i]}); } } }); if (this.actions !== undefined) { this.actions.forEach(function (action) { responses_text_arr.push({'response_id': action._id.$oid, 'response_name': action.action_name, 'response_text': action.action_description}); }); } this.responses_text_arr = responses_text_arr; } getEntities() { this.apiService.requestEntities(this.projectObjectId).subscribe(entities => { if (entities) { this.entities = entities; this.convertToEntityTextArray(); this.entityControl = new FormControl('', requireEntityMatch(this.entities)); this.entitiesfilteredOptions = this.entityControl.valueChanges.pipe( startWith(''), map(value => this._filter_entities(value)) ); } }, err => console.error('Observer got an error: ' + err), () => console.log('Observer got a complete notification')); } convertToEntityTextArray() { const entities_text_arr = new Array<object>(); this.entities.forEach(function (entity) { if (entity.entity_slot.type === 'categorical') { const entities_values = entity.entity_slot.values; for (let i = 0; i < entities_values.length; i++) { // tslint:disable-next-line:max-line-length entities_text_arr.push({'entity_name': entity.entity_name, 'entity_value': entities_values[i]}); } } else { entities_text_arr.push({'entity_name': entity.entity_name, 'entity_value': ''}); } }); this.entities_text_arr = entities_text_arr; } /** * Initialises the tripForm * @method initForm */ initForm(story?: Story): void { const intents_responses: FormArray = new FormArray([]); this.storyForm = this.fb.group({ intents_responses: intents_responses }); if (!story) { // Creating a new story this.addIntentToStory(); // this.addResponseToStory(); } else { console.log("Story", story); // Editing a story story.story.forEach((intent_response, intentresponseIndex) => { if (intent_response.type === 'intent') { this.addIntentToStory(intent_response); if (this.intent_response_entity_arr[intentresponseIndex] === undefined) { this.intent_response_entity_arr[intentresponseIndex] = new Array<object>(); } this.intent_response_entity_arr[intentresponseIndex] = intent_response.entities; } else if (intent_response.type === 'response') { this.addResponseToStory(intent_response); if (this.intent_response_entity_arr[intentresponseIndex] === undefined) { this.intent_response_entity_arr[intentresponseIndex] = new Array<object>(); } const entities = []; const s = intent_response.value; const arrStr = s.split(/[{}]/); for (let i = 0; i < arrStr.length; i++) { if (/\s/.test(arrStr[i]) === false && arrStr[i].trim() !== '') { entities.push(arrStr[i]); } } this.intent_response_entity_arr[intentresponseIndex] = entities; } }); } } displayIntentWith(intent?: Intent): string | undefined { return intent ? intent.intent_text : undefined; } displayResponseWith(response?: Response): string | undefined { return response ? response.response_text : undefined; } displayEntityWith(entity?: Entity): string | undefined { return entity ? entity.entity_name : undefined; } private _filter_intents(intent: string): string[] { const filterValue = intent.toLowerCase(); return this.intents_text_arr.filter(option => option.intent_text.toLowerCase().includes(filterValue)); } private _filter_entities(entity: string): string[] { const filterValue = entity.toLowerCase(); return this.entities_text_arr.filter(option => option.entity_name.toLowerCase().includes(filterValue)); } private _filter_responses(response: string): string[] { const filterValue = response.toLowerCase(); return this.responses_text_arr.filter(option => option.response_text.toLowerCase().includes(filterValue)); } /** * Adds an intent FormGroup to the intents <FormArray>FormControl(__intents__) * @method addCity * @param void * @return void */ addIntentToStory(intent_response?: IntentResponse): void { const intent_key = intent_response ? intent_response.key : ''; const intent_value = intent_response ? intent_response.value : ''; const type = intent_response ? intent_response.type : 'intent'; (<FormArray>this.storyForm.controls['intents_responses']).push( new FormGroup({ key: new FormControl(intent_key, Validators.required), value: new FormControl(intent_value, Validators.required), type: new FormControl(type), }) ); if ((<FormArray>this.storyForm.controls['intents_responses']).length > 0) { this.disable_response = false; } const intent_length = (<FormArray>this.storyForm.controls['intents_responses']).length; const intentControl = (<FormArray>this.storyForm.controls['intents_responses']).at(intent_length - 1); intentControl['controls'].value.valueChanges.pipe( startWith(''), map(value => typeof value === 'string' ? value : value[0].text), map(text => text ? this._filter_intents(text.toString()) : this.intents_text_arr.slice()) ).subscribe(filteredIntentResult => { this.intentsfilteredOptions = filteredIntentResult; }); adjustScroll(); } addResponseToStory(intent_response?: IntentResponse): void { const response_key = intent_response ? intent_response.key : ''; const response_value = intent_response ? intent_response.value : ''; const type = intent_response ? intent_response.type : 'response'; (<FormArray>this.storyForm.controls['intents_responses']).push( new FormGroup({ key: new FormControl(response_key, Validators.required), value: new FormControl(response_value, Validators.required), type: new FormControl(type), }) ); const response_length = (<FormArray>this.storyForm.controls['intents_responses']).length; const responseControl = (<FormArray>this.storyForm.controls['intents_responses']).at(response_length - 1); responseControl['controls'].value.valueChanges.pipe( startWith(''), map(value => typeof value === 'string' ? value : value[0].text), map(text => text ? this._filter_responses(text.toString()) : this.responses_text_arr.slice()) ).subscribe(filteredResponseResult => { this.responsesfilteredOptions = filteredResponseResult; }); adjustScroll(); } addIntentResponseDetailsToStory(type: string, intent_response_insert_index?: number) { let show_ir_error = false; this.storyForm.value.intents_responses.forEach(function (intent_response) { if (intent_response.value.trim() === '') { show_ir_error = true; } }); this.show_ir_error = show_ir_error; if (this.show_ir_error) { setTimeout(() => { this.show_ir_error = false; }, 2000); } else { // tslint:disable-next-line: max-line-length const ir_insert_index = intent_response_insert_index ? intent_response_insert_index : (<FormArray>this.storyForm.controls['intents_responses']).length; const insert_ir_to_story = { project_id: this.projectObjectId, domain_id: this.domainObjectId, object_id: this.storyObjectId, position: ir_insert_index, story: [{ key: '', value: '', type: type, entities: [] }] }; this.apiService.insertStoryDetails(insert_ir_to_story, this.storyObjectId).subscribe(result => { if (result) { this.forceReload(); } }, err => console.error('Observer got an error: ' + err), () => console.log('Observer got a complete notification')); } } removeIntentResponseFromStory(intent_response_index: number, intent_response: any, entities?: any) { const delete_ir_to_story = { project_id: this.projectObjectId, domain_id: this.domainObjectId, object_id: this.storyObjectId, doc_index: intent_response_index, story: [{ key: intent_response.value.key, value: intent_response.value.value, type: intent_response.value.type, entities: entities ? entities : [] }] }; this.apiService.deleteStoryDetails(delete_ir_to_story, this.storyObjectId).subscribe(result => { if (result) { this.forceReload(); } }, err => console.error('Observer got an error: ' + err), () => console.log('Observer got a complete notification')); adjustScroll(); } // tslint:disable-next-line: max-line-length onIntentResponseEntityChange(event: any, intent_response_index: number, intent_name: string, intent_text: string, type: string, entities?: any) { const update_ir_in_story = { project_id: this.projectObjectId, domain_id: this.domainObjectId, object_id: this.storyObjectId, doc_index: intent_response_index, story: { key: intent_name, value: intent_text, type: type, entities: entities ? entities : [] } }; this.apiService.updateStoryDetails(update_ir_in_story, this.storyObjectId).subscribe(result => { if (result) { console.log(result); this.forceReload(); this.on_intent_response_entity = true; } }, err => console.error('Observer got an error: ' + err), () => console.log('Observer got a complete notification')); } validateIntentInput(intent_index: number, event: any) { if (this.on_intent_response_entity === false) { const intentControl = (<FormArray>this.storyForm.controls['intents_responses']).at(intent_index); const validate_intent = this.intents_text_arr.filter(value => (value.intent_text === intentControl.value.value))[0]; if (validate_intent !== undefined) { intentControl.value.key = validate_intent.intent_name; intentControl.value.value = validate_intent.intent_text; intentControl.value.type = 'intent'; this.onIntentResponseEntityChange(event, intent_index, intentControl.value.key, intentControl.value.value, 'intent'); } else { event.srcElement.value = ''; intentControl.value.key = ''; intentControl.value.value = ''; intentControl.value.type = 'intent'; intentControl['controls'].value.valueChanges.pipe( startWith(''), map(value => typeof value === 'string' ? value : value[0].text), map(text => text ? this._filter_intents(text.toString()) : this.intents_text_arr.slice()) ).subscribe(filteredIntentResult => { this.intentsfilteredOptions = filteredIntentResult; }); } } else { this.on_intent_response_entity = false; } } validateResponseInput(response_index: number, event: any) { if (this.on_intent_response_entity === false) { const responseControl = (<FormArray>this.storyForm.controls['intents_responses']).at(response_index); const validate_response = this.responses_text_arr.filter(value => value.response_text === responseControl.value.value)[0]; if (validate_response !== undefined) { responseControl.value.key = validate_response.response_name; responseControl.value.value = validate_response.response_text; responseControl.value.type = 'response'; this.onIntentResponseEntityChange(event, response_index, responseControl.value.key, responseControl.value.value, 'response'); } else { event.srcElement.value = ''; responseControl.value.key = ''; responseControl.value.value = ''; responseControl.value.type = 'response'; responseControl['controls'].value.valueChanges.pipe( startWith(''), map(value => typeof value === 'string' ? value : value[0].text), map(text => text ? this._filter_responses(text.toString()) : this.responses_text_arr.slice()) ).subscribe(filteredResponseResult => { this.responsesfilteredOptions = filteredResponseResult; }); } } } onEntityChange(event: any, intent_response_index: number, intent_response: any) { if (event.type === 'mousedown') { const entity_name_value = event.srcElement.innerText.split(':'); if (entity_name_value[1] === '') { const dialogRef = this.dialog.open(AddEntityValueComponent); dialogRef.afterClosed().subscribe(res => { if (res) { entity_name_value[1] = res; // tslint:disable-next-line: max-line-length this.intent_response_entity_arr[intent_response_index].push({'entity_name': entity_name_value[0], 'entity_value': entity_name_value[1]}); // tslint:disable-next-line: max-line-length this.onIntentResponseEntityChange(event, intent_response_index, intent_response.value.key, intent_response.value.value, intent_response.value.type, this.intent_response_entity_arr[intent_response_index]); } }); } else { // tslint:disable-next-line: max-line-length this.intent_response_entity_arr[intent_response_index].push({'entity_name': entity_name_value[0], 'entity_value': entity_name_value[1]}); // tslint:disable-next-line: max-line-length this.onIntentResponseEntityChange(event, intent_response_index, intent_response.value.key, intent_response.value.value, intent_response.value.type, this.intent_response_entity_arr[intent_response_index]); } } } // tslint:disable-next-line: max-line-length removeEntityFromIntentResponse(intent_response: any, intent_response_index: number, intent_response_entity_arr: any, entity_index: number) { intent_response_entity_arr.splice(entity_index, 1); // tslint:disable-next-line: max-line-length this.onIntentResponseEntityChange(true, intent_response_index, intent_response.value.key, intent_response.value.value, intent_response.value.type, intent_response_entity_arr); } handleSpacebar(event: any) { if (event.keyCode === 32 || event.keyCode === 13) { event.stopPropagation(); } } forceReload() { this.apiService.forceStoryDetailsCacheReload('reset'); this.apiService.forceActionsCacheReload('reset'); this.apiService.forceEntitiesCacheReload('reset'); this.apiService.forceIntentsCacheReload('reset'); this.apiService.forceResponsesCacheReload('reset'); this.getStory(); } ngOnDestroy(): void { for (let i = 0; i < this.currentStory['story'].length; i++) { if (this.currentStory['story'][i]['key'] === '') { this.removeIntentResponseFromStory(i, this.currentStory['story'][i]); } } this.currentStory = undefined; this.apiService.forceStoryDetailsCacheReload('finish'); this.apiService.forceActionsCacheReload('finish'); this.apiService.forceEntitiesCacheReload('finish'); this.apiService.forceIntentsCacheReload('finish'); this.apiService.forceResponsesCacheReload('finish'); this.dialog.closeAll(); } } function requireIntentMatch(intents: any): ValidatorFn { return (control: AbstractControl): { [key: string]: boolean } | null => { if (intents.find(value => value.intent_text.includes(control.value)) === undefined) { return { 'invalid': true }; } return null; }; } function requireResponseMatch(responses: any): ValidatorFn { return (control: AbstractControl): { [key: string]: boolean } | null => { if (responses.find(value => value.response_text.includes(control.value)) === undefined) { return { 'invalid': true }; } return null; }; } function requireEntityMatch(entities: any): ValidatorFn { return (control: AbstractControl): { [key: string]: boolean } | null => { if (entities.find(value => value.entity_name.includes(control.value)) === undefined) { return { 'invalid': true }; } return null; }; }
the_stack
import 'reflect-metadata'; import * as Discord from 'discord.js'; import * as Path from 'path'; // eslint-disable-next-line no-duplicate-imports import { ClientEvents, ClientOptions, ClientApplication, Guild, Message, User, PermissionResolvable } from 'discord.js'; import { Logger, logger } from '../util/logger/Logger'; import { BaseCommandName } from '../types/BaseCommandName'; import { ClientStorage } from '../storage/ClientStorage'; import { Command } from '../command/Command'; import { CommandDispatcher } from '../command/CommandDispatcher'; import { CommandLoader } from '../command/CommandLoader'; import { CommandRegistry } from '../command/CommandRegistry'; import { CompactModeHelper } from '../command/CompactModeHelper'; import { EventLoader } from '../event/EventLoader'; import { GuildStorage } from '../storage/GuildStorage'; import { GuildStorageLoader } from '../storage/GuildStorageLoader'; import { JSONProvider } from '../storage/JSONProvider'; import { Lang } from '../localization/Lang'; import { ListenerUtil } from '../util/ListenerUtil'; import { MiddlewareFunction } from '../types/MiddlewareFunction'; import { PluginConstructor } from '../types/PluginConstructor'; import { PluginLoader } from './PluginLoader'; import { RateLimitManager } from '../command/RateLimitManager'; import { ResolverConstructor } from '../types/ResolverConstructor'; import { ResolverLoader } from '../command/resolvers/ResolverLoader'; import { StorageProviderConstructor } from '../types/StorageProviderConstructor'; import { Time } from '../util/Time'; import { Util } from '../util/Util'; import { Message as YAMDBFMessage } from '../types/Message'; import { YAMDBFOptions } from '../types/YAMDBFOptions'; const { on, once, registerListeners } = ListenerUtil; /** * The YAMDBF Client through which you can access [storage]{@link Client#storage} * and any of the properties available on a typical Discord.js Client instance * @extends {external:Client} * @param {YAMDBFOptions} options Object containing required client properties * @param {external:ClientOptions} [clientOptions] Discord.js ClientOptions */ export class Client extends Discord.Client { @logger('Client') private readonly _logger!: Logger; private readonly _token: string; private readonly _plugins: (PluginConstructor | string)[]; private readonly _guildStorageLoader: GuildStorageLoader; private readonly _commandLoader!: CommandLoader; private readonly _dispatcher!: CommandDispatcher; private _ratelimit!: string; public readonly commandsDir: string | null; public readonly eventsDir: string | null; public readonly localeDir: string | null; public readonly owner: string[]; public readonly defaultLang: string; public readonly statusText: string | null; public readonly readyText: string; public readonly unknownCommandError: boolean; public readonly dmHelp: boolean; public readonly passive: boolean; public readonly pause: boolean; public readonly disableBase: BaseCommandName[]; public readonly provider: StorageProviderConstructor; public readonly plugins: PluginLoader; public readonly storage: ClientStorage; public readonly commands: CommandRegistry<this>; public readonly rateLimitManager: RateLimitManager; public readonly eventLoader!: EventLoader; public readonly resolvers: ResolverLoader; public readonly argsParser: (input: string, command?: Command, message?: YAMDBFMessage) => string[]; public readonly buttons: { [key: string]: string }; public readonly compact: boolean; public readonly tsNode: boolean; // Internals public readonly middleware: MiddlewareFunction[]; public readonly customResolvers: ResolverConstructor[]; // eslint-disable-next-line complexity public constructor(options: YAMDBFOptions, clientOptions?: ClientOptions) { super(clientOptions); Reflect.defineMetadata('YAMDBFClient', true, this); // Hook logger to provide shard ID(s) in base transport logs if (this.shard) Logger.shard = this.shard.ids.join('-'); this._token = options.token! ?? process.env.DISCORD_TOKEN!; /** * The owner/owners of the bot, represented as an array of IDs. * These IDs determine who is allowed to use commands flagged as * `ownerOnly` * @type {string[]} */ this.owner = typeof options.owner !== 'undefined' ? options.owner instanceof Array ? options.owner : [options.owner] : []; /** * Directory to find command class files. Optional * if client is passive.<br> * **See:** {@link Client#passive} * @type {string} */ this.commandsDir = options.commandsDir ? Path.resolve(options.commandsDir) : null; /** * Directory to find Event class files. Optional * if client is passive.<br> * **See:** {@link Client#passive} * @type {string} */ this.eventsDir = options.eventsDir ? Path.resolve(options.eventsDir) : null; /** * Directory to find custom localization files * @type {string} */ this.localeDir = options.localeDir ? Path.resolve(options.localeDir) : null; /** * Default language to use for localization * @type {string} */ this.defaultLang = options.defaultLang ?? 'en_us'; /** * Status text for the client * @type {string} */ this.statusText = options.statusText ?? null; /** * Text to output when the client is ready. If not * provided nothing will be logged, giving the * opportunity to log something more dynamic * on `clientReady` * @type {string} */ this.readyText = options.readyText!; /** * Whether or not a generic 'command not found' message * should be given in DMs to instruct the user to * use the `help` command. `true` by default * @type {boolean} */ this.unknownCommandError = options.unknownCommandError ?? true; /** * Whether or not the help command should send its output * in a DM to the command caller * @type {boolean} */ this.dmHelp = options.dmHelp ?? true; /** * Whether or not this client is passive. Passive clients * will not register a command dispatcher or a message * listener. This allows passive clients to be created that * do not respond to any commands but are able to perform * actions based on whatever the framework user wants * @type {boolean} */ this.passive = options.passive ?? false; /** * Whether or not the client will pause after loading Client * Storage, giving the opportunity to add/change default * settings before guild settings are created for the first * time. If this is used, you must create a listener for `'pause'`, * and call `<Client>.continue()` when you have finished doing * what you need to do. * * If adding new default settings is desired *after* guild settings * have already been generated for the first time, they should be * added after `'clientReady'` so they can be properly pushed to * the settings for all guilds * @type {boolean} */ this.pause = options.pause ?? false; /** * Array of base command names to skip when loading commands. Base commands * may only be disabled by name, not by alias * @type {BaseCommandName[]} */ this.disableBase = options.disableBase ?? []; // Set the global ratelimit if provided if (options.ratelimit) this.ratelimit = options.ratelimit; /** * A convenient instance of {@link RateLimitManager} for use anywhere * the Client is available * @type {RateLimitManager} */ this.rateLimitManager = new RateLimitManager(); /** * The EventLoader the client uses to load events. The client will load events * from the `eventsdir` directory passed in your `YAMDBFOptions`. * * Can be used by plugins to register directories to load custom event handlers from * @type {EventLoader} */ this.eventLoader = new EventLoader(this); // Set the logger level if provided if (typeof options.logLevel !== 'undefined') this._logger.setLogLevel(options.logLevel); /** * The chosen storage provider to use for the Client. * Defaults to {@link JSONProvider} * @type {StorageProvider} */ this.provider = options.provider ?? JSONProvider; // Plugins to load this._plugins = options.plugins ?? []; /** * Loads plugins and contains loaded plugins in case * accessing a loaded plugin at runtime is desired * @type {PluginLoader} */ this.plugins = new PluginLoader(this, this._plugins); // Middleware function storage for the client instance this.middleware = []; /** * Client-specific storage. Also contains a `guilds` Collection property containing * all GuildStorage instances * @type {ClientStorage} */ this.storage = new ClientStorage(this); this._guildStorageLoader = new GuildStorageLoader(this); /** * [Collection]{@link external:Collection} containing all loaded commands * @type {CommandRegistry<string, Command>} */ this.commands = new CommandRegistry<this, string, Command<this>>(this); /** * ResolverLoader instance containing loaded argument resolvers * @type {ResolverLoader} */ this.resolvers = new ResolverLoader(this); this.customResolvers = options.customResolvers ?? []; this.resolvers.loadResolvers(); /** * Whether or not compact mode is enabled * @type {boolean} */ this.compact = typeof options.compact !== 'undefined' ? options.compact : false; /** * Button shortcuts for compact mode. Defaults are * `success`, `fail`, and `working`. These can be overwritten * via the `buttons` field in {@link YAMDBFOptions} * @type {object} */ this.buttons = { success: '✅', fail: '❌', working: '🕐', ...options.buttons ?? {} }; /** * The argument parsing function the framework will use to parse * command arguments from message content input. Defaults to * splitting on {@link Command#argOpts.separator} * @type {Function} */ this.argsParser = options.argsParser ?? Util.parseArgs; /** * Whether or not ts-node is in use, allowing the Client * to attempt to load .ts files when loading Commands * @type {boolean} */ this.tsNode = options.tsNode ?? false; Lang.createInstance(this); Lang.loadLocalizations(); CompactModeHelper.createInstance(this); if (!this.passive) { this._commandLoader = new CommandLoader(this); this._dispatcher = new CommandDispatcher(this); if (this.eventsDir) this.eventLoader.addSourceDir(this.eventsDir); this._logger.info('Loading base commands...'); this._commandLoader.loadCommandsFrom(Path.join(__dirname, '../command/base'), true); // Disable setlang command if there is only one language if (Lang.langNames.length === 1 && !this.disableBase.includes('setlang') && this.commands.has('setlang')) this.commands.get('setlang')!.disable(); } registerListeners(this); } // #region Event handlers // @ts-ignore - Handled via ListenerUtil // eslint-disable-next-line @typescript-eslint/naming-convention @once('ready') private async __onReadyEvent(): Promise<void> { // Set default owner (OAuth Application owner) if none exists if (this.owner.length < 1) { const app: ClientApplication = await this.fetchApplication(); if (typeof app.owner !== 'undefined') this.owner[0] = app.owner!.id; } await this.storage.init(); // Load defaultGuildSettings into storage the first time the client is run if (!await this.storage.exists('defaultGuildSettings')) await this.storage.set('defaultGuildSettings', require('../storage/defaultGuildSettings.json')); if (this.pause) this.emit('pause'); else this.__onContinueEvent(); if (this.statusText) this.user!.setActivity(this.statusText); } // eslint-disable-next-line @typescript-eslint/naming-convention @once('continue') private async __onContinueEvent(): Promise<void> { await this._guildStorageLoader.init(); await this._guildStorageLoader.loadStorages(); await this._guildStorageLoader.cleanGuilds(); this._logger.info('Loading plugins...'); await this.plugins.loadPlugins(); if (!this.passive) { if (this.commandsDir) { this._logger.info('Loading custom commands...'); this._commandLoader.loadCommandsFrom(this.commandsDir); } this.commands.checkDuplicateAliases(); this.commands.checkReservedCommandNames(); this._logger.info('Initializing commands...'); const initSuccess: boolean = await this.commands.initCommands(); this._logger.info(`Commands initialized${initSuccess ? '' : ' with errors'}.`); Lang.loadCommandLocalizations(); this._dispatcher.setReady(); const commands: number = this.commands.size; const groups: number = this.commands.groups.length; this._logger.info( `Command dispatcher ready -- ${commands} commands in ${groups} groups` ); if (this.eventLoader.hasSources()) { this._logger.info('Loading events from registered sources...'); this.eventLoader.loadFromSources(); } } if (typeof this.readyText !== 'undefined') this._logger.log(this.readyText); this.emit('clientReady'); if (!this.user!.bot) this._logger.warn([ 'Userbots are no longer supported and no precautions are', 'taken to protect your account from accidentally abusing', 'the Discord API. Creating a userbot is NOT recommended.' ].join(' ')); } // @ts-ignore - Handled via ListenerUtil // eslint-disable-next-line @typescript-eslint/naming-convention @on('guildCreate') private async __onGuildCreateEvent(guild: Guild): Promise<void> { if (this.storage.guilds.has(guild.id)) { // Handle guild returning to the same shard in the same session const storage: GuildStorage = this.storage.guilds.get(guild.id)!; if (await storage.settings.exists('YAMDBFInternal.remove')) await storage.settings.remove('YAMDBFInternal.remove'); } else await this._guildStorageLoader.loadStorages(); } // @ts-ignore - Handled via ListenerUtil // eslint-disable-next-line @typescript-eslint/naming-convention @on('guildDelete') private __onGuildDeleteEvent(guild: Guild): void { if (this.storage.guilds.has(guild.id)) this.storage.guilds.get(guild.id)!.settings.set( 'YAMDBFInternal.remove', Date.now() + Time.parseShorthand('7d')! ); } // #endregion // #region Getters/Setters /** * The global ratelimit for all command usage per user * @type {string} */ public get ratelimit(): string { return this._ratelimit; } public set ratelimit(value: string) { Util.parseRateLimit(value); this._ratelimit = value; } // #endregion /** * Starts the login process, culminating in the `clientReady` event * @returns {Client} */ public start(): this { if (!this._token) throw new Error('Client cannot be started without being given a token.'); this.login(this._token); return this; } /** * Shortcut method for `<Client>.emit('continue')` * @returns {void} */ protected continue(): void { this.emit('continue'); } /** * Returns whether or not the given user is an owner * of the client/bot * @param {external:User} user User to check * @returns {boolean} */ public isOwner(user: User): boolean { return this.owner.includes(user.id); } /** * Set the value of a default setting key and push it to all guild * setting storages. Will not overwrite a setting in guild settings * storage if there is already an existing key with the given value * @param {string} key The key to use in settings storage * @param {any} value The value to use in settings storage * @returns {Promise<Client>} */ public async setDefaultSetting(key: string, value: any): Promise<this> { await this.storage.set(`defaultGuildSettings.${key}`, value); for (const guildStorage of this.storage.guilds.values()) if (!await guildStorage.settings.exists(key)) await guildStorage.settings.set(key, value); return this; } /** * Remove a `defaultGuildSettings` item. Will not remove from any current * guild settings, but will remove the item from the defaults added to * new guild settings storages upon creation * @param {string} key The key to use in settings storage * @returns {Promise<Client>} */ public async removeDefaultSetting(key: string): Promise<this> { await this.storage.remove(`defaultGuildSettings.${key}`); return this; } /** * Check if a default guild setting exists * @param {string} key The default settings key to check for * @returns {Promise<boolean>} */ public async defaultSettingExists(key: string): Promise<boolean> { return this.storage.exists(`defaultGuildSettings.${key}`); } /** * Shortcut to return the command prefix for the provided guild * @param {external:Guild} guild The Guild to get the prefix of * @returns {Promise<string | null>} */ public async getPrefix(guild: Guild): Promise<string | null> { if (!guild || !this.storage.guilds.has(guild.id)) return null; return await this.storage.guilds.get(guild.id)!.settings.get('prefix') ?? null; } /** * Generate a bot invite URL based on the permissions included * in all of the commands the client currently has loaded. * * >**Note:** This should be run after `clientReady` to ensure * no command permissions are missing from the permissions set * that will be used to generate the URL * @returns {Promise<string>} */ public async createBotInvite(): Promise<string> { const perms: Set<PermissionResolvable> = new Set(); for (const command of this.commands.values()) for (const perm of command.clientPermissions) perms.add(perm); return this.generateInvite({ permissions: Array.from(perms) }); } /** * Clean out expired guild storage/settings * @returns {Promise<void>} */ public async sweepStorages(): Promise<void> { await this._guildStorageLoader.cleanGuilds(); } /** * Adds a middleware function to be used when any command is called * to make modifications to args, determine if the command can * be run, or anything else you want to do every time any command * is called. * * See {@link MiddlewareFunction} for information on how a middleware * function should be represented * * Usage example: * ``` * <Client>.use((message, args) => [message, args.map(a => a.toUpperCase())]); * ``` * This will add a middleware function to all commands that will attempt * to transform all args to uppercase. This will of course fail if any * of the args are not a string. * * >**Note:** Middleware functions should only be added to the client one * time each and thus should not be added within any sort of event or loop. * Multiple separate middleware functions can be added to the via multiple * separate calls to this method * * >**Warning:** Do not use middleware for overriding the default argument * splitting. Use {@link YAMDBFOptions.argsParser} instead. Otherwise * you will see inconsistent results when using Command shortcuts, as * argument splitting for shortcut interpolation always happens before * middleware is run * @param {MiddlewareFunction} func The middleware function to use * @returns {Client} */ public use(func: MiddlewareFunction): this { this.middleware.push(func); return this; } /** * Reload custom commands. Used internally by the `reload` command * @private */ public reloadCustomCommands(): number { if (!this.commandsDir) throw new Error('Client is missing `commandsDir`, cannot reload Commands'); return this._commandLoader.loadCommandsFrom(this.commandsDir); } /** * Reload Events from all registered event source directories * @private */ public reloadEvents(): number { return this.eventLoader.loadFromSources(); } // #region Discord.js on() events public on<K extends keyof ClientEvents>(event: K, listener: (...args: ClientEvents[K]) => void): this; public on<S extends string | symbol>( event: Exclude<S, keyof ClientEvents>, listener: (...args: any[]) => void, ): this; // #endregion public on( event: 'command', listener: (name: string, args: any[], execTime: number, message: Message) => void ): this; public on( event: 'unknownCommand', listener: (name: string, args: any[], message: Message) => void ): this; public on(event: 'noCommand', listener: (message: Message) => void): this; public on(event: 'blacklistAdd' | 'blacklistRemove', listener: (user: User, global: boolean) => void): this; public on(event: 'pause' | 'continue' | 'clientReady', listener: () => void): this; /** * Emitted whenever a command is successfully called * @memberof Client * @event event:command * @param {string} name Name of the called command * @param {any[]} args Args passed to the called command * @param {number} execTime Time command took to execute * @param {external:Message} message Message that triggered the command */ /** * Emitted whenever a command is called that doesn't exist * @memberof Client * @event event:unknownCommand * @param {string} name The name of the command that was attempted to be called * @param {any[]} args Args passed to the unknown command * @param {external:Message} message Message that triggered the unknown command */ /** * Emitted whenever a message is received that does not contain a command or unknown command * @memberof Client * @event event:noCommand * @param {external:Message} message Message that did not contain a command or unknown command */ /** * Emitted whenever a user is blacklisted * @memberof Client * @event event:blacklistAdd * @param {User} user User who was blacklisted * @param {boolean} global Whether or not blacklisting is global */ /** * Emitted whenever a user is removed from the blacklist * @memberof Client * @event event:blacklistRemove * @param {User} user User who was removed * @param {boolean} global Whether or not removal is global */ /** * Emitted when the client is waiting for you to send a `continue` event, * after which `clientReady` will be emitted * @memberof Client * @event event:pause */ /** * To be emitted after the `pause` event when you have finished setting * things up that should be set up before the client is ready for use * @memberof Client * @event event:continue */ /** * Emitted when the client is ready. Should be used instead of Discord.js' * `ready` event, as this is the point that everything is set up within the * YAMDBF Client and it's all ready to go * @memberof Client * @event event:clientReady */ // on() wrapper to support overload signatures public on(event: string, listener: (...args: any[]) => void): this { return super.on(event, listener); } // #region Discord.js once() events public once<K extends keyof ClientEvents>(event: K, listener: (...args: ClientEvents[K]) => void): this; public once<S extends string | symbol>( event: Exclude<S, keyof ClientEvents>, listener: (...args: any[]) => void, ): this; // #endregion public once( event: 'command', listener: (name: string, args: any[], execTime: number, message: Message) => void ): this; public once(event: 'unknownCommand', listener: (name: string, args: any[], message: Message) => void): this; public once(event: 'noCommand', listener: (message: Message) => void): this; public once(event: 'blacklistAdd' | 'blacklistRemove', listener: (user: User, global: boolean) => void): this; public once(event: 'pause' | 'continue' | 'clientReady', listener: () => void): this; // Once() wrapper to support overload signatures public once(event: string, listener: (...args: any[]) => void): this { return super.once(event, listener); } }
the_stack
import { HttpClient, HttpResponse, HttpEvent } from '@angular/common/http'; import { Inject, Injectable, Optional } from '@angular/core'; import { TeamsAPIClientInterface } from './teams-api-client.interface'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; import { USE_DOMAIN, USE_HTTP_OPTIONS, TeamsAPIClient } from './teams-api-client.service'; import { DefaultHttpOptions, HttpOptions } from '../../types'; import * as models from '../../models'; import * as guards from '../../guards'; @Injectable() export class GuardedTeamsAPIClient extends TeamsAPIClient implements TeamsAPIClientInterface { constructor( readonly httpClient: HttpClient, @Optional() @Inject(USE_DOMAIN) domain?: string, @Optional() @Inject(USE_HTTP_OPTIONS) options?: DefaultHttpOptions, ) { super(httpClient, domain, options); } /** * Delete team. * In order to delete a team, the authenticated user must be an owner of the * org that the team is associated with. * * Response generated for [ 204 ] HTTP response code. */ deleteTeamsTeamId( args: Exclude<TeamsAPIClientInterface['deleteTeamsTeamIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteTeamsTeamId( args: Exclude<TeamsAPIClientInterface['deleteTeamsTeamIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteTeamsTeamId( args: Exclude<TeamsAPIClientInterface['deleteTeamsTeamIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; deleteTeamsTeamId( args: Exclude<TeamsAPIClientInterface['deleteTeamsTeamIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { return super.deleteTeamsTeamId(args, requestHttpOptions, observe); } /** * Get team. * Response generated for [ 200 ] HTTP response code. */ getTeamsTeamId( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Team>; getTeamsTeamId( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Team>>; getTeamsTeamId( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Team>>; getTeamsTeamId( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Team | HttpResponse<models.Team> | HttpEvent<models.Team>> { return super.getTeamsTeamId(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isTeam(res) || console.error(`TypeGuard for response 'models.Team' caught inconsistency.`, res))); } /** * Edit team. * In order to edit a team, the authenticated user must be an owner of the org * that the team is associated with. * * Response generated for [ 200 ] HTTP response code. */ patchTeamsTeamId( args: Exclude<TeamsAPIClientInterface['patchTeamsTeamIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Team>; patchTeamsTeamId( args: Exclude<TeamsAPIClientInterface['patchTeamsTeamIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Team>>; patchTeamsTeamId( args: Exclude<TeamsAPIClientInterface['patchTeamsTeamIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Team>>; patchTeamsTeamId( args: Exclude<TeamsAPIClientInterface['patchTeamsTeamIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Team | HttpResponse<models.Team> | HttpEvent<models.Team>> { return super.patchTeamsTeamId(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isTeam(res) || console.error(`TypeGuard for response 'models.Team' caught inconsistency.`, res))); } /** * List team members. * In order to list members in a team, the authenticated user must be a member * of the team. * * Response generated for [ 200 ] HTTP response code. */ getTeamsTeamIdMembers( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdMembersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Users>; getTeamsTeamIdMembers( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdMembersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Users>>; getTeamsTeamIdMembers( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdMembersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Users>>; getTeamsTeamIdMembers( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdMembersParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Users | HttpResponse<models.Users> | HttpEvent<models.Users>> { return super.getTeamsTeamIdMembers(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isUsers(res) || console.error(`TypeGuard for response 'models.Users' caught inconsistency.`, res))); } /** * The "Remove team member" API is deprecated and is scheduled for removal in the next major version of the API. We recommend using the Remove team membership API instead. It allows you to remove both active and pending memberships. * * * Remove team member. * In order to remove a user from a team, the authenticated user must have 'admin' * permissions to the team or be an owner of the org that the team is associated * with. * NOTE This does not delete the user, it just remove them from the team. * * Response generated for [ 204 ] HTTP response code. */ deleteTeamsTeamIdMembersUsername( args: Exclude<TeamsAPIClientInterface['deleteTeamsTeamIdMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteTeamsTeamIdMembersUsername( args: Exclude<TeamsAPIClientInterface['deleteTeamsTeamIdMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteTeamsTeamIdMembersUsername( args: Exclude<TeamsAPIClientInterface['deleteTeamsTeamIdMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; deleteTeamsTeamIdMembersUsername( args: Exclude<TeamsAPIClientInterface['deleteTeamsTeamIdMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { return super.deleteTeamsTeamIdMembersUsername(args, requestHttpOptions, observe); } /** * The "Get team member" API is deprecated and is scheduled for removal in the next major version of the API. We recommend using the Get team membership API instead. It allows you to get both active and pending memberships. * * * Get team member. * In order to get if a user is a member of a team, the authenticated user mus * be a member of the team. * * Response generated for [ 204 ] HTTP response code. */ getTeamsTeamIdMembersUsername( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getTeamsTeamIdMembersUsername( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getTeamsTeamIdMembersUsername( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; getTeamsTeamIdMembersUsername( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { return super.getTeamsTeamIdMembersUsername(args, requestHttpOptions, observe); } /** * The API (described below) is deprecated and is scheduled for removal in the next major version of the API. We recommend using the Add team membership API instead. It allows you to invite new organization members to your teams. * * * Add team member. * In order to add a user to a team, the authenticated user must have 'admin' * permissions to the team or be an owner of the org that the team is associated * with. * * Response generated for [ 204 ] HTTP response code. */ putTeamsTeamIdMembersUsername( args: Exclude<TeamsAPIClientInterface['putTeamsTeamIdMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; putTeamsTeamIdMembersUsername( args: Exclude<TeamsAPIClientInterface['putTeamsTeamIdMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; putTeamsTeamIdMembersUsername( args: Exclude<TeamsAPIClientInterface['putTeamsTeamIdMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; putTeamsTeamIdMembersUsername( args: Exclude<TeamsAPIClientInterface['putTeamsTeamIdMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { return super.putTeamsTeamIdMembersUsername(args, requestHttpOptions, observe); } /** * Remove team membership. * In order to remove a membership between a user and a team, the authenticated user must have 'admin' permissions to the team or be an owner of the organization that the team is associated with. NOTE: This does not delete the user, it just removes their membership from the team. * * Response generated for [ 204 ] HTTP response code. */ deleteTeamsTeamIdMembershipsUsername( args: Exclude<TeamsAPIClientInterface['deleteTeamsTeamIdMembershipsUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteTeamsTeamIdMembershipsUsername( args: Exclude<TeamsAPIClientInterface['deleteTeamsTeamIdMembershipsUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteTeamsTeamIdMembershipsUsername( args: Exclude<TeamsAPIClientInterface['deleteTeamsTeamIdMembershipsUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; deleteTeamsTeamIdMembershipsUsername( args: Exclude<TeamsAPIClientInterface['deleteTeamsTeamIdMembershipsUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { return super.deleteTeamsTeamIdMembershipsUsername(args, requestHttpOptions, observe); } /** * Get team membership. * In order to get a user's membership with a team, the authenticated user must be a member of the team or an owner of the team's organization. * * Response generated for [ 200 ] HTTP response code. */ getTeamsTeamIdMembershipsUsername( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdMembershipsUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.TeamMembership>; getTeamsTeamIdMembershipsUsername( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdMembershipsUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.TeamMembership>>; getTeamsTeamIdMembershipsUsername( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdMembershipsUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.TeamMembership>>; getTeamsTeamIdMembershipsUsername( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdMembershipsUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.TeamMembership | HttpResponse<models.TeamMembership> | HttpEvent<models.TeamMembership>> { return super.getTeamsTeamIdMembershipsUsername(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isTeamMembership(res) || console.error(`TypeGuard for response 'models.TeamMembership' caught inconsistency.`, res))); } /** * Add team membership. * In order to add a membership between a user and a team, the authenticated user must have 'admin' permissions to the team or be an owner of the organization that the team is associated with. * * * If the user is already a part of the team's organization (meaning they're on at least one other team in the organization), this endpoint will add the user to the team. * * * If the user is completely unaffiliated with the team's organization (meaning they're on none of the organization's teams), this endpoint will send an invitation to the user via email. This newly-created membership will be in the 'pending' state until the user accepts the invitation, at which point the membership will transition to the 'active' state and the user will be added as a member of the team. * * Response generated for [ 200 ] HTTP response code. */ putTeamsTeamIdMembershipsUsername( args: Exclude<TeamsAPIClientInterface['putTeamsTeamIdMembershipsUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.TeamMembership>; putTeamsTeamIdMembershipsUsername( args: Exclude<TeamsAPIClientInterface['putTeamsTeamIdMembershipsUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.TeamMembership>>; putTeamsTeamIdMembershipsUsername( args: Exclude<TeamsAPIClientInterface['putTeamsTeamIdMembershipsUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.TeamMembership>>; putTeamsTeamIdMembershipsUsername( args: Exclude<TeamsAPIClientInterface['putTeamsTeamIdMembershipsUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.TeamMembership | HttpResponse<models.TeamMembership> | HttpEvent<models.TeamMembership>> { return super.putTeamsTeamIdMembershipsUsername(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isTeamMembership(res) || console.error(`TypeGuard for response 'models.TeamMembership' caught inconsistency.`, res))); } /** * List team repos * Response generated for [ 200 ] HTTP response code. */ getTeamsTeamIdRepos( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.TeamRepos>; getTeamsTeamIdRepos( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.TeamRepos>>; getTeamsTeamIdRepos( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.TeamRepos>>; getTeamsTeamIdRepos( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.TeamRepos | HttpResponse<models.TeamRepos> | HttpEvent<models.TeamRepos>> { return super.getTeamsTeamIdRepos(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isTeamRepos(res) || console.error(`TypeGuard for response 'models.TeamRepos' caught inconsistency.`, res))); } /** * In order to add a repository to a team, the authenticated user must be an owner of the org that the team is associated with. Also, the repository must be owned by the organization, or a direct fork of a repository owned by the organization. * Response generated for [ default ] HTTP response code. */ putTeamsTeamIdReposOrgRepo( args: Exclude<TeamsAPIClientInterface['putTeamsTeamIdReposOrgRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; putTeamsTeamIdReposOrgRepo( args: Exclude<TeamsAPIClientInterface['putTeamsTeamIdReposOrgRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; putTeamsTeamIdReposOrgRepo( args: Exclude<TeamsAPIClientInterface['putTeamsTeamIdReposOrgRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; putTeamsTeamIdReposOrgRepo( args: Exclude<TeamsAPIClientInterface['putTeamsTeamIdReposOrgRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { return super.putTeamsTeamIdReposOrgRepo(args, requestHttpOptions, observe); } /** * In order to remove a repository from a team, the authenticated user must be an owner of the org that the team is associated with. NOTE: This does not delete the repository, it just removes it from the team. * Response generated for [ 204 ] HTTP response code. */ deleteTeamsTeamIdReposOwnerRepo( args: Exclude<TeamsAPIClientInterface['deleteTeamsTeamIdReposOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteTeamsTeamIdReposOwnerRepo( args: Exclude<TeamsAPIClientInterface['deleteTeamsTeamIdReposOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteTeamsTeamIdReposOwnerRepo( args: Exclude<TeamsAPIClientInterface['deleteTeamsTeamIdReposOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; deleteTeamsTeamIdReposOwnerRepo( args: Exclude<TeamsAPIClientInterface['deleteTeamsTeamIdReposOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { return super.deleteTeamsTeamIdReposOwnerRepo(args, requestHttpOptions, observe); } /** * Check if a team manages a repository * Response generated for [ default ] HTTP response code. */ getTeamsTeamIdReposOwnerRepo( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdReposOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getTeamsTeamIdReposOwnerRepo( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdReposOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getTeamsTeamIdReposOwnerRepo( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdReposOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; getTeamsTeamIdReposOwnerRepo( args: Exclude<TeamsAPIClientInterface['getTeamsTeamIdReposOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { return super.getTeamsTeamIdReposOwnerRepo(args, requestHttpOptions, observe); } }
the_stack
const defaultInitialVars: InitialVars = { isWatchingSourceFile: false } declare var acquireVsCodeApi: any declare var initialContent: string declare var initialConfig: CsvEditSettings | undefined declare var initialVars: InitialVars let vscode: VsExtension | undefined = undefined if (typeof acquireVsCodeApi !== 'undefined') { vscode = acquireVsCodeApi() } if (typeof initialConfig === 'undefined') { // tslint:disable-next-line:no-duplicate-variable var initialConfig = undefined as CsvEditSettings | undefined // tslint:disable-next-line:no-duplicate-variable var initialVars = { ...defaultInitialVars } } const csv: typeof import('papaparse') = (window as any).Papa //handsontable instance let hot: import('../thirdParty/handsontable/handsontable') | null //add toFormat to big numbers //@ts-ignore toFormat(Big) /** * the default csv content to used if we get empty content * handson table will throw if we pass in a 1D array because it expects an object? */ const defaultCsvContentIfEmpty = `,\n,` /** * TODO check * stores the header row after initial parse... * if we have header rows in data (checked) we set this to the header row * if we uncheck header row read option then we use this to insert the header row again as data row * can be null if we have 0 rows * {string[] | null} */ let headerRowWithIndex: HeaderRowWithIndex | null = null let lastClickedHeaderCellTh: Element | null = null let editHeaderCellTextInputEl: HTMLInputElement | null = null let editHeaderCellTextInputLeftOffsetInPx: number = 0 let handsontableOverlayScrollLeft: number = 0 let _onTableScrollThrottled: ((this: HTMLDivElement, e: Event) => void) | null = null let hiddenPhysicalRowIndices: number[] = [] let copyPasteRowLimit = 10000000 let copyPasteColLimit = 10000000 type HeaderRowWithIndexUndoStackItem = { action: 'added' | 'removed' visualIndex: number headerData: Array<string | null> } let headerRowWithIndexUndoStack: Array<HeaderRowWithIndexUndoStackItem> = [] let headerRowWithIndexRedoStack: Array<HeaderRowWithIndexUndoStackItem> = [] /** * this is part of the output from papaparse * for each column * true: column was originally quoted * false: was not quoted * * this is expanded via {@link _normalizeDataArray} so we have information about every column * see {@link parseCsv} for quoting rules (e.g. header rows, ...) * * so this is set in {@link displayData} and should be kept up-to-date because it's used for unparsing */ let columnIsQuoted: boolean[] //csv reader options + some ui options //this gets overwritten with the real configuration in setCsvReadOptionsInitial let defaultCsvReadOptions: CsvReadOptions = { header: false, //always use false to get an array of arrays comments: '#', delimiter: '', //auto detect newline: '', //auto detect quoteChar: '"', escapeChar: '"', skipEmptyLines: true, dynamicTyping: false, _hasHeader: false, } //this gets overwritten with the real configuration in setCsvWriteOptionsInitial let defaultCsvWriteOptions: CsvWriteOptions = { header: false, comments: '#', delimiter: '', //'' = use from input, will be set from empty to string when exporting (or earlier) newline: '', //set by editor quoteChar: '"', escapeChar: '"', quoteAllFields: false, quoteEmptyOrNullFields: false, retainQuoteInformation: true, } //will be set when we read the csv content let newLineFromInput = '\n' //we need to store this because for collapsed columns we need to change the selection //and we need to know if we we need to change the column or not let lastHandsonMoveWas: 'tab' | 'enter' | null = null /** * true: the cell/row color is changed if the first cell is a comment, (might have negative impact on performance e.g. for large data sets), * false: no additional highlighting (comments are still treated as comments) */ let highlightCsvComments: boolean = true /** * true: new columns will get true as quote information (also for added columns via expanding), * false: new columns will get false as quote information */ let newColumnQuoteInformationIsQuoted: boolean = false /** * true: cell content is wrapped and the row height is changed, * false: no wrapping (content is hidden) */ let enableWrapping: boolean = true /** * true: borders are set to 0 (in css). This helps if you encounter some border color issues, * false: normal borders */ let disableBorders: boolean = false /** * fixes the first X rows so they will stay in view even if you scroll */ let fixedRowsTop: number = 0 /** * fixes the first X columns so they will stay in view even if you scroll */ let fixedColumnsLeft: number = 0 /** * true: we started with has header option enabled which caused an event * because we change the table when removing the header row from the table body we need to clear the undo... * false: nothing to do */ let isFirstHasHeaderChangedEvent = true /** * the initial width for columns, 0 or a negative number will disable this and auto column size is used on initial render */ let initialColumnWidth: number = 0 /** * this is only needed if we want to display header rows but we have only 1 row... * handsontable always needs at least one row so we cannot remove the first row and use it as header * so we store here that we want to set the first row as header row immediately after we have at least 2 rows * true: use the first row as header row immediately after we have at least 2 rows * false: do not use the first row as header (also false we have toggle has header option and have >= 2 rows) */ let shouldApplyHasHeaderAfterRowsAdded = false /** * table is editable or not, also disables some related ui, e.g. buttons * set via {@link CsvEditSettings.initiallyIsInReadonlyMode} */ let isReadonlyMode = false /** * stores the widths of the handsontable columns * THIS is always synced with the ui * it allows us to modify the widths better e.g. restore widths... * * uses visual column indices! * * inspired by https://github.com/YaroslavOvdii/fliplet-widget-data-source/blob/master/js/spreadsheet.js (also see https://github.com/Fliplet/fliplet-widget-data-source/pull/81/files) */ let allColWidths: number[] = [] //afterRender is called directly after we render the table but we might want to apply old col widths here let isInitialHotRender = true const csvEditorWrapper = _getById('csv-editor-wrapper') const csvEditorDiv = _getById('csv-editor') const helModalDiv = _getById('help-modal') const askReadAgainModalDiv = _getById('ask-read-again-modal') const askReloadFileModalDiv = _getById('ask-reload-file-modal') const sourceFileChangedDiv = _getById('source-file-changed-modal') //we also have some css that rely on these ids const readContent = _getById('read-options-content') const writeContent = _getById('write-options-content') const previewContent = _getById('preview-content') const btnApplyChangesToFileAndSave = _getById(`btn-apply-changes-to-file-and-save`) const readDelimiterTooltip = _getById('read-delimiter-tooltip') const readDelimiterTooltipText = "Empty to auto detect" const receivedCsvProgBar = _getById('received-csv-prog-bar') as HTMLProgressElement const receivedCsvProgBarWrapper = _getById('received-csv-prog-bar-wrapper') as HTMLDivElement const statusInfo = _getById('status-info') as HTMLSpanElement const fixedRowsTopInfoSpan = _getById('fixed-rows-top-info') as HTMLDivElement const fixedRowsTopIcon = _getById('fixed-rows-icon') as HTMLSpanElement const fixedRowsTopText = _getById('fixed-rows-text') as HTMLSpanElement const fixedColumnsTopInfoSpan = _getById('fixed-columns-top-info') as HTMLDivElement const fixedColumnsTopIcon = _getById('fixed-columns-icon') as HTMLSpanElement const fixedColumnsTopText = _getById('fixed-columns-text') as HTMLSpanElement const showCommentsBtn = _getById('show-comments-btn') as HTMLButtonElement const hideCommentsBtn = _getById('hide-comments-btn') as HTMLButtonElement const newlineSameSsInputOption = _getById('newline-same-as-input-option') as HTMLOptionElement const newlineSameSsInputOptionText = `Same as input` updateNewLineSelect() //add this to the first wrong column const warningTooltipTextWhenCommentRowNotFirstCellIsUsed = `Please use only the first cell in comment row (others are not exported)` const unsavedChangesIndicator = _getById('unsaved-changes-indicator') as HTMLSpanElement const reloadFileSpan = _getById('reload-file') as HTMLSpanElement //reread the file content... const sourceFileUnwatchedIndicator = _getById('source-file-unwatched-indicator') as HTMLSpanElement const hasHeaderReadOptionInput = _getById('has-header') as HTMLInputElement const hasHeaderLabel = _getById(`has-header-label`) as HTMLLabelElement const leftSidePanelToggle = document.getElementById('left-panel-toggle') if (vscode && !leftSidePanelToggle) throw new Error(`element with id 'left-panel-toggle' not found`) //null is ok for browser const leftPanelToggleIconExpand = document.getElementById(`left-panel-toggle-icon-expand`) as HTMLElement //<i> if (vscode && !leftPanelToggleIconExpand) throw new Error(`element with id 'left-panel-toggle-icon-expand' not found`) //null is ok for browser const sideBarResizeHandle = _getById(`side-panel-resize-handle`) as HTMLDivElement //--- side stats const sidePanel = _getById(`side-panel`) as HTMLDivElement const statSelectedRows = _getById(`stat-selected-rows`) as HTMLDivElement const statSelectedCols = _getById(`stat-selected-cols`) as HTMLDivElement const statRowsCount = _getById(`stat-rows-count`) as HTMLDivElement const statColsCount = _getById(`stat-cols-count`) as HTMLDivElement const statSelectedCellsCount = _getById(`stat-selected-cells-count`) as HTMLDivElement const statSelectedNotEmptyCells = _getById(`stat-selected-not-empty-cells`) as HTMLDivElement const statSumOfNumbers = _getById(`stat-sum-of-numbers`) as HTMLDivElement const numbersStyleEnRadio = _getById(`numbers-style-en`) as HTMLInputElement //radio const numbersStyleNonEnRadio = _getById(`numbers-style-non-en`) as HTMLInputElement //radio const isReadonlyModeToggleSpan = _getById(`is-readonly-mode-toggle`) as HTMLSpanElement //--- find widget controls const findWidgetInstance = new FindWidget() setupSideBarResizeHandle() /* main */ //set defaults when we are in browser setCsvReadOptionsInitial(defaultCsvReadOptions) setCsvWriteOptionsInitial(defaultCsvWriteOptions) if (typeof initialContent === 'undefined') { // tslint:disable-next-line:no-duplicate-variable var initialContent = '' } if (initialContent === undefined) { initialContent = '' } // initialContent = `123,wet // 4,5` // initialContent = // ` // #test , wer // # wetwet // 1,2,3 // 4,5,6,7,8 // 4,5,6,7,8 // ` if (!vscode) { console.log("initialConfig: ", initialConfig) console.log("initialContent: " + initialContent) } //set values from extension config setupAndApplyInitialConfigPart1(initialConfig, initialVars) setupGlobalShortcutsInVs() //see readDataAgain let _data = parseCsv(initialContent, defaultCsvReadOptions) //when we get data from vs code we receive it via messages if (_data && !vscode) { let _exampleData: string[][] = [] let initialRows = 5 let initialCols = 5 _exampleData = [...Array(initialRows).keys()].map(p => [...Array(initialCols).keys()].map(k => '') ) //@ts-ignore // _exampleData = Handsontable.helper.createSpreadsheetData(100, 20) // _exampleData = Handsontable.helper.createSpreadsheetData(1000, 20) // _exampleData = Handsontable.helper.createSpreadsheetData(10000, 21) // _exampleData = Handsontable.helper.createSpreadsheetData(100000, 20) _data = { columnIsQuoted: _exampleData[0].map(p => false), data: _exampleData } displayData(_data, defaultCsvReadOptions) } if (vscode) { receivedCsvProgBarWrapper.style.display = "block" window.addEventListener('message', (e) => { handleVsCodeMessage(e) }) _postReadyMessage() // console.log(JSON.stringify(vscode.getState())) } //-------------------------------------------------- global shortcuts //only in vs code not in browser //register this before handsontable so we can first apply our actions function setupGlobalShortcutsInVs() { if (vscode) { Mousetrap.bindGlobal(['meta+s', 'ctrl+s'], (e) => { e.preventDefault() postApplyContent(true) }) } Mousetrap.bindGlobal(['ctrl+ins'], (e) => { insertRowBelow() }) Mousetrap.bindGlobal(['ctrl+shift+ins'], (e) => { insertRowAbove() }) //---- some shortcuts are also in ui.ts where the handsontable instance is created... //needed for core handsontable shortcuts e.g. that involve arrow keys }
the_stack
import { KeyboardShortcutHandler } from 'background/keyboard-shortcut-handler'; import { UserConfigurationStore } from 'background/stores/global/user-configuration-store'; import { TabContextStoreHub } from 'background/stores/tab-context-store-hub'; import { VisualizationStore } from 'background/stores/visualization-store'; import { TabContextManager } from 'background/tab-context-manager'; import { UsageLogger } from 'background/usage-logger'; import { BaseStore } from 'common/base-store'; import { BrowserAdapter } from 'common/browser-adapters/browser-adapter'; import { CommandsAdapter } from 'common/browser-adapters/commands-adapter'; import { VisualizationConfigurationFactory } from 'common/configs/visualization-configuration-factory'; import { WebVisualizationConfigurationFactory } from 'common/configs/web-visualization-configuration-factory'; import { DisplayableStrings } from 'common/constants/displayable-strings'; import { TelemetryEventSource } from 'common/extension-telemetry-events'; import { Logger } from 'common/logging/logger'; import { Message } from 'common/message'; import { Messages } from 'common/messages'; import { NotificationCreator } from 'common/notification-creator'; import { TelemetryDataFactory } from 'common/telemetry-data-factory'; import { VisualizationStoreData } from 'common/types/store-data/visualization-store-data'; import { VisualizationType } from 'common/types/visualization-type'; import { UrlValidator } from 'common/url-validator'; import { IMock, It, Mock, MockBehavior, Times } from 'typemoq'; import { Tabs } from 'webextension-polyfill'; import { VisualizationStoreDataBuilder } from '../../common/visualization-store-data-builder'; describe('KeyboardShortcutHandler', () => { const existingTabId = 1; let testSubject: KeyboardShortcutHandler; let browserAdapterMock: IMock<BrowserAdapter>; let commandsAdapterMock: IMock<CommandsAdapter>; let urlValidatorMock: IMock<UrlValidator>; let tabContextManagerMock: IMock<TabContextManager>; let visualizationStoreMock: IMock<BaseStore<VisualizationStoreData>>; let loggerMock: IMock<Logger>; let usageLoggerMock: IMock<UsageLogger>; let commandCallback: (commandId: string) => Promise<void>; let notificationCreatorMock: IMock<NotificationCreator>; let storeState: VisualizationStoreData; let simulatedIsFirstTimeUserConfiguration: boolean; let simulatedIsSupportedUrlResponse: boolean; let simulatedActiveTabId: Number; let simulatedActiveTabUrl: string; let visualizationConfigurationFactory: VisualizationConfigurationFactory; const testSource: TelemetryEventSource = TelemetryEventSource.ShortcutCommand; beforeEach(() => { visualizationConfigurationFactory = new WebVisualizationConfigurationFactory(); visualizationStoreMock = Mock.ofType(VisualizationStore, MockBehavior.Strict); visualizationStoreMock.setup(vs => vs.getState()).returns(() => storeState); tabContextManagerMock = Mock.ofType<TabContextManager>(); tabContextManagerMock .setup(t => t.getTabContextStores(existingTabId)) .returns( () => ({ visualizationStore: visualizationStoreMock.object } as TabContextStoreHub), ); browserAdapterMock = Mock.ofType<BrowserAdapter>(); browserAdapterMock .setup(adapter => adapter.tabsQuery(It.isValue({ active: true, currentWindow: true }))) .returns(() => Promise.resolve([ { id: simulatedActiveTabId, url: simulatedActiveTabUrl } as Tabs.Tab, ]), ) .verifiable(); commandsAdapterMock = Mock.ofType<CommandsAdapter>(); commandsAdapterMock .setup(adapter => adapter.addCommandListener(It.isAny())) .callback(callback => { commandCallback = callback; }) .verifiable(); urlValidatorMock = Mock.ofType(UrlValidator); urlValidatorMock .setup(uV => uV.isSupportedUrl(It.isAny())) .returns(async () => simulatedIsSupportedUrlResponse) .verifiable(); notificationCreatorMock = Mock.ofType(NotificationCreator); const userConfigurationStoreMock = Mock.ofType(UserConfigurationStore, MockBehavior.Strict); userConfigurationStoreMock .setup(s => s.getState()) .returns(() => { return { isFirstTime: simulatedIsFirstTimeUserConfiguration, enableTelemetry: true, enableHighContrast: false, lastSelectedHighContrast: false, bugService: 'none', bugServicePropertiesMap: {}, adbLocation: null, lastWindowState: null, lastWindowBounds: null, showAutoDetectedFailuresDialog: true, }; }); loggerMock = Mock.ofType<Logger>(); usageLoggerMock = Mock.ofType<UsageLogger>(); testSubject = new KeyboardShortcutHandler( tabContextManagerMock.object, browserAdapterMock.object, urlValidatorMock.object, notificationCreatorMock.object, new WebVisualizationConfigurationFactory(), new TelemetryDataFactory(), userConfigurationStoreMock.object, commandsAdapterMock.object, loggerMock.object, usageLoggerMock.object, ); testSubject.initialize(); // Individual tests may override these; these are preset to simple/arbitrary values // that would enable normal happy-path operation of the testSubject. storeState = new VisualizationStoreDataBuilder().build(); simulatedIsFirstTimeUserConfiguration = false; simulatedActiveTabId = existingTabId; simulatedActiveTabUrl = 'https://arbitrary.url'; simulatedIsSupportedUrlResponse = true; }); const supportedVisualizationTypes = [ ['Issues', VisualizationType.Issues], ['Landmarks', VisualizationType.Landmarks], ['Headings', VisualizationType.Headings], ['Color', VisualizationType.Color], ['TabStops', VisualizationType.TabStops], ['NeedsReview', VisualizationType.NeedsReview], ]; const visualizationTypesThatShouldNotifyOnEnable = [ ['Issues', VisualizationType.Issues], ['Landmarks', VisualizationType.Landmarks], ['Headings', VisualizationType.Headings], ['Color', VisualizationType.Color], ['NeedsReview', VisualizationType.NeedsReview], ]; const visualizationTypesThatShouldNotNotifyOnEnable = [ ['TabStops', VisualizationType.TabStops], ]; it.each(supportedVisualizationTypes)( `enables previously-disabled '%s' visualizer`, async (_, visualizationType: VisualizationType) => { storeState = new VisualizationStoreDataBuilder().withDisable(visualizationType).build(); const configuration = visualizationConfigurationFactory.getConfiguration(visualizationType); let receivedMessage: Message; tabContextManagerMock .setup(t => t.interpretMessageForTab(existingTabId, It.isAny())) .returns((_tabId, message) => { receivedMessage = message; return true; }) .verifiable(); await commandCallback(configuration.chromeCommand); expect(receivedMessage).toEqual({ tabId: existingTabId, messageType: Messages.Visualizations.Common.Toggle, payload: { enabled: true, telemetry: { triggeredBy: 'shortcut', enabled: true, source: testSource, }, test: visualizationType, }, }); usageLoggerMock.verify(m => m.record(), Times.once()); tabContextManagerMock.verifyAll(); }, ); it.each(supportedVisualizationTypes)( `disables previously-enabled '%s' visualizer`, async (_, visualizationType: VisualizationType) => { storeState = new VisualizationStoreDataBuilder().withEnable(visualizationType).build(); const configuration = visualizationConfigurationFactory.getConfiguration(visualizationType); let receivedMessage: Message; tabContextManagerMock .setup(t => t.interpretMessageForTab(existingTabId, It.isAny())) .returns((_tabId, message) => { receivedMessage = message; return true; }) .verifiable(); await commandCallback(configuration.chromeCommand); expect(receivedMessage).toEqual({ tabId: existingTabId, messageType: Messages.Visualizations.Common.Toggle, payload: { enabled: false, telemetry: { triggeredBy: 'shortcut', enabled: false, source: testSource, }, test: visualizationType, }, }); usageLoggerMock.verify(m => m.record(), Times.once()); tabContextManagerMock.verifyAll(); }, ); it.each(visualizationTypesThatShouldNotifyOnEnable)( `emits the expected 'enabled' notification when enabling '%s' visualizer`, async (_, visualizationType: VisualizationType) => { storeState = new VisualizationStoreDataBuilder().withDisable(visualizationType).build(); const configuration = visualizationConfigurationFactory.getConfiguration(visualizationType); const enableMessage = configuration.displayableData.enableMessage; notificationCreatorMock .setup(nc => nc.createNotification(enableMessage)) .verifiable(Times.once()); await commandCallback(configuration.chromeCommand); usageLoggerMock.verify(m => m.record(), Times.once()); notificationCreatorMock.verifyAll(); }, ); it.each(visualizationTypesThatShouldNotNotifyOnEnable)( `does not emit unexpected 'enabled' notification when enabling '%s' visualizer`, async (_, visualizationType: VisualizationType) => { storeState = new VisualizationStoreDataBuilder().withDisable(visualizationType).build(); const configuration = visualizationConfigurationFactory.getConfiguration(visualizationType); notificationCreatorMock .setup(nc => nc.createNotification(It.isAny())) .verifiable(Times.never()); await commandCallback(configuration.chromeCommand); usageLoggerMock.verify(m => m.record(), Times.once()); notificationCreatorMock.verifyAll(); }, ); it('does not emit toggle messages for unknown command strings', async () => { tabContextManagerMock .setup(t => t.interpretMessageForTab(It.isAny(), It.isAny())) .verifiable(Times.never()); await commandCallback('unknown-command'); usageLoggerMock.verify(m => m.record(), Times.once()); tabContextManagerMock.verifyAll(); }); it('does not emit toggle messages if the first-time dialog has not been dismissed yet', async () => { simulatedIsFirstTimeUserConfiguration = true; tabContextManagerMock .setup(t => t.interpretMessageForTab(It.isAny(), It.isAny())) .verifiable(Times.never()); await commandCallback(getArbitraryValidChromeCommand()); usageLoggerMock.verify(m => m.record(), Times.never()); tabContextManagerMock.verifyAll(); }); it('does not emit toggle messages when the active/current tab has no known tab context', async () => { simulatedActiveTabId = 12; expect(simulatedActiveTabId !== existingTabId); tabContextManagerMock .setup(t => t.interpretMessageForTab(It.isAny(), It.isAny())) .verifiable(Times.never()); await commandCallback(getArbitraryValidChromeCommand()); usageLoggerMock.verify(m => m.record(), Times.once()); tabContextManagerMock.verifyAll(); }); it('does not emit toggle messages if scanning is in progress already', async () => { storeState = new VisualizationStoreDataBuilder() .withEnable(VisualizationType.Issues) .withEnable(VisualizationType.Headings) .with('scanning', 'headings') .build(); const configuration = visualizationConfigurationFactory.getConfiguration( VisualizationType.Issues, ); tabContextManagerMock .setup(t => t.interpretMessageForTab(It.isAny(), It.isAny())) .verifiable(Times.never()); await commandCallback(configuration.chromeCommand); usageLoggerMock.verify(m => m.record(), Times.once()); tabContextManagerMock.verifyAll(); }); it("does not emit toggle messages if the active/current tab's URL is not supported", async () => { simulatedIsSupportedUrlResponse = false; tabContextManagerMock .setup(t => t.interpretMessageForTab(It.isAny(), It.isAny())) .verifiable(Times.never()); await commandCallback(getArbitraryValidChromeCommand()); usageLoggerMock.verify(m => m.record(), Times.once()); tabContextManagerMock.verifyAll(); }); it.each` protocol | expectedNotificationMessage ${'file://'} | ${DisplayableStrings.fileUrlDoesNotHaveAccess} ${'chrome://'} | ${DisplayableStrings.urlNotScannable.join('\n')} `( 'emits the expected notification when the active/current tab is an unsupported $protocol URL', async ({ protocol, expectedNotificationMessage }) => { simulatedActiveTabUrl = `${protocol}arbitrary-host`; simulatedIsSupportedUrlResponse = false; notificationCreatorMock .setup(nc => nc.createNotification(expectedNotificationMessage)) .verifiable(); await commandCallback(getArbitraryValidChromeCommand()); usageLoggerMock.verify(m => m.record(), Times.once()); notificationCreatorMock.verifyAll(); }, ); function getArbitraryValidChromeCommand(): string { const configuration = visualizationConfigurationFactory.getConfiguration( VisualizationType.Issues, ); return configuration.chromeCommand; } });
the_stack
import React, { Component, MouseEventHandler } from 'react' import cx from 'classnames' import analytics from 'src/analytics' import { Annotation as AnnotationFlawed, AnnotationPrivacyLevels, } from 'src/annotations/types' import { AnnotationSharingInfo, AnnotationSharingAccess, } from 'src/content-sharing/ui/types' import AnnotationEditable from 'src/annotations/components/AnnotationEditable' import { HoverBox } from 'src/common-ui/components/design-library/HoverBox' import { PageNotesCopyPaster } from 'src/copy-paster' import { contentSharing, auth, tags, } from 'src/util/remote-functions-background' import SingleNoteShareMenu from 'src/overview/sharing/SingleNoteShareMenu' import { INIT_FORM_STATE } from 'src/sidebar/annotations-sidebar/containers/logic' import type { EditForm, EditForms, } from 'src/sidebar/annotations-sidebar/containers/types' import { AnnotationMode } from 'src/sidebar/annotations-sidebar/types' import { copyToClipboard } from 'src/annotations/content_script/utils' import { ContentSharingInterface } from 'src/content-sharing/background/types' import { RemoteCopyPasterInterface } from 'src/copy-paster/background/types' import TagPicker from 'src/tags/ui/TagPicker' const styles = require('./annotation-list.css') // TODO (sidebar-refactor): somewhere this type regressed and `isBookmarked` got // changed to `hasBookmark` type Annotation = Omit<AnnotationFlawed, 'isBookmarked'> & { hasBookmark: boolean } export interface Props { activeShareMenuNoteId: string | undefined activeTagPickerNoteId: string | undefined activeCopyPasterAnnotationId: string | undefined /** Override for expanding annotations by default */ isExpandedOverride: boolean /** Array of matched annotations, limited to 3 */ annotations: Annotation[] /** URL of the page to which these annotations belong */ pageUrl: string /** Opens the annotation sidebar with all of the annotations */ openAnnotationSidebar: MouseEventHandler goToAnnotation: (annotation: Annotation) => void handleEditAnnotation: (url: string, comment: string, tags: string[]) => void handleDeleteAnnotation: (url: string) => void setActiveTagPickerNoteId: (id: string) => void setActiveShareMenuNoteId?: (id: string) => void setActiveCopyPasterAnnotationId?: (id: string) => void contentSharing: ContentSharingInterface copyPaster: RemoteCopyPasterInterface } interface SharingInfo { [annotationUrl: string]: AnnotationSharingInfo } interface State { /** Boolean to denote whether the list is expanded or not */ isExpanded: boolean /** The previous prop to compare in getDerivedStateFromProps */ prevIsExpandedOverride: boolean /** Received annotations are stored and manipulated through edit/delete */ annotations: Annotation[] editForms: EditForms annotationModes: { [annotationUrl: string]: AnnotationMode } annotationsSharingInfo: SharingInfo sharingAccess: AnnotationSharingAccess } class AnnotationList extends Component<Props, State> { private authBG = auth private tagsBG = tags private contentShareBG = contentSharing state: State = { /* The initial value is set to the isExpandedOverride which is fetched from localStorage. */ isExpanded: this.props.isExpandedOverride, prevIsExpandedOverride: this.props.isExpandedOverride, // TODO: This shouldn't be in state - get it out and ensure wherever it gets passed down as props from properly handles state mutations annotations: this.props.annotations, editForms: this.props.annotations.reduce( (acc, curr) => ({ ...acc, [curr.url]: { ...INIT_FORM_STATE, commentText: curr.comment, tags: curr.tags, }, }), {}, ), annotationModes: this.props.annotations.reduce( (acc, curr) => ({ ...acc, [curr.url]: 'default' }), {}, ), sharingAccess: 'sharing-allowed', annotationsSharingInfo: {}, } /** * We compare if the previous isExpandedOverride prop is different from * the current isExpandedOverride, then we set the state accordingly. */ static getDerivedStateFromProps(props: Props, state: State): State { if (props.isExpandedOverride !== state.prevIsExpandedOverride) { return { ...state, isExpanded: props.isExpandedOverride, prevIsExpandedOverride: props.isExpandedOverride, } } return state } async componentDidMount() { await this.detectSharedAnnotations() } private async detectSharedAnnotations() { const annotationSharingInfo: SharingInfo = {} const annotationUrls = this.props.annotations.map((a) => a.url) const remoteIds = await this.contentShareBG.getRemoteAnnotationIds({ annotationUrls, }) for (const localId of Object.keys(remoteIds)) { annotationSharingInfo[localId] = { status: 'shared', taskState: 'pristine', privacyLevel: AnnotationPrivacyLevels.SHARED, } } this.setState(() => ({ annotationsSharingInfo: annotationSharingInfo, })) } private updateAnnotationShareState = (annotationUrl: string) => ( info: AnnotationSharingInfo, ) => this.setState((state) => ({ annotationsSharingInfo: { ...state.annotationsSharingInfo, [annotationUrl]: info, }, })) private toggleIsExpanded = () => { this.setState( (prevState: State): State => ({ ...prevState, isExpanded: !prevState.isExpanded, }), ) } private handleEditAnnotation = (url: string) => () => { const { annotations, editForms } = this.state const index = annotations.findIndex((annot) => annot.url === url) const form = editForms[url] const annotation: Annotation = annotations[index] if ( !annotation || (!annotation.body && !form.commentText?.length && !form.tags?.length) ) { return } const newAnnotations: Annotation[] = [ ...annotations.slice(0, index), { ...annotation, comment: form.commentText, tags: form.tags, lastEdited: new Date(), }, ...annotations.slice(index + 1), ] this.props.handleEditAnnotation(url, form.commentText, form.tags) this.setState((state) => ({ annotations: newAnnotations, annotationModes: { ...state.annotationModes, [url]: 'default' }, editForms: { ...state.editForms, [url]: { ...INIT_FORM_STATE, commentText: state.editForms[url].commentText, tags: state.editForms[url].tags, }, }, })) } private handleDeleteAnnotation = (url: string) => () => { this.props.handleDeleteAnnotation(url) // Delete the annotation in the state too const { annotations } = this.state const index = this.state.annotations.findIndex( (annot) => annot.url === url, ) const newAnnotations = [ ...annotations.slice(0, index), ...annotations.slice(index + 1), ] this.setState({ annotations: newAnnotations, }) } private handleGoToAnnotation = (annotation: Annotation) => () => { this.props.goToAnnotation(annotation) } private handleTagPickerClick = (url: string) => () => { this.props.setActiveTagPickerNoteId(url) } private handleEditCancel = (url: string, commentText: string) => () => this.setState((state) => ({ annotationModes: { [url]: 'default' }, editForms: { ...state.editForms, [url]: { ...state.editForms[url], commentText, }, }, })) private handleShareClick = (url: string) => () => { if (this.props.setActiveShareMenuNoteId != null) { this.props.setActiveShareMenuNoteId(url) } } private renderTagPicker(annot: Annotation) { if (this.props.activeTagPickerNoteId !== annot.url) { return null } return ( <div className={styles.hoverBoxWrapper}> <HoverBox> <TagPicker onUpdateEntrySelection={(args) => this.tagsBG.updateTagForPage({ ...args, url: annot.url, }) } initialSelectedEntries={() => annot.tags} onClickOutside={() => this.props.setActiveTagPickerNoteId(undefined) } /> </HoverBox> </div> ) } private renderCopyPasterManager(annot: Annotation) { if (this.props.activeCopyPasterAnnotationId !== annot.url) { return null } return ( <div className={styles.hoverBoxWrapper}> <HoverBox> <PageNotesCopyPaster copyPaster={this.props.copyPaster} annotationUrls={[annot.url]} normalizedPageUrls={[annot.pageUrl]} onClickOutside={() => this.props.setActiveCopyPasterAnnotationId?.( undefined, ) } /> </HoverBox> </div> ) } private renderShareMenu(annot: Annotation) { if (this.props.activeShareMenuNoteId !== annot.url) { return null } return ( <div className={styles.hoverBoxWrapper}> <HoverBox> <SingleNoteShareMenu contentSharingBG={this.props.contentSharing} copyLink={async (link) => { analytics.trackEvent({ category: 'ContentSharing', action: 'copyNoteLink', }) await copyToClipboard(link) }} annotationUrl={annot.url} postShareHook={({ isShared, isProtected }) => this.updateAnnotationShareState(annot.url)({ status: isShared ? 'shared' : 'unshared', taskState: 'success', privacyLevel: isProtected ? AnnotationPrivacyLevels.PROTECTED : undefined, }) } closeShareMenu={() => this.props.setActiveShareMenuNoteId?.(undefined) } /> </HoverBox> </div> ) } private handleEditFormUpdate = ( url: string, deriveState: (state: State) => Partial<EditForm>, ) => { this.setState((state) => ({ editForms: { ...state.editForms, [url]: { ...state.editForms[url], ...deriveState(state), }, }, })) } private renderAnnotations() { return this.state.annotations.map((annot) => ( <AnnotationEditable key={annot.url} {...annot} body={annot.body} comment={annot.comment} className={styles.annotation} createdWhen={annot.createdWhen!} isShared={false} isBulkShareProtected={false} mode={this.state.annotationModes[annot.url]} onGoToAnnotation={this.handleGoToAnnotation(annot)} renderShareMenuForAnnotation={() => this.renderShareMenu(annot)} renderCopyPasterForAnnotation={() => this.renderCopyPasterManager(annot) } renderTagsPickerForAnnotation={() => this.renderTagPicker(annot) } annotationEditDependencies={{ comment: this.state.editForms[annot.url].commentText, onCommentChange: (commentText) => this.handleEditFormUpdate(annot.url, () => ({ commentText, })), onEditCancel: this.handleEditCancel( annot.url, annot.comment, ), onEditConfirm: this.handleEditAnnotation(annot.url), }} annotationFooterDependencies={{ onEditIconClick: () => this.setState({ annotationModes: { [annot.url]: 'edit', }, }), onEditCancel: this.handleEditCancel( annot.url, annot.comment, ), onEditConfirm: this.handleEditAnnotation(annot.url), onDeleteCancel: this.handleEditCancel( annot.url, annot.comment, ), onDeleteConfirm: this.handleDeleteAnnotation(annot.url), onDeleteIconClick: () => this.setState({ annotationModes: { [annot.url]: 'delete' }, }), onTagIconClick: this.handleTagPickerClick(annot.url), onShareClick: this.handleShareClick(annot.url), onCopyPasterBtnClick: this.props.setActiveCopyPasterAnnotationId != null ? () => this.props.setActiveCopyPasterAnnotationId( annot.url, ) : undefined, }} /> )) } render() { const { isExpanded } = this.state return ( <div className={cx({ [styles.parentExpanded]: isExpanded, })} > {/* Annotation count text and toggle arrow */} <div className={cx(styles.resultCount, { [styles.expandedCount]: this.state.isExpanded, })} onClick={this.toggleIsExpanded} > <b>{this.props.annotations.length}</b>{' '} <span className={styles.resultsText}>results</span> <span className={cx(styles.icon, { [styles.inverted]: this.state.isExpanded, })} /> </div> {/* Container for displaying AnnotationBox */} <div className={styles.annotationList}> {isExpanded ? this.renderAnnotations() : null} </div> </div> ) } } export default AnnotationList
the_stack
import { defineComponent, computed, ref, provide, inject, getCurrentInstance, watch, onMounted, onBeforeUnmount, withDirectives, Fragment, vShow, h, reactive, } from 'vue' import { useTimeoutFn } from '@vueuse/core' import ElCollapseTransition from '@element-plus/components/collapse-transition' import ElPopper from '@element-plus/components/popper' import { buildProps } from '@element-plus/utils/props' import { throwError } from '@element-plus/utils/error' import useMenu from './use-menu' import { useMenuCssVar } from './use-menu-css-var' import type { Placement } from '@element-plus/components/popper' import type { ExtractPropTypes, VNodeArrayChildren, CSSProperties } from 'vue' import type { MenuProvider, SubMenuProvider } from './types' export const subMenuProps = buildProps({ index: { type: String, required: true, }, showTimeout: { type: Number, default: 300, }, hideTimeout: { type: Number, default: 300, }, popperClass: String, disabled: Boolean, popperAppendToBody: { type: Boolean, default: undefined, }, } as const) export type SubMenuProps = ExtractPropTypes<typeof subMenuProps> const COMPONENT_NAME = 'ElSubMenu' export default defineComponent({ name: COMPONENT_NAME, props: subMenuProps, setup(props, { slots, expose }) { const instance = getCurrentInstance()! const { paddingStyle, indexPath, parentMenu } = useMenu( instance, computed(() => props.index) ) // inject const rootMenu = inject<MenuProvider>('rootMenu') if (!rootMenu) throwError(COMPONENT_NAME, 'can not inject root menu') const subMenu = inject<SubMenuProvider>(`subMenu:${parentMenu.value!.uid}`) if (!subMenu) throwError(COMPONENT_NAME, 'can not inject sub menu') const items = ref<MenuProvider['items']>({}) const subMenus = ref<MenuProvider['subMenus']>({}) let timeout: (() => void) | undefined const currentPlacement = ref<Placement | ''>('') const mouseInChild = ref(false) const verticalTitleRef = ref<HTMLDivElement>() const vPopper = ref() // computed const subMenuTitleIcon = computed(() => { return (mode.value === 'horizontal' && isFirstLevel.value) || (mode.value === 'vertical' && !rootMenu.props.collapse) ? 'el-icon-arrow-down' : 'el-icon-arrow-right' }) const isFirstLevel = computed(() => { let isFirstLevel = true let parent = instance.parent while (parent && parent.type.name !== 'ElMenu') { if (['ElSubMenu', 'ElMenuItemGroup'].includes(parent.type.name!)) { isFirstLevel = false break } else { parent = parent.parent } } return isFirstLevel }) const appendToBody = computed(() => { return props.popperAppendToBody === undefined ? isFirstLevel.value : Boolean(props.popperAppendToBody) }) const menuTransitionName = computed(() => rootMenu.props.collapse ? 'el-zoom-in-left' : 'el-zoom-in-top' ) const fallbackPlacements = computed<Placement[]>(() => mode.value === 'horizontal' && isFirstLevel.value ? [ 'bottom-start', 'bottom-end', 'top-start', 'top-end', 'right-start', 'left-start', ] : [ 'right-start', 'left-start', 'bottom-start', 'bottom-end', 'top-start', 'top-end', ] ) const opened = computed(() => rootMenu.openedMenus.includes(props.index)) const active = computed(() => { let isActive = false Object.values(items.value).forEach((item) => { if (item.active) { isActive = true } }) Object.values(subMenus.value).forEach((subItem) => { if (subItem.active) { isActive = true } }) return isActive }) const backgroundColor = computed(() => rootMenu.props.backgroundColor || '') const activeTextColor = computed(() => rootMenu.props.activeTextColor || '') const textColor = computed(() => rootMenu.props.textColor || '') const mode = computed(() => rootMenu.props.mode) const item = reactive({ index: props.index, indexPath, active, }) const titleStyle = computed<CSSProperties>(() => { if (mode.value !== 'horizontal') { return { color: textColor.value, } } return { borderBottomColor: active.value ? rootMenu.props.activeTextColor ? activeTextColor.value : '' : 'transparent', color: active.value ? activeTextColor.value : textColor.value, } }) // methods const doDestroy = () => vPopper.value?.doDestroy() const handleCollapseToggle = (value: boolean) => { if (value) { updatePlacement() } else { doDestroy() } } const handleClick = () => { if ( (rootMenu.props.menuTrigger === 'hover' && rootMenu.props.mode === 'horizontal') || (rootMenu.props.collapse && rootMenu.props.mode === 'vertical') || props.disabled ) return rootMenu.handleSubMenuClick({ index: props.index, indexPath: indexPath.value, active: active.value, }) } const handleMouseenter = ( event: MouseEvent | FocusEvent, showTimeout = props.showTimeout ) => { if (event.type === 'focus' && !event.relatedTarget) { return } if ( (rootMenu.props.menuTrigger === 'click' && rootMenu.props.mode === 'horizontal') || (!rootMenu.props.collapse && rootMenu.props.mode === 'vertical') || props.disabled ) { return } mouseInChild.value = true timeout?.() ;({ stop: timeout } = useTimeoutFn( () => rootMenu.openMenu(props.index, indexPath.value), showTimeout )) if (appendToBody.value) { parentMenu.value.vnode.el?.dispatchEvent(new MouseEvent('mouseenter')) } } const handleMouseleave = (deepDispatch = false) => { if ( (rootMenu.props.menuTrigger === 'click' && rootMenu.props.mode === 'horizontal') || (!rootMenu.props.collapse && rootMenu.props.mode === 'vertical') ) { return } mouseInChild.value = false timeout?.() ;({ stop: timeout } = useTimeoutFn( () => !mouseInChild.value && rootMenu.closeMenu(props.index), props.hideTimeout )) if (appendToBody.value && deepDispatch) { if (instance.parent?.type.name === 'ElSubMenu') { subMenu.handleMouseleave?.(true) } } } const updatePlacement = () => { currentPlacement.value = mode.value === 'horizontal' && isFirstLevel.value ? 'bottom-start' : 'right-start' } watch( () => rootMenu.props.collapse, (value) => handleCollapseToggle(Boolean(value)) ) // provide { const addSubMenu: SubMenuProvider['addSubMenu'] = (item) => { subMenus.value[item.index] = item } const removeSubMenu: SubMenuProvider['removeSubMenu'] = (item) => { delete subMenus.value[item.index] } provide<SubMenuProvider>(`subMenu:${instance.uid}`, { addSubMenu, removeSubMenu, handleMouseleave, }) } // expose expose({ opened, }) // lifecycle onMounted(() => { rootMenu.addSubMenu(item) subMenu.addSubMenu(item) updatePlacement() }) onBeforeUnmount(() => { subMenu.removeSubMenu(item) rootMenu.removeSubMenu(item) }) return () => { const titleTag: VNodeArrayChildren = [ slots.title?.(), h('i', { class: ['el-sub-menu__icon-arrow', subMenuTitleIcon.value], }), ] const ulStyle = useMenuCssVar(rootMenu.props) // this render function is only used for bypass `Vue`'s compiler caused patching issue. // temporarily mark ElPopper as any due to type inconsistency. const child = rootMenu.isMenuPopup ? h( // TODO: correct popper's type. ElPopper as any, { ref: vPopper, manualMode: true, visible: opened.value, effect: 'light', pure: true, offset: 6, showArrow: false, popperClass: props.popperClass, placement: currentPlacement.value, appendToBody: appendToBody.value, fallbackPlacements: fallbackPlacements.value, transition: menuTransitionName.value, gpuAcceleration: false, }, { default: () => h( 'div', { class: [`el-menu--${mode.value}`, props.popperClass], onMouseenter: (evt: MouseEvent) => handleMouseenter(evt, 100), onMouseleave: () => handleMouseleave(true), onFocus: (evt: FocusEvent) => handleMouseenter(evt, 100), }, [ h( 'ul', { class: [ 'el-menu el-menu--popup', `el-menu--popup-${currentPlacement.value}`, ], style: ulStyle.value, }, [slots.default?.()] ), ] ), trigger: () => h( 'div', { class: 'el-sub-menu__title', style: [ paddingStyle.value, titleStyle.value, { backgroundColor: backgroundColor.value }, ], onClick: handleClick, }, titleTag ), } ) : h(Fragment, {}, [ h( 'div', { class: 'el-sub-menu__title', style: [ paddingStyle.value, titleStyle.value, { backgroundColor: backgroundColor.value }, ], ref: verticalTitleRef, onClick: handleClick, }, titleTag ), h( ElCollapseTransition, {}, { default: () => withDirectives( h( 'ul', { role: 'menu', class: 'el-menu el-menu--inline', style: ulStyle.value, }, [slots.default?.()] ), [[vShow, opened.value]] ), } ), ]) return h( 'li', { class: [ 'el-sub-menu', { 'is-active': active.value, 'is-opened': opened.value, 'is-disabled': props.disabled, }, ], role: 'menuitem', ariaHaspopup: true, ariaExpanded: opened.value, onMouseenter: handleMouseenter, onMouseleave: () => handleMouseleave(true), onFocus: handleMouseenter, }, [child] ) } }, })
the_stack
import { set } from 'lodash'; import path from 'path'; import R from 'ramda'; import fs from 'fs-extra'; import { DEFAULT_BINDINGS_PREFIX } from '../../../../constants'; import { resolvePackageData } from '../../../../utils/packages'; import generateTree, { MadgeTree } from './generate-tree-madge'; import { FoundPackages, MissingGroupItem, MissingHandler } from './missing-handler'; import { convertPathMapToRelativePaths, getPathMapWithLinkFilesData, PathMapItem } from './path-map'; import { DependencyTreeParams, FileObject, ImportSpecifier, ResolveModulesConfig, DependenciesTree, DependenciesTreeItem, } from './types/dependency-tree-type'; export type LinkFile = { file: string; importSpecifiers: ImportSpecifier[]; }; /** * Gets a list of dependencies and group them by types (files, components, packages) * It's also transform the node package dependencies from array of paths to object in this format: * {dependencyName: version} (like in package.json) * * componentDir is the root of working directory (used for node packages version calculation) */ function groupDependencyList( dependenciesPaths: string[], componentDir: string, bindingPrefix: string, isLegacyProject: boolean ): DependenciesTreeItem { const resultGroups = new DependenciesTreeItem(); const isPackage = (str: string) => str.includes('node_modules/'); const isBitLegacyComponent = (str: string) => isLegacyProject && (str.includes(`node_modules/${bindingPrefix}`) || str.includes(`node_modules/${DEFAULT_BINDINGS_PREFIX}`)); const isBitLegacyInsideHarmony = (str: string) => !isLegacyProject && (str.includes(`node_modules/${bindingPrefix}`) || str.includes(`node_modules/${DEFAULT_BINDINGS_PREFIX}`)); dependenciesPaths.forEach((dependencyPath) => { if (!isPackage(dependencyPath)) { resultGroups.files.push({ file: dependencyPath }); return; } const resolvedPackage = resolvePackageData(componentDir, path.join(componentDir, dependencyPath)); if (!resolvedPackage) { // package doesn't have package.json, probably it's a custom-resolve-module dep file resultGroups.unidentifiedPackages.push(dependencyPath); return; } // If the package is a component add it to the components list // @todo: currently, for author, the package.json doesn't have any version. // we might change this decision later. see https://github.com/teambit/bit/pull/2924 if (resolvedPackage.componentId) { resultGroups.components.push(resolvedPackage); return; } if (isBitLegacyComponent(dependencyPath)) { resultGroups.components.push(resolvedPackage); return; } if (isBitLegacyInsideHarmony(dependencyPath)) { const pkgRootDir = resolvedPackage.packageJsonContent?.componentRootFolder; const hasLegacyBitFiles = pkgRootDir && fs.existsSync(path.join(pkgRootDir, '.bit_env_has_installed')); if (hasLegacyBitFiles) { throw new Error(`error: legacy dependency "${resolvedPackage.name}" was imported to one of the files in "${componentDir}". this workspace is Harmony and therefore legacy components/packages are unsupported. remove the import statement to fix this error`); } } const version = resolvedPackage.versionUsedByDependent || resolvedPackage.concreteVersion; const packageWithVersion = { [resolvedPackage.name]: version, }; Object.assign(resultGroups.packages, packageWithVersion); }); return resultGroups; } /** * Run over each entry in the tree and transform the dependencies from list of paths * to object with dependencies types * * @returns new tree with grouped dependencies */ function MadgeTreeToDependenciesTree( tree: MadgeTree, componentDir: string, bindingPrefix: string, isLegacyProject: boolean ): DependenciesTree { const result: DependenciesTree = {}; Object.keys(tree).forEach((filePath) => { if (tree[filePath] && !R.isEmpty(tree[filePath])) { result[filePath] = groupDependencyList(tree[filePath], componentDir, bindingPrefix, isLegacyProject); } else { result[filePath] = new DependenciesTreeItem(); } }); return result; } /** * add extra data such as custom-resolve and link-files from pathMap */ function updateTreeWithPathMap(tree: DependenciesTree, pathMapAbsolute: PathMapItem[], baseDir: string): void { if (!pathMapAbsolute.length) return; const pathMapRelative = convertPathMapToRelativePaths(pathMapAbsolute, baseDir); const pathMap = getPathMapWithLinkFilesData(pathMapRelative); Object.keys(tree).forEach((filePath: string) => { const treeFiles = tree[filePath].files; if (!treeFiles.length) return; // file has no dependency const mainFilePathMap = pathMap.find((file) => file.file === filePath); if (!mainFilePathMap) throw new Error(`updateTreeWithPathMap: PathMap is missing for ${filePath}`); // a file might have a cycle dependency with itself, remove it from the dependencies. tree[filePath].files = treeFiles.filter((dependency) => dependency.file !== filePath); tree[filePath].files.forEach((fileObject: FileObject) => { const dependencyPathMap = mainFilePathMap.dependencies.find((file) => file.resolvedDep === fileObject.file); if (!dependencyPathMap) { throw new Error(`updateTreeWithPathMap: dependencyPathMap is missing for ${fileObject.file}`); } fileObject.importSource = dependencyPathMap.importSource; fileObject.isCustomResolveUsed = dependencyPathMap.isCustomResolveUsed; if (dependencyPathMap.linkFile) { fileObject.isLink = true; fileObject.linkDependencies = dependencyPathMap.realDependencies; return fileObject; } if (dependencyPathMap.importSpecifiers && dependencyPathMap.importSpecifiers.length) { const depImportSpecifiers = dependencyPathMap.importSpecifiers.map((importSpecifier) => { return { mainFile: importSpecifier, }; }); fileObject.importSpecifiers = depImportSpecifiers; } return fileObject; }); }); } /** * config aliases are passed later on to webpack-enhancer and it expects them to have the full path */ function getResolveConfigAbsolute( workspacePath: string, resolveConfig: ResolveModulesConfig | null | undefined ): ResolveModulesConfig | null | undefined { if (!resolveConfig) return resolveConfig; const resolveConfigAbsolute = R.clone(resolveConfig); if (resolveConfig.modulesDirectories) { resolveConfigAbsolute.modulesDirectories = resolveConfig.modulesDirectories.map((moduleDirectory) => { return path.isAbsolute(moduleDirectory) ? moduleDirectory : path.join(workspacePath, moduleDirectory); }); } if (resolveConfigAbsolute.aliases) { Object.keys(resolveConfigAbsolute.aliases).forEach((alias) => { if (!path.isAbsolute(resolveConfigAbsolute.aliases[alias])) { resolveConfigAbsolute.aliases[alias] = path.join(workspacePath, resolveConfigAbsolute.aliases[alias]); } }); } return resolveConfigAbsolute; } function mergeManuallyFoundPackagesToTree( foundPackages: FoundPackages, missingGroups: MissingGroupItem[], tree: DependenciesTree ) { if (R.isEmpty(foundPackages.components) && R.isEmpty(foundPackages.packages)) return; // Merge manually found packages (by groupMissing()) with the packages found by Madge (generate-tree-madge) Object.keys(foundPackages.packages).forEach((pkg) => { // locate package in groups(contains missing) missingGroups.forEach((fileDep: MissingGroupItem) => { if (fileDep.packages && fileDep.packages.includes(pkg)) { fileDep.packages = fileDep.packages.filter((packageName) => packageName !== pkg); set(tree[fileDep.originFile], ['packages', pkg], foundPackages.packages[pkg]); } }); }); foundPackages.components.forEach((component) => { missingGroups.forEach((fileDep: MissingGroupItem) => { if ( fileDep.components && ((component.fullPath && fileDep.components.includes(component.fullPath)) || fileDep.components.includes(component.name)) ) { fileDep.components = fileDep.components.filter((existComponent) => { return existComponent !== component.fullPath && existComponent !== component.name; }); (tree[fileDep.originFile] ||= new DependenciesTreeItem()).components.push(component); } if (fileDep.packages && fileDep.packages.includes(component.name)) { fileDep.packages = fileDep.packages.filter((packageName) => packageName !== component.name); (tree[fileDep.originFile] ||= new DependenciesTreeItem()).components.push(component); } }); }); } function mergeMissingToTree(missingGroups, tree: DependenciesTree) { if (R.isEmpty(missingGroups)) return; missingGroups.forEach((missing) => { const missingCloned = R.clone(missing); delete missingCloned.originFile; (tree[missing.originFile] ||= new DependenciesTreeItem()).missing = missingCloned; }); } function mergeErrorsToTree(errors, tree: DependenciesTree) { if (R.isEmpty(errors)) return; Object.keys(errors).forEach((file) => { (tree[file] ||= new DependenciesTreeItem()).error = errors[file]; }); } /** * Function for fetching dependency tree of file or dir * @param baseDir working directory * @param workspacePath * @param filePaths path of the file to calculate the dependencies * @param bindingPrefix */ export async function getDependencyTree({ componentDir, // component rootDir, for legacy-authored it's the same as workspacePath workspacePath, filePaths, bindingPrefix, isLegacyProject, resolveModulesConfig, visited = {}, cacheProjectAst, }: DependencyTreeParams): Promise<{ tree: DependenciesTree }> { const resolveConfigAbsolute = getResolveConfigAbsolute(workspacePath, resolveModulesConfig); const config = { baseDir: componentDir, includeNpm: true, requireConfig: null, webpackConfig: null, visited, nonExistent: [], resolveConfig: resolveConfigAbsolute, cacheProjectAst, }; // This is important because without this, madge won't know to resolve files if we run the // CMD not from the root dir const fullPaths = filePaths.map((filePath) => { if (filePath.startsWith(componentDir)) { return filePath; } return path.resolve(componentDir, filePath); }); const { madgeTree, skipped, pathMap, errors } = generateTree(fullPaths, config); const tree: DependenciesTree = MadgeTreeToDependenciesTree(madgeTree, componentDir, bindingPrefix, isLegacyProject); const { missingGroups, foundPackages } = new MissingHandler( skipped, componentDir, workspacePath, bindingPrefix, isLegacyProject ).groupAndFindMissing(); if (foundPackages) mergeManuallyFoundPackagesToTree(foundPackages, missingGroups, tree); if (errors) mergeErrorsToTree(errors, tree); if (missingGroups) mergeMissingToTree(missingGroups, tree); if (pathMap) updateTreeWithPathMap(tree, pathMap, componentDir); return { tree }; }
the_stack
import _path from './_path'; import _pkgutil from './_pkgutil'; const haveWeb = typeof globalThis.window == 'object'; function split_path(self: any) { if (self._is_split) return; self._is_split = true; var value = self._value; var val = ''; var i = value.indexOf('?'); if (i != -1) { val = value.substr(0, i); var search = self._search = value.substr(i); i = search.indexOf('#'); if (i != -1) { self._search = search.substr(0, i); self._hash = search.substr(i); } } else { i = value.indexOf('#'); if (i != -1) { val = value.substr(0, i); self._hash = value.substr(i); } else { val = value; } } self._value = _pkgutil.resolve(val); } function parse_base_ext_name(self: any) { if (self._basename == -1) { split_path(self); var mat = self._value.match(/([^\/\\]+)?(\.[^\/\\\.]+)$|[^\/\\]+$/); if (mat) { self._basename = mat[0]; self._extname = mat[2] || ''; } else { self._extname = self._basename = ''; } } } function parse_path(self: any) { if (self._is_parse) return; self._is_parse = true; split_path(self); var mat = self._value.match(/^(([a-z]+:)\/\/)?(([^\/:]+)(?::(\d+))?)?(\/.*)?/); if (mat) { self._protocol = mat[2] || ''; self._origin = mat[1] || ''; if ( mat[3] ) { // http:// or ftp:// or lib:// self._origin += mat[3]; self._hostname = mat[4]; self._port = mat[5] ? mat[5] : ''; } var path = self._filename = mat[6] || '/'; var i = path.lastIndexOf('/'); if (i > 0) { self._dirname = path.substr(0, i); } else { self._dirname = '/'; } } else { throw new Error(`Parse url error, Illegal URL ${self._value}`); } } function parse_params(self: any) { if (self._params) return; split_path(self); var params: Dict = self._params = {}; if (self._search[0] != '?') return; var ls = self._search.substr(1).split('&'); for (var i = 0; i < ls.length; i++) { var o = ls[i].split('='); params[ o[0] ] = decodeURIComponent(o[1] || ''); } } function parse_hash_params(self: any) { if (self._hash_params) return; split_path(self); var params: Dict = self._hash_params = {}; if (self._hash[0] != '#') return; var ls = self._hash.substr(1).split('&'); for (var i = 0; i < ls.length; i++) { var o = ls[i].split('='); params[ o[0] ] = decodeURIComponent(o[1] || ''); } } function querystringStringify(prefix: string, params: Dict) { var rev = []; for (var i in params) { rev.push(i + '=' + encodeURIComponent(params[i])); } return rev.length ? prefix + rev.join('&') : ''; } /** * @class URL */ export class URL { /** * @arg [path] {String} * @constructor */ constructor(path: string = '') { if (!path && haveWeb) { path = location.href; } (<any>this)._value = path; } // href: "http://xxxx.xxx:81/v1.1.0/ftr/path.js?sasasas&asasasa#sdsdsd" get href(): string { parse_path(this); return (<any>this)._origin + (<any>this)._filename + (<any>this)._search + (<any>this)._hash; } /** * full path * filename: "/D:/Documents/test.js" */ get filename(): string { parse_path(this); return (<any>this)._filename; } /** * @get path /a/b/s/test.html?aaaaa=100 */ get path(): string { parse_path(this); return (<any>this)._filename + (<any>this)._search; } /** * full path dir * dirname: "/D:/Documents" */ get dirname(): string { parse_path(this); return (<any>this)._dirname; } // search: "?sasasas&asasasa" get search(): string { split_path(this); return (<any>this)._search; } // hash: "#sdsdsd" get hash(): string { split_path(this); return (<any>this)._hash; } // host: "fasttr.org:81" get host(): string { parse_path(this); return (<any>this)._hostname + ((<any>this)._port ? ':' + (<any>this)._port : ''); } // hostname: "fasttr.org" get hostname(): string { parse_path(this); return (<any>this)._hostname; } // origin: "http://fasttr.org:81" get origin(): string { parse_path(this); return (<any>this)._origin; } // get path base name get basename(): string { parse_base_ext_name(this); return (<any>this)._basename; } // path extname get extname(): string { parse_base_ext_name(this); return (<any>this)._extname; } // port: "81" get port(): string { parse_path(this); return (<any>this)._port; } // protocol: "http:" get protocol(): string { parse_path(this); return (<any>this)._protocol; } get params(): Dict<string> { parse_params(this); return (<any>this)._params; } set params(value: Dict<string>) { (<any>this)._params = {...value}; (<any>this)._search = querystringStringify('?', (<any>this)._params); } get hashParams(): Dict<string> { parse_hash_params(this); return (<any>this)._hash_params; } set hashParams(value: Dict<string>){ (<any>this)._hash_params = {...value}; (<any>this)._hash = querystringStringify('#', (<any>this)._hash_params); } // get path param getParam(name: string): string { return (<any>this).params[name]; } // set path param setParam(name: string, value: string): URL { this.params[name] = value || ''; (<any>this)._search = querystringStringify('?', (<any>this)._params); return this; } // del path param deleteParam(name: string): URL { delete this.params[name]; (<any>this)._search = querystringStringify('?', (<any>this)._params); return this; } // del all prams clearParam(): URL { (<any>this)._params = {}; (<any>this)._search = ''; return this; } // get hash param getHash(name: string): string { return this.hashParams[name]; } // set hash param setHash(name: string, value: string): URL { this.hashParams[name] = value || ''; (<any>this)._hash = querystringStringify('#', (<any>this)._hash_params); return this; } // del hash param deleteHash(name: string): URL { delete this.hashParams[name]; (<any>this)._hash = querystringStringify('#', (<any>this)._hash_params); return this; } // del hash all params clearHash(): URL { (this as any)._hash_params = {}; (this as any)._hash = ''; return this; } // relative path relative(targetPath: string): string { var target = new URL(targetPath); if ( this.origin != target.origin ) return (this as any)._origin + (this as any)._filename; var ls: string[] = (this as any)._filename == '/' ? [] : (this as any)._filename.split('/'); var ls2: string[] = (target as any)._filename == '/' ? [] : (target as any)._filename.split('/'); var len = Math.max(ls.length, ls2.length); for (var i = 1; i < len; i++) { if (ls[i] != ls2[i]) { len = ls.length - i; if (len > 0) { ls = []; for (var j = 0; j < len; j++) ls.push('..'); return ls.join('/') + '/' + ls2.splice(i).join('/'); } return ls2.splice(i).join('/'); } } return '.'; } toJSON(): string { return this.href; } } (URL as any).prototype._is_split = false; (URL as any).prototype._is_parse = false; (URL as any).prototype._value = ''; (URL as any).prototype._hostname = ''; (URL as any).prototype._port = ''; (URL as any).prototype._protocol = ''; (URL as any).prototype._search = ''; (URL as any).prototype._hash = ''; (URL as any).prototype._origin = ''; (URL as any).prototype._filename = ''; (URL as any).prototype._dirname = ''; (URL as any).prototype._basename = -1; (URL as any).prototype._extname = -1; (URL as any).prototype._params = null; (URL as any).prototype._hash_params = null; function get_path(path?: string): URL { return new URL(path); } export default { ..._path, URL: URL, /** * @func isAbsolute(path) is absolute path */ isAbsolute: _pkgutil.isAbsolute, // func /** * @func resolve(path) resolve path */ resolve: _pkgutil.resolve, // func /** * @func fallbackPath() */ fallbackPath: _pkgutil.fallbackPath, /** * full filename */ basename(path?: string) { return get_path(path).basename; }, /** * full filename */ dirname(path?: string) { return get_path(path).dirname; }, /** * full filename */ extname(path?: string) { return get_path(path).extname; }, /** * full filename */ filename(path?: string) { return get_path(path).filename; }, /** * full path */ path(path?: string) { return get_path(path).path; }, search(path?: string) { return get_path(path).search; }, hash(path?: string) { return get_path(path).hash; }, host(path?: string) { return get_path(path).host; }, hostname(path?: string) { return get_path(path).hostname; }, // href origin origin(path?: string) { return get_path(path).origin; }, // port: "81" port(path?: string) { return get_path(path).port; }, // protocol: "http:" protocol(path?: string) { return get_path(path).protocol; }, // href params params(path?: string) { return get_path(path).params; }, // hash params hashParams(path?: string) { return get_path(path).hashParams; }, // get path param getParam(name: string, path?: string) { return get_path(path).getParam(name); }, // set path param setParam(name: string, value: string, path?: string) { return get_path(path).setParam(name, value).href; }, // del path param deleteParam(name: string, path?: string) { return get_path(path).deleteParam(name).href; }, // del all hash param clearParam(path?: string) { return get_path(path).clearParam().href; }, // get hash param getHash(name: string, path?: string) { return get_path(path).getHash(name); }, // set hash param setHash(name: string, value: string, path?: string) { return get_path(path).setHash(name, value).href; }, // del hash param deleteHash(name: string, path?: string) { return get_path(path).deleteHash(name).href; }, // del all hash param clearHash(path?: string) { return get_path(path).clearHash().href; }, // relative path relative(path: string, target: string) { if (arguments.length > 1) return get_path(path).relative(target); else return get_path(path).relative(path); }, }
the_stack
declare namespace ergometer.utils { /** * @return {Object} */ /** * It limits concurrently executed promises * * @param {Number} [maxPendingPromises=Infinity] max number of concurrently executed promises * @param {Number} [maxQueuedPromises=Infinity] max number of queued promises * @constructor * * @example * * var queue = new Queue(1); * * queue.add(function () { * // resolve of this promise will resume next request * return downloadTarballFromGithub(url, file); * }) * .then(function (file) { * doStuffWith(file); * }); * * queue.add(function () { * return downloadTarballFromGithub(url, file); * }) * // This request will be paused * .then(function (file) { * doStuffWith(file); * }); */ interface IPromiseFunction { (...args: any[]): Promise<any | void>; } class FunctionQueue { /** * @param {*} value * @returns {LocalPromise} */ private resolveWith(value); private maxPendingPromises; private maxQueuedPromises; private pendingPromises; private queue; constructor(maxPendingPromises?: number, maxQueuedPromises?: number); /** * @param {promiseGenerator} a function which returns a promise * @param {context} the object which is the context where the function is called in * @param {params} array of parameters for the function * @return {Promise} promise which is resolved when the function is acually called */ add(promiseGenerator: IPromiseFunction, context: any, ...params: any[]): Promise<any | void>; /** * Number of simultaneously running promises (which are resolving) * * @return {number} */ getPendingLength(): number; /** * Number of queued promises (which are waiting) * * @return {number} */ getQueueLength(): number; /** * @returns {boolean} true if first item removed from queue * @private */ private _dequeue(); } } /** * * Created by tijmen on 01-06-15. * * License: * * Copyright 2016 Tijmen van Gulik (tijmen@vangulik.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ declare namespace ergometer.pubSub { interface ISubscription { (...args: any[]): void; } interface ISubscriptionItem { object: any; func: ISubscription; } interface IDictionary { [name: string]: ISubscriptionItem[]; } class PubSub { private registry; pub(name: string, ...args: any[]): void; pubASync(name: string, ...args: any[]): void; sub(applyObject: any, name: string, fn: ISubscription): void; unsub(name: string, fn: ISubscription): void; subscribeCount(name: string): number; } interface ISubscriptionChanged { (sender: any, count: number): void; } class Event<T extends ISubscription> { protected _subscribed: ISubscriptionItem[]; protected _subScriptionChangedEvent: ISubscriptionChanged; protected doChangedEvent(): void; protected findSubscription(event: T): ISubscriptionItem; sub(applyObject: any, event: T): void; unsub(event: T): void; protected doPub(args: any[]): void; readonly pub: T; readonly pubAsync: T; readonly count: number; registerChangedEvent(func: ISubscriptionChanged): void; } } /** * Created by tijmen on 01-02-16. */ declare namespace ergometer.ble { interface IDevice { address: string; name: string; rssi: number; _internalDevice: any; } interface IFoundFunc { (device: IDevice): void; } interface IDriver { startScan(foundFn?: IFoundFunc): Promise<void>; stopScan(): void; connect(device: IDevice, disconnectFn: () => void): Promise<void>; disconnect(): void; writeCharacteristic(serviceUIID: string, characteristicUUID: string, data: ArrayBufferView): Promise<void>; readCharacteristic(serviceUIID: string, characteristicUUID: string): Promise<ArrayBuffer>; enableNotification(serviceUIID: string, characteristicUUID: string, receive: (data: ArrayBuffer) => void): Promise<void>; disableNotification(serviceUIID: string, characteristicUUID: string): Promise<void>; } } /** * Created by tijmen on 01-02-16. */ declare namespace ergometer.ble { class DriverBleat implements IDriver { private _device; private getCharacteristic(serviceUid, characteristicUid); connect(device: IDevice, disconnectFn: () => void): Promise<void>; disconnect(): void; startScan(foundFn?: IFoundFunc): Promise<void>; stopScan(): Promise<void>; writeCharacteristic(serviceUIID: string, characteristicUUID: string, data: ArrayBufferView): Promise<void>; readCharacteristic(serviceUIID: string, characteristicUUID: string): Promise<ArrayBuffer>; enableNotification(serviceUIID: string, characteristicUUID: string, receive: (data: ArrayBuffer) => void): Promise<void>; disableNotification(serviceUIID: string, characteristicUUID: string): Promise<void>; } } /** * Created by tijmen on 03/04/2017. */ /** * Created by tijmen on 01-02-16. * * see simpleBLE.d.ts for the definitions of the simpleBLE * It assumes that there simple ble is already imported as a var named simpleBLE * */ declare namespace ergometer.ble { class DriverSimpleBLE implements IDriver { connect(device: IDevice, disconnectFn: () => void): Promise<void>; disconnect(): void; startScan(foundFn?: IFoundFunc): Promise<void>; stopScan(): Promise<void>; writeCharacteristic(serviceUIID: string, characteristicUUID: string, data: ArrayBufferView): Promise<void>; readCharacteristic(serviceUIID: string, characteristicUUID: string): Promise<ArrayBuffer>; enableNotification(serviceUIID: string, characteristicUUID: string, receive: (data: ArrayBuffer) => void): Promise<void>; disableNotification(serviceUIID: string, characteristicUUID: string): Promise<void>; } } /** * Created by tijmen on 17-07-16. */ /** * Created by tijmen on 01-02-16. */ declare namespace ergometer.ble { function hasWebBlueTooth(): boolean; class DriverWebBlueTooth implements IDriver { private _device; private _server; private _disconnectFn; private _listenerMap; private _listerCharacteristicMap; private _performanceMonitor; constructor(performanceMonitor: PerformanceMonitorBase); private getCharacteristic(serviceUid, characteristicUid); private onDisconnected(event); private clearConnectionVars(); connect(device: IDevice, disconnectFn: () => void): Promise<void>; disconnect(): void; startScan(foundFn?: IFoundFunc): Promise<void>; stopScan(): Promise<void>; writeCharacteristic(serviceUIID: string, characteristicUUID: string, data: ArrayBufferView): Promise<void>; readCharacteristic(serviceUIID: string, characteristicUUID: string): Promise<ArrayBuffer>; private onCharacteristicValueChanged(event); enableNotification(serviceUIID: string, characteristicUUID: string, receive: (data: ArrayBuffer) => void): Promise<void>; disableNotification(serviceUIID: string, characteristicUUID: string): Promise<void>; } } /** * Created by tijmen on 16-02-16. */ declare namespace ergometer.ble { interface IRecordDevice { address: string; name: string; rssi: number; } interface IRecordCharacteristic { serviceUIID: string; characteristicUUID: string; data?: string; } enum RecordingEventType { startScan = 0, scanFoundFn = 1, stopScan = 2, connect = 3, disconnectFn = 4, disconnect = 5, writeCharacteristic = 6, readCharacteristic = 7, enableNotification = 8, notificationReceived = 9, disableNotification = 10, } interface IRecordingItem { timeStamp: number; eventType: string; timeStampReturn?: number; data?: IRecordCharacteristic | IRecordDevice; error?: any; } class RecordingDriver implements IDriver { private _realDriver; private _startTime; private _events; _performanceMonitor: PerformanceMonitorBase; constructor(performanceMonitor: PerformanceMonitorBase, realDriver: IDriver); protected getRelativeTime(): number; addRecording(eventType: RecordingEventType, data?: IRecordCharacteristic | IRecordDevice): IRecordingItem; events: ergometer.ble.IRecordingItem[]; clear(): void; startRecording(): void; protected recordResolveFunc(resolve: () => void, rec: IRecordingItem): () => void; protected recordResolveBufferFunc(resolve: (data: ArrayBuffer) => void, rec: IRecordingItem): (data: ArrayBuffer) => void; protected recordErrorFunc(reject: (e) => void, rec: IRecordingItem): (e) => void; startScan(foundFn?: IFoundFunc): Promise<void>; stopScan(): void; connect(device: IDevice, disconnectFn: () => void): Promise<void>; disconnect(): void; writeCharacteristic(serviceUIID: string, characteristicUUID: string, data: ArrayBufferView): Promise<void>; readCharacteristic(serviceUIID: string, characteristicUUID: string): Promise<ArrayBuffer>; enableNotification(serviceUIID: string, characteristicUUID: string, receive: (data: ArrayBuffer) => void): Promise<void>; disableNotification(serviceUIID: string, characteristicUUID: string): Promise<void>; } } /** * Created by tijmen on 18-02-16. */ declare namespace ergometer.ble { interface CallBackEvent extends IRecordingItem { resolve?: (e?: any) => void; reject?: (e: any) => void; } class ReplayDriver implements IDriver { private _realDriver; private _events; private _eventCallBackMethods; private _eventCallbacks; private _playing; private _eventIndex; private _startTime; private _checkQueueTimerId; private _performanceMonitor; protected getRelativeTime(): number; constructor(performanceMonitor: PerformanceMonitorBase, realDriver: IDriver); readonly events: ergometer.ble.IRecordingItem[]; protected isCallBack(eventType: RecordingEventType): boolean; protected isSameEvent(event1: IRecordingItem, event2: IRecordingItem): boolean; protected runEvent(event: IRecordingItem, queuedEvent: CallBackEvent): void; protected runTimedEvent(event: IRecordingItem, queuedEvent: CallBackEvent): void; protected removeEvent(i: number): void; protected checkQueue(): void; protected checkAllEventsProcessd(): boolean; protected timeNextCheck(timeStamp?: number): void; protected addEvent(eventType: RecordingEventType, isMethod: boolean, resolve?: (e?: any) => void, reject?: (e: any) => void, serviceUIID?: string, characteristicUUID?: string): void; replay(events: IRecordingItem[]): void; playing: boolean; startScan(foundFn?: IFoundFunc): Promise<void>; stopScan(): void; connect(device: IDevice, disconnectFn: () => void): Promise<void>; disconnect(): void; writeCharacteristic(serviceUIID: string, characteristicUUID: string, data: ArrayBufferView): Promise<void>; readCharacteristic(serviceUIID: string, characteristicUUID: string): Promise<ArrayBuffer>; enableNotification(serviceUIID: string, characteristicUUID: string, receive: (data: ArrayBuffer) => void): Promise<void>; disableNotification(serviceUIID: string, characteristicUUID: string): Promise<void>; } } declare namespace ergometer.usb { const USB_CSAVE_SIZE = 120; const WRITE_BUF_SIZE = 121; const REPORT_TYPE = 2; } declare namespace ergometer.usb { type DisconnectFunc = () => void; type Devices = IDevice[]; interface IDevice { readonly vendorId: number; readonly productId: number; readonly productName: string; readonly serialNumber: string; open(disconnect: () => void, error: (err: any) => void): Promise<void>; close(): Promise<void>; sendData(data: ArrayBuffer): Promise<void>; readData(): Promise<DataView>; } interface IDriver { requestDevics(): Promise<Devices>; } } declare namespace ergometer.usb { class DeviceNodeHid implements IDevice { private _disconnect; private _onError; private _deviceInfo; private _hid; vendorId: number; productId: number; productName: string; serialNumber: string; constructor(deviceInfo: any); callError(err: any): void; open(disconnect: DisconnectFunc, error: (err: any) => void): Promise<void>; close(): Promise<void>; sendData(data: ArrayBuffer): Promise<void>; readData(): Promise<DataView>; } class DriverNodeHid implements IDriver { requestDevics(): Promise<Devices>; } } /** * Created by tijmen on 16-01-16. * * translation of concept 2 csafe.h to typescript version 9/16/08 10:51a */ declare namespace ergometer.csafe.defs { const EXT_FRAME_START_BYTE = 240; const FRAME_START_BYTE = 241; const FRAME_END_BYTE = 242; const FRAME_STUFF_BYTE = 243; const FRAME_MAX_STUFF_OFFSET_BYTE = 3; const FRAME_FLG_LEN = 2; const EXT_FRAME_ADDR_LEN = 2; const FRAME_CHKSUM_LEN = 1; const SHORT_CMD_TYPE_MSK = 128; const LONG_CMD_HDR_LENGTH = 2; const LONG_CMD_BYTE_CNT_OFFSET = 1; const RSP_HDR_LENGTH = 2; const FRAME_STD_TYPE = 0; const FRAME_EXT_TYPE = 1; const DESTINATION_ADDR_HOST = 0; const DESTINATION_ADDR_ERG_MASTER = 1; const DESTINATION_ADDR_BROADCAST = 255; const DESTINATION_ADDR_ERG_DEFAULT = 253; const FRAME_MAXSIZE = 96; const INTERFRAMEGAP_MIN = 50; const CMDUPLIST_MAXSIZE = 10; const MEMORY_BLOCKSIZE = 64; const FORCEPLOT_BLOCKSIZE = 32; const HEARTBEAT_BLOCKSIZE = 32; const MANUFACTURE_ID = 22; const CLASS_ID = 2; const MODEL_NUM = 5; const UNITS_TYPE = 0; const SERIALNUM_DIGITS = 9; const HMS_FORMAT_CNT = 3; const YMD_FORMAT_CNT = 3; const ERRORCODE_FORMAT_CNT = 3; const CTRL_CMD_LONG_MIN = 1; const CFG_CMD_LONG_MIN = 16; const DATA_CMD_LONG_MIN = 32; const AUDIO_CMD_LONG_MIN = 64; const TEXTCFG_CMD_LONG_MIN = 96; const TEXTSTATUS_CMD_LONG_MIN = 101; const CAP_CMD_LONG_MIN = 112; const PMPROPRIETARY_CMD_LONG_MIN = 118; const CTRL_CMD_SHORT_MIN = 128; const STATUS_CMD_SHORT_MIN = 145; const DATA_CMD_SHORT_MIN = 160; const AUDIO_CMD_SHORT_MIN = 192; const TEXTCFG_CMD_SHORT_MIN = 224; const TEXTSTATUS_CMD_SHORT_MIN = 229; const enum SHORT_CTRL_CMDS { GETSTATUS_CMD = 128, RESET_CMD = 129, GOIDLE_CMD = 130, GOHAVEID_CMD = 131, GOINUSE_CMD = 133, GOFINISHED_CMD = 134, GOREADY_CMD = 135, BADID_CMD = 136, CTRL_CMD_SHORT_MAX = 137, } const enum SHORT_STATUS_CMDS { GETVERSION_CMD = 145, GETID_CMD = 146, GETUNITS_CMD = 147, GETSERIAL_CMD = 148, GETLIST_CMD = 152, GETUTILIZATION_CMD = 153, GETMOTORCURRENT_CMD = 154, GETODOMETER_CMD = 155, GETERRORCODE_CMD = 156, GETSERVICECODE_CMD = 157, GETUSERCFG1_CMD = 158, GETUSERCFG2_CMD = 159, STATUS_CMD_SHORT_MAX = 160, } const enum SHORT_DATA_CMDS { GETTWORK_CMD = 160, GETHORIZONTAL_CMD = 161, GETVERTICAL_CMD = 162, GETCALORIES_CMD = 163, GETPROGRAM_CMD = 164, GETSPEED_CMD = 165, GETPACE_CMD = 166, GETCADENCE_CMD = 167, GETGRADE_CMD = 168, GETGEAR_CMD = 169, GETUPLIST_CMD = 170, GETUSERINFO_CMD = 171, GETTORQUE_CMD = 172, GETHRCUR_CMD = 176, GETHRTZONE_CMD = 178, GETMETS_CMD = 179, GETPOWER_CMD = 180, GETHRAVG_CMD = 181, GETHRMAX_CMD = 182, GETUSERDATA1_CMD = 190, GETUSERDATA2_CMD = 191, DATA_CMD_SHORT_MAX = 192, } const enum SHORT_AUDIO_CMDS { GETAUDIOCHANNEL_CMD = 192, GETAUDIOVOLUME_CMD = 193, GETAUDIOMUTE_CMD = 194, AUDIO_CMD_SHORT_MAX = 195, } const enum SHORT_TEXTCFG_CMDS { ENDTEXT_CMD = 224, DISPLAYPOPUP_CMD = 225, TEXTCFG_CMD_SHORT_MAX = 226, } const enum SHORT_TEXTSTATUS_CMDS { GETPOPUPSTATUS_CMD = 229, TEXTSTATUS_CMD_SHORT_MAX = 230, } const enum LONG_CTRL_CMDS { AUTOUPLOAD_CMD = 1, UPLIST_CMD = 2, UPSTATUSSEC_CMD = 4, UPLISTSEC_CMD = 5, CTRL_CMD_LONG_MAX = 6, } const enum LONG_CFG_CMDS { IDDIGITS_CMD = 16, SETTIME_CMD = 17, SETDATE_CMD = 18, SETTIMEOUT_CMD = 19, SETUSERCFG1_CMD = 26, SETUSERCFG2_CMD = 27, CFG_CMD_LONG_MAX = 28, } const enum LONG_DATA_CMDS { SETTWORK_CMD = 32, SETHORIZONTAL_CMD = 33, SETVERTICAL_CMD = 34, SETCALORIES_CMD = 35, SETPROGRAM_CMD = 36, SETSPEED_CMD = 37, SETGRADE_CMD = 40, SETGEAR_CMD = 41, SETUSERINFO_CMD = 43, SETTORQUE_CMD = 44, SETLEVEL_CMD = 45, SETTARGETHR_CMD = 48, SETGOAL_CMD = 50, SETMETS_CMD = 51, SETPOWER_CMD = 52, SETHRZONE_CMD = 53, SETHRMAX_CMD = 54, DATA_CMD_LONG_MAX = 55, } const enum LONG_AUDIO_CMDS { SETCHANNELRANGE_CMD = 64, SETVOLUMERANGE_CMD = 65, SETAUDIOMUTE_CMD = 66, SETAUDIOCHANNEL_CMD = 67, SETAUDIOVOLUME_CMD = 68, AUDIO_CMD_LONG_MAX = 69, } const enum LONG_TEXTCFG_CMDS { STARTTEXT_CMD = 96, APPENDTEXT_CMD = 97, TEXTCFG_CMD_LONG_MAX = 98, } const enum LONG_TEXTSTATUS_CMDS { GETTEXTSTATUS_CMD = 101, TEXTSTATUS_CMD_LONG_MAX = 102, } const enum LONG_CAP_CMDS { GETCAPS_CMD = 112, GETUSERCAPS1_CMD = 126, GETUSERCAPS2_CMD = 127, CAP_CMD_LONG_MAX = 128, } const enum LONG_PMPROPRIETARY_CMDS { SETPMCFG_CMD = 118, SETPMDATA_CMD = 119, GETPMCFG_CMD = 126, GETPMDATA_CMD = 127, PMPROPRIETARY_CMD_LONG_MAX = 128, } const GETPMCFG_CMD_SHORT_MIN = 128; const GETPMCFG_CMD_LONG_MIN = 80; const SETPMCFG_CMD_SHORT_MIN = 224; const SETPMCFG_CMD_LONG_MIN = 0; const GETPMDATA_CMD_SHORT_MIN = 160; const GETPMDATA_CMD_LONG_MIN = 104; const SETPMDATA_CMD_SHORT_MIN = 208; const SETPMDATA_CMD_LONG_MIN = 48; const enum PM_SHORT_PULL_CFG_CMDS { PM_GET_FW_VERSION = 128, PM_GET_HW_VERSION = 129, PM_GET_HW_ADDRESS = 130, PM_GET_TICK_TIMEBASE = 131, PM_GET_HRM = 132, PM_GET_SCREENSTATESTATUS = 134, PM_GET_RACE_LANE_REQUEST = 135, PM_GET_ERG_LOGICALADDR_REQUEST = 136, PM_GET_WORKOUTTYPE = 137, PM_GET_DISPLAYTYPE = 138, PM_GET_DISPLAYUNITS = 139, PM_GET_LANGUAGETYPE = 140, PM_GET_WORKOUTSTATE = 141, PM_GET_INTERVALTYPE = 142, PM_GET_OPERATIONALSTATE = 143, PM_GET_LOGCARDSTATE = 144, PM_GET_LOGCARDSTATUS = 145, PM_GET_POWERUPSTATE = 146, PM_GET_ROWINGSTATE = 147, PM_GET_SCREENCONTENT_VERSION = 148, PM_GET_COMMUNICATIONSTATE = 149, PM_GET_RACEPARTICIPANTCOUNT = 150, PM_GET_BATTERYLEVELPERCENT = 151, PM_GET_RACEMODESTATUS = 152, PM_GET_INTERNALLOGPARAMS = 153, PM_GET_PRODUCTCONFIGURATION = 154, PM_GET_ERGSLAVEDISCOVERREQUESTSTATUS = 155, PM_GET_WIFICONFIG = 156, PM_GET_CPUTICKRATE = 157, PM_GET_LOGCARDCENSUS = 158, PM_GET_WORKOUTINTERVALCOUNT = 159, GETPMCFG_CMD_SHORT_MAX = 160, } const enum PM_SHORT_PULL_DATA_CMDS { PM_GET_WORKTIME = 160, PM_GET_PROJECTED_WORKTIME = 161, PM_GET_TOTAL_RESTTIME = 162, PM_GET_WORKDISTANCE = 163, PM_GET_TOTAL_WORKDISTANCE = 164, PM_GET_PROJECTED_WORKDISTANCE = 165, PM_GET_RESTDISTANCE = 166, PM_GET_TOTAL_RESTDISTANCE = 167, PM_GET_STROKE_500MPACE = 168, PM_GET_STROKE_POWER = 169, PM_GET_STROKE_CALORICBURNRATE = 170, PM_GET_SPLIT_AVG_500MPACE = 171, PM_GET_SPLIT_AVG_POWER = 172, PM_GET_SPLIT_AVG_CALORICBURNRATE = 173, PM_GET_SPLIT_AVG_CALORIES = 174, PM_GET_TOTAL_AVG_500MPACE = 175, PM_GET_TOTAL_AVG_POWER = 176, PM_GET_TOTAL_AVG_CALORICBURNRATE = 177, PM_GET_TOTAL_AVG_CALORIES = 178, PM_GET_STROKERATE = 179, PM_GET_SPLIT_AVG_STROKERATE = 180, PM_GET_TOTAL_AVG_STROKERATE = 181, PM_GET_AVG_HEARTRATE = 182, PM_GET_ENDING_AVG_HEARTRATE = 183, PM_GET_REST_AVG_HEARTRATE = 184, PM_GET_SPLITTIME = 185, PM_GET_LASTSPLITTIME = 186, PM_GET_SPLITDISTANCE = 187, PM_GET_LASTSPLITDISTANCE = 188, PM_GET_LASTRESTDISTANCE = 189, PM_GET_TARGETPACETIME = 190, PM_GET_STROKESTATE = 191, PM_GET_STROKERATESTATE = 192, PM_GET_DRAGFACTOR = 193, PM_GET_ENCODERPERIOD = 194, PM_GET_HEARTRATESTATE = 195, PM_GET_SYNCDATA = 196, PM_GET_SYNCDATAALL = 197, PM_GET_RACEDATA = 198, PM_GET_TICKTIME = 199, PM_GET_ERRORTYPE = 200, PM_GET_ERRORVALUE = 201, PM_GET_STATUSTYPE = 202, PM_GET_STATUSVALUE = 203, PM_GET_EPMSTATUS = 204, PM_GET_DISPLAYUPDATETIME = 205, PM_GET_SYNCFRACTIONALTIME = 206, PM_GET_RESTTIME = 207, GETPMDATA_CMD_SHORT_MAX = 208, } const enum PM_SHORT_PUSH_DATA_CMDS { PM_SET_SYNC_DISTANCE = 208, PM_SET_SYNC_STROKEPACE = 209, PM_SET_SYNC_AVG_HEARTRATE = 210, PM_SET_SYNC_TIME = 211, PM_SET_SYNC_SPLIT_DATA = 212, PM_SET_SYNC_ENCODER_PERIOD = 213, PM_SET_SYNC_VERSION_INFO = 214, PM_SET_SYNC_RACETICKTIME = 215, PM_SET_SYNC_DATAALL = 216, SETPMDATA_CMD_SHORT_MAX = 217, } const enum PM_SHORT_PUSH_CFG_CMDS { PM_SET_RESET_ALL = 224, PM_SET_RESET_ERGNUMBER = 225, SETPMCFG_CMD_SHORT_MAX = 226, } const enum PM_LONG_PUSH_CFG_CMDS { PM_SET_BAUDRATE = 0, PM_SET_WORKOUTTYPE = 1, PM_SET_STARTTYPE = 2, PM_SET_WORKOUTDURATION = 3, PM_SET_RESTDURATION = 4, PM_SET_SPLITDURATION = 5, PM_SET_TARGETPACETIME = 6, PM_SET_INTERVALIDENTIFIER = 7, PM_SET_OPERATIONALSTATE = 8, PM_SET_RACETYPE = 9, PM_SET_WARMUPDURATION = 10, PM_SET_RACELANESETUP = 11, PM_SET_RACELANEVERIFY = 12, PM_SET_RACESTARTPARAMS = 13, PM_SET_ERGSLAVEDISCOVERYREQUEST = 14, PM_SET_BOATNUMBER = 15, PM_SET_ERGNUMBER = 16, PM_SET_COMMUNICATIONSTATE = 17, PM_SET_CMDUPLIST = 18, PM_SET_SCREENSTATE = 19, PM_CONFIGURE_WORKOUT = 20, PM_SET_TARGETAVGWATTS = 21, PM_SET_TARGETCALSPERHR = 22, PM_SET_INTERVALTYPE = 23, PM_SET_WORKOUTINTERVALCOUNT = 24, PM_SET_DISPLAYUPDATERATE = 25, PM_SET_AUTHENPASSWORD = 26, PM_SET_TICKTIME = 27, PM_SET_TICKTIMEOFFSET = 28, PM_SET_RACEDATASAMPLETICKS = 29, PM_SET_RACEOPERATIONTYPE = 30, PM_SET_RACESTATUSDISPLAYTICKS = 31, PM_SET_RACESTATUSWARNINGTICKS = 32, PM_SET_RACEIDLEMODEPARAMS = 33, PM_SET_DATETIME = 34, PM_SET_LANGUAGETYPE = 35, PM_SET_WIFICONFIG = 36, PM_SET_CPUTICKRATE = 37, PM_SET_LOGCARDUSER = 38, PM_SET_SCREENERRORMODE = 39, PM_SET_CABLETEST = 40, PM_SET_USER_ID = 41, PM_SET_USER_PROFILE = 42, PM_SET_HRM = 43, PM_SET_SENSOR_CHANNEL = 47, SETPMCFG_CMD_LONG_MAX = 48, } const enum PM_LONG_PUSH_DATA_CMDS { PM_SET_TEAM_DISTANCE = 48, PM_SET_TEAM_FINISH_TIME = 49, PM_SET_RACEPARTICIPANT = 50, PM_SET_RACESTATUS = 51, PM_SET_LOGCARDMEMORY = 52, PM_SET_DISPLAYSTRING = 53, PM_SET_DISPLAYBITMAP = 54, PM_SET_LOCALRACEPARTICIPANT = 55, PM_SET_ANTRFMODE = 78, PM_SET_MEMORY = 79, SETPMDATA_CMD_LONG_MAX = 80, } const enum PM_LONG_PULL_CFG_CMDS { PM_GET_ERGNUMBER = 80, PM_GET_ERGNUMBERREQUEST = 81, PM_GET_USERIDSTRING = 82, PM_GET_LOCALRACEPARTICIPANT = 83, PM_GET_USER_ID = 84, PM_GET_USER_PROFILE = 85, GETPMCFG_CMD_LONG_MAX = 86, } const enum PM_LONG_PULL_DATA_CMDS { PM_GET_MEMORY = 104, PM_GET_LOGCARDMEMORY = 105, PM_GET_INTERNALLOGMEMORY = 106, PM_GET_FORCEPLOTDATA = 107, PM_GET_HEARTBEATDATA = 108, PM_GET_UI_EVENTS = 109, GETPMDATA_CMD_LONG_MAX = 110, } const PREVOK_FLG = 0; const PREVREJECT_FLG = 16; const PREVBAD_FLG = 32; const PREVNOTRDY_FLG = 48; const PREVFRAMESTATUS_MSK = 48; const SLAVESTATE_ERR_FLG = 0; const SLAVESTATE_RDY_FLG = 1; const SLAVESTATE_IDLE_FLG = 2; const SLAVESTATE_HAVEID_FLG = 3; const SLAVESTATE_INUSE_FLG = 5; const SLAVESTATE_PAUSE_FLG = 6; const SLAVESTATE_FINISH_FLG = 7; const SLAVESTATE_MANUAL_FLG = 8; const SLAVESTATE_OFFLINE_FLG = 9; const FRAMECNT_FLG = 128; const SLAVESTATE_MSK = 15; const AUTOSTATUS_FLG = 1; const UPSTATUS_FLG = 2; const UPLIST_FLG = 4; const ACK_FLG = 16; const EXTERNCONTROL_FLG = 64; const CAPCODE_PROTOCOL = 0; const CAPCODE_POWER = 1; const CAPCODE_TEXT = 2; const DISTANCE_MILE_0_0 = 1; const DISTANCE_MILE_0_1 = 2; const DISTANCE_MILE_0_2 = 3; const DISTANCE_MILE_0_3 = 4; const DISTANCE_FEET_0_0 = 5; const DISTANCE_INCH_0_0 = 6; const WEIGHT_LBS_0_0 = 7; const WEIGHT_LBS_0_1 = 8; const DISTANCE_FEET_1_0 = 10; const SPEED_MILEPERHOUR_0_0 = 16; const SPEED_MILEPERHOUR_0_1 = 17; const SPEED_MILEPERHOUR_0_2 = 18; const SPEED_FEETPERMINUTE_0_0 = 19; const DISTANCE_KM_0_0 = 33; const DISTANCE_KM_0_1 = 34; const DISTANCE_KM_0_2 = 35; const DISTANCE_METER_0_0 = 36; const DISTANCE_METER_0_1 = 37; const DISTANCE_CM_0_0 = 38; const WEIGHT_KG_0_0 = 39; const WEIGHT_KG_0_1 = 40; const SPEED_KMPERHOUR_0_0 = 48; const SPEED_KMPERHOUR_0_1 = 49; const SPEED_KMPERHOUR_0_2 = 50; const SPEED_METERPERMINUTE_0_0 = 51; const PACE_MINUTEPERMILE_0_0 = 55; const PACE_MINUTEPERKM_0_0 = 56; const PACE_SECONDSPERKM_0_0 = 57; const PACE_SECONDSPERMILE_0_0 = 58; const DISTANCE_FLOORS_0_0 = 65; const DISTANCE_FLOORS_0_1 = 66; const DISTANCE_STEPS_0_0 = 67; const DISTANCE_REVS_0_0 = 68; const DISTANCE_STRIDES_0_0 = 69; const DISTANCE_STROKES_0_0 = 70; const MISC_BEATS_0_0 = 71; const ENERGY_CALORIES_0_0 = 72; const GRADE_PERCENT_0_0 = 74; const GRADE_PERCENT_0_2 = 75; const GRADE_PERCENT_0_1 = 76; const CADENCE_FLOORSPERMINUTE_0_1 = 79; const CADENCE_FLOORSPERMINUTE_0_0 = 80; const CADENCE_STEPSPERMINUTE_0_0 = 81; const CADENCE_REVSPERMINUTE_0_0 = 82; const CADENCE_STRIDESPERMINUTE_0_0 = 83; const CADENCE_STROKESPERMINUTE_0_0 = 84; const MISC_BEATSPERMINUTE_0_0 = 85; const BURN_CALORIESPERMINUTE_0_0 = 86; const BURN_CALORIESPERHOUR_0_0 = 87; const POWER_WATTS_0_0 = 88; const ENERGY_INCHLB_0_0 = 90; const ENERGY_FOOTLB_0_0 = 91; const ENERGY_NM_0_0 = 92; const KG_TO_LBS = 2.2046; const LBS_TO_KG: number; const IDDIGITS_MIN = 2; const IDDIGITS_MAX = 5; const DEFAULT_IDDIGITS = 5; const DEFAULT_ID = 0; const MANUAL_ID = 999999999; const DEFAULT_SLAVESTATE_TIMEOUT = 20; const PAUSED_SLAVESTATE_TIMEOUT = 220; const INUSE_SLAVESTATE_TIMEOUT = 6; const IDLE_SLAVESTATE_TIMEOUT = 30; const BASE_YEAR = 1900; const DEFAULT_STATUSUPDATE_INTERVAL = 256; const DEFAULT_CMDUPLIST_INTERVAL = 256; } /** * Created by tijmen on 19-01-16. * * Extensible frame work so you can add your own csafe commands to the buffer * * this is the core, you do not have to change this code. * */ declare namespace ergometer.csafe { interface ICommandParamsBase { onError?: ErrorHandler; onDataReceived?: (data: any) => void; } interface IRawCommand { waitForResponse: boolean; command: number; detailCommand?: number; data?: number[]; onDataReceived?: (data: DataView) => void; onError?: ErrorHandler; _timestamp?: number; } interface IBuffer { rawCommands: IRawCommand[]; clear(): IBuffer; addRawCommand(info: IRawCommand): any; send(success?: () => void, error?: ErrorHandler): Promise<void>; } interface ICommand { (buffer: IBuffer, monitor: PerformanceMonitorBase): void; } class CommandManagager { private _commands; register(createCommand: ICommand): void; apply(buffer: IBuffer, monitor: PerformanceMonitorBase): void; } var commandManager: CommandManagager; interface ICommandSetStandardValue extends ICommandParamsBase { value: number; } function registerStandardSet<T extends ICommandParamsBase>(functionName: string, command: number, setParams: (params: T) => number[]): void; function registerStandardSetConfig<T extends ICommandParamsBase>(functionName: string, command: number, setParams: (params: T) => number[]): void; function registerStandardShortGet<T extends ICommandParamsBase, U>(functionName: string, command: number, converter: (data: DataView) => U): void; function registerStandardLongGet<T extends ICommandParamsBase, U>(functionName: string, detailCommand: number, converter: (data: DataView) => U): void; } /** * Created by tijmen on 19-01-16. * * Extensible frame work so you can add your own csafe commands to the buffer * */ declare namespace ergometer.csafe { interface ICommandStrokeState extends ICommandParamsBase { onDataReceived: (state: StrokeState) => void; } interface IBuffer { getStrokeState(params: ICommandStrokeState): IBuffer; } interface ICommandDragFactor extends ICommandParamsBase { onDataReceived: (state: number) => void; } interface IBuffer { getDragFactor(params: ICommandDragFactor): IBuffer; } interface ICommandWorkDistance extends ICommandParamsBase { onDataReceived: (value: number) => void; } interface IBuffer { getWorkDistance(params: ICommandWorkDistance): IBuffer; } interface ICommandWorkTime extends ICommandParamsBase { onDataReceived: (value: number) => void; } interface IBuffer { getWorkTime(params: ICommandWorkTime): IBuffer; } interface ICommandPowerCurve { onDataReceived: (curve: number[]) => void; onError?: ErrorHandler; } interface IBuffer { getPowerCurve(params: ICommandPowerCurve): IBuffer; } interface ICommandGetWorkoutType extends ICommandParamsBase { onDataReceived: (value: WorkoutType) => void; } interface IBuffer { getWorkoutType(params: ICommandParamsBase): IBuffer; } interface ICommandGetWorkoutState extends ICommandParamsBase { onDataReceived: (value: WorkoutState) => void; } interface IBuffer { getWorkoutState(params: ICommandParamsBase): IBuffer; } interface ICommandGetWorkoutIntervalCount extends ICommandParamsBase { onDataReceived: (value: number) => void; } interface IBuffer { getWorkoutIntervalCount(params: ICommandParamsBase): IBuffer; } interface ICommandGetWorkoutIntervalType extends ICommandParamsBase { onDataReceived: (value: IntervalType) => void; } interface IBuffer { getWorkoutIntervalType(params: ICommandParamsBase): IBuffer; } interface ICommandGetWorkoutIntervalRestTime extends ICommandParamsBase { onDataReceived: (value: number) => void; } interface IBuffer { getWorkoutIntervalRestTime(params: ICommandParamsBase): IBuffer; } interface ICommandGetWork extends ICommandParamsBase { onDataReceived: (value: number) => void; } interface IBuffer { getWork(params: ICommandParamsBase): IBuffer; } interface ICommandProgramParams extends ICommandParamsBase { value: Program; } interface IBuffer { setProgram(params: ICommandProgramParams): IBuffer; } interface ICommandTimeParams extends ICommandParamsBase { hour: number; minute: number; second: number; } interface IBuffer { setTime(params: ICommandTimeParams): IBuffer; } interface ICommandDateParams extends ICommandParamsBase { year: number; month: number; day: number; } interface IBuffer { setDate(params: ICommandDateParams): IBuffer; } interface IBuffer { setTimeout(params: ICommandSetStandardValue): IBuffer; } interface IBuffer { setWork(params: ICommandTimeParams): IBuffer; } interface ICommandDistanceParams extends ICommandSetStandardValue { unit: Unit; } interface IBuffer { setDistance(params: ICommandDistanceParams): IBuffer; } interface IBuffer { setTotalCalories(params: ICommandSetStandardValue): IBuffer; } interface ICommandPowerParams extends ICommandSetStandardValue { unit: Unit; } interface IBuffer { setPower(params: ICommandPowerParams): IBuffer; } } /** * Created by tijmen on 19-01-16. * * Extensible frame work so you can add your own csafe commands to the buffer * */ declare namespace ergometer.csafe { interface IVersion { ManufacturerId: number; CID: number; Model: number; HardwareVersion: number; FirmwareVersion: number; } interface ICommandGetVersion extends ICommandParamsBase { onDataReceived: (version: IVersion) => void; } interface IBuffer { getVersion(params: ICommandGetVersion): IBuffer; } interface IDistance { value: number; unit: Unit; } interface ICommandGetDistance extends ICommandParamsBase { onDataReceived: (version: IDistance) => void; } interface IBuffer { getDistance(params: ICommandParamsBase): IBuffer; } interface ICommandGetPace extends ICommandParamsBase { onDataReceived: (value: number) => void; } interface IBuffer { getPace(params: ICommandParamsBase): IBuffer; } interface ICommandGetPower extends ICommandParamsBase { onDataReceived: (value: number) => void; } interface IBuffer { getPower(params: ICommandParamsBase): IBuffer; } interface ICommandGetCadence extends ICommandParamsBase { onDataReceived: (value: number) => void; } interface IBuffer { getCadence(params: ICommandParamsBase): IBuffer; } interface ICommandGetHorizontal extends ICommandParamsBase { onDataReceived: (value: number) => void; } interface IBuffer { getHorizontal(params: ICommandParamsBase): IBuffer; } interface ICommandGetCalories extends ICommandParamsBase { onDataReceived: (value: number) => void; } interface IBuffer { getCalories(params: ICommandParamsBase): IBuffer; } interface ICommandHeartRate extends ICommandParamsBase { onDataReceived: (value: number) => void; } interface IBuffer { getHeartRate(params: ICommandParamsBase): IBuffer; } } /** * Created by tijmen on 06-02-16. */ declare namespace ergometer.csafe { interface ICommandSetWorkOutType extends ICommandParamsBase { value: WorkoutType; } interface IBuffer { setWorkoutType(params: ICommandSetWorkOutType): IBuffer; } } /** * Created by tijmen on 28-12-15. */ declare namespace ergometer { const enum RowingSampleRate { rate1sec = 0, rate500ms = 1, rate250ms = 2, rate100ms = 3, } const enum ErgmachineType { staticD = 0, staticC = 1, staticA = 2, staticB = 3, staticE = 5, staticDynamic = 8, slidesA = 16, slidesB = 17, slidesC = 18, slidesD = 19, slidesE = 20, slidesDynamic = 32, staticDyno = 64, staticSki = 128, num = 129, } const enum WorkoutType { justRowNoSplits = 0, justRowSplits = 1, fixedDistanceNoAplits = 2, fixedDistanceSplits = 3, fixedTimeNoAplits = 4, fixedTimeAplits = 5, fixedTimeInterval = 6, fixedDistanceInterval = 7, variableInterval = 8, variableUndefinedRestInterval = 9, fixedCalorie = 10, fixedWattMinutes = 11, } const enum IntervalType { time = 0, dist = 1, rest = 2, timertUndefined = 3, distanceRestUndefined = 4, restUndefined = 5, cal = 6, calRestUndefined = 7, wattMinute = 8, wattMinuteRestUndefined = 9, none = 255, } const enum WorkoutState { waitToBegin = 0, workoutRow = 1, countDownPause = 2, intervalRest = 3, intervalWorktime = 4, intervalWorkDistance = 5, intervalRestEndToWorkTime = 6, intervalRestEndToWorkDistance = 7, intervalWorktimeTorest = 8, intervalWorkDistanceToEest = 9, workoutEnd = 10, terminate = 11, workoutLogged = 12, rearm = 13, } const enum RowingState { inactive = 0, active = 1, } const enum StrokeState { waitingForWheelToReachMinSpeedState = 0, waitingForWheelToAccelerateState = 1, drivingState = 2, dwellingAfterDriveState = 3, recoveryState = 4, } const enum WorkoutDurationType { timeDuration = 0, caloriesDuration = 64, distanceDuration = 128, wattsDuration = 192, } const enum SampleRate { rate1sec = 0, rate500ms = 1, rate250ms = 2, rate100ms = 3, } const enum Program { Programmed = 0, StandardList1 = 1, StandardList2 = 2, StandardList3 = 3, StandardList4 = 4, StandardList5 = 5, CustomList1 = 6, CustomList2 = 7, CustomList3 = 8, CustomList4 = 9, CustomList5 = 10, FavoritesList1 = 11, FavoritesList2 = 12, FavoritesList3 = 13, FavoritesList4 = 14, FavoritesList5 = 15, } const enum Unit { distanceMile = 1, distanceMile1 = 2, distanceMile2 = 3, distanceMile3 = 4, distanceFeet = 5, distanceInch = 6, weightLbs = 7, weightLbs1 = 8, distanceFeet10 = 10, speedMilePerHour = 16, speedMilePerHour1 = 17, speedMilePerHour2 = 18, speedFeetPerMinute = 19, distanceKm = 33, distanceKm1 = 34, distanceKm2 = 35, distanceMeter = 36, distanceMeter1 = 37, distance_cm = 38, weightKg = 39, weightKg1 = 40, speedKmPerHour = 48, speedKmPerHour1 = 49, speedKmPerHour2 = 50, speedMeterPerMinute = 51, paceMinutePermile = 55, paceMinutePerkm = 56, paceSecondsPerkm = 57, paceSecondsPermile = 58, distanceFloors = 65, distanceFloors1 = 66, distanceSteps = 67, distanceRevs = 68, distanceStrides = 69, distanceStrokes = 70, miscBeats = 71, energyCalories = 72, gradePercent = 74, gradePercent2 = 75, gradePercent1 = 76, cadenceFloorsPerMinute1 = 79, cadenceFloorsPerMinute = 80, cadenceStepsPerMinute = 81, cadenceRevsPerMinute = 82, cadenceStridesPerMinute = 83, cadenceStrokesPerMinute = 84, miscBeatsPerMinute = 85, burnCaloriesPerMinute = 86, burnCaloriesPerHour = 87, powerWatts = 88, energyInchlb = 90, energyFootlb = 91, energyNm = 92, } interface RowingGeneralStatus { elapsedTime: number; distance: number; workoutType: WorkoutType; intervalType: IntervalType; workoutState: WorkoutState; rowingState: RowingState; strokeState: StrokeState; totalWorkDistance: number; workoutDuration: number; workoutDurationType: WorkoutDurationType; dragFactor: number; } interface RowingAdditionalStatus1 { elapsedTime: number; speed: number; strokeRate: number; heartRate: number; currentPace: number; averagePace: number; restDistance: number; restTime: number; averagePower: number; } interface RowingAdditionalStatus2 { elapsedTime: number; intervalCount: number; averagePower: number; totalCalories: number; splitAveragePace: number; splitAveragePower: number; splitAverageCalories: number; lastSplitTime: number; lastSplitDistance: number; } interface RowingStrokeData { elapsedTime: number; distance: number; driveLength: number; driveTime: number; strokeRecoveryTime: number; strokeDistance: number; peakDriveForce: number; averageDriveForce: number; workPerStroke: number; strokeCount: number; } interface RowingAdditionalStrokeData { elapsedTime: number; strokePower: number; strokeCalories: number; strokeCount: number; projectedWorkTime: number; projectedWorkDistance: number; workPerStroke: number; } interface RowingSplitIntervalData { elapsedTime: number; distance: number; intervalTime: number; intervalDistance: number; intervalRestTime: number; intervalRestDistance: number; intervalType: IntervalType; intervalNumber: number; } interface RowingAdditionalSplitIntervalData { elapsedTime: number; intervalAverageStrokeRate: number; intervalWorkHeartrate: number; intervalRestHeartrate: number; intervalAveragePace: number; intervalTotalCalories: number; intervalAverageCalories: number; intervalSpeed: number; intervalPower: number; splitAverageDragFactor: number; intervalNumber: number; } interface WorkoutSummaryData { logEntryDate: number; logEntryTime: number; elapsedTime: number; distance: number; averageStrokeRate: number; endingHeartrate: number; averageHeartrate: number; minHeartrate: number; maxHeartrate: number; dragFactorAverage: number; recoveryHeartRate: number; workoutType: WorkoutType; averagePace: number; } interface AdditionalWorkoutSummaryData { logEntryDate: number; logEntryTime: number; intervalType: IntervalType; intervalSize: number; intervalCount: number; totalCalories: number; watts: number; totalRestDistance: number; intervalRestTime: number; averageCalories: number; } interface AdditionalWorkoutSummaryData2 { logEntryDate: number; logEntryTime: number; averagePace: number; gameIdentifier: number; gameScore: number; ergMachineType: ErgmachineType; } interface HeartRateBeltInformation { manufacturerId: number; deviceType: number; beltId: number; } } /** * Concept 2 ergometer Performance Monitor api for Cordova * * This will will work with the PM5 * * Created by tijmen on 01-06-15. * License: * * Copyright 2016 Tijmen van Gulik (tijmen@vangulik.org) * Copyright 2016 Tijmen van Gulik (tijmen@vangulik.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ declare namespace ergometer { interface ErrorHandler { (e: any): void; } enum LogLevel { error = 0, info = 1, debug = 2, trace = 3, } interface LogEvent extends pubSub.ISubscription { (text: string, logLevel: LogLevel): void; } interface ParsedCSafeCommand { command: number; detailCommand: number; data: Uint8Array; } enum MonitorConnectionState { inactive = 0, deviceReady = 1, scanning = 2, connecting = 3, connected = 4, servicesFound = 5, readyForCommunication = 6, } interface ConnectionStateChangedEvent extends pubSub.ISubscription { (oldState: MonitorConnectionState, newState: MonitorConnectionState): void; } interface PowerCurveEvent extends pubSub.ISubscription { (data: number[]): void; } /** * * Usage: * * Create this class to acess the performance data * var performanceMonitor= new ergometer.PerformanceMonitor(); * * after this connect to the events to get data * performanceMonitor.rowingGeneralStatusEvent.sub(this,this.onRowingGeneralStatus); * On some android phones you can connect to a limited number of events. Use the multiplex property to overcome * this problem. When the multi plex mode is switched on the data send to the device can be a a bit different, see * the documentation in the properties You must set the multi plex property before connecting * performanceMonitor.multiplex=true; * * to start the connection first start scanning for a device, * you should call when the cordova deviceready event is called (or later) * performanceMonitor.startScan((device : ergometer.DeviceInfo) : boolean => { * //return true when you want to connect to the device * return device.name=='My device name'; * }); * to connect at at a later time * performanceMonitor.connectToDevice('my device name'); * the devices which where found during the scan are collected in * performanceMonitor.devices * when you connect to a device the scan is stopped, when you want to stop the scan earlier you need to call * performanceMonitor.stopScan * */ class PerformanceMonitorBase { private _logEvent; private _logLevel; private _csafeBuffer; private _waitResponseCommands; protected _connectionState: MonitorConnectionState; protected _powerCurve: number[]; protected _splitCommandsWhenToBig: boolean; protected _checkFrameEnding: boolean; private _connectionStateChangedEvent; private _powerCurveEvent; private _checksumCheckEnabled; constructor(); protected initialize(): void; protected enableDisableNotification(): void; /** * returns error and other log information. Some errors can only be received using the logEvent * @returns {pubSub.Event<LogEvent>} */ readonly logEvent: pubSub.Event<LogEvent>; readonly powerCurveEvent: pubSub.Event<ergometer.PowerCurveEvent>; readonly powerCurve: number[]; /** * Print debug info to console and application UI. * @param info */ traceInfo(info: string): void; /** * * @param info */ debugInfo(info: string): void; /** * * @param info */ showInfo(info: string): void; /** * call the global error hander and call the optional error handler if given * @param error */ handleError(error: string, errorFn?: ErrorHandler): void; /** * Get an error function which adds the errorDescription to the error ,cals the global and an optional local funcion * @param errorDescription * @param errorFn */ getErrorHandlerFunc(errorDescription: string, errorFn?: ErrorHandler): ErrorHandler; /** * By default it the logEvent will return errors if you want more debug change the log level * @returns {LogLevel} */ /** * By default it the logEvent will return errors if you want more debug change the log level * @param value */ logLevel: LogLevel; disconnect(): void; /** * read the current connection state * @returns {MonitorConnectionState} */ readonly connectionState: MonitorConnectionState; protected connected(): void; /** * * @param value */ protected changeConnectionState(value: MonitorConnectionState): void; /** * event which is called when the connection state is changed. For example this way you * can check if the device is disconnected. * connect to the using .sub(this,myFunction) * @returns {pubSub.Event<ConnectionStateChangedEvent>} */ readonly connectionStateChangedEvent: pubSub.Event<ConnectionStateChangedEvent>; protected removeOldSendCommands(): void; protected driver_write(data: ArrayBufferView): Promise<void>; /** * send everyt thing which is put into the csave buffer * * @param success * @param error * @returns {Promise<void>|Promise} use promis instead of success and error function */ sendCSafeBuffer(): Promise<void>; protected sendCsafeCommands(byteArray: number[]): Promise<void>; protected receivedCSaveCommand(parsed: ParsedCSafeCommand): void; private _csafeState; protected resetStartCsafe(): void; handeReceivedDriverData(dataView: DataView): void; protected getPacketSize(): number; readonly csafeBuffer: ergometer.csafe.IBuffer; } } /** * Concept 2 ergometer Performance Monitor api for Cordova * * This will will work with the PM5 * * Created by tijmen on 01-06-15. * License: * * Copyright 2016 Tijmen van Gulik (tijmen@vangulik.org) * Copyright 2016 Tijmen van Gulik (tijmen@vangulik.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ declare namespace ergometer { class UsbDevice { vendorId: number; productId: number; productName: string; serialNumber: string; } type UsbDevices = UsbDevice[]; interface StrokeStateChangedEvent extends pubSub.ISubscription { (oldState: StrokeState, newState: StrokeState, duration: number): void; } interface TrainingDataEvent extends pubSub.ISubscription { (data: TrainingData): void; } interface StrokeDataEvent extends pubSub.ISubscription { (data: StrokeData): void; } class StrokeData { dragFactor: number; workDistance: number; workTime: number; splitTime: number; power: number; strokesPerMinuteAverage: number; strokesPerMinute: number; distance: number; totCalories: number; caloriesPerHour: number; heartRate: number; } class TrainingData { workoutType: WorkoutType; duration: number; distance: number; workoutState: WorkoutState; workoutIntervalCount: number; intervalType: IntervalType; restTime: number; endDistance: number; endDuration: number; } class PerformanceMonitorUsb extends PerformanceMonitorBase { private _driver; private _device; private _nSPMReads; private _nSPM; private _strokeStateEvent; private _trainingDataEvent; private _strokeDataEvent; private _strokeData; private _trainingData; private _strokeState; private _lastTrainingTime; private _csafeBuzy; readonly csafeBuzy: boolean; readonly strokeData: StrokeData; readonly trainingData: TrainingData; readonly strokeState: StrokeState; readonly device: ergometer.usb.IDevice; readonly strokeStateEvent: pubSub.Event<StrokeStateChangedEvent>; readonly trainingDataEvent: pubSub.Event<TrainingDataEvent>; readonly strokeDataEvent: pubSub.Event<StrokeDataEvent>; static canUseNodeHid(): boolean; static canUseUsb(): boolean; protected initialize(): void; driver: ergometer.usb.IDriver; protected driver_write(data: ArrayBufferView): Promise<void>; sendCSafeBuffer(): Promise<void>; requestDevics(): Promise<UsbDevices>; disconnect(): void; private disconnected(); connectToDevice(device: UsbDevice): Promise<void>; protected getPacketSize(): number; protected highResolutionUpdate(): Promise<void>; private handlePowerCurve(); protected connected(): void; private _autoUpdating; private listeningToEvents(); protected autoUpdate(first?: boolean): void; protected nextAutoUpdate(): void; protected update(): Promise<void>; private _startPhaseTime; protected calcStrokeStateDuration(): number; protected lowResolutionUpdate(): Promise<void>; protected newStrokeState(state: StrokeState): void; protected trainingDataUpdate(): Promise<void>; private resetStartRowing(); } } /** * Concept 2 ergometer Performance Monitor api for Cordova * * This will will work with the PM5 * * Created by tijmen on 01-06-15. * License: * * Copyright 2016 Tijmen van Gulik (tijmen@vangulik.org) * Copyright 2016 Tijmen van Gulik (tijmen@vangulik.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ declare namespace ergometer { interface RowingGeneralStatusEvent extends pubSub.ISubscription { (data: RowingGeneralStatus): void; } interface RowingAdditionalStatus1Event extends pubSub.ISubscription { (data: RowingAdditionalStatus1): void; } interface RowingAdditionalStatus2Event extends pubSub.ISubscription { (data: RowingAdditionalStatus2): void; } interface RowingStrokeDataEvent extends pubSub.ISubscription { (data: RowingStrokeData): void; } interface RowingAdditionalStrokeDataEvent extends pubSub.ISubscription { (data: RowingAdditionalStrokeData): void; } interface RowingSplitIntervalDataEvent extends pubSub.ISubscription { (data: RowingSplitIntervalData): void; } interface RowingAdditionalSplitIntervalDataEvent extends pubSub.ISubscription { (data: RowingAdditionalSplitIntervalData): void; } interface WorkoutSummaryDataEvent extends pubSub.ISubscription { (data: WorkoutSummaryData): void; } interface AdditionalWorkoutSummaryDataEvent extends pubSub.ISubscription { (data: AdditionalWorkoutSummaryData): void; } interface AdditionalWorkoutSummaryData2Event extends pubSub.ISubscription { (data: AdditionalWorkoutSummaryData2): void; } interface HeartRateBeltInformationEvent extends pubSub.ISubscription { (data: HeartRateBeltInformation): void; } interface DeviceInfo { connected: boolean; name: string; address: string; quality: number; serial?: string; hardwareRevision?: string; firmwareRevision?: string; manufacturer?: string; } /** * * Usage: * * Create this class to acess the performance data * var performanceMonitor= new ergometer.PerformanceMonitor(); * * after this connect to the events to get data * performanceMonitor.rowingGeneralStatusEvent.sub(this,this.onRowingGeneralStatus); * On some android phones you can connect to a limited number of events. Use the multiplex property to overcome * this problem. When the multi plex mode is switched on the data send to the device can be a a bit different, see * the documentation in the properties You must set the multi plex property before connecting * performanceMonitor.multiplex=true; * * to start the connection first start scanning for a device, * you should call when the cordova deviceready event is called (or later) * performanceMonitor.startScan((device : ergometer.DeviceInfo) : boolean => { * //return true when you want to connect to the device * return device.name=='My device name'; * }); * to connect at at a later time * performanceMonitor.connectToDevice('my device name'); * the devices which where found during the scan are collected in * performanceMonitor.devices * when you connect to a device the scan is stopped, when you want to stop the scan earlier you need to call * performanceMonitor.stopScan * */ class PerformanceMonitorBle extends PerformanceMonitorBase { private _driver; private _recordingDriver; private _replayDriver; private _rowingGeneralStatusEvent; private _rowingAdditionalStatus1Event; private _rowingAdditionalStatus2Event; private _rowingStrokeDataEvent; private _rowingAdditionalStrokeDataEvent; private _rowingSplitIntervalDataEvent; private _rowingAdditionalSplitIntervalDataEvent; private _workoutSummaryDataEvent; private _additionalWorkoutSummaryDataEvent; private _additionalWorkoutSummaryData2Event; private _heartRateBeltInformationEvent; private _deviceInfo; private _rowingGeneralStatus; private _rowingAdditionalStatus1; private _rowingAdditionalStatus2; private _rowingStrokeData; private _rowingAdditionalStrokeData; private _rowingSplitIntervalData; private _rowingAdditionalSplitIntervalData; private _workoutSummaryData; private _additionalWorkoutSummaryData; private _additionalWorkoutSummaryData2; private _heartRateBeltInformation; private _devices; private _multiplex; private _multiplexSubscribeCount; private _sampleRate; private _autoReConnect; private _generalStatusEventAttachedByPowerCurve; private _recording; protected readonly recordingDriver: ergometer.ble.RecordingDriver; recording: boolean; readonly replayDriver: ble.ReplayDriver; replaying: boolean; replay(events: ble.IRecordingItem[]): void; recordingEvents: ble.IRecordingItem[]; protected readonly driver: ergometer.ble.IDriver; /** * when the connection is lost re-connect * @returns {boolean} */ /** * * when the connection is lost re-connect * @param value */ autoReConnect: boolean; /** * On some android phones you can connect to a limited number of events. Use the multiplex property to overcome * this problem. When the multi plex mode is switched on the data send to the device can be a a bit different, see * the documentation in the properties You must set the multi plex property before connecting * * @returns {boolean} */ /** * On some android phones you can connect to a limited number of events. Use the multiplex property to overcome * this problem. When the multi plex mode is switched on the data send to the device can be a a bit different, see * the documentation in the properties You must set the multi plex property before connecting * @param value */ multiplex: boolean; /** * an array of of performance monitor devices which where found during the scan. * the array is sorted by connection quality (best on top) * * @returns {DeviceInfo[]} */ readonly devices: ergometer.DeviceInfo[]; /** * The values of the last rowingGeneralStatus event * * @returns {RowingGeneralStatus} */ readonly rowingGeneralStatus: RowingGeneralStatus; /** * The values of the last rowingAdditionalStatus1 event * @returns {RowingAdditionalStatus1} */ readonly rowingAdditionalStatus1: RowingAdditionalStatus1; /** * The values of the last RowingAdditionalStatus2 event * @returns {RowingAdditionalStatus2} */ readonly rowingAdditionalStatus2: RowingAdditionalStatus2; /** * The values of the last rowingStrokeData event * @returns {RowingStrokeData} */ readonly rowingStrokeData: RowingStrokeData; /** * The values of the last rowingAdditionalStrokeData event * @returns {RowingAdditionalStrokeData} */ readonly rowingAdditionalStrokeData: RowingAdditionalStrokeData; /** * The values of the last rowingSplitIntervalData event * @returns {RowingSplitIntervalData} */ readonly rowingSplitIntervalData: RowingSplitIntervalData; /** * The values of the last rowingAdditionalSplitIntervalData event * @returns {RowingAdditionalSplitIntervalData} */ readonly rowingAdditionalSplitIntervalData: RowingAdditionalSplitIntervalData; /** * The values of the last workoutSummaryData event * @returns {WorkoutSummaryData} */ readonly workoutSummaryData: WorkoutSummaryData; /** * The values of the last additionalWorkoutSummaryData event * @returns {AdditionalWorkoutSummaryData} */ readonly additionalWorkoutSummaryData: AdditionalWorkoutSummaryData; /** * The values of the last AdditionalWorkoutSummaryData2 event * @returns {AdditionalWorkoutSummaryData2} */ readonly additionalWorkoutSummaryData2: AdditionalWorkoutSummaryData2; /** * The values of the last heartRateBeltInformation event * @returns {HeartRateBeltInformation} */ readonly heartRateBeltInformation: HeartRateBeltInformation; /** * read rowingGeneralStatus data * connect to the using .sub(this,myFunction) * @returns {pubSub.Event<RowingGeneralStatusEvent>} */ readonly rowingGeneralStatusEvent: pubSub.Event<RowingGeneralStatusEvent>; /** * read rowingGeneralStatus1 data * connect to the using .sub(this,myFunction) * @returns {pubSub.Event<RowingAdditionalStatus1Event>} */ readonly rowingAdditionalStatus1Event: pubSub.Event<RowingAdditionalStatus1Event>; /** * read rowingAdditionalStatus2 data * connect to the using .sub(this,myFunction) * @returns {pubSub.Event<RowingAdditionalStatus2Event>} */ readonly rowingAdditionalStatus2Event: pubSub.Event<RowingAdditionalStatus2Event>; /** * read rowingStrokeData data * connect to the using .sub(this,myFunction) * @returns {pubSub.Event<RowingStrokeDataEvent>} */ readonly rowingStrokeDataEvent: pubSub.Event<RowingStrokeDataEvent>; /** * read rowingAdditionalStrokeData data * connect to the using .sub(this,myFunction) * @returns {pubSub.Event<RowingAdditionalStrokeDataEvent>} */ readonly rowingAdditionalStrokeDataEvent: pubSub.Event<RowingAdditionalStrokeDataEvent>; /** * read rowingSplitIntervalDat data * connect to the using .sub(this,myFunction) * @returns {pubSub.Event<RowingSplitIntervalDataEvent>} */ readonly rowingSplitIntervalDataEvent: pubSub.Event<RowingSplitIntervalDataEvent>; /** * read rowingAdditionalSplitIntervalData data * connect to the using .sub(this,myFunction) * @returns {pubSub.Event<RowingAdditionalSplitIntervalDataEvent>} */ readonly rowingAdditionalSplitIntervalDataEvent: pubSub.Event<RowingAdditionalSplitIntervalDataEvent>; /** * read workoutSummaryData data * connect to the using .sub(this,myFunction) * @returns {pubSub.Event<WorkoutSummaryDataEvent>} */ readonly workoutSummaryDataEvent: pubSub.Event<WorkoutSummaryDataEvent>; /** * read additionalWorkoutSummaryData data * connect to the using .sub(this,myFunction) * @returns {pubSub.Event<AdditionalWorkoutSummaryDataEvent>} */ readonly additionalWorkoutSummaryDataEvent: pubSub.Event<AdditionalWorkoutSummaryDataEvent>; /** * read additionalWorkoutSummaryData2 data * connect to the using .sub(this,myFunction) * @returns {pubSub.Event<AdditionalWorkoutSummaryData2Event>} */ readonly additionalWorkoutSummaryData2Event: pubSub.Event<AdditionalWorkoutSummaryData2Event>; /** * read heartRateBeltInformation data * connect to the using .sub(this,myFunction) * @returns {pubSub.Event<HeartRateBeltInformationEvent>} */ readonly heartRateBeltInformationEvent: pubSub.Event<HeartRateBeltInformationEvent>; /** * Get device information of the connected device. * @returns {DeviceInfo} */ readonly deviceInfo: ergometer.DeviceInfo; /** * read the performance montitor sample rate. By default this is 500 ms * @returns {number} */ /** * Change the performance monitor sample rate. * @param value */ sampleRate: SampleRate; /** * disconnect the current connected device */ disconnect(): void; /** * */ protected enableMultiplexNotification(): void; /** * */ protected disableMultiPlexNotification(): void; /** * */ protected enableDisableNotification(): void; protected onPowerCurveRowingGeneralStatus(data: ergometer.RowingGeneralStatus): void; currentDriverIsWebBlueTooth(): boolean; /** * */ protected initialize(): void; /** * When low level initialization complete, this function is called. */ /** * * @param device */ protected removeDevice(device: DeviceInfo): void; /** * * @param device */ protected addDevice(device: DeviceInfo): void; /** * * @param name * @returns {DeviceInfo} */ protected findDevice(name: string): DeviceInfo; /** * */ stopScan(): void; /** * Scan for device use the deviceFound to connect . * @param deviceFound */ startScan(deviceFound: (device: DeviceInfo) => boolean, errorFn?: ErrorHandler): Promise<void>; /** * connect to a specific device. This should be a PM5 device which is found by the startScan. You can * only call this function after startScan is called. Connection to a device will stop the scan. * @param deviceName */ connectToDevice(deviceName: string): Promise<void>; /** * the promise is never fail * @param serviceUUID * @param UUID * @param readValue */ protected readStringCharacteristic(serviceUUID: string, UUID: string): Promise<string>; /** * the promise will never fail * @param done */ protected readSampleRate(): Promise<void>; /** * * @param done */ protected readPheripheralInfo(): Promise<void>; /** * * @param data */ protected handleRowingGeneralStatus(data: DataView): void; protected calcPace(lowByte: any, highByte: number): number; /** * * @param data */ protected handleRowingAdditionalStatus1(data: DataView): void; /** * * @param data */ protected handleRowingAdditionalStatus2(data: DataView): void; /** * * @param data */ protected handleRowingStrokeData(data: DataView): void; /** * * @param data */ protected handleRowingAdditionalStrokeData(data: DataView): void; /** * * @param data */ protected handleRowingSplitIntervalData(data: DataView): void; /** * * @param data */ protected handleRowingAdditionalSplitIntervalData(data: DataView): void; /** * * @param data */ protected handleWorkoutSummaryData(data: DataView): void; /** * * @param data */ protected handleAdditionalWorkoutSummaryData(data: DataView): void; /** * * @param data */ protected handleAdditionalWorkoutSummaryData2(data: DataView): void; /** * * @param data */ protected handleHeartRateBeltInformation(data: DataView): void; handleCSafeNotifications(): void; /** * * @param data */ protected handleDataCallbackMulti(data: ArrayBuffer): void; /** * * @param data * @param func */ protected handleDataCallback(data: ArrayBuffer, func: (data: DataView) => void): void; protected driver_write(data: ArrayBufferView): Promise<void>; protected getPacketSize(): number; } }
the_stack
import React = require("react"); import ReactDOM = require("react-dom"); import * as csx from '../../base/csx'; import {BaseComponent} from "../../ui"; import * as ui from "../../ui"; import * as utils from "../../../common/utils"; import * as styles from "../../styles/styles"; import * as state from "../../state/state"; import * as uix from "../../uix"; import * as commands from "../../commands/commands"; import Modal = require('react-modal'); import {server} from "../../../socket/socketClient"; import {Types} from "../../../socket/socketContract"; import {modal} from "../../styles/styles"; import {Robocop} from "../../components/robocop"; import * as docCache from "../model/docCache"; import {CodeEditor} from "../editor/codeEditor"; import {RefactoringsByFilePath, Refactoring} from "../../../common/types"; import * as typestyle from "typestyle"; const inputClassName = typestyle.style(styles.modal.inputStyleBase); export interface Props { info: Types.GetRenameInfoResponse; alreadyOpenFilePaths: string[]; currentlyClosedFilePaths: string[]; unmount: () => any; } export interface State { invalidMessage?: string; selectedIndex?: number; flattened?: { filePath: string, preview: ts.TextSpan, indexForFilePath: number, totalForFilePath: number }[]; } let validationErrorStyle = { color: 'red', fontFamily: 'monospace', fontSize: '1.2rem', padding: '5px', } let summaryStyle = { padding: '5px', backgroundColor: '#222', color: '#CCC', fontSize: '.8rem', } export class RenameVariable extends BaseComponent<Props, State>{ constructor(props: Props) { super(props); let flattended = utils.selectMany(Object.keys(props.info.locations).map(filePath => { let refs = props.info.locations[filePath].slice().reverse(); return refs.map((preview,i) => { return { filePath, preview, indexForFilePath: i + 1, totalForFilePath: refs.length, }; }); })); this.state = { selectedIndex: 0, flattened: flattended }; } componentDidMount() { this.disposible.add(commands.esc.on(() => { this.props.unmount(); })); setTimeout(() => { this.focus(); let input = (ReactDOM.findDOMNode(this.refs.mainInput) as HTMLInputElement) let len = input.value.length; input.setSelectionRange(0, len); }); } componentDidUpdate() { setTimeout(() => { let selected = ReactDOM.findDOMNode(this.refs.selectedTabTitle) as HTMLDivElement; if (selected) { selected.scrollIntoViewIfNeeded(false); } }); } refs: { [string: string]: any; mainInput: any; selectedTabTitle: any; } render() { let selectedPreview = this.state.flattened[this.state.selectedIndex]; let filePathsRendered = this.state.flattened.map((item,i)=>{ let selected = i == this.state.selectedIndex; let active = selected ? styles.tabHeaderActive : {}; let ref = selected && "selectedTabTitle"; return ( <div ref={ref} key={item.filePath + i} style={csx.extend(styles.tabHeader,active,{overflow:'hidden'})} onClick={()=>this.selectAndRefocus(i)}> <div title={item.filePath} style={{overflow:'hidden',textOverflow:'ellipsis'}}>{utils.getFileName(item.filePath)} ({item.indexForFilePath} of {item.totalForFilePath})</div> </div> ); }); let previewRendered = <CodeEditor key={selectedPreview.filePath} filePath={selectedPreview.filePath} readOnly={true} preview={selectedPreview.preview} />; return ( <Modal isOpen={true} onRequestClose={this.props.unmount}> <div style={csx.extend(csx.vertical, csx.flex)}> <div style={csx.extend(csx.horizontal, csx.content)}> <h4>Rename</h4> <div style={csx.flex}></div> <div style={{fontSize:'0.9rem', color:'grey'} as any}> <code style={modal.keyStrokeStyle}>Esc</code> to exit <code style={modal.keyStrokeStyle}>Enter</code> to select {' '}<code style={modal.keyStrokeStyle}>Up / Down</code> to see usages </div> </div> <div style={csx.extend(styles.padded1TopBottom, csx.vertical, csx.content)}> <input defaultValue={this.props.info.displayName} className={inputClassName} type="text" ref="mainInput" placeholder="Filter" onChange={this.onChangeFilter} onKeyDown={this.onChangeSelected} /> </div> { this.state.invalidMessage && <div style={csx.extend(csx.content,validationErrorStyle)}>{this.state.invalidMessage}</div> } <div style={csx.extend(csx.content,summaryStyle)}> {this.state.flattened.length} usages, {this.props.alreadyOpenFilePaths.length} files open, {this.props.currentlyClosedFilePaths.length} files closed </div> <div style={csx.extend(csx.horizontal, csx.flex, { overflow: 'hidden' })}> <div style={{width:'200px', overflow:'auto'} as any}> {filePathsRendered} </div> <div style={csx.extend(csx.flex, csx.flexRoot, styles.modal.previewContainerStyle)}> {previewRendered} </div> </div> </div> </Modal> ); } onChangeFilter = (e) => { let newText = (ReactDOM.findDOMNode(this.refs.mainInput) as HTMLInputElement).value; if (newText.replace(/\s/g, '') !== newText.trim()) { this.setState({ invalidMessage: 'The new variable must not contain a space' }); } else if (!newText.trim()) { this.setState({ invalidMessage: 'Please provide a new name or press esc to abort rename' }); } else { this.setState({ invalidMessage: '' }); } }; onChangeSelected = (event) => { let keyStates = ui.getKeyStates(event); if (keyStates.up || keyStates.tabPrevious) { event.preventDefault(); let selectedIndex = utils.rangeLimited({ num: this.state.selectedIndex - 1, min: 0, max: this.state.flattened.length - 1, loopAround: true }); this.setState({selectedIndex}); } if (keyStates.down || keyStates.tabNext) { event.preventDefault(); let selectedIndex = utils.rangeLimited({ num: this.state.selectedIndex + 1, min: 0, max: this.state.flattened.length - 1, loopAround: true }); this.setState({selectedIndex}); } if (keyStates.enter) { event.preventDefault(); let newText = (ReactDOM.findDOMNode(this.refs.mainInput) as HTMLInputElement).value.trim(); let refactorings: RefactoringsByFilePath = {}; Object.keys(this.props.info.locations).map(filePath => { refactorings[filePath] = []; let forPath = refactorings[filePath]; this.props.info.locations[filePath].forEach(loc=>{ let refactoring: Refactoring = { filePath: filePath, span: loc, newText } forPath.push(refactoring); }); }); uix.API.applyRefactorings(refactorings); setTimeout(()=>{this.props.unmount()}); } }; selectAndRefocus = (index: number) => { this.setState({selectedIndex:index}); this.focus(); }; focus = () => { let input = (ReactDOM.findDOMNode(this.refs.mainInput) as HTMLInputElement) input.focus(); } } import * as monacoUtils from "../monacoUtils"; import CommonEditorRegistry = monaco.CommonEditorRegistry; import ICommonCodeEditor = monaco.ICommonCodeEditor; import TPromise = monaco.Promise; import EditorAction = monaco.EditorAction; import KeyMod = monaco.KeyMod; import KeyCode = monaco.KeyCode; import ServicesAccessor = monaco.ServicesAccessor; import IActionOptions = monaco.IActionOptions; import EditorContextKeys = monaco.EditorContextKeys; class RenameVariableAction extends EditorAction { constructor() { super({ id: 'editor.action.renameVariable', label: 'TypeScript: Rename Variable', alias: 'TypeScript: Rename Variable', precondition: EditorContextKeys.Writable, kbOpts: { kbExpr: EditorContextKeys.TextFocus, primary: KeyCode.F2 } }); } public run(accessor:ServicesAccessor, editor:ICommonCodeEditor): void | TPromise<void> { const filePath = editor.filePath; if (!state.inActiveProjectFilePath(filePath)) { ui.notifyInfoNormalDisappear('The current file is no in the active project'); return; } let position = monacoUtils.getCurrentPosition(editor); server.getRenameInfo({filePath,position}).then((res)=>{ if (!res.canRename){ ui.notifyInfoNormalDisappear("Rename not available at cursor location"); } else { let filePaths = Object.keys(res.locations); // if there is only a single file path and that is the current and there aren't that many usages // we do the rename inline if (filePaths.length == 1 && filePaths[0] == filePath && res.locations[filePath].length < 5) { selectName(editor, res.locations[filePath]); } else { let {alreadyOpenFilePaths, currentlyClosedFilePaths} = uix.API.getClosedVsOpenFilePaths(filePaths); const {node,unmount} = ui.getUnmountableNode(); ReactDOM.render(<RenameVariable info={res} alreadyOpenFilePaths={alreadyOpenFilePaths} currentlyClosedFilePaths={currentlyClosedFilePaths} unmount={unmount} />, node); } } }); } } CommonEditorRegistry.registerEditorAction(new RenameVariableAction()); /** Selects the locations keeping the current one as the first (to allow easy escape back to current cursor) */ function selectName(editor: monaco.ICommonCodeEditor, locations: ts.TextSpan[]) { const ranges: monaco.ISelection[] = []; const curPos = editor.getSelection(); for (var i = 0; i < locations.length; i++) { var ref = locations[i]; let from = editor.getModel().getPositionAt(ref.start); let to = editor.getModel().getPositionAt(ref.start + ref.length); const range = new monaco.Range(from.lineNumber, from.column, to.lineNumber, to.column); const selection: monaco.ISelection = { selectionStartLineNumber: from.lineNumber, selectionStartColumn: from.column, positionLineNumber: to.lineNumber, positionColumn: to.column } if (!monaco.Range.containsRange(range, curPos)) ranges.push(selection); else ranges.unshift(selection); } editor.setSelections(ranges); }
the_stack
import * as coreClient from "@azure/core-client"; /** The List Operation response. */ export interface OperationListResult { /** * The list of operations * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: OperationValue[]; } /** Describes the properties of a Operation value. */ export interface OperationValue { /** * The origin of the operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly origin?: string; /** * The name of the operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The display name of the operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly operation?: string; /** * The display name of the resource the operation applies to. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly resource?: string; /** * The description of the operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly description?: string; /** * The resource provider for the operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provider?: string; } /** An error response from the Container service. */ export interface CloudError { /** Details about the error. */ error?: CloudErrorBody; } /** An error response from the Container service. */ export interface CloudErrorBody { /** An identifier for the error. Codes are invariant and are intended to be consumed programmatically. */ code?: string; /** A message describing the error, intended to be suitable for display in a user interface. */ message?: string; /** The target of the particular error. For example, the name of the property in error. */ target?: string; /** A list of additional details about the error. */ details?: CloudErrorBody[]; } /** The OS option profile. */ export interface OSOptionProfile { /** * The ID of the OS option resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The name of the OS option resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The type of the OS option resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** The list of OS options. */ osOptionPropertyList: OSOptionProperty[]; } /** OS option property. */ export interface OSOptionProperty { /** The OS type. */ osType: string; /** Whether the image is FIPS-enabled. */ enableFipsImage: boolean; } /** The response from the List Managed Clusters operation. */ export interface ManagedClusterListResult { /** The list of managed clusters. */ value?: ManagedCluster[]; /** * The URL to get the next set of managed cluster results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** The SKU of a Managed Cluster. */ export interface ManagedClusterSKU { /** The name of a managed cluster SKU. */ name?: ManagedClusterSKUName; /** If not specified, the default is 'Free'. See [uptime SLA](https://docs.microsoft.com/azure/aks/uptime-sla) for more details. */ tier?: ManagedClusterSKUTier; } /** The complex type of the extended location. */ export interface ExtendedLocation { /** The name of the extended location. */ name?: string; /** The type of the extended location. */ type?: ExtendedLocationTypes; } /** Identity for the managed cluster. */ export interface ManagedClusterIdentity { /** * The principal id of the system assigned identity which is used by master components. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly principalId?: string; /** * The tenant id of the system assigned identity which is used by master components. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly tenantId?: string; /** For more information see [use managed identities in AKS](https://docs.microsoft.com/azure/aks/use-managed-identity). */ type?: ResourceIdentityType; /** The keys must be ARM resource IDs in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. */ userAssignedIdentities?: { [propertyName: string]: ManagedServiceIdentityUserAssignedIdentitiesValue; }; } export interface ManagedServiceIdentityUserAssignedIdentitiesValue { /** * The principal id of user assigned identity. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly principalId?: string; /** * The client id of user assigned identity. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly clientId?: string; } /** Describes the Power State of the cluster */ export interface PowerState { /** Tells whether the cluster is Running or Stopped */ code?: Code; } /** Properties for the container service agent pool profile. */ export interface ManagedClusterAgentPoolProfileProperties { /** Number of agents (VMs) to host docker containers. Allowed values must be in the range of 0 to 1000 (inclusive) for user pools and in the range of 1 to 1000 (inclusive) for system pools. The default value is 1. */ count?: number; /** VM size availability varies by region. If a node contains insufficient compute resources (memory, cpu, etc) pods might fail to run correctly. For more details on restricted VM sizes, see: https://docs.microsoft.com/azure/aks/quotas-skus-regions */ vmSize?: string; /** OS Disk Size in GB to be used to specify the disk size for every machine in the master/agent pool. If you specify 0, it will apply the default osDisk size according to the vmSize specified. */ osDiskSizeGB?: number; /** The default is 'Ephemeral' if the VM supports it and has a cache disk larger than the requested OSDiskSizeGB. Otherwise, defaults to 'Managed'. May not be changed after creation. For more information see [Ephemeral OS](https://docs.microsoft.com/azure/aks/cluster-configuration#ephemeral-os). */ osDiskType?: OSDiskType; /** Determines the placement of emptyDir volumes, container runtime data root, and Kubelet ephemeral storage. */ kubeletDiskType?: KubeletDiskType; /** Determines the type of workload a node can run. */ workloadRuntime?: WorkloadRuntime; /** If this is not specified, a VNET and subnet will be generated and used. If no podSubnetID is specified, this applies to nodes and pods, otherwise it applies to just nodes. This is of the form: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName} */ vnetSubnetID?: string; /** If omitted, pod IPs are statically assigned on the node subnet (see vnetSubnetID for more details). This is of the form: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName} */ podSubnetID?: string; /** The maximum number of pods that can run on a node. */ maxPods?: number; /** The operating system type. The default is Linux. */ osType?: OSType; /** Specifies an OS SKU. This value must not be specified if OSType is Windows. */ osSKU?: Ossku; /** The maximum number of nodes for auto-scaling */ maxCount?: number; /** The minimum number of nodes for auto-scaling */ minCount?: number; /** Whether to enable auto-scaler */ enableAutoScaling?: boolean; /** This also effects the cluster autoscaler behavior. If not specified, it defaults to Delete. */ scaleDownMode?: ScaleDownMode; /** The type of Agent Pool. */ type?: AgentPoolType; /** A cluster must have at least one 'System' Agent Pool at all times. For additional information on agent pool restrictions and best practices, see: https://docs.microsoft.com/azure/aks/use-system-pools */ mode?: AgentPoolMode; /** As a best practice, you should upgrade all node pools in an AKS cluster to the same Kubernetes version. The node pool version must have the same major version as the control plane. The node pool minor version must be within two minor versions of the control plane version. The node pool version cannot be greater than the control plane version. For more information see [upgrading a node pool](https://docs.microsoft.com/azure/aks/use-multiple-node-pools#upgrade-a-node-pool). */ orchestratorVersion?: string; /** * The version of node image * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nodeImageVersion?: string; /** Settings for upgrading the agentpool */ upgradeSettings?: AgentPoolUpgradeSettings; /** * The current deployment or provisioning state. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: string; /** When an Agent Pool is first created it is initially Running. The Agent Pool can be stopped by setting this field to Stopped. A stopped Agent Pool stops all of its VMs and does not accrue billing charges. An Agent Pool can only be stopped if it is Running and provisioning state is Succeeded */ powerState?: PowerState; /** The list of Availability zones to use for nodes. This can only be specified if the AgentPoolType property is 'VirtualMachineScaleSets'. */ availabilityZones?: string[]; /** Some scenarios may require nodes in a node pool to receive their own dedicated public IP addresses. A common scenario is for gaming workloads, where a console needs to make a direct connection to a cloud virtual machine to minimize hops. For more information see [assigning a public IP per node](https://docs.microsoft.com/azure/aks/use-multiple-node-pools#assign-a-public-ip-per-node-for-your-node-pools). The default is false. */ enableNodePublicIP?: boolean; /** This is of the form: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIPPrefixName} */ nodePublicIPPrefixID?: string; /** The Virtual Machine Scale Set priority. If not specified, the default is 'Regular'. */ scaleSetPriority?: ScaleSetPriority; /** This cannot be specified unless the scaleSetPriority is 'Spot'. If not specified, the default is 'Delete'. */ scaleSetEvictionPolicy?: ScaleSetEvictionPolicy; /** Possible values are any decimal value greater than zero or -1 which indicates the willingness to pay any on-demand price. For more details on spot pricing, see [spot VMs pricing](https://docs.microsoft.com/azure/virtual-machines/spot-vms#pricing) */ spotMaxPrice?: number; /** The tags to be persisted on the agent pool virtual machine scale set. */ tags?: { [propertyName: string]: string }; /** The node labels to be persisted across all nodes in agent pool. */ nodeLabels?: { [propertyName: string]: string }; /** The taints added to new nodes during node pool create and scale. For example, key=value:NoSchedule. */ nodeTaints?: string[]; /** The ID for Proximity Placement Group. */ proximityPlacementGroupID?: string; /** The Kubelet configuration on the agent pool nodes. */ kubeletConfig?: KubeletConfig; /** The OS configuration of Linux agent nodes. */ linuxOSConfig?: LinuxOSConfig; /** This is only supported on certain VM sizes and in certain Azure regions. For more information, see: https://docs.microsoft.com/azure/aks/enable-host-encryption */ enableEncryptionAtHost?: boolean; /** Whether to enable UltraSSD */ enableUltraSSD?: boolean; /** See [Add a FIPS-enabled node pool](https://docs.microsoft.com/azure/aks/use-multiple-node-pools#add-a-fips-enabled-node-pool-preview) for more details. */ enableFips?: boolean; /** GPUInstanceProfile to be used to specify GPU MIG instance profile for supported GPU VM SKU. */ gpuInstanceProfile?: GPUInstanceProfile; /** CreationData to be used to specify the source Snapshot ID if the node pool will be created/upgraded using a snapshot. */ creationData?: CreationData; } /** Settings for upgrading an agentpool */ export interface AgentPoolUpgradeSettings { /** This can either be set to an integer (e.g. '5') or a percentage (e.g. '50%'). If a percentage is specified, it is the percentage of the total agent pool size at the time of the upgrade. For percentages, fractional nodes are rounded up. If not specified, the default is 1. For more information, including best practices, see: https://docs.microsoft.com/azure/aks/upgrade-cluster#customize-node-surge-upgrade */ maxSurge?: string; } /** See [AKS custom node configuration](https://docs.microsoft.com/azure/aks/custom-node-configuration) for more details. */ export interface KubeletConfig { /** The default is 'none'. See [Kubernetes CPU management policies](https://kubernetes.io/docs/tasks/administer-cluster/cpu-management-policies/#cpu-management-policies) for more information. Allowed values are 'none' and 'static'. */ cpuManagerPolicy?: string; /** The default is true. */ cpuCfsQuota?: boolean; /** The default is '100ms.' Valid values are a sequence of decimal numbers with an optional fraction and a unit suffix. For example: '300ms', '2h45m'. Supported units are 'ns', 'us', 'ms', 's', 'm', and 'h'. */ cpuCfsQuotaPeriod?: string; /** To disable image garbage collection, set to 100. The default is 85% */ imageGcHighThreshold?: number; /** This cannot be set higher than imageGcHighThreshold. The default is 80% */ imageGcLowThreshold?: number; /** For more information see [Kubernetes Topology Manager](https://kubernetes.io/docs/tasks/administer-cluster/topology-manager). The default is 'none'. Allowed values are 'none', 'best-effort', 'restricted', and 'single-numa-node'. */ topologyManagerPolicy?: string; /** Allowed list of unsafe sysctls or unsafe sysctl patterns (ending in `*`). */ allowedUnsafeSysctls?: string[]; /** If set to true it will make the Kubelet fail to start if swap is enabled on the node. */ failSwapOn?: boolean; /** The maximum size (e.g. 10Mi) of container log file before it is rotated. */ containerLogMaxSizeMB?: number; /** The maximum number of container log files that can be present for a container. The number must be ≥ 2. */ containerLogMaxFiles?: number; /** The maximum number of processes per pod. */ podMaxPids?: number; } /** See [AKS custom node configuration](https://docs.microsoft.com/azure/aks/custom-node-configuration) for more details. */ export interface LinuxOSConfig { /** Sysctl settings for Linux agent nodes. */ sysctls?: SysctlConfig; /** Valid values are 'always', 'madvise', and 'never'. The default is 'always'. For more information see [Transparent Hugepages](https://www.kernel.org/doc/html/latest/admin-guide/mm/transhuge.html#admin-guide-transhuge). */ transparentHugePageEnabled?: string; /** Valid values are 'always', 'defer', 'defer+madvise', 'madvise' and 'never'. The default is 'madvise'. For more information see [Transparent Hugepages](https://www.kernel.org/doc/html/latest/admin-guide/mm/transhuge.html#admin-guide-transhuge). */ transparentHugePageDefrag?: string; /** The size in MB of a swap file that will be created on each node. */ swapFileSizeMB?: number; } /** Sysctl settings for Linux agent nodes. */ export interface SysctlConfig { /** Sysctl setting net.core.somaxconn. */ netCoreSomaxconn?: number; /** Sysctl setting net.core.netdev_max_backlog. */ netCoreNetdevMaxBacklog?: number; /** Sysctl setting net.core.rmem_default. */ netCoreRmemDefault?: number; /** Sysctl setting net.core.rmem_max. */ netCoreRmemMax?: number; /** Sysctl setting net.core.wmem_default. */ netCoreWmemDefault?: number; /** Sysctl setting net.core.wmem_max. */ netCoreWmemMax?: number; /** Sysctl setting net.core.optmem_max. */ netCoreOptmemMax?: number; /** Sysctl setting net.ipv4.tcp_max_syn_backlog. */ netIpv4TcpMaxSynBacklog?: number; /** Sysctl setting net.ipv4.tcp_max_tw_buckets. */ netIpv4TcpMaxTwBuckets?: number; /** Sysctl setting net.ipv4.tcp_fin_timeout. */ netIpv4TcpFinTimeout?: number; /** Sysctl setting net.ipv4.tcp_keepalive_time. */ netIpv4TcpKeepaliveTime?: number; /** Sysctl setting net.ipv4.tcp_keepalive_probes. */ netIpv4TcpKeepaliveProbes?: number; /** Sysctl setting net.ipv4.tcp_keepalive_intvl. */ netIpv4TcpkeepaliveIntvl?: number; /** Sysctl setting net.ipv4.tcp_tw_reuse. */ netIpv4TcpTwReuse?: boolean; /** Sysctl setting net.ipv4.ip_local_port_range. */ netIpv4IpLocalPortRange?: string; /** Sysctl setting net.ipv4.neigh.default.gc_thresh1. */ netIpv4NeighDefaultGcThresh1?: number; /** Sysctl setting net.ipv4.neigh.default.gc_thresh2. */ netIpv4NeighDefaultGcThresh2?: number; /** Sysctl setting net.ipv4.neigh.default.gc_thresh3. */ netIpv4NeighDefaultGcThresh3?: number; /** Sysctl setting net.netfilter.nf_conntrack_max. */ netNetfilterNfConntrackMax?: number; /** Sysctl setting net.netfilter.nf_conntrack_buckets. */ netNetfilterNfConntrackBuckets?: number; /** Sysctl setting fs.inotify.max_user_watches. */ fsInotifyMaxUserWatches?: number; /** Sysctl setting fs.file-max. */ fsFileMax?: number; /** Sysctl setting fs.aio-max-nr. */ fsAioMaxNr?: number; /** Sysctl setting fs.nr_open. */ fsNrOpen?: number; /** Sysctl setting kernel.threads-max. */ kernelThreadsMax?: number; /** Sysctl setting vm.max_map_count. */ vmMaxMapCount?: number; /** Sysctl setting vm.swappiness. */ vmSwappiness?: number; /** Sysctl setting vm.vfs_cache_pressure. */ vmVfsCachePressure?: number; } /** Data used when creating a target resource from a source resource. */ export interface CreationData { /** This is the ARM ID of the source object to be used to create the target object. */ sourceResourceId?: string; } /** Profile for Linux VMs in the container service cluster. */ export interface ContainerServiceLinuxProfile { /** The administrator username to use for Linux VMs. */ adminUsername: string; /** The SSH configuration for Linux-based VMs running on Azure. */ ssh: ContainerServiceSshConfiguration; } /** SSH configuration for Linux-based VMs running on Azure. */ export interface ContainerServiceSshConfiguration { /** The list of SSH public keys used to authenticate with Linux-based VMs. A maximum of 1 key may be specified. */ publicKeys: ContainerServiceSshPublicKey[]; } /** Contains information about SSH certificate public key data. */ export interface ContainerServiceSshPublicKey { /** Certificate public key used to authenticate with VMs through SSH. The certificate must be in PEM format with or without headers. */ keyData: string; } /** Profile for Windows VMs in the managed cluster. */ export interface ManagedClusterWindowsProfile { /** Specifies the name of the administrator account. <br><br> **Restriction:** Cannot end in "." <br><br> **Disallowed values:** "administrator", "admin", "user", "user1", "test", "user2", "test1", "user3", "admin1", "1", "123", "a", "actuser", "adm", "admin2", "aspnet", "backup", "console", "david", "guest", "john", "owner", "root", "server", "sql", "support", "support_388945a0", "sys", "test2", "test3", "user4", "user5". <br><br> **Minimum-length:** 1 character <br><br> **Max-length:** 20 characters */ adminUsername: string; /** Specifies the password of the administrator account. <br><br> **Minimum-length:** 8 characters <br><br> **Max-length:** 123 characters <br><br> **Complexity requirements:** 3 out of 4 conditions below need to be fulfilled <br> Has lower characters <br>Has upper characters <br> Has a digit <br> Has a special character (Regex match [\W_]) <br><br> **Disallowed values:** "abc@123", "P@$$w0rd", "P@ssw0rd", "P@ssword123", "Pa$$word", "pass@word1", "Password!", "Password1", "Password22", "iloveyou!" */ adminPassword?: string; /** The license type to use for Windows VMs. See [Azure Hybrid User Benefits](https://azure.microsoft.com/pricing/hybrid-benefit/faq/) for more details. */ licenseType?: LicenseType; /** For more details on CSI proxy, see the [CSI proxy GitHub repo](https://github.com/kubernetes-csi/csi-proxy). */ enableCSIProxy?: boolean; /** The Windows gMSA Profile in the Managed Cluster. */ gmsaProfile?: WindowsGmsaProfile; } /** Windows gMSA Profile in the managed cluster. */ export interface WindowsGmsaProfile { /** Specifies whether to enable Windows gMSA in the managed cluster. */ enabled?: boolean; /** Specifies the DNS server for Windows gMSA. <br><br> Set it to empty if you have configured the DNS server in the vnet which is used to create the managed cluster. */ dnsServer?: string; /** Specifies the root domain name for Windows gMSA. <br><br> Set it to empty if you have configured the DNS server in the vnet which is used to create the managed cluster. */ rootDomainName?: string; } /** Information about a service principal identity for the cluster to use for manipulating Azure APIs. */ export interface ManagedClusterServicePrincipalProfile { /** The ID for the service principal. */ clientId: string; /** The secret password associated with the service principal in plain text. */ secret?: string; } /** A Kubernetes add-on profile for a managed cluster. */ export interface ManagedClusterAddonProfile { /** Whether the add-on is enabled or not. */ enabled: boolean; /** Key-value pairs for configuring an add-on. */ config?: { [propertyName: string]: string }; /** * Information of user assigned identity used by this add-on. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly identity?: ManagedClusterAddonProfileIdentity; } /** Details about a user assigned identity. */ export interface UserAssignedIdentity { /** The resource ID of the user assigned identity. */ resourceId?: string; /** The client ID of the user assigned identity. */ clientId?: string; /** The object ID of the user assigned identity. */ objectId?: string; } /** See [use AAD pod identity](https://docs.microsoft.com/azure/aks/use-azure-ad-pod-identity) for more details on pod identity integration. */ export interface ManagedClusterPodIdentityProfile { /** Whether the pod identity addon is enabled. */ enabled?: boolean; /** Running in Kubenet is disabled by default due to the security related nature of AAD Pod Identity and the risks of IP spoofing. See [using Kubenet network plugin with AAD Pod Identity](https://docs.microsoft.com/azure/aks/use-azure-ad-pod-identity#using-kubenet-network-plugin-with-azure-active-directory-pod-managed-identities) for more information. */ allowNetworkPluginKubenet?: boolean; /** The pod identities to use in the cluster. */ userAssignedIdentities?: ManagedClusterPodIdentity[]; /** The pod identity exceptions to allow. */ userAssignedIdentityExceptions?: ManagedClusterPodIdentityException[]; } /** Details about the pod identity assigned to the Managed Cluster. */ export interface ManagedClusterPodIdentity { /** The name of the pod identity. */ name: string; /** The namespace of the pod identity. */ namespace: string; /** The binding selector to use for the AzureIdentityBinding resource. */ bindingSelector?: string; /** The user assigned identity details. */ identity: UserAssignedIdentity; /** * The current provisioning state of the pod identity. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: ManagedClusterPodIdentityProvisioningState; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningInfo?: ManagedClusterPodIdentityProvisioningInfo; } export interface ManagedClusterPodIdentityProvisioningInfo { /** Pod identity assignment error (if any). */ error?: ManagedClusterPodIdentityProvisioningError; } /** An error response from the pod identity provisioning. */ export interface ManagedClusterPodIdentityProvisioningError { /** Details about the error. */ error?: ManagedClusterPodIdentityProvisioningErrorBody; } /** An error response from the pod identity provisioning. */ export interface ManagedClusterPodIdentityProvisioningErrorBody { /** An identifier for the error. Codes are invariant and are intended to be consumed programmatically. */ code?: string; /** A message describing the error, intended to be suitable for display in a user interface. */ message?: string; /** The target of the particular error. For example, the name of the property in error. */ target?: string; /** A list of additional details about the error. */ details?: ManagedClusterPodIdentityProvisioningErrorBody[]; } /** See [disable AAD Pod Identity for a specific Pod/Application](https://azure.github.io/aad-pod-identity/docs/configure/application_exception/) for more details. */ export interface ManagedClusterPodIdentityException { /** The name of the pod identity exception. */ name: string; /** The namespace of the pod identity exception. */ namespace: string; /** The pod labels to match. */ podLabels: { [propertyName: string]: string }; } /** Profile of network configuration. */ export interface ContainerServiceNetworkProfile { /** Network plugin used for building the Kubernetes network. */ networkPlugin?: NetworkPlugin; /** Network policy used for building the Kubernetes network. */ networkPolicy?: NetworkPolicy; /** This cannot be specified if networkPlugin is anything other than 'azure'. */ networkMode?: NetworkMode; /** A CIDR notation IP range from which to assign pod IPs when kubenet is used. */ podCidr?: string; /** A CIDR notation IP range from which to assign service cluster IPs. It must not overlap with any Subnet IP ranges. */ serviceCidr?: string; /** An IP address assigned to the Kubernetes DNS service. It must be within the Kubernetes service address range specified in serviceCidr. */ dnsServiceIP?: string; /** A CIDR notation IP range assigned to the Docker bridge network. It must not overlap with any Subnet IP ranges or the Kubernetes service address range. */ dockerBridgeCidr?: string; /** This can only be set at cluster creation time and cannot be changed later. For more information see [egress outbound type](https://docs.microsoft.com/azure/aks/egress-outboundtype). */ outboundType?: OutboundType; /** The default is 'standard'. See [Azure Load Balancer SKUs](https://docs.microsoft.com/azure/load-balancer/skus) for more information about the differences between load balancer SKUs. */ loadBalancerSku?: LoadBalancerSku; /** Profile of the cluster load balancer. */ loadBalancerProfile?: ManagedClusterLoadBalancerProfile; /** Profile of the cluster NAT gateway. */ natGatewayProfile?: ManagedClusterNATGatewayProfile; /** One IPv4 CIDR is expected for single-stack networking. Two CIDRs, one for each IP family (IPv4/IPv6), is expected for dual-stack networking. */ podCidrs?: string[]; /** One IPv4 CIDR is expected for single-stack networking. Two CIDRs, one for each IP family (IPv4/IPv6), is expected for dual-stack networking. They must not overlap with any Subnet IP ranges. */ serviceCidrs?: string[]; /** IP families are used to determine single-stack or dual-stack clusters. For single-stack, the expected value is IPv4. For dual-stack, the expected values are IPv4 and IPv6. */ ipFamilies?: IpFamily[]; } /** Profile of the managed cluster load balancer. */ export interface ManagedClusterLoadBalancerProfile { /** Desired managed outbound IPs for the cluster load balancer. */ managedOutboundIPs?: ManagedClusterLoadBalancerProfileManagedOutboundIPs; /** Desired outbound IP Prefix resources for the cluster load balancer. */ outboundIPPrefixes?: ManagedClusterLoadBalancerProfileOutboundIPPrefixes; /** Desired outbound IP resources for the cluster load balancer. */ outboundIPs?: ManagedClusterLoadBalancerProfileOutboundIPs; /** The effective outbound IP resources of the cluster load balancer. */ effectiveOutboundIPs?: ResourceReference[]; /** The desired number of allocated SNAT ports per VM. Allowed values are in the range of 0 to 64000 (inclusive). The default value is 0 which results in Azure dynamically allocating ports. */ allocatedOutboundPorts?: number; /** Desired outbound flow idle timeout in minutes. Allowed values are in the range of 4 to 120 (inclusive). The default value is 30 minutes. */ idleTimeoutInMinutes?: number; /** Enable multiple standard load balancers per AKS cluster or not. */ enableMultipleStandardLoadBalancers?: boolean; } /** Desired managed outbound IPs for the cluster load balancer. */ export interface ManagedClusterLoadBalancerProfileManagedOutboundIPs { /** The desired number of IPv4 outbound IPs created/managed by Azure for the cluster load balancer. Allowed values must be in the range of 1 to 100 (inclusive). The default value is 1. */ count?: number; /** The desired number of IPv6 outbound IPs created/managed by Azure for the cluster load balancer. Allowed values must be in the range of 1 to 100 (inclusive). The default value is 0 for single-stack and 1 for dual-stack. */ countIPv6?: number; } /** Desired outbound IP Prefix resources for the cluster load balancer. */ export interface ManagedClusterLoadBalancerProfileOutboundIPPrefixes { /** A list of public IP prefix resources. */ publicIPPrefixes?: ResourceReference[]; } /** A reference to an Azure resource. */ export interface ResourceReference { /** The fully qualified Azure resource id. */ id?: string; } /** Desired outbound IP resources for the cluster load balancer. */ export interface ManagedClusterLoadBalancerProfileOutboundIPs { /** A list of public IP resources. */ publicIPs?: ResourceReference[]; } /** Profile of the managed cluster NAT gateway. */ export interface ManagedClusterNATGatewayProfile { /** Profile of the managed outbound IP resources of the cluster NAT gateway. */ managedOutboundIPProfile?: ManagedClusterManagedOutboundIPProfile; /** The effective outbound IP resources of the cluster NAT gateway. */ effectiveOutboundIPs?: ResourceReference[]; /** Desired outbound flow idle timeout in minutes. Allowed values are in the range of 4 to 120 (inclusive). The default value is 4 minutes. */ idleTimeoutInMinutes?: number; } /** Profile of the managed outbound IP resources of the managed cluster. */ export interface ManagedClusterManagedOutboundIPProfile { /** The desired number of outbound IPs created/managed by Azure. Allowed values must be in the range of 1 to 16 (inclusive). The default value is 1. */ count?: number; } /** For more details see [managed AAD on AKS](https://docs.microsoft.com/azure/aks/managed-aad). */ export interface ManagedClusterAADProfile { /** Whether to enable managed AAD. */ managed?: boolean; /** Whether to enable Azure RBAC for Kubernetes authorization. */ enableAzureRbac?: boolean; /** The list of AAD group object IDs that will have admin role of the cluster. */ adminGroupObjectIDs?: string[]; /** The client AAD application ID. */ clientAppID?: string; /** The server AAD application ID. */ serverAppID?: string; /** The server AAD application secret. */ serverAppSecret?: string; /** The AAD tenant ID to use for authentication. If not specified, will use the tenant of the deployment subscription. */ tenantID?: string; } /** Auto upgrade profile for a managed cluster. */ export interface ManagedClusterAutoUpgradeProfile { /** For more information see [setting the AKS cluster auto-upgrade channel](https://docs.microsoft.com/azure/aks/upgrade-cluster#set-auto-upgrade-channel). */ upgradeChannel?: UpgradeChannel; } /** Parameters to be applied to the cluster-autoscaler when enabled */ export interface ManagedClusterPropertiesAutoScalerProfile { /** Valid values are 'true' and 'false' */ balanceSimilarNodeGroups?: string; /** If not specified, the default is 'random'. See [expanders](https://github.com/kubernetes/autoscaler/blob/master/cluster-autoscaler/FAQ.md#what-are-expanders) for more information. */ expander?: Expander; /** The default is 10. */ maxEmptyBulkDelete?: string; /** The default is 600. */ maxGracefulTerminationSec?: string; /** The default is '15m'. Values must be an integer followed by an 'm'. No unit of time other than minutes (m) is supported. */ maxNodeProvisionTime?: string; /** The default is 45. The maximum is 100 and the minimum is 0. */ maxTotalUnreadyPercentage?: string; /** For scenarios like burst/batch scale where you don't want CA to act before the kubernetes scheduler could schedule all the pods, you can tell CA to ignore unscheduled pods before they're a certain age. The default is '0s'. Values must be an integer followed by a unit ('s' for seconds, 'm' for minutes, 'h' for hours, etc). */ newPodScaleUpDelay?: string; /** This must be an integer. The default is 3. */ okTotalUnreadyCount?: string; /** The default is '10'. Values must be an integer number of seconds. */ scanInterval?: string; /** The default is '10m'. Values must be an integer followed by an 'm'. No unit of time other than minutes (m) is supported. */ scaleDownDelayAfterAdd?: string; /** The default is the scan-interval. Values must be an integer followed by an 'm'. No unit of time other than minutes (m) is supported. */ scaleDownDelayAfterDelete?: string; /** The default is '3m'. Values must be an integer followed by an 'm'. No unit of time other than minutes (m) is supported. */ scaleDownDelayAfterFailure?: string; /** The default is '10m'. Values must be an integer followed by an 'm'. No unit of time other than minutes (m) is supported. */ scaleDownUnneededTime?: string; /** The default is '20m'. Values must be an integer followed by an 'm'. No unit of time other than minutes (m) is supported. */ scaleDownUnreadyTime?: string; /** The default is '0.5'. */ scaleDownUtilizationThreshold?: string; /** The default is true. */ skipNodesWithLocalStorage?: string; /** The default is true. */ skipNodesWithSystemPods?: string; } /** Access profile for managed cluster API server. */ export interface ManagedClusterAPIServerAccessProfile { /** IP ranges are specified in CIDR format, e.g. 137.117.106.88/29. This feature is not compatible with clusters that use Public IP Per Node, or clusters that are using a Basic Load Balancer. For more information see [API server authorized IP ranges](https://docs.microsoft.com/azure/aks/api-server-authorized-ip-ranges). */ authorizedIPRanges?: string[]; /** For more details, see [Creating a private AKS cluster](https://docs.microsoft.com/azure/aks/private-clusters). */ enablePrivateCluster?: boolean; /** The default is System. For more details see [configure private DNS zone](https://docs.microsoft.com/azure/aks/private-clusters#configure-private-dns-zone). Allowed values are 'system' and 'none'. */ privateDNSZone?: string; /** Whether to create additional public FQDN for private cluster or not. */ enablePrivateClusterPublicFqdn?: boolean; /** Whether to disable run command for the cluster or not. */ disableRunCommand?: boolean; } /** A private link resource */ export interface PrivateLinkResource { /** The ID of the private link resource. */ id?: string; /** The name of the private link resource. */ name?: string; /** The resource type. */ type?: string; /** The group ID of the resource. */ groupId?: string; /** The RequiredMembers of the resource */ requiredMembers?: string[]; /** * The private link service ID of the resource, this field is exposed only to NRP internally. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly privateLinkServiceID?: string; } /** Cluster HTTP proxy configuration. */ export interface ManagedClusterHttpProxyConfig { /** The HTTP proxy server endpoint to use. */ httpProxy?: string; /** The HTTPS proxy server endpoint to use. */ httpsProxy?: string; /** The endpoints that should not go through proxy. */ noProxy?: string[]; /** Alternative CA cert to use for connecting to proxy servers. */ trustedCa?: string; } /** Security profile for the container service cluster. */ export interface ManagedClusterSecurityProfile { /** Azure Defender settings for the security profile. */ azureDefender?: ManagedClusterSecurityProfileAzureDefender; } /** Azure Defender settings for the security profile. */ export interface ManagedClusterSecurityProfileAzureDefender { /** Whether to enable Azure Defender */ enabled?: boolean; /** Resource ID of the Log Analytics workspace to be associated with Azure Defender. When Azure Defender is enabled, this field is required and must be a valid workspace resource ID. When Azure Defender is disabled, leave the field empty. */ logAnalyticsWorkspaceResourceId?: string; } /** The Resource model definition. */ export interface Resource { /** * Resource Id * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * Resource name * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * Resource type * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** Resource location */ location: string; /** Resource tags */ tags?: { [propertyName: string]: string }; } /** The list of available upgrades for compute pools. */ export interface ManagedClusterUpgradeProfile { /** * The ID of the upgrade profile. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The name of the upgrade profile. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The type of the upgrade profile. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** The list of available upgrade versions for the control plane. */ controlPlaneProfile: ManagedClusterPoolUpgradeProfile; /** The list of available upgrade versions for agent pools. */ agentPoolProfiles: ManagedClusterPoolUpgradeProfile[]; } /** The list of available upgrade versions. */ export interface ManagedClusterPoolUpgradeProfile { /** The Kubernetes version (major.minor.patch). */ kubernetesVersion: string; /** The Agent Pool name. */ name?: string; /** The operating system type. The default is Linux. */ osType: OSType; /** List of orchestrator types and versions available for upgrade. */ upgrades?: ManagedClusterPoolUpgradeProfileUpgradesItem[]; } export interface ManagedClusterPoolUpgradeProfileUpgradesItem { /** The Kubernetes version (major.minor.patch). */ kubernetesVersion?: string; /** Whether the Kubernetes version is currently in preview. */ isPreview?: boolean; } /** The list credential result response. */ export interface CredentialResults { /** * Base64-encoded Kubernetes configuration file. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly kubeconfigs?: CredentialResult[]; } /** The credential result response. */ export interface CredentialResult { /** * The name of the credential. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * Base64-encoded Kubernetes configuration file. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: Uint8Array; } /** Tags object for patch operations. */ export interface TagsObject { /** Resource tags. */ tags?: { [propertyName: string]: string }; } /** The response from the List maintenance configurations operation. */ export interface MaintenanceConfigurationListResult { /** The list of maintenance configurations. */ value?: MaintenanceConfiguration[]; /** * The URL to get the next set of maintenance configuration results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Metadata pertaining to creation and last modification of the resource. */ export interface SystemData { /** The identity that created the resource. */ createdBy?: string; /** The type of identity that created the resource. */ createdByType?: CreatedByType; /** The UTC timestamp of resource creation. */ createdAt?: Date; /** The identity that last modified the resource. */ lastModifiedBy?: string; /** The type of identity that last modified the resource. */ lastModifiedByType?: CreatedByType; /** The type of identity that last modified the resource. */ lastModifiedAt?: Date; } /** Time in a week. */ export interface TimeInWeek { /** The day of the week. */ day?: WeekDay; /** Each integer hour represents a time range beginning at 0m after the hour ending at the next hour (non-inclusive). 0 corresponds to 00:00 UTC, 23 corresponds to 23:00 UTC. Specifying [0, 1] means the 00:00 - 02:00 UTC time range. */ hourSlots?: number[]; } /** For example, between 2021-05-25T13:00:00Z and 2021-05-25T14:00:00Z. */ export interface TimeSpan { /** The start of a time span */ start?: Date; /** The end of a time span */ end?: Date; } /** Reference to another subresource. */ export interface SubResource { /** * Resource ID. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The name of the resource that is unique within a resource group. This name can be used to access the resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * Resource type * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; } /** The response from the List Agent Pools operation. */ export interface AgentPoolListResult { /** The list of agent pools. */ value?: AgentPool[]; /** * The URL to get the next set of agent pool results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** The list of available upgrades for an agent pool. */ export interface AgentPoolUpgradeProfile { /** * The ID of the agent pool upgrade profile. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The name of the agent pool upgrade profile. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The type of the agent pool upgrade profile. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** The Kubernetes version (major.minor.patch). */ kubernetesVersion: string; /** The operating system type. The default is Linux. */ osType: OSType; /** List of orchestrator types and versions available for upgrade. */ upgrades?: AgentPoolUpgradeProfilePropertiesUpgradesItem[]; /** The latest AKS supported node image version. */ latestNodeImageVersion?: string; } export interface AgentPoolUpgradeProfilePropertiesUpgradesItem { /** The Kubernetes version (major.minor.patch). */ kubernetesVersion?: string; /** Whether the Kubernetes version is currently in preview. */ isPreview?: boolean; } /** The list of available versions for an agent pool. */ export interface AgentPoolAvailableVersions { /** * The ID of the agent pool version list. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The name of the agent pool version list. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * Type of the agent pool version list. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** List of versions available for agent pool. */ agentPoolVersions?: AgentPoolAvailableVersionsPropertiesAgentPoolVersionsItem[]; } export interface AgentPoolAvailableVersionsPropertiesAgentPoolVersionsItem { /** Whether this version is the default agent pool version. */ default?: boolean; /** The Kubernetes version (major.minor.patch). */ kubernetesVersion?: string; /** Whether Kubernetes version is currently in preview. */ isPreview?: boolean; } /** A list of private endpoint connections */ export interface PrivateEndpointConnectionListResult { /** The collection value. */ value?: PrivateEndpointConnection[]; } /** A private endpoint connection */ export interface PrivateEndpointConnection { /** * The ID of the private endpoint connection. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The name of the private endpoint connection. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The resource type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** * The current provisioning state. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: PrivateEndpointConnectionProvisioningState; /** The resource of private endpoint. */ privateEndpoint?: PrivateEndpoint; /** A collection of information about the state of the connection between service consumer and provider. */ privateLinkServiceConnectionState?: PrivateLinkServiceConnectionState; } /** Private endpoint which a connection belongs to. */ export interface PrivateEndpoint { /** The resource ID of the private endpoint */ id?: string; } /** The state of a private link service connection. */ export interface PrivateLinkServiceConnectionState { /** The private link service connection status. */ status?: ConnectionStatus; /** The private link service connection description. */ description?: string; } /** A list of private link resources */ export interface PrivateLinkResourcesListResult { /** The collection value. */ value?: PrivateLinkResource[]; } /** A run command request */ export interface RunCommandRequest { /** The command to run. */ command: string; /** A base64 encoded zip file containing the files required by the command. */ context?: string; /** AuthToken issued for AKS AAD Server App. */ clusterToken?: string; } /** run command result. */ export interface RunCommandResult { /** * The command id. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * provisioning State * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: string; /** * The exit code of the command * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly exitCode?: number; /** * The time when the command started. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly startedAt?: Date; /** * The time when the command finished. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly finishedAt?: Date; /** * The command output. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly logs?: string; /** * An explanation of why provisioningState is set to failed (if so). * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly reason?: string; } /** Collection of OutboundEnvironmentEndpoint */ export interface OutboundEnvironmentEndpointCollection { /** Collection of resources. */ value: OutboundEnvironmentEndpoint[]; /** * Link to next page of resources. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Egress endpoints which AKS agent nodes connect to for common purpose. */ export interface OutboundEnvironmentEndpoint { /** The category of endpoints accessed by the AKS agent node, e.g. azure-resource-management, apiserver, etc. */ category?: string; /** The endpoints that AKS agent nodes connect to */ endpoints?: EndpointDependency[]; } /** A domain name that AKS agent nodes are reaching at. */ export interface EndpointDependency { /** The domain name of the dependency. */ domainName?: string; /** The Ports and Protocols used when connecting to domainName. */ endpointDetails?: EndpointDetail[]; } /** connect information from the AKS agent nodes to a single endpoint. */ export interface EndpointDetail { /** An IP Address that Domain Name currently resolves to. */ ipAddress?: string; /** The port an endpoint is connected to. */ port?: number; /** The protocol used for connection */ protocol?: string; /** Description of the detail */ description?: string; } /** The response from the List Snapshots operation. */ export interface SnapshotListResult { /** The list of snapshots. */ value?: Snapshot[]; /** * The URL to get the next set of snapshot results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Profile for the container service master. */ export interface ContainerServiceMasterProfile { /** Number of masters (VMs) in the container service cluster. Allowed values are 1, 3, and 5. The default value is 1. */ count?: Count; /** DNS prefix to be used to create the FQDN for the master pool. */ dnsPrefix: string; /** Size of agent VMs. */ vmSize: ContainerServiceVMSizeTypes; /** OS Disk Size in GB to be used to specify the disk size for every machine in this master/agent pool. If you specify 0, it will apply the default osDisk size according to the vmSize specified. */ osDiskSizeGB?: number; /** VNet SubnetID specifies the VNet's subnet identifier. */ vnetSubnetID?: string; /** FirstConsecutiveStaticIP used to specify the first static ip of masters. */ firstConsecutiveStaticIP?: string; /** Storage profile specifies what kind of storage used. Choose from StorageAccount and ManagedDisks. Leave it empty, we will choose for you based on the orchestrator choice. */ storageProfile?: ContainerServiceStorageProfileTypes; /** * FQDN for the master pool. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly fqdn?: string; } /** Profile for diagnostics on the container service cluster. */ export interface ContainerServiceDiagnosticsProfile { /** Profile for diagnostics on the container service VMs. */ vmDiagnostics: ContainerServiceVMDiagnostics; } /** Profile for diagnostics on the container service VMs. */ export interface ContainerServiceVMDiagnostics { /** Whether the VM diagnostic agent is provisioned on the VM. */ enabled: boolean; /** * The URI of the storage account where diagnostics are stored. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly storageUri?: string; } /** Profile for the container service agent pool. */ export type ManagedClusterAgentPoolProfile = ManagedClusterAgentPoolProfileProperties & { /** Windows agent pool names must be 6 characters or less. */ name: string; }; /** Information of user assigned identity used by this add-on. */ export type ManagedClusterAddonProfileIdentity = UserAssignedIdentity & {}; /** Managed cluster. */ export type ManagedCluster = Resource & { /** The managed cluster SKU. */ sku?: ManagedClusterSKU; /** The extended location of the Virtual Machine. */ extendedLocation?: ExtendedLocation; /** The identity of the managed cluster, if configured. */ identity?: ManagedClusterIdentity; /** * The current provisioning state. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: string; /** * The Power State of the cluster. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly powerState?: PowerState; /** * The max number of agent pools for the managed cluster. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly maxAgentPools?: number; /** When you upgrade a supported AKS cluster, Kubernetes minor versions cannot be skipped. All upgrades must be performed sequentially by major version number. For example, upgrades between 1.14.x -> 1.15.x or 1.15.x -> 1.16.x are allowed, however 1.14.x -> 1.16.x is not allowed. See [upgrading an AKS cluster](https://docs.microsoft.com/azure/aks/upgrade-cluster) for more details. */ kubernetesVersion?: string; /** This cannot be updated once the Managed Cluster has been created. */ dnsPrefix?: string; /** This cannot be updated once the Managed Cluster has been created. */ fqdnSubdomain?: string; /** * The FQDN of the master pool. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly fqdn?: string; /** * The FQDN of private cluster. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly privateFqdn?: string; /** * The Azure Portal requires certain Cross-Origin Resource Sharing (CORS) headers to be sent in some responses, which Kubernetes APIServer doesn't handle by default. This special FQDN supports CORS, allowing the Azure Portal to function properly. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly azurePortalFqdn?: string; /** The agent pool properties. */ agentPoolProfiles?: ManagedClusterAgentPoolProfile[]; /** The profile for Linux VMs in the Managed Cluster. */ linuxProfile?: ContainerServiceLinuxProfile; /** The profile for Windows VMs in the Managed Cluster. */ windowsProfile?: ManagedClusterWindowsProfile; /** Information about a service principal identity for the cluster to use for manipulating Azure APIs. */ servicePrincipalProfile?: ManagedClusterServicePrincipalProfile; /** The profile of managed cluster add-on. */ addonProfiles?: { [propertyName: string]: ManagedClusterAddonProfile }; /** See [use AAD pod identity](https://docs.microsoft.com/azure/aks/use-azure-ad-pod-identity) for more details on AAD pod identity integration. */ podIdentityProfile?: ManagedClusterPodIdentityProfile; /** The name of the resource group containing agent pool nodes. */ nodeResourceGroup?: string; /** Whether to enable Kubernetes Role-Based Access Control. */ enableRbac?: boolean; /** (DEPRECATING) Whether to enable Kubernetes pod security policy (preview). This feature is set for removal on October 15th, 2020. Learn more at aka.ms/aks/azpodpolicy. */ enablePodSecurityPolicy?: boolean; /** The network configuration profile. */ networkProfile?: ContainerServiceNetworkProfile; /** The Azure Active Directory configuration. */ aadProfile?: ManagedClusterAADProfile; /** The auto upgrade configuration. */ autoUpgradeProfile?: ManagedClusterAutoUpgradeProfile; /** Parameters to be applied to the cluster-autoscaler when enabled */ autoScalerProfile?: ManagedClusterPropertiesAutoScalerProfile; /** The access profile for managed cluster API server. */ apiServerAccessProfile?: ManagedClusterAPIServerAccessProfile; /** This is of the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskEncryptionSets/{encryptionSetName}' */ diskEncryptionSetID?: string; /** Identities associated with the cluster. */ identityProfile?: { [propertyName: string]: UserAssignedIdentity }; /** Private link resources associated with the cluster. */ privateLinkResources?: PrivateLinkResource[]; /** If set to true, getting static credentials will be disabled for this cluster. This must only be used on Managed Clusters that are AAD enabled. For more details see [disable local accounts](https://docs.microsoft.com/azure/aks/managed-aad#disable-local-accounts-preview). */ disableLocalAccounts?: boolean; /** Configurations for provisioning the cluster with HTTP proxy servers. */ httpProxyConfig?: ManagedClusterHttpProxyConfig; /** Security profile for the managed cluster. */ securityProfile?: ManagedClusterSecurityProfile; /** Allow or deny public network access for AKS */ publicNetworkAccess?: PublicNetworkAccess; }; /** Managed cluster Access Profile. */ export type ManagedClusterAccessProfile = Resource & { /** Base64-encoded Kubernetes configuration file. */ kubeConfig?: Uint8Array; }; /** A node pool snapshot resource. */ export type Snapshot = Resource & { /** * The system metadata relating to this snapshot. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; /** CreationData to be used to specify the source agent pool resource ID to create this snapshot. */ creationData?: CreationData; /** The type of a snapshot. The default is NodePool. */ snapshotType?: SnapshotType; /** * The version of Kubernetes. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly kubernetesVersion?: string; /** * The version of node image. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nodeImageVersion?: string; /** * The operating system type. The default is Linux. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly osType?: OSType; /** * Specifies an OS SKU. This value must not be specified if OSType is Windows. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly osSku?: Ossku; /** * The size of the VM. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly vmSize?: string; /** * Whether to use a FIPS-enabled OS. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly enableFips?: boolean; }; /** See [planned maintenance](https://docs.microsoft.com/azure/aks/planned-maintenance) for more information about planned maintenance. */ export type MaintenanceConfiguration = SubResource & { /** * The system metadata relating to this resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; /** If two array entries specify the same day of the week, the applied configuration is the union of times in both entries. */ timeInWeek?: TimeInWeek[]; /** Time slots on which upgrade is not allowed. */ notAllowedTime?: TimeSpan[]; }; /** Agent Pool. */ export type AgentPool = SubResource & { /** Number of agents (VMs) to host docker containers. Allowed values must be in the range of 0 to 1000 (inclusive) for user pools and in the range of 1 to 1000 (inclusive) for system pools. The default value is 1. */ count?: number; /** VM size availability varies by region. If a node contains insufficient compute resources (memory, cpu, etc) pods might fail to run correctly. For more details on restricted VM sizes, see: https://docs.microsoft.com/azure/aks/quotas-skus-regions */ vmSize?: string; /** OS Disk Size in GB to be used to specify the disk size for every machine in the master/agent pool. If you specify 0, it will apply the default osDisk size according to the vmSize specified. */ osDiskSizeGB?: number; /** The default is 'Ephemeral' if the VM supports it and has a cache disk larger than the requested OSDiskSizeGB. Otherwise, defaults to 'Managed'. May not be changed after creation. For more information see [Ephemeral OS](https://docs.microsoft.com/azure/aks/cluster-configuration#ephemeral-os). */ osDiskType?: OSDiskType; /** Determines the placement of emptyDir volumes, container runtime data root, and Kubelet ephemeral storage. */ kubeletDiskType?: KubeletDiskType; /** Determines the type of workload a node can run. */ workloadRuntime?: WorkloadRuntime; /** If this is not specified, a VNET and subnet will be generated and used. If no podSubnetID is specified, this applies to nodes and pods, otherwise it applies to just nodes. This is of the form: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName} */ vnetSubnetID?: string; /** If omitted, pod IPs are statically assigned on the node subnet (see vnetSubnetID for more details). This is of the form: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName} */ podSubnetID?: string; /** The maximum number of pods that can run on a node. */ maxPods?: number; /** The operating system type. The default is Linux. */ osType?: OSType; /** Specifies an OS SKU. This value must not be specified if OSType is Windows. */ osSKU?: Ossku; /** The maximum number of nodes for auto-scaling */ maxCount?: number; /** The minimum number of nodes for auto-scaling */ minCount?: number; /** Whether to enable auto-scaler */ enableAutoScaling?: boolean; /** This also effects the cluster autoscaler behavior. If not specified, it defaults to Delete. */ scaleDownMode?: ScaleDownMode; /** The type of Agent Pool. */ typePropertiesType?: AgentPoolType; /** A cluster must have at least one 'System' Agent Pool at all times. For additional information on agent pool restrictions and best practices, see: https://docs.microsoft.com/azure/aks/use-system-pools */ mode?: AgentPoolMode; /** As a best practice, you should upgrade all node pools in an AKS cluster to the same Kubernetes version. The node pool version must have the same major version as the control plane. The node pool minor version must be within two minor versions of the control plane version. The node pool version cannot be greater than the control plane version. For more information see [upgrading a node pool](https://docs.microsoft.com/azure/aks/use-multiple-node-pools#upgrade-a-node-pool). */ orchestratorVersion?: string; /** * The version of node image * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nodeImageVersion?: string; /** Settings for upgrading the agentpool */ upgradeSettings?: AgentPoolUpgradeSettings; /** * The current deployment or provisioning state. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: string; /** When an Agent Pool is first created it is initially Running. The Agent Pool can be stopped by setting this field to Stopped. A stopped Agent Pool stops all of its VMs and does not accrue billing charges. An Agent Pool can only be stopped if it is Running and provisioning state is Succeeded */ powerState?: PowerState; /** The list of Availability zones to use for nodes. This can only be specified if the AgentPoolType property is 'VirtualMachineScaleSets'. */ availabilityZones?: string[]; /** Some scenarios may require nodes in a node pool to receive their own dedicated public IP addresses. A common scenario is for gaming workloads, where a console needs to make a direct connection to a cloud virtual machine to minimize hops. For more information see [assigning a public IP per node](https://docs.microsoft.com/azure/aks/use-multiple-node-pools#assign-a-public-ip-per-node-for-your-node-pools). The default is false. */ enableNodePublicIP?: boolean; /** This is of the form: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIPPrefixName} */ nodePublicIPPrefixID?: string; /** The Virtual Machine Scale Set priority. If not specified, the default is 'Regular'. */ scaleSetPriority?: ScaleSetPriority; /** This cannot be specified unless the scaleSetPriority is 'Spot'. If not specified, the default is 'Delete'. */ scaleSetEvictionPolicy?: ScaleSetEvictionPolicy; /** Possible values are any decimal value greater than zero or -1 which indicates the willingness to pay any on-demand price. For more details on spot pricing, see [spot VMs pricing](https://docs.microsoft.com/azure/virtual-machines/spot-vms#pricing) */ spotMaxPrice?: number; /** The tags to be persisted on the agent pool virtual machine scale set. */ tags?: { [propertyName: string]: string }; /** The node labels to be persisted across all nodes in agent pool. */ nodeLabels?: { [propertyName: string]: string }; /** The taints added to new nodes during node pool create and scale. For example, key=value:NoSchedule. */ nodeTaints?: string[]; /** The ID for Proximity Placement Group. */ proximityPlacementGroupID?: string; /** The Kubelet configuration on the agent pool nodes. */ kubeletConfig?: KubeletConfig; /** The OS configuration of Linux agent nodes. */ linuxOSConfig?: LinuxOSConfig; /** This is only supported on certain VM sizes and in certain Azure regions. For more information, see: https://docs.microsoft.com/azure/aks/enable-host-encryption */ enableEncryptionAtHost?: boolean; /** Whether to enable UltraSSD */ enableUltraSSD?: boolean; /** See [Add a FIPS-enabled node pool](https://docs.microsoft.com/azure/aks/use-multiple-node-pools#add-a-fips-enabled-node-pool-preview) for more details. */ enableFips?: boolean; /** GPUInstanceProfile to be used to specify GPU MIG instance profile for supported GPU VM SKU. */ gpuInstanceProfile?: GPUInstanceProfile; /** CreationData to be used to specify the source Snapshot ID if the node pool will be created/upgraded using a snapshot. */ creationData?: CreationData; }; /** Defines headers for AgentPools_upgradeNodeImageVersion operation. */ export interface AgentPoolsUpgradeNodeImageVersionHeaders { /** URL to query for status of the operation. */ azureAsyncOperation?: string; } /** Known values of {@link ManagedClusterSKUName} that the service accepts. */ export enum KnownManagedClusterSKUName { Basic = "Basic" } /** * Defines values for ManagedClusterSKUName. \ * {@link KnownManagedClusterSKUName} can be used interchangeably with ManagedClusterSKUName, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Basic** */ export type ManagedClusterSKUName = string; /** Known values of {@link ManagedClusterSKUTier} that the service accepts. */ export enum KnownManagedClusterSKUTier { /** Guarantees 99.95% availability of the Kubernetes API server endpoint for clusters that use Availability Zones and 99.9% of availability for clusters that don't use Availability Zones. */ Paid = "Paid", /** No guaranteed SLA, no additional charges. Free tier clusters have an SLO of 99.5%. */ Free = "Free" } /** * Defines values for ManagedClusterSKUTier. \ * {@link KnownManagedClusterSKUTier} can be used interchangeably with ManagedClusterSKUTier, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Paid**: Guarantees 99.95% availability of the Kubernetes API server endpoint for clusters that use Availability Zones and 99.9% of availability for clusters that don't use Availability Zones. \ * **Free**: No guaranteed SLA, no additional charges. Free tier clusters have an SLO of 99.5%. */ export type ManagedClusterSKUTier = string; /** Known values of {@link ExtendedLocationTypes} that the service accepts. */ export enum KnownExtendedLocationTypes { EdgeZone = "EdgeZone" } /** * Defines values for ExtendedLocationTypes. \ * {@link KnownExtendedLocationTypes} can be used interchangeably with ExtendedLocationTypes, * this enum contains the known values that the service supports. * ### Known values supported by the service * **EdgeZone** */ export type ExtendedLocationTypes = string; /** Known values of {@link Code} that the service accepts. */ export enum KnownCode { /** The cluster is running. */ Running = "Running", /** The cluster is stopped. */ Stopped = "Stopped" } /** * Defines values for Code. \ * {@link KnownCode} can be used interchangeably with Code, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Running**: The cluster is running. \ * **Stopped**: The cluster is stopped. */ export type Code = string; /** Known values of {@link OSDiskType} that the service accepts. */ export enum KnownOSDiskType { /** Azure replicates the operating system disk for a virtual machine to Azure storage to avoid data loss should the VM need to be relocated to another host. Since containers aren't designed to have local state persisted, this behavior offers limited value while providing some drawbacks, including slower node provisioning and higher read/write latency. */ Managed = "Managed", /** Ephemeral OS disks are stored only on the host machine, just like a temporary disk. This provides lower read/write latency, along with faster node scaling and cluster upgrades. */ Ephemeral = "Ephemeral" } /** * Defines values for OSDiskType. \ * {@link KnownOSDiskType} can be used interchangeably with OSDiskType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Managed**: Azure replicates the operating system disk for a virtual machine to Azure storage to avoid data loss should the VM need to be relocated to another host. Since containers aren't designed to have local state persisted, this behavior offers limited value while providing some drawbacks, including slower node provisioning and higher read\/write latency. \ * **Ephemeral**: Ephemeral OS disks are stored only on the host machine, just like a temporary disk. This provides lower read\/write latency, along with faster node scaling and cluster upgrades. */ export type OSDiskType = string; /** Known values of {@link KubeletDiskType} that the service accepts. */ export enum KnownKubeletDiskType { /** Kubelet will use the OS disk for its data. */ OS = "OS", /** Kubelet will use the temporary disk for its data. */ Temporary = "Temporary" } /** * Defines values for KubeletDiskType. \ * {@link KnownKubeletDiskType} can be used interchangeably with KubeletDiskType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **OS**: Kubelet will use the OS disk for its data. \ * **Temporary**: Kubelet will use the temporary disk for its data. */ export type KubeletDiskType = string; /** Known values of {@link WorkloadRuntime} that the service accepts. */ export enum KnownWorkloadRuntime { /** Nodes will use Kubelet to run standard OCI container workloads. */ OCIContainer = "OCIContainer", /** Nodes will use Krustlet to run WASM workloads using the WASI provider (Preview). */ WasmWasi = "WasmWasi" } /** * Defines values for WorkloadRuntime. \ * {@link KnownWorkloadRuntime} can be used interchangeably with WorkloadRuntime, * this enum contains the known values that the service supports. * ### Known values supported by the service * **OCIContainer**: Nodes will use Kubelet to run standard OCI container workloads. \ * **WasmWasi**: Nodes will use Krustlet to run WASM workloads using the WASI provider (Preview). */ export type WorkloadRuntime = string; /** Known values of {@link OSType} that the service accepts. */ export enum KnownOSType { /** Use Linux. */ Linux = "Linux", /** Use Windows. */ Windows = "Windows" } /** * Defines values for OSType. \ * {@link KnownOSType} can be used interchangeably with OSType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Linux**: Use Linux. \ * **Windows**: Use Windows. */ export type OSType = string; /** Known values of {@link Ossku} that the service accepts. */ export enum KnownOssku { Ubuntu = "Ubuntu", CBLMariner = "CBLMariner" } /** * Defines values for Ossku. \ * {@link KnownOssku} can be used interchangeably with Ossku, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Ubuntu** \ * **CBLMariner** */ export type Ossku = string; /** Known values of {@link ScaleDownMode} that the service accepts. */ export enum KnownScaleDownMode { /** Create new instances during scale up and remove instances during scale down. */ Delete = "Delete", /** Attempt to start deallocated instances (if they exist) during scale up and deallocate instances during scale down. */ Deallocate = "Deallocate" } /** * Defines values for ScaleDownMode. \ * {@link KnownScaleDownMode} can be used interchangeably with ScaleDownMode, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Delete**: Create new instances during scale up and remove instances during scale down. \ * **Deallocate**: Attempt to start deallocated instances (if they exist) during scale up and deallocate instances during scale down. */ export type ScaleDownMode = string; /** Known values of {@link AgentPoolType} that the service accepts. */ export enum KnownAgentPoolType { /** Create an Agent Pool backed by a Virtual Machine Scale Set. */ VirtualMachineScaleSets = "VirtualMachineScaleSets", /** Use of this is strongly discouraged. */ AvailabilitySet = "AvailabilitySet" } /** * Defines values for AgentPoolType. \ * {@link KnownAgentPoolType} can be used interchangeably with AgentPoolType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **VirtualMachineScaleSets**: Create an Agent Pool backed by a Virtual Machine Scale Set. \ * **AvailabilitySet**: Use of this is strongly discouraged. */ export type AgentPoolType = string; /** Known values of {@link AgentPoolMode} that the service accepts. */ export enum KnownAgentPoolMode { /** System agent pools are primarily for hosting critical system pods such as CoreDNS and metrics-server. System agent pools osType must be Linux. System agent pools VM SKU must have at least 2vCPUs and 4GB of memory. */ System = "System", /** User agent pools are primarily for hosting your application pods. */ User = "User" } /** * Defines values for AgentPoolMode. \ * {@link KnownAgentPoolMode} can be used interchangeably with AgentPoolMode, * this enum contains the known values that the service supports. * ### Known values supported by the service * **System**: System agent pools are primarily for hosting critical system pods such as CoreDNS and metrics-server. System agent pools osType must be Linux. System agent pools VM SKU must have at least 2vCPUs and 4GB of memory. \ * **User**: User agent pools are primarily for hosting your application pods. */ export type AgentPoolMode = string; /** Known values of {@link ScaleSetPriority} that the service accepts. */ export enum KnownScaleSetPriority { /** Spot priority VMs will be used. There is no SLA for spot nodes. See [spot on AKS](https://docs.microsoft.com/azure/aks/spot-node-pool) for more information. */ Spot = "Spot", /** Regular VMs will be used. */ Regular = "Regular" } /** * Defines values for ScaleSetPriority. \ * {@link KnownScaleSetPriority} can be used interchangeably with ScaleSetPriority, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Spot**: Spot priority VMs will be used. There is no SLA for spot nodes. See [spot on AKS](https:\/\/docs.microsoft.com\/azure\/aks\/spot-node-pool) for more information. \ * **Regular**: Regular VMs will be used. */ export type ScaleSetPriority = string; /** Known values of {@link ScaleSetEvictionPolicy} that the service accepts. */ export enum KnownScaleSetEvictionPolicy { /** Nodes in the underlying Scale Set of the node pool are deleted when they're evicted. */ Delete = "Delete", /** Nodes in the underlying Scale Set of the node pool are set to the stopped-deallocated state upon eviction. Nodes in the stopped-deallocated state count against your compute quota and can cause issues with cluster scaling or upgrading. */ Deallocate = "Deallocate" } /** * Defines values for ScaleSetEvictionPolicy. \ * {@link KnownScaleSetEvictionPolicy} can be used interchangeably with ScaleSetEvictionPolicy, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Delete**: Nodes in the underlying Scale Set of the node pool are deleted when they're evicted. \ * **Deallocate**: Nodes in the underlying Scale Set of the node pool are set to the stopped-deallocated state upon eviction. Nodes in the stopped-deallocated state count against your compute quota and can cause issues with cluster scaling or upgrading. */ export type ScaleSetEvictionPolicy = string; /** Known values of {@link GPUInstanceProfile} that the service accepts. */ export enum KnownGPUInstanceProfile { MIG1G = "MIG1g", MIG2G = "MIG2g", MIG3G = "MIG3g", MIG4G = "MIG4g", MIG7G = "MIG7g" } /** * Defines values for GPUInstanceProfile. \ * {@link KnownGPUInstanceProfile} can be used interchangeably with GPUInstanceProfile, * this enum contains the known values that the service supports. * ### Known values supported by the service * **MIG1g** \ * **MIG2g** \ * **MIG3g** \ * **MIG4g** \ * **MIG7g** */ export type GPUInstanceProfile = string; /** Known values of {@link LicenseType} that the service accepts. */ export enum KnownLicenseType { /** No additional licensing is applied. */ None = "None", /** Enables Azure Hybrid User Benefits for Windows VMs. */ WindowsServer = "Windows_Server" } /** * Defines values for LicenseType. \ * {@link KnownLicenseType} can be used interchangeably with LicenseType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **None**: No additional licensing is applied. \ * **Windows_Server**: Enables Azure Hybrid User Benefits for Windows VMs. */ export type LicenseType = string; /** Known values of {@link ManagedClusterPodIdentityProvisioningState} that the service accepts. */ export enum KnownManagedClusterPodIdentityProvisioningState { Assigned = "Assigned", Updating = "Updating", Deleting = "Deleting", Failed = "Failed" } /** * Defines values for ManagedClusterPodIdentityProvisioningState. \ * {@link KnownManagedClusterPodIdentityProvisioningState} can be used interchangeably with ManagedClusterPodIdentityProvisioningState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Assigned** \ * **Updating** \ * **Deleting** \ * **Failed** */ export type ManagedClusterPodIdentityProvisioningState = string; /** Known values of {@link NetworkPlugin} that the service accepts. */ export enum KnownNetworkPlugin { /** Use the Azure CNI network plugin. See [Azure CNI (advanced) networking](https://docs.microsoft.com/azure/aks/concepts-network#azure-cni-advanced-networking) for more information. */ Azure = "azure", /** Use the Kubenet network plugin. See [Kubenet (basic) networking](https://docs.microsoft.com/azure/aks/concepts-network#kubenet-basic-networking) for more information. */ Kubenet = "kubenet" } /** * Defines values for NetworkPlugin. \ * {@link KnownNetworkPlugin} can be used interchangeably with NetworkPlugin, * this enum contains the known values that the service supports. * ### Known values supported by the service * **azure**: Use the Azure CNI network plugin. See [Azure CNI (advanced) networking](https:\/\/docs.microsoft.com\/azure\/aks\/concepts-network#azure-cni-advanced-networking) for more information. \ * **kubenet**: Use the Kubenet network plugin. See [Kubenet (basic) networking](https:\/\/docs.microsoft.com\/azure\/aks\/concepts-network#kubenet-basic-networking) for more information. */ export type NetworkPlugin = string; /** Known values of {@link NetworkPolicy} that the service accepts. */ export enum KnownNetworkPolicy { /** Use Calico network policies. See [differences between Azure and Calico policies](https://docs.microsoft.com/azure/aks/use-network-policies#differences-between-azure-and-calico-policies-and-their-capabilities) for more information. */ Calico = "calico", /** Use Azure network policies. See [differences between Azure and Calico policies](https://docs.microsoft.com/azure/aks/use-network-policies#differences-between-azure-and-calico-policies-and-their-capabilities) for more information. */ Azure = "azure" } /** * Defines values for NetworkPolicy. \ * {@link KnownNetworkPolicy} can be used interchangeably with NetworkPolicy, * this enum contains the known values that the service supports. * ### Known values supported by the service * **calico**: Use Calico network policies. See [differences between Azure and Calico policies](https:\/\/docs.microsoft.com\/azure\/aks\/use-network-policies#differences-between-azure-and-calico-policies-and-their-capabilities) for more information. \ * **azure**: Use Azure network policies. See [differences between Azure and Calico policies](https:\/\/docs.microsoft.com\/azure\/aks\/use-network-policies#differences-between-azure-and-calico-policies-and-their-capabilities) for more information. */ export type NetworkPolicy = string; /** Known values of {@link NetworkMode} that the service accepts. */ export enum KnownNetworkMode { /** No bridge is created. Intra-VM Pod to Pod communication is through IP routes created by Azure CNI. See [Transparent Mode](https://docs.microsoft.com/azure/aks/faq#transparent-mode) for more information. */ Transparent = "transparent", /** This is no longer supported */ Bridge = "bridge" } /** * Defines values for NetworkMode. \ * {@link KnownNetworkMode} can be used interchangeably with NetworkMode, * this enum contains the known values that the service supports. * ### Known values supported by the service * **transparent**: No bridge is created. Intra-VM Pod to Pod communication is through IP routes created by Azure CNI. See [Transparent Mode](https:\/\/docs.microsoft.com\/azure\/aks\/faq#transparent-mode) for more information. \ * **bridge**: This is no longer supported */ export type NetworkMode = string; /** Known values of {@link OutboundType} that the service accepts. */ export enum KnownOutboundType { /** The load balancer is used for egress through an AKS assigned public IP. This supports Kubernetes services of type 'loadBalancer'. For more information see [outbound type loadbalancer](https://docs.microsoft.com/azure/aks/egress-outboundtype#outbound-type-of-loadbalancer). */ LoadBalancer = "loadBalancer", /** Egress paths must be defined by the user. This is an advanced scenario and requires proper network configuration. For more information see [outbound type userDefinedRouting](https://docs.microsoft.com/azure/aks/egress-outboundtype#outbound-type-of-userdefinedrouting). */ UserDefinedRouting = "userDefinedRouting", /** The AKS-managed NAT gateway is used for egress. */ ManagedNATGateway = "managedNATGateway", /** The user-assigned NAT gateway associated to the cluster subnet is used for egress. This is an advanced scenario and requires proper network configuration. */ UserAssignedNATGateway = "userAssignedNATGateway" } /** * Defines values for OutboundType. \ * {@link KnownOutboundType} can be used interchangeably with OutboundType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **loadBalancer**: The load balancer is used for egress through an AKS assigned public IP. This supports Kubernetes services of type 'loadBalancer'. For more information see [outbound type loadbalancer](https:\/\/docs.microsoft.com\/azure\/aks\/egress-outboundtype#outbound-type-of-loadbalancer). \ * **userDefinedRouting**: Egress paths must be defined by the user. This is an advanced scenario and requires proper network configuration. For more information see [outbound type userDefinedRouting](https:\/\/docs.microsoft.com\/azure\/aks\/egress-outboundtype#outbound-type-of-userdefinedrouting). \ * **managedNATGateway**: The AKS-managed NAT gateway is used for egress. \ * **userAssignedNATGateway**: The user-assigned NAT gateway associated to the cluster subnet is used for egress. This is an advanced scenario and requires proper network configuration. */ export type OutboundType = string; /** Known values of {@link LoadBalancerSku} that the service accepts. */ export enum KnownLoadBalancerSku { /** Use a a standard Load Balancer. This is the recommended Load Balancer SKU. For more information about on working with the load balancer in the managed cluster, see the [standard Load Balancer](https://docs.microsoft.com/azure/aks/load-balancer-standard) article. */ Standard = "standard", /** Use a basic Load Balancer with limited functionality. */ Basic = "basic" } /** * Defines values for LoadBalancerSku. \ * {@link KnownLoadBalancerSku} can be used interchangeably with LoadBalancerSku, * this enum contains the known values that the service supports. * ### Known values supported by the service * **standard**: Use a a standard Load Balancer. This is the recommended Load Balancer SKU. For more information about on working with the load balancer in the managed cluster, see the [standard Load Balancer](https:\/\/docs.microsoft.com\/azure\/aks\/load-balancer-standard) article. \ * **basic**: Use a basic Load Balancer with limited functionality. */ export type LoadBalancerSku = string; /** Known values of {@link IpFamily} that the service accepts. */ export enum KnownIpFamily { IPv4 = "IPv4", IPv6 = "IPv6" } /** * Defines values for IpFamily. \ * {@link KnownIpFamily} can be used interchangeably with IpFamily, * this enum contains the known values that the service supports. * ### Known values supported by the service * **IPv4** \ * **IPv6** */ export type IpFamily = string; /** Known values of {@link UpgradeChannel} that the service accepts. */ export enum KnownUpgradeChannel { /** Automatically upgrade the cluster to the latest supported patch release on the latest supported minor version. In cases where the cluster is at a version of Kubernetes that is at an N-2 minor version where N is the latest supported minor version, the cluster first upgrades to the latest supported patch version on N-1 minor version. For example, if a cluster is running version 1.17.7 and versions 1.17.9, 1.18.4, 1.18.6, and 1.19.1 are available, your cluster first is upgraded to 1.18.6, then is upgraded to 1.19.1. */ Rapid = "rapid", /** Automatically upgrade the cluster to the latest supported patch release on minor version N-1, where N is the latest supported minor version. For example, if a cluster is running version 1.17.7 and versions 1.17.9, 1.18.4, 1.18.6, and 1.19.1 are available, your cluster is upgraded to 1.18.6. */ Stable = "stable", /** Automatically upgrade the cluster to the latest supported patch version when it becomes available while keeping the minor version the same. For example, if a cluster is running version 1.17.7 and versions 1.17.9, 1.18.4, 1.18.6, and 1.19.1 are available, your cluster is upgraded to 1.17.9. */ Patch = "patch", /** Automatically upgrade the node image to the latest version available. Microsoft provides patches and new images for image nodes frequently (usually weekly), but your running nodes won't get the new images unless you do a node image upgrade. Turning on the node-image channel will automatically update your node images whenever a new version is available. */ NodeImage = "node-image", /** Disables auto-upgrades and keeps the cluster at its current version of Kubernetes. */ None = "none" } /** * Defines values for UpgradeChannel. \ * {@link KnownUpgradeChannel} can be used interchangeably with UpgradeChannel, * this enum contains the known values that the service supports. * ### Known values supported by the service * **rapid**: Automatically upgrade the cluster to the latest supported patch release on the latest supported minor version. In cases where the cluster is at a version of Kubernetes that is at an N-2 minor version where N is the latest supported minor version, the cluster first upgrades to the latest supported patch version on N-1 minor version. For example, if a cluster is running version 1.17.7 and versions 1.17.9, 1.18.4, 1.18.6, and 1.19.1 are available, your cluster first is upgraded to 1.18.6, then is upgraded to 1.19.1. \ * **stable**: Automatically upgrade the cluster to the latest supported patch release on minor version N-1, where N is the latest supported minor version. For example, if a cluster is running version 1.17.7 and versions 1.17.9, 1.18.4, 1.18.6, and 1.19.1 are available, your cluster is upgraded to 1.18.6. \ * **patch**: Automatically upgrade the cluster to the latest supported patch version when it becomes available while keeping the minor version the same. For example, if a cluster is running version 1.17.7 and versions 1.17.9, 1.18.4, 1.18.6, and 1.19.1 are available, your cluster is upgraded to 1.17.9. \ * **node-image**: Automatically upgrade the node image to the latest version available. Microsoft provides patches and new images for image nodes frequently (usually weekly), but your running nodes won't get the new images unless you do a node image upgrade. Turning on the node-image channel will automatically update your node images whenever a new version is available. \ * **none**: Disables auto-upgrades and keeps the cluster at its current version of Kubernetes. */ export type UpgradeChannel = string; /** Known values of {@link Expander} that the service accepts. */ export enum KnownExpander { /** Selects the node group that will have the least idle CPU (if tied, unused memory) after scale-up. This is useful when you have different classes of nodes, for example, high CPU or high memory nodes, and only want to expand those when there are pending pods that need a lot of those resources. */ LeastWaste = "least-waste", /** Selects the node group that would be able to schedule the most pods when scaling up. This is useful when you are using nodeSelector to make sure certain pods land on certain nodes. Note that this won't cause the autoscaler to select bigger nodes vs. smaller, as it can add multiple smaller nodes at once. */ MostPods = "most-pods", /** Selects the node group that has the highest priority assigned by the user. It's configuration is described in more details [here](https://github.com/kubernetes/autoscaler/blob/master/cluster-autoscaler/expander/priority/readme.md). */ Priority = "priority", /** Used when you don't have a particular need for the node groups to scale differently. */ Random = "random" } /** * Defines values for Expander. \ * {@link KnownExpander} can be used interchangeably with Expander, * this enum contains the known values that the service supports. * ### Known values supported by the service * **least-waste**: Selects the node group that will have the least idle CPU (if tied, unused memory) after scale-up. This is useful when you have different classes of nodes, for example, high CPU or high memory nodes, and only want to expand those when there are pending pods that need a lot of those resources. \ * **most-pods**: Selects the node group that would be able to schedule the most pods when scaling up. This is useful when you are using nodeSelector to make sure certain pods land on certain nodes. Note that this won't cause the autoscaler to select bigger nodes vs. smaller, as it can add multiple smaller nodes at once. \ * **priority**: Selects the node group that has the highest priority assigned by the user. It's configuration is described in more details [here](https:\/\/github.com\/kubernetes\/autoscaler\/blob\/master\/cluster-autoscaler\/expander\/priority\/readme.md). \ * **random**: Used when you don't have a particular need for the node groups to scale differently. */ export type Expander = string; /** Known values of {@link PublicNetworkAccess} that the service accepts. */ export enum KnownPublicNetworkAccess { Enabled = "Enabled", Disabled = "Disabled" } /** * Defines values for PublicNetworkAccess. \ * {@link KnownPublicNetworkAccess} can be used interchangeably with PublicNetworkAccess, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabled** \ * **Disabled** */ export type PublicNetworkAccess = string; /** Known values of {@link CreatedByType} that the service accepts. */ export enum KnownCreatedByType { User = "User", Application = "Application", ManagedIdentity = "ManagedIdentity", Key = "Key" } /** * Defines values for CreatedByType. \ * {@link KnownCreatedByType} can be used interchangeably with CreatedByType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **User** \ * **Application** \ * **ManagedIdentity** \ * **Key** */ export type CreatedByType = string; /** Known values of {@link WeekDay} that the service accepts. */ export enum KnownWeekDay { Sunday = "Sunday", Monday = "Monday", Tuesday = "Tuesday", Wednesday = "Wednesday", Thursday = "Thursday", Friday = "Friday", Saturday = "Saturday" } /** * Defines values for WeekDay. \ * {@link KnownWeekDay} can be used interchangeably with WeekDay, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Sunday** \ * **Monday** \ * **Tuesday** \ * **Wednesday** \ * **Thursday** \ * **Friday** \ * **Saturday** */ export type WeekDay = string; /** Known values of {@link PrivateEndpointConnectionProvisioningState} that the service accepts. */ export enum KnownPrivateEndpointConnectionProvisioningState { Succeeded = "Succeeded", Creating = "Creating", Deleting = "Deleting", Failed = "Failed" } /** * Defines values for PrivateEndpointConnectionProvisioningState. \ * {@link KnownPrivateEndpointConnectionProvisioningState} can be used interchangeably with PrivateEndpointConnectionProvisioningState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Succeeded** \ * **Creating** \ * **Deleting** \ * **Failed** */ export type PrivateEndpointConnectionProvisioningState = string; /** Known values of {@link ConnectionStatus} that the service accepts. */ export enum KnownConnectionStatus { Pending = "Pending", Approved = "Approved", Rejected = "Rejected", Disconnected = "Disconnected" } /** * Defines values for ConnectionStatus. \ * {@link KnownConnectionStatus} can be used interchangeably with ConnectionStatus, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Pending** \ * **Approved** \ * **Rejected** \ * **Disconnected** */ export type ConnectionStatus = string; /** Known values of {@link SnapshotType} that the service accepts. */ export enum KnownSnapshotType { /** The snapshot is a snapshot of a node pool. */ NodePool = "NodePool" } /** * Defines values for SnapshotType. \ * {@link KnownSnapshotType} can be used interchangeably with SnapshotType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **NodePool**: The snapshot is a snapshot of a node pool. */ export type SnapshotType = string; /** Known values of {@link ContainerServiceVMSizeTypes} that the service accepts. */ export enum KnownContainerServiceVMSizeTypes { StandardA1 = "Standard_A1", StandardA10 = "Standard_A10", StandardA11 = "Standard_A11", StandardA1V2 = "Standard_A1_v2", StandardA2 = "Standard_A2", StandardA2V2 = "Standard_A2_v2", StandardA2MV2 = "Standard_A2m_v2", StandardA3 = "Standard_A3", StandardA4 = "Standard_A4", StandardA4V2 = "Standard_A4_v2", StandardA4MV2 = "Standard_A4m_v2", StandardA5 = "Standard_A5", StandardA6 = "Standard_A6", StandardA7 = "Standard_A7", StandardA8 = "Standard_A8", StandardA8V2 = "Standard_A8_v2", StandardA8MV2 = "Standard_A8m_v2", StandardA9 = "Standard_A9", StandardB2Ms = "Standard_B2ms", StandardB2S = "Standard_B2s", StandardB4Ms = "Standard_B4ms", StandardB8Ms = "Standard_B8ms", StandardD1 = "Standard_D1", StandardD11 = "Standard_D11", StandardD11V2 = "Standard_D11_v2", StandardD11V2Promo = "Standard_D11_v2_Promo", StandardD12 = "Standard_D12", StandardD12V2 = "Standard_D12_v2", StandardD12V2Promo = "Standard_D12_v2_Promo", StandardD13 = "Standard_D13", StandardD13V2 = "Standard_D13_v2", StandardD13V2Promo = "Standard_D13_v2_Promo", StandardD14 = "Standard_D14", StandardD14V2 = "Standard_D14_v2", StandardD14V2Promo = "Standard_D14_v2_Promo", StandardD15V2 = "Standard_D15_v2", StandardD16V3 = "Standard_D16_v3", StandardD16SV3 = "Standard_D16s_v3", StandardD1V2 = "Standard_D1_v2", StandardD2 = "Standard_D2", StandardD2V2 = "Standard_D2_v2", StandardD2V2Promo = "Standard_D2_v2_Promo", StandardD2V3 = "Standard_D2_v3", StandardD2SV3 = "Standard_D2s_v3", StandardD3 = "Standard_D3", StandardD32V3 = "Standard_D32_v3", StandardD32SV3 = "Standard_D32s_v3", StandardD3V2 = "Standard_D3_v2", StandardD3V2Promo = "Standard_D3_v2_Promo", StandardD4 = "Standard_D4", StandardD4V2 = "Standard_D4_v2", StandardD4V2Promo = "Standard_D4_v2_Promo", StandardD4V3 = "Standard_D4_v3", StandardD4SV3 = "Standard_D4s_v3", StandardD5V2 = "Standard_D5_v2", StandardD5V2Promo = "Standard_D5_v2_Promo", StandardD64V3 = "Standard_D64_v3", StandardD64SV3 = "Standard_D64s_v3", StandardD8V3 = "Standard_D8_v3", StandardD8SV3 = "Standard_D8s_v3", StandardDS1 = "Standard_DS1", StandardDS11 = "Standard_DS11", StandardDS11V2 = "Standard_DS11_v2", StandardDS11V2Promo = "Standard_DS11_v2_Promo", StandardDS12 = "Standard_DS12", StandardDS12V2 = "Standard_DS12_v2", StandardDS12V2Promo = "Standard_DS12_v2_Promo", StandardDS13 = "Standard_DS13", StandardDS132V2 = "Standard_DS13-2_v2", StandardDS134V2 = "Standard_DS13-4_v2", StandardDS13V2 = "Standard_DS13_v2", StandardDS13V2Promo = "Standard_DS13_v2_Promo", StandardDS14 = "Standard_DS14", StandardDS144V2 = "Standard_DS14-4_v2", StandardDS148V2 = "Standard_DS14-8_v2", StandardDS14V2 = "Standard_DS14_v2", StandardDS14V2Promo = "Standard_DS14_v2_Promo", StandardDS15V2 = "Standard_DS15_v2", StandardDS1V2 = "Standard_DS1_v2", StandardDS2 = "Standard_DS2", StandardDS2V2 = "Standard_DS2_v2", StandardDS2V2Promo = "Standard_DS2_v2_Promo", StandardDS3 = "Standard_DS3", StandardDS3V2 = "Standard_DS3_v2", StandardDS3V2Promo = "Standard_DS3_v2_Promo", StandardDS4 = "Standard_DS4", StandardDS4V2 = "Standard_DS4_v2", StandardDS4V2Promo = "Standard_DS4_v2_Promo", StandardDS5V2 = "Standard_DS5_v2", StandardDS5V2Promo = "Standard_DS5_v2_Promo", StandardE16V3 = "Standard_E16_v3", StandardE16SV3 = "Standard_E16s_v3", StandardE2V3 = "Standard_E2_v3", StandardE2SV3 = "Standard_E2s_v3", StandardE3216SV3 = "Standard_E32-16s_v3", StandardE328SV3 = "Standard_E32-8s_v3", StandardE32V3 = "Standard_E32_v3", StandardE32SV3 = "Standard_E32s_v3", StandardE4V3 = "Standard_E4_v3", StandardE4SV3 = "Standard_E4s_v3", StandardE6416SV3 = "Standard_E64-16s_v3", StandardE6432SV3 = "Standard_E64-32s_v3", StandardE64V3 = "Standard_E64_v3", StandardE64SV3 = "Standard_E64s_v3", StandardE8V3 = "Standard_E8_v3", StandardE8SV3 = "Standard_E8s_v3", StandardF1 = "Standard_F1", StandardF16 = "Standard_F16", StandardF16S = "Standard_F16s", StandardF16SV2 = "Standard_F16s_v2", StandardF1S = "Standard_F1s", StandardF2 = "Standard_F2", StandardF2S = "Standard_F2s", StandardF2SV2 = "Standard_F2s_v2", StandardF32SV2 = "Standard_F32s_v2", StandardF4 = "Standard_F4", StandardF4S = "Standard_F4s", StandardF4SV2 = "Standard_F4s_v2", StandardF64SV2 = "Standard_F64s_v2", StandardF72SV2 = "Standard_F72s_v2", StandardF8 = "Standard_F8", StandardF8S = "Standard_F8s", StandardF8SV2 = "Standard_F8s_v2", StandardG1 = "Standard_G1", StandardG2 = "Standard_G2", StandardG3 = "Standard_G3", StandardG4 = "Standard_G4", StandardG5 = "Standard_G5", StandardGS1 = "Standard_GS1", StandardGS2 = "Standard_GS2", StandardGS3 = "Standard_GS3", StandardGS4 = "Standard_GS4", StandardGS44 = "Standard_GS4-4", StandardGS48 = "Standard_GS4-8", StandardGS5 = "Standard_GS5", StandardGS516 = "Standard_GS5-16", StandardGS58 = "Standard_GS5-8", StandardH16 = "Standard_H16", StandardH16M = "Standard_H16m", StandardH16Mr = "Standard_H16mr", StandardH16R = "Standard_H16r", StandardH8 = "Standard_H8", StandardH8M = "Standard_H8m", StandardL16S = "Standard_L16s", StandardL32S = "Standard_L32s", StandardL4S = "Standard_L4s", StandardL8S = "Standard_L8s", StandardM12832Ms = "Standard_M128-32ms", StandardM12864Ms = "Standard_M128-64ms", StandardM128Ms = "Standard_M128ms", StandardM128S = "Standard_M128s", StandardM6416Ms = "Standard_M64-16ms", StandardM6432Ms = "Standard_M64-32ms", StandardM64Ms = "Standard_M64ms", StandardM64S = "Standard_M64s", StandardNC12 = "Standard_NC12", StandardNC12SV2 = "Standard_NC12s_v2", StandardNC12SV3 = "Standard_NC12s_v3", StandardNC24 = "Standard_NC24", StandardNC24R = "Standard_NC24r", StandardNC24RsV2 = "Standard_NC24rs_v2", StandardNC24RsV3 = "Standard_NC24rs_v3", StandardNC24SV2 = "Standard_NC24s_v2", StandardNC24SV3 = "Standard_NC24s_v3", StandardNC6 = "Standard_NC6", StandardNC6SV2 = "Standard_NC6s_v2", StandardNC6SV3 = "Standard_NC6s_v3", StandardND12S = "Standard_ND12s", StandardND24Rs = "Standard_ND24rs", StandardND24S = "Standard_ND24s", StandardND6S = "Standard_ND6s", StandardNV12 = "Standard_NV12", StandardNV24 = "Standard_NV24", StandardNV6 = "Standard_NV6" } /** * Defines values for ContainerServiceVMSizeTypes. \ * {@link KnownContainerServiceVMSizeTypes} can be used interchangeably with ContainerServiceVMSizeTypes, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Standard_A1** \ * **Standard_A10** \ * **Standard_A11** \ * **Standard_A1_v2** \ * **Standard_A2** \ * **Standard_A2_v2** \ * **Standard_A2m_v2** \ * **Standard_A3** \ * **Standard_A4** \ * **Standard_A4_v2** \ * **Standard_A4m_v2** \ * **Standard_A5** \ * **Standard_A6** \ * **Standard_A7** \ * **Standard_A8** \ * **Standard_A8_v2** \ * **Standard_A8m_v2** \ * **Standard_A9** \ * **Standard_B2ms** \ * **Standard_B2s** \ * **Standard_B4ms** \ * **Standard_B8ms** \ * **Standard_D1** \ * **Standard_D11** \ * **Standard_D11_v2** \ * **Standard_D11_v2_Promo** \ * **Standard_D12** \ * **Standard_D12_v2** \ * **Standard_D12_v2_Promo** \ * **Standard_D13** \ * **Standard_D13_v2** \ * **Standard_D13_v2_Promo** \ * **Standard_D14** \ * **Standard_D14_v2** \ * **Standard_D14_v2_Promo** \ * **Standard_D15_v2** \ * **Standard_D16_v3** \ * **Standard_D16s_v3** \ * **Standard_D1_v2** \ * **Standard_D2** \ * **Standard_D2_v2** \ * **Standard_D2_v2_Promo** \ * **Standard_D2_v3** \ * **Standard_D2s_v3** \ * **Standard_D3** \ * **Standard_D32_v3** \ * **Standard_D32s_v3** \ * **Standard_D3_v2** \ * **Standard_D3_v2_Promo** \ * **Standard_D4** \ * **Standard_D4_v2** \ * **Standard_D4_v2_Promo** \ * **Standard_D4_v3** \ * **Standard_D4s_v3** \ * **Standard_D5_v2** \ * **Standard_D5_v2_Promo** \ * **Standard_D64_v3** \ * **Standard_D64s_v3** \ * **Standard_D8_v3** \ * **Standard_D8s_v3** \ * **Standard_DS1** \ * **Standard_DS11** \ * **Standard_DS11_v2** \ * **Standard_DS11_v2_Promo** \ * **Standard_DS12** \ * **Standard_DS12_v2** \ * **Standard_DS12_v2_Promo** \ * **Standard_DS13** \ * **Standard_DS13-2_v2** \ * **Standard_DS13-4_v2** \ * **Standard_DS13_v2** \ * **Standard_DS13_v2_Promo** \ * **Standard_DS14** \ * **Standard_DS14-4_v2** \ * **Standard_DS14-8_v2** \ * **Standard_DS14_v2** \ * **Standard_DS14_v2_Promo** \ * **Standard_DS15_v2** \ * **Standard_DS1_v2** \ * **Standard_DS2** \ * **Standard_DS2_v2** \ * **Standard_DS2_v2_Promo** \ * **Standard_DS3** \ * **Standard_DS3_v2** \ * **Standard_DS3_v2_Promo** \ * **Standard_DS4** \ * **Standard_DS4_v2** \ * **Standard_DS4_v2_Promo** \ * **Standard_DS5_v2** \ * **Standard_DS5_v2_Promo** \ * **Standard_E16_v3** \ * **Standard_E16s_v3** \ * **Standard_E2_v3** \ * **Standard_E2s_v3** \ * **Standard_E32-16s_v3** \ * **Standard_E32-8s_v3** \ * **Standard_E32_v3** \ * **Standard_E32s_v3** \ * **Standard_E4_v3** \ * **Standard_E4s_v3** \ * **Standard_E64-16s_v3** \ * **Standard_E64-32s_v3** \ * **Standard_E64_v3** \ * **Standard_E64s_v3** \ * **Standard_E8_v3** \ * **Standard_E8s_v3** \ * **Standard_F1** \ * **Standard_F16** \ * **Standard_F16s** \ * **Standard_F16s_v2** \ * **Standard_F1s** \ * **Standard_F2** \ * **Standard_F2s** \ * **Standard_F2s_v2** \ * **Standard_F32s_v2** \ * **Standard_F4** \ * **Standard_F4s** \ * **Standard_F4s_v2** \ * **Standard_F64s_v2** \ * **Standard_F72s_v2** \ * **Standard_F8** \ * **Standard_F8s** \ * **Standard_F8s_v2** \ * **Standard_G1** \ * **Standard_G2** \ * **Standard_G3** \ * **Standard_G4** \ * **Standard_G5** \ * **Standard_GS1** \ * **Standard_GS2** \ * **Standard_GS3** \ * **Standard_GS4** \ * **Standard_GS4-4** \ * **Standard_GS4-8** \ * **Standard_GS5** \ * **Standard_GS5-16** \ * **Standard_GS5-8** \ * **Standard_H16** \ * **Standard_H16m** \ * **Standard_H16mr** \ * **Standard_H16r** \ * **Standard_H8** \ * **Standard_H8m** \ * **Standard_L16s** \ * **Standard_L32s** \ * **Standard_L4s** \ * **Standard_L8s** \ * **Standard_M128-32ms** \ * **Standard_M128-64ms** \ * **Standard_M128ms** \ * **Standard_M128s** \ * **Standard_M64-16ms** \ * **Standard_M64-32ms** \ * **Standard_M64ms** \ * **Standard_M64s** \ * **Standard_NC12** \ * **Standard_NC12s_v2** \ * **Standard_NC12s_v3** \ * **Standard_NC24** \ * **Standard_NC24r** \ * **Standard_NC24rs_v2** \ * **Standard_NC24rs_v3** \ * **Standard_NC24s_v2** \ * **Standard_NC24s_v3** \ * **Standard_NC6** \ * **Standard_NC6s_v2** \ * **Standard_NC6s_v3** \ * **Standard_ND12s** \ * **Standard_ND24rs** \ * **Standard_ND24s** \ * **Standard_ND6s** \ * **Standard_NV12** \ * **Standard_NV24** \ * **Standard_NV6** */ export type ContainerServiceVMSizeTypes = string; /** Known values of {@link ContainerServiceStorageProfileTypes} that the service accepts. */ export enum KnownContainerServiceStorageProfileTypes { StorageAccount = "StorageAccount", ManagedDisks = "ManagedDisks" } /** * Defines values for ContainerServiceStorageProfileTypes. \ * {@link KnownContainerServiceStorageProfileTypes} can be used interchangeably with ContainerServiceStorageProfileTypes, * this enum contains the known values that the service supports. * ### Known values supported by the service * **StorageAccount** \ * **ManagedDisks** */ export type ContainerServiceStorageProfileTypes = string; /** Defines values for ResourceIdentityType. */ export type ResourceIdentityType = "SystemAssigned" | "UserAssigned" | "None"; /** Defines values for Count. */ export type Count = 1 | 3 | 5; /** Optional parameters. */ export interface OperationsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult; /** Optional parameters. */ export interface ManagedClustersGetOSOptionsOptionalParams extends coreClient.OperationOptions { /** The resource type for which the OS options needs to be returned */ resourceType?: string; } /** Contains response data for the getOSOptions operation. */ export type ManagedClustersGetOSOptionsResponse = OSOptionProfile; /** Optional parameters. */ export interface ManagedClustersListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type ManagedClustersListResponse = ManagedClusterListResult; /** Optional parameters. */ export interface ManagedClustersListByResourceGroupOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroup operation. */ export type ManagedClustersListByResourceGroupResponse = ManagedClusterListResult; /** Optional parameters. */ export interface ManagedClustersGetUpgradeProfileOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getUpgradeProfile operation. */ export type ManagedClustersGetUpgradeProfileResponse = ManagedClusterUpgradeProfile; /** Optional parameters. */ export interface ManagedClustersGetAccessProfileOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getAccessProfile operation. */ export type ManagedClustersGetAccessProfileResponse = ManagedClusterAccessProfile; /** Optional parameters. */ export interface ManagedClustersListClusterAdminCredentialsOptionalParams extends coreClient.OperationOptions { /** server fqdn type for credentials to be returned */ serverFqdn?: string; } /** Contains response data for the listClusterAdminCredentials operation. */ export type ManagedClustersListClusterAdminCredentialsResponse = CredentialResults; /** Optional parameters. */ export interface ManagedClustersListClusterUserCredentialsOptionalParams extends coreClient.OperationOptions { /** server fqdn type for credentials to be returned */ serverFqdn?: string; } /** Contains response data for the listClusterUserCredentials operation. */ export type ManagedClustersListClusterUserCredentialsResponse = CredentialResults; /** Optional parameters. */ export interface ManagedClustersListClusterMonitoringUserCredentialsOptionalParams extends coreClient.OperationOptions { /** server fqdn type for credentials to be returned */ serverFqdn?: string; } /** Contains response data for the listClusterMonitoringUserCredentials operation. */ export type ManagedClustersListClusterMonitoringUserCredentialsResponse = CredentialResults; /** Optional parameters. */ export interface ManagedClustersGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type ManagedClustersGetResponse = ManagedCluster; /** Optional parameters. */ export interface ManagedClustersCreateOrUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the createOrUpdate operation. */ export type ManagedClustersCreateOrUpdateResponse = ManagedCluster; /** Optional parameters. */ export interface ManagedClustersUpdateTagsOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the updateTags operation. */ export type ManagedClustersUpdateTagsResponse = ManagedCluster; /** Optional parameters. */ export interface ManagedClustersDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface ManagedClustersResetServicePrincipalProfileOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface ManagedClustersResetAADProfileOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface ManagedClustersRotateClusterCertificatesOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface ManagedClustersStopOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface ManagedClustersStartOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface ManagedClustersRunCommandOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the runCommand operation. */ export type ManagedClustersRunCommandResponse = RunCommandResult; /** Optional parameters. */ export interface ManagedClustersGetCommandResultOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getCommandResult operation. */ export type ManagedClustersGetCommandResultResponse = RunCommandResult; /** Optional parameters. */ export interface ManagedClustersListOutboundNetworkDependenciesEndpointsOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listOutboundNetworkDependenciesEndpoints operation. */ export type ManagedClustersListOutboundNetworkDependenciesEndpointsResponse = OutboundEnvironmentEndpointCollection; /** Optional parameters. */ export interface ManagedClustersListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type ManagedClustersListNextResponse = ManagedClusterListResult; /** Optional parameters. */ export interface ManagedClustersListByResourceGroupNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroupNext operation. */ export type ManagedClustersListByResourceGroupNextResponse = ManagedClusterListResult; /** Optional parameters. */ export interface ManagedClustersListOutboundNetworkDependenciesEndpointsNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listOutboundNetworkDependenciesEndpointsNext operation. */ export type ManagedClustersListOutboundNetworkDependenciesEndpointsNextResponse = OutboundEnvironmentEndpointCollection; /** Optional parameters. */ export interface MaintenanceConfigurationsListByManagedClusterOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByManagedCluster operation. */ export type MaintenanceConfigurationsListByManagedClusterResponse = MaintenanceConfigurationListResult; /** Optional parameters. */ export interface MaintenanceConfigurationsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type MaintenanceConfigurationsGetResponse = MaintenanceConfiguration; /** Optional parameters. */ export interface MaintenanceConfigurationsCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type MaintenanceConfigurationsCreateOrUpdateResponse = MaintenanceConfiguration; /** Optional parameters. */ export interface MaintenanceConfigurationsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface MaintenanceConfigurationsListByManagedClusterNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByManagedClusterNext operation. */ export type MaintenanceConfigurationsListByManagedClusterNextResponse = MaintenanceConfigurationListResult; /** Optional parameters. */ export interface AgentPoolsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type AgentPoolsListResponse = AgentPoolListResult; /** Optional parameters. */ export interface AgentPoolsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type AgentPoolsGetResponse = AgentPool; /** Optional parameters. */ export interface AgentPoolsCreateOrUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the createOrUpdate operation. */ export type AgentPoolsCreateOrUpdateResponse = AgentPool; /** Optional parameters. */ export interface AgentPoolsDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface AgentPoolsGetUpgradeProfileOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getUpgradeProfile operation. */ export type AgentPoolsGetUpgradeProfileResponse = AgentPoolUpgradeProfile; /** Optional parameters. */ export interface AgentPoolsGetAvailableAgentPoolVersionsOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getAvailableAgentPoolVersions operation. */ export type AgentPoolsGetAvailableAgentPoolVersionsResponse = AgentPoolAvailableVersions; /** Optional parameters. */ export interface AgentPoolsUpgradeNodeImageVersionOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface AgentPoolsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type AgentPoolsListNextResponse = AgentPoolListResult; /** Optional parameters. */ export interface PrivateEndpointConnectionsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type PrivateEndpointConnectionsListResponse = PrivateEndpointConnectionListResult; /** Optional parameters. */ export interface PrivateEndpointConnectionsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type PrivateEndpointConnectionsGetResponse = PrivateEndpointConnection; /** Optional parameters. */ export interface PrivateEndpointConnectionsUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the update operation. */ export type PrivateEndpointConnectionsUpdateResponse = PrivateEndpointConnection; /** Optional parameters. */ export interface PrivateEndpointConnectionsDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface PrivateLinkResourcesListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type PrivateLinkResourcesListResponse = PrivateLinkResourcesListResult; /** Optional parameters. */ export interface ResolvePrivateLinkServiceIdPostOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the post operation. */ export type ResolvePrivateLinkServiceIdPostResponse = PrivateLinkResource; /** Optional parameters. */ export interface SnapshotsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type SnapshotsListResponse = SnapshotListResult; /** Optional parameters. */ export interface SnapshotsListByResourceGroupOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroup operation. */ export type SnapshotsListByResourceGroupResponse = SnapshotListResult; /** Optional parameters. */ export interface SnapshotsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type SnapshotsGetResponse = Snapshot; /** Optional parameters. */ export interface SnapshotsCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type SnapshotsCreateOrUpdateResponse = Snapshot; /** Optional parameters. */ export interface SnapshotsUpdateTagsOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the updateTags operation. */ export type SnapshotsUpdateTagsResponse = Snapshot; /** Optional parameters. */ export interface SnapshotsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface SnapshotsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type SnapshotsListNextResponse = SnapshotListResult; /** Optional parameters. */ export interface SnapshotsListByResourceGroupNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroupNext operation. */ export type SnapshotsListByResourceGroupNextResponse = SnapshotListResult; /** Optional parameters. */ export interface ContainerServiceClientOptionalParams extends coreClient.ServiceClientOptions { /** server parameter */ $host?: string; /** Api Version */ apiVersion?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import { getBestSelectorForAction } from './selector'; import type { Action } from '../types'; import { ActionType, BaseAction, ScriptType, TagName, isSupportedActionType, } from '../types'; const FILLABLE_INPUT_TYPES = [ '', 'date', 'datetime', 'datetime-local', 'email', 'month', 'number', 'password', 'search', 'tel', 'text', 'time', 'url', 'week', ]; // only used in ActionContext export const truncateText = (str: string, maxLen: number) => { return `${str.substring(0, maxLen)}${str.length > maxLen ? '...' : ''}`; }; export const isActionStateful = (action: Action) => { return action.tagName === TagName.TextArea; }; type ActionState = { causesNavigation: boolean; isStateful: boolean; }; export class ActionContext extends BaseAction { private readonly action: Action; private readonly scriptType: ScriptType; private readonly actionState: ActionState; constructor( action: Action, scriptType: ScriptType, actionState: ActionState ) { super(); this.action = action; this.actionState = actionState; this.scriptType = scriptType; } getType() { return this.action.type; } getTagName() { return this.action.tagName; } getValue() { return this.action.value; } getInputType() { return this.action.inputType; } // (FIXME: shouldn't expose action) getAction() { return this.action; } getActionState() { return this.actionState; } getDescription() { const { type, selectors, tagName, value } = this.action; switch (type) { case ActionType.Click: return `Click on <${tagName.toLowerCase()}> ${ selectors.text != null && selectors.text.length > 0 ? `"${truncateText(selectors.text.replace(/\s/g, ' '), 25)}"` : getBestSelectorForAction(this.action, this.scriptType) }`; case ActionType.Hover: return `Hover over <${tagName.toLowerCase()}> ${ selectors.text != null && selectors.text.length > 0 ? `"${truncateText(selectors.text.replace(/\s/g, ' '), 25)}"` : getBestSelectorForAction(this.action, this.scriptType) }`; case ActionType.Input: return `Fill ${truncateText( JSON.stringify(value ?? ''), 16 )} on <${tagName.toLowerCase()}> ${getBestSelectorForAction( this.action, this.scriptType )}`; case ActionType.Keydown: return `Press ${this.action.key} on ${tagName.toLowerCase()}`; case ActionType.Load: return `Load "${this.action.url}"`; case ActionType.Resize: return `Resize window to ${this.action.width} x ${this.action.height}`; case ActionType.Wheel: return `Scroll wheel by X:${this.action.deltaX}, Y:${this.action.deltaY}`; case ActionType.FullScreenshot: return `Take full page screenshot`; case ActionType.AwaitText: return `Wait for text ${truncateText( JSON.stringify(this.action.text), 25 )} to appear`; case ActionType.DragAndDrop: return `Drag n drop ${getBestSelectorForAction( this.action, this.scriptType )} from (${this.action.sourceX}, ${this.action.sourceY}) to (${ this.action.targetX }, ${this.action.targetY})`; default: return ''; } } getBestSelector(): string | null { return getBestSelectorForAction(this.action, this.scriptType); } } export abstract class ScriptBuilder { protected readonly codes: string[]; protected readonly actionContexts: ActionContext[]; protected readonly showComments: boolean; constructor(showComments: boolean) { this.codes = []; this.actionContexts = []; this.showComments = showComments; } abstract click: (selector: string, causesNavigation: boolean) => this; abstract hover: (selector: string, causesNavigation: boolean) => this; abstract load: (url: string) => this; abstract resize: (width: number, height: number) => this; abstract fill: ( selector: string, value: string, causesNavigation: boolean ) => this; abstract type: ( selector: string, value: string, causesNavigation: boolean ) => this; abstract keydown: ( selector: string, key: string, causesNavigation: boolean ) => this; abstract select: ( selector: string, key: string, causesNavigation: boolean ) => this; abstract wheel: ( deltaX: number, deltaY: number, pageXOffset?: number, pageYOffset?: number ) => this; abstract dragAndDrop: ( sourceX: number, sourceY: number, targetX: number, targetY: number ) => this; abstract fullScreenshot: () => this; abstract awaitText: (test: string) => this; abstract buildScript: () => string; private transformActionIntoCodes = (actionContext: ActionContext) => { if (this.showComments) { const actionDescription = actionContext.getDescription(); this.pushComments(`// ${actionDescription}`); } const bestSelector = actionContext.getBestSelector(); const tagName = actionContext.getTagName(); const value = actionContext.getValue(); const inputType = actionContext.getInputType(); const { causesNavigation } = actionContext.getActionState(); // (FIXME: getters for special fields) const action: any = actionContext.getAction(); switch (actionContext.getType()) { case ActionType.Click: this.click(bestSelector as string, causesNavigation); break; case ActionType.Hover: this.hover(bestSelector as string, causesNavigation); break; case ActionType.Keydown: this.keydown( bestSelector as string, action.key ?? '', causesNavigation ); break; case ActionType.Input: { if (tagName === TagName.Select) { this.select(bestSelector as string, value ?? '', causesNavigation); } else if ( // If the input is "fillable" or a text area tagName === TagName.Input && inputType != null && FILLABLE_INPUT_TYPES.includes(inputType) ) { // Do more actionability checks this.fill(bestSelector as string, value ?? '', causesNavigation); } else if (tagName === TagName.TextArea) { this.fill(bestSelector as string, value ?? '', causesNavigation); } else { this.type(bestSelector as string, value ?? '', causesNavigation); } break; } case ActionType.Load: this.load(action.url); break; case ActionType.Resize: this.resize(action.width, action.height); break; case ActionType.Wheel: this.wheel( action.deltaX, action.deltaY, action.pageXOffset, action.pageYOffset ); break; case ActionType.FullScreenshot: this.fullScreenshot(); break; case ActionType.AwaitText: this.awaitText(action.text); break; case ActionType.DragAndDrop: this.dragAndDrop( action.sourceX, action.sourceY, action.targetX, action.targetY ); break; default: break; } }; protected pushComments = (comments: string) => { this.codes.push(`\n ${comments}`); return this; }; protected pushCodes = (codes: string) => { this.codes.push(`\n ${codes}\n`); return this; }; pushActionContext = (actionContext: ActionContext) => { this.actionContexts.push(actionContext); }; buildCodes = () => { let prevActionContext: ActionContext | undefined; for (const actionContext of this.actionContexts) { if (!actionContext.getActionState().isStateful) { if ( prevActionContext !== undefined && prevActionContext.getActionState().isStateful ) { this.transformActionIntoCodes(prevActionContext); } this.transformActionIntoCodes(actionContext); } prevActionContext = actionContext; } // edge case if ( prevActionContext !== undefined && prevActionContext.getActionState().isStateful ) { this.transformActionIntoCodes(prevActionContext); } return this; }; // for test getLatestCode = () => this.codes[this.codes.length - 1]; } export class PlaywrightScriptBuilder extends ScriptBuilder { private waitForNavigation() { return `page.waitForNavigation()`; } private waitForActionAndNavigation(action: string) { return `await Promise.all([\n ${action},\n ${this.waitForNavigation()}\n ]);`; } click = (selector: string, causesNavigation: boolean) => { const actionStr = `page.click('${selector}')`; const action = causesNavigation ? this.waitForActionAndNavigation(actionStr) : `await ${actionStr};`; this.pushCodes(action); return this; }; hover = (selector: string, causesNavigation: boolean) => { const actionStr = `page.hover('${selector}')`; const action = causesNavigation ? this.waitForActionAndNavigation(actionStr) : `await ${actionStr};`; this.pushCodes(action); return this; }; load = (url: string) => { this.pushCodes(`await page.goto('${url}');`); return this; }; resize = (width: number, height: number) => { this.pushCodes( `await page.setViewportSize({ width: ${width}, height: ${height} });` ); return this; }; fill = (selector: string, value: string, causesNavigation: boolean) => { const actionStr = `page.fill('${selector}', ${JSON.stringify(value)})`; const action = causesNavigation ? this.waitForActionAndNavigation(actionStr) : `await ${actionStr};`; this.pushCodes(action); return this; }; type = (selector: string, value: string, causesNavigation: boolean) => { const actionStr = `page.type('${selector}', ${JSON.stringify(value)})`; const action = causesNavigation ? this.waitForActionAndNavigation(actionStr) : `await ${actionStr};`; this.pushCodes(action); return this; }; select = (selector: string, option: string, causesNavigation: boolean) => { const actionStr = `page.selectOption('${selector}', '${option}')`; const action = causesNavigation ? this.waitForActionAndNavigation(actionStr) : `await ${actionStr};`; this.pushCodes(action); return this; }; keydown = (selector: string, key: string, causesNavigation: boolean) => { const actionStr = `page.press('${selector}', '${key}')`; const action = causesNavigation ? this.waitForActionAndNavigation(actionStr) : `await ${actionStr};`; this.pushCodes(action); return this; }; wheel = (deltaX: number, deltaY: number) => { this.pushCodes( `await page.mouse.wheel(${Math.floor(deltaX)}, ${Math.floor(deltaY)});` ); return this; }; fullScreenshot = () => { this.pushCodes( `await page.screenshot({ path: 'screenshot.png', fullPage: true });` ); return this; }; awaitText = (text: string) => { this.pushCodes(`await page.waitForSelector('text=${text}');`); return this; }; dragAndDrop = ( sourceX: number, sourceY: number, targetX: number, targetY: number ) => { this.pushCodes( [ `await page.mouse.move(${sourceX}, ${sourceY});`, ' await page.mouse.down();', ` await page.mouse.move(${targetX}, ${targetY});`, ' await page.mouse.up();', ].join('\n') ); return this; }; buildScript = () => { return `import { test, expect } from '@playwright/test'; test('Written with DeploySentinel Recorder', async ({ page }) => {${this.codes.join( '' )}});`; }; } export class PuppeteerScriptBuilder extends ScriptBuilder { private waitForSelector(selector: string) { return `page.waitForSelector('${selector}')`; } private waitForNavigation() { return `page.waitForNavigation()`; } private waitForSelectorAndNavigation(selector: string, action: string) { return `await ${this.waitForSelector( selector )};\n await Promise.all([\n ${action},\n ${this.waitForNavigation()}\n ]);`; } click = (selector: string, causesNavigation: boolean) => { const pageClick = `page.click('${selector}')`; if (causesNavigation) { this.pushCodes(this.waitForSelectorAndNavigation(selector, pageClick)); } else { this.pushCodes( `await ${this.waitForSelector(selector)};\n await ${pageClick};` ); } return this; }; hover = (selector: string, causesNavigation: boolean) => { const pageHover = `page.hover('${selector}')`; if (causesNavigation) { this.pushCodes(this.waitForSelectorAndNavigation(selector, pageHover)); } else { this.pushCodes( `await ${this.waitForSelector(selector)};\n await ${pageHover};` ); } return this; }; load = (url: string) => { this.pushCodes(`await page.goto('${url}');`); return this; }; resize = (width: number, height: number) => { this.pushCodes( `await page.setViewport({ width: ${width}, height: ${height} });` ); return this; }; type = (selector: string, value: string, causesNavigation: boolean) => { const pageType = `page.type('${selector}', ${JSON.stringify(value)})`; if (causesNavigation) { this.pushCodes(this.waitForSelectorAndNavigation(selector, pageType)); } else { this.pushCodes( `await ${this.waitForSelector(selector)};\n await ${pageType};` ); } return this; }; // Puppeteer doesn't support `fill` so we'll do our own actionability checks // but still type fill = (selector: string, value: string, causesNavigation: boolean) => { const pageType = `page.type('${selector}', ${JSON.stringify(value)})`; if (causesNavigation) { this.pushCodes( this.waitForSelectorAndNavigation( `${selector}:not([disabled])`, pageType ) ); } else { // Do more actionability checks this.pushCodes( `await ${this.waitForSelector( `${selector}:not([disabled])` )};\n await ${pageType};` ); } return this; }; select = (selector: string, option: string, causesNavigation: boolean) => { const pageSelectOption = `page.select('${selector}', '${option}')`; if (causesNavigation) { this.pushCodes( this.waitForSelectorAndNavigation(selector, pageSelectOption) ); } else { this.pushCodes( `await ${this.waitForSelector(selector)};\n await ${pageSelectOption};` ); } return this; }; keydown = (selector: string, key: string, causesNavigation: boolean) => { const pagePress = `page.keyboard.press('${key}')`; if (causesNavigation) { this.pushCodes(this.waitForSelectorAndNavigation(selector, pagePress)); } else { this.pushCodes( `await page.waitForSelector('${selector}');\n await page.keyboard.press('${key}');` ); } return this; }; wheel = (deltaX: number, deltaY: number) => { this.pushCodes( `await page.evaluate(() => window.scrollBy(${deltaX}, ${deltaY}));` ); return this; }; fullScreenshot = () => { this.pushCodes( `await page.screenshot({ path: 'screenshot.png', fullPage: true });` ); return this; }; awaitText = (text: string) => { this.pushCodes( `await page.waitForFunction("document.body.innerText.includes('${text}')");` ); return this; }; dragAndDrop = ( sourceX: number, sourceY: number, targetX: number, targetY: number ) => { this.pushCodes( [ `await page.mouse.move(${sourceX}, ${sourceY});`, ' await page.mouse.down();', ` await page.mouse.move(${targetX}, ${targetY});`, ' await page.mouse.up();', ].join('\n') ); return this; }; buildScript = () => { return `const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({ // headless: false, slowMo: 100, // Uncomment to visualize test }); const page = await browser.newPage(); ${this.codes.join('')} await browser.close(); })();`; }; } export class CypressScriptBuilder extends ScriptBuilder { // Cypress automatically detects and waits for the page to finish loading click = (selector: string, causesNavigation: boolean) => { this.pushCodes(`cy.get('${selector}').click();`); return this; }; hover = (selector: string, causesNavigation: boolean) => { this.pushCodes(`cy.get('${selector}').trigger('mouseover');`); return this; }; load = (url: string) => { this.pushCodes(`cy.visit('${url}');`); return this; }; resize = (width: number, height: number) => { this.pushCodes(`cy.viewport(${width}, ${height});`); return this; }; fill = (selector: string, value: string, causesNavigation: boolean) => { this.pushCodes(`cy.get('${selector}').type(${JSON.stringify(value)});`); return this; }; type = (selector: string, value: string, causesNavigation: boolean) => { this.pushCodes(`cy.get('${selector}').type(${JSON.stringify(value)});`); return this; }; select = (selector: string, option: string, causesNavigation: boolean) => { this.pushCodes(`cy.get('${selector}').select('${option}');`); return this; }; keydown = (selector: string, key: string, causesNavigation: boolean) => { this.pushCodes(`cy.get('${selector}').type('{${key}}');`); return this; }; wheel = ( deltaX: number, deltaY: number, pageXOffset?: number, pageYOffset?: number ) => { this.pushCodes( `cy.scrollTo(${Math.floor(pageXOffset ?? 0)}, ${Math.floor( pageYOffset ?? 0 )});` ); return this; }; fullScreenshot = () => { this.pushCodes(`cy.screenshot();`); return this; }; awaitText = (text: string) => { this.pushCodes(`cy.contains('${text}');`); return this; }; dragAndDrop = ( sourceX: number, sourceY: number, targetX: number, targetY: number ) => { // TODO -> IMPLEMENT ME this.pushCodes(''); return this; }; buildScript = () => { return `it('Written with DeploySentinel Recorder', () => {${this.codes.join( '' )}});`; }; } export const genCode = ( actions: Action[], showComments: boolean, scriptType: ScriptType ): string => { let scriptBuilder: ScriptBuilder; switch (scriptType) { case ScriptType.Playwright: scriptBuilder = new PlaywrightScriptBuilder(showComments); break; case ScriptType.Puppeteer: scriptBuilder = new PuppeteerScriptBuilder(showComments); break; case ScriptType.Cypress: scriptBuilder = new CypressScriptBuilder(showComments); break; default: throw new Error('Unsupported script type'); } for (let i = 0; i < actions.length; i++) { const action = actions[i]; if (!isSupportedActionType(action.type)) { continue; } const nextAction = actions[i + 1]; const causesNavigation = nextAction?.type === ActionType.Navigate; scriptBuilder.pushActionContext( new ActionContext(action, scriptType, { causesNavigation, isStateful: isActionStateful(action), }) ); } return scriptBuilder.buildCodes().buildScript(); };
the_stack
import { AppEncryptionBox, EncryptionBoxHandle, EncryptionBoxInfo, } from "@tonclient/core"; import { expect, test } from "../jest"; import { runner } from "../runner"; function text2base64(text: string): string { return Buffer.from(text, "utf8").toString("base64"); } // The "//-----" partitions are derived from TON-SDK/ton_client/src/crypto file structure test("crypto - encrypt large blocks", async () => { const client = runner.getClient(); const ourKeys = await client.crypto.nacl_box_keypair(); const theirKeys = await client.crypto.nacl_box_keypair(); async function testBuffer() { const nonce = Buffer.from((await client.crypto.generate_random_bytes({length: 24})).bytes, "base64").toString("hex"); const decrypted = (await client.crypto.generate_random_bytes({ // FIXME: length: 100000000, // 100 MB to many timeout length: 1000000, // 1 MB // @ts-ignore // TODO: response_binary_type: 'base64' | 'blob' | 'as_params' response_binary_type: 'blob' })).bytes; const encrypted = (await client.crypto.nacl_box({ decrypted: decrypted, secret: ourKeys.secret, their_public: theirKeys.public, nonce, })).encrypted; const decrypted2 = (await client.crypto.nacl_box_open({ encrypted, secret: theirKeys.secret, their_public: ourKeys.public, nonce, })).decrypted; if (typeof decrypted2 === 'string') { expect(decrypted2).toEqual(decrypted); } else { // Blob const hash = (await client.crypto.sha512({ data: decrypted, // @ts-ignore // TODO: response_binary_type: 'base64' | 'blob' | 'as_params' response_binary_type: 'base64' })).hash; const hash2 = (await client.crypto.sha512({ data: decrypted2, // @ts-ignore // TODO: response_binary_type: 'base64' | 'blob' | 'as_params' response_binary_type: 'base64' })).hash; expect(hash).toEqual(hash2); } } await Promise.all([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(_ => testBuffer())); }); test("crypto: factorize", async () => { const crypto = runner.getClient().crypto; const result = await crypto.factorize({composite: "17ED48941A08F981"}); expect(result.factors.length).toEqual(2); expect(result.factors[0]).toEqual("494C553B"); expect(result.factors[1]).toEqual("53911073"); }); test("crypto: modular_power", async () => { const crypto = runner.getClient().crypto; const result = await crypto.modular_power({ base: "0123456789ABCDEF", exponent: "0123", modulus: "01234567", }); expect(result.modular_power).toEqual("63bfdf"); }); test("crypto: ton_crc16", async () => { const crypto = runner.getClient().crypto; const result = await crypto.ton_crc16({ data: "RWFzdGVyIGVnZw==", }); expect(result.crc).toEqual(4743); }); test("crypto: generate_random_bytes", async () => { const crypto = runner.getClient().crypto; const result = await crypto.generate_random_bytes({length: 32}); const result2 = await crypto.generate_random_bytes({length: 32}); expect(result.bytes.length).toEqual(44); expect(result2.bytes.length).toEqual(44); expect(result).not.toEqual(result2); }); // ------------------------- keys ------------------------- test("crypto: convert_public_key_to_ton_safe_format", async () => { const crypto = runner.getClient().crypto; const result = await crypto.convert_public_key_to_ton_safe_format({ public_key: "5329c056c33e3a2a787bf2ae4c2afda87e4231898a5438e0cfd7a06dc4fac067", }); expect(result.ton_public_key).toEqual("PuZTKcBWwz46Knh78q5MKv2ofkIxiYpUOODP16BtxPrAZ_ed"); }); test("crypto: generate_random_sign_keys", async () => { const crypto = runner.getClient().crypto; const result = await crypto.generate_random_sign_keys(); const result2 = await crypto.generate_random_sign_keys(); expect(result.public.length).toEqual(64); expect(result.secret.length).toEqual(64); expect(result.public).not.toEqual(result.secret); expect(result2.public.length).toEqual(64); expect(result2.secret.length).toEqual(64); expect(result2.public).not.toEqual(result2.secret); expect(result.public).not.toEqual(result2.public); expect(result.secret).not.toEqual(result2.secret); }); test("crypto: sign", async () => { const crypto = runner.getClient().crypto; const result = await crypto.sign({ keys: { public: "bb3e649a4675cdb579803820a97dcba9594f1a1aefa7cb2b4da844ca9d32d348", secret: "52ae9e942cda06326de0905dea4d2c9c2fc7674f3fbd96495a5e92d099fc2507", }, unsigned: "RWFzdGVyIGVnZw==", }); expect(result).toEqual({ signed: "aTRQ4/TbSVcFHB096JpAxZOLwHjs3Sdf07gVVxPsV6csr/ChRoY48Ue9Z5eHzyRxwZZbHl6SYXwgTh0HI1HqB0Vhc3RlciBlZ2c=", signature: "693450e3f4db4957051c1d3de89a40c5938bc078ecdd275fd3b8155713ec57a72caff0a1468638f147bd679787cf2471c1965b1e5e92617c204e1d072351ea07", }); }); test("crypto: verify_signature", async () => { const crypto = runner.getClient().crypto; const result = await crypto.verify_signature({ public: "bb3e649a4675cdb579803820a97dcba9594f1a1aefa7cb2b4da844ca9d32d348", signed: "aTRQ4/TbSVcFHB096JpAxZOLwHjs3Sdf07gVVxPsV6csr/ChRoY48Ue9Z5eHzyRxwZZbHl6SYXwgTh0HI1HqB0Vhc3RlciBlZ2c=", }); expect(result.unsigned).toEqual("RWFzdGVyIGVnZw=="); }); // ------------------------- hash ------------------------- test("crypto: sha256", async () => { const crypto = runner.getClient().crypto; const result = await crypto.sha256({ data: text2base64("Message to hash with sha 256"), }); expect(result.hash).toEqual("16fd057308dd358d5a9b3ba2de766b2dfd5e308478fc1f7ba5988db2493852f5"); }); test("crypto: sha512", async () => { const crypto = runner.getClient().crypto; const result = await crypto.sha512({ data: text2base64("Message to hash with sha 512"), }); expect(result.hash) .toEqual( "2616a44e0da827f0244e93c2b0b914223737a6129bc938b8edf2780ac9482960baa9b7c7cdb11457c1cebd5ae77e295ed94577f32d4c963dc35482991442daa5"); }); // ------------------------- scrypt ------------------------- test("crypto: scrypt", async () => { const crypto = runner.getClient().crypto; let result = await crypto.scrypt({ password: text2base64("Test Password"), salt: text2base64("Test Salt"), log_n: 10, r: 8, p: 16, dk_len: 64, }); expect(result.key) .toEqual( "52e7fcf91356eca55fc5d52f16f5d777e3521f54e3c570c9bbb7df58fc15add73994e5db42be368de7ebed93c9d4f21f9be7cc453358d734b04a057d0ed3626d"); }); // ------------------------- nacl ------------------------- test("crypto: nacl_sign_keypair_from_secret_key", async () => { const crypto = runner.getClient().crypto; const result = await crypto.nacl_sign_keypair_from_secret_key({ secret: "56b6a77093d6fdf14e593f36275d872d75de5b341942376b2a08759f3cbae78f", }); expect(result).toEqual({ public: "1869b7ef29d58026217e9cf163cbfbd0de889bdf1bf4daebf5433a312f5b8d6e", secret: "56b6a77093d6fdf14e593f36275d872d75de5b341942376b2a08759f3cbae78f1869b7ef29d58026217e9cf163cbfbd0de889bdf1bf4daebf5433a312f5b8d6e", }); }); test("crypto: nacl_sign", async () => { const crypto = runner.getClient().crypto; const result = await crypto.nacl_sign({ unsigned: text2base64("Test Message"), secret: "56b6a77093d6fdf14e593f36275d872d75de5b341942376b2a08759f3cbae78f1869b7ef29d58026217e9cf163cbfbd0de889bdf1bf4daebf5433a312f5b8d6e", }); expect(result.signed).toEqual("+wz+QO6l1slgZS5s65BNqKcu4vz24FCJz4NSAxef9lu0jFfs8x3PzSZRC+pn5k8+aJi3xYMA3BQzglQmjK3hA1Rlc3QgTWVzc2FnZQ=="); }); test("crypto: nacl_sign_open", async () => { const crypto = runner.getClient().crypto; const result = await crypto.nacl_sign_open({ signed: "+wz+QO6l1slgZS5s65BNqKcu4vz24FCJz4NSAxef9lu0jFfs8x3PzSZRC+pn5k8+aJi3xYMA3BQzglQmjK3hA1Rlc3QgTWVzc2FnZQ==", public: "1869b7ef29d58026217e9cf163cbfbd0de889bdf1bf4daebf5433a312f5b8d6e", }); expect(result.unsigned).toEqual(text2base64("Test Message")); }); test("crypto: nacl_sign_detached", async () => { const crypto = runner.getClient().crypto; const sign = await crypto.nacl_sign_detached({ unsigned: text2base64("Test Message"), secret: "56b6a77093d6fdf14e593f36275d872d75de5b341942376b2a08759f3cbae78f1869b7ef29d58026217e9cf163cbfbd0de889bdf1bf4daebf5433a312f5b8d6e", }); expect(sign.signature) .toEqual( "fb0cfe40eea5d6c960652e6ceb904da8a72ee2fcf6e05089cf835203179ff65bb48c57ecf31dcfcd26510bea67e64f3e6898b7c58300dc14338254268cade103"); }); test("crypto: nacl_sign_detached_verify success", async () => { const crypto = runner.getClient().crypto; const result = await crypto.nacl_sign_detached_verify({ public: "1869b7ef29d58026217e9cf163cbfbd0de889bdf1bf4daebf5433a312f5b8d6e", signature: "fb0cfe40eea5d6c960652e6ceb904da8a72ee2fcf6e05089cf835203179ff65bb48c57ecf31dcfcd26510bea67e64f3e6898b7c58300dc14338254268cade103", unsigned: text2base64("Test Message"), }); expect(result.succeeded).toBeTruthy(); }); test("crypto: nacl_sign_detached_verify failure", async () => { const crypto = runner.getClient().crypto; const result = await crypto.nacl_sign_detached_verify({ public: "2869b7ef29d58026217e9cf163cbfbd0de889bdf1bf4daebf5433a312f5b8d6e", signature: "fb0cfe40eea5d6c960652e6ceb904da8a72ee2fcf6e05089cf835203179ff65bb48c57ecf31dcfcd26510bea67e64f3e6898b7c58300dc14338254268cade103", unsigned: text2base64("Test Message") }); expect(result.succeeded).toBeFalsy(); }); test("crypto: nacl_box_keypair", async () => { const crypto = runner.getClient().crypto; const result = await crypto.nacl_box_keypair(); const result2 = await crypto.nacl_box_keypair(); expect(result.public.length).toEqual(64); expect(result.secret.length).toEqual(64); expect(result.public) .toEqual( (await crypto.nacl_box_keypair_from_secret_key({ secret: result.secret })).public); expect(result2.public.length).toEqual(64); expect(result2.secret.length).toEqual(64); expect(result2.public) .toEqual( (await crypto.nacl_box_keypair_from_secret_key({ secret: result2.secret })).public); expect(result.public).not.toEqual(result2.public); expect(result.secret).not.toEqual(result2.secret); }); test("crypto: nacl_box_keypair_from_secret_key", async () => { const crypto = runner.getClient().crypto; const result = await crypto.nacl_box_keypair_from_secret_key({ secret: "e207b5966fb2c5be1b71ed94ea813202706ab84253bdf4dc55232f82a1caf0d4" }); expect(result).toEqual({ public: "a53b003d3ffc1e159355cb37332d67fc235a7feb6381e36c803274074dc3933a", secret: "e207b5966fb2c5be1b71ed94ea813202706ab84253bdf4dc55232f82a1caf0d4", }); }); test("crypto: nacl_box", async () => { const crypto = runner.getClient().crypto; const encrypted1 = await crypto.nacl_box({ decrypted: text2base64("Test Message"), nonce: "cd7f99924bf422544046e83595dd5803f17536f5c9a11746", their_public: "c4e2d9fe6a6baf8d1812b799856ef2a306291be7a7024837ad33a8530db79c6b", secret: "d9b9dc5033fb416134e5d2107fdbacab5aadb297cb82dbdcd137d663bac59f7f", }); expect(encrypted1.encrypted).toEqual("li4XED4kx/pjQ2qdP0eR2d/K30uN94voNADxwA=="); }); test("crypto: nacl_box_open", async () => { const crypto = runner.getClient().crypto; const keysA = await crypto.nacl_box_keypair(); const keysB = await crypto.nacl_box_keypair(); const encrypted = await crypto.nacl_box({ secret: keysA.secret, their_public: keysB.public, nonce: "cd7f99924bf422544046e83595dd5803f17536f5c9a11746", decrypted: "AQID", }); const decryptedA = await crypto.nacl_box_open({ secret: keysA.secret, their_public: keysB.public, nonce: "cd7f99924bf422544046e83595dd5803f17536f5c9a11746", encrypted: encrypted.encrypted, }); const decryptedB = await crypto.nacl_box_open({ secret: keysB.secret, their_public: keysA.public, nonce: "cd7f99924bf422544046e83595dd5803f17536f5c9a11746", encrypted: encrypted.encrypted, }); expect(decryptedA.decrypted).toEqual("AQID"); expect(decryptedB.decrypted).toEqual("AQID"); }); test("crypto: nacl_secret_box", async () => { const crypto = runner.getClient().crypto; const result = await crypto.nacl_secret_box({ decrypted: text2base64("Test Message"), nonce: "2a33564717595ebe53d91a785b9e068aba625c8453a76e45", key: "8f68445b4e78c000fe4d6b7fc826879c1e63e3118379219a754ae66327764bd8", }); expect(result.encrypted).toEqual("JL7ejKWe2KXmrsns41yfXoQF0t/C1Q8RGyzQ2A=="); }); test("crypto: nacl_secret_box_open", async () => { const crypto = runner.getClient().crypto; const result = await crypto.nacl_box_open({ encrypted: "li4XED4kx/pjQ2qdP0eR2d/K30uN94voNADxwA==", nonce: "cd7f99924bf422544046e83595dd5803f17536f5c9a11746", their_public: "c4e2d9fe6a6baf8d1812b799856ef2a306291be7a7024837ad33a8530db79c6b", secret: "d9b9dc5033fb416134e5d2107fdbacab5aadb297cb82dbdcd137d663bac59f7f", }); expect(result.decrypted).toEqual(text2base64("Test Message")); }); test("crypto: nacl_secret_box and nacl_secret_box_open with ' and \" and : {} in the text", async () => { const crypto = runner.getClient().crypto; const box = await crypto.nacl_secret_box({ decrypted: text2base64("Text with ' and \" and : {}"), nonce: "2a33564717595ebe53d91a785b9e068aba625c8453a76e45", key: "8f68445b4e78c000fe4d6b7fc826879c1e63e3118379219a754ae66327764bd8", }); const result = await crypto.nacl_secret_box_open({ encrypted: box.encrypted, nonce: "2a33564717595ebe53d91a785b9e068aba625c8453a76e45", key: "8f68445b4e78c000fe4d6b7fc826879c1e63e3118379219a754ae66327764bd8", }); expect(result.decrypted).toEqual("VGV4dCB3aXRoICcgYW5kICIgYW5kIDoge30="); expect(result.decrypted).toEqual(text2base64("Text with ' and \" and : {}")); }); // ------------------------- mnemonic ------------------------- test("crypto: mnemonic_words", async () => { const crypto = runner.getClient().crypto; const result = await crypto.mnemonic_words({}); expect(result.words.split(" ").length).toEqual(2048); expect(result.words) .toEqual( "abandon ability able about above absent absorb abstract absurd abuse access accident account accuse achieve acid acoustic acquire across " + "act action actor actress actual adapt add addict address adjust admit adult advance advice aerobic affair afford afraid again age agent " + "agree ahead aim air airport aisle alarm album alcohol alert alien all alley allow almost alone alpha already also alter always amateur " + "amazing among amount amused analyst anchor ancient anger angle angry animal ankle announce annual another answer antenna antique anxiety " + "any apart apology appear apple approve april arch arctic area arena argue arm armed armor army around arrange arrest arrive arrow art " + "artefact artist artwork ask aspect assault asset assist assume asthma athlete atom attack attend attitude attract auction audit august " + "aunt author auto autumn average avocado avoid awake aware away awesome awful awkward axis baby bachelor bacon badge bag balance balcony " + "ball bamboo banana banner bar barely bargain barrel base basic basket battle beach bean beauty because become beef before begin behave " + "behind believe below belt bench benefit best betray better between beyond bicycle bid bike bind biology bird birth bitter black blade " + "blame blanket blast bleak bless blind blood blossom blouse blue blur blush board boat body boil bomb bone bonus book boost border boring " + "borrow boss bottom bounce box boy bracket brain brand brass brave bread breeze brick bridge brief bright bring brisk broccoli broken " + "bronze broom brother brown brush bubble buddy budget buffalo build bulb bulk bullet bundle bunker burden burger burst bus business busy " + "butter buyer buzz cabbage cabin cable cactus cage cake call calm camera camp can canal cancel candy cannon canoe canvas canyon capable " + "capital captain car carbon card cargo carpet carry cart case cash casino castle casual cat catalog catch category cattle caught cause " + "caution cave ceiling celery cement census century cereal certain chair chalk champion change chaos chapter charge chase chat cheap check " + "cheese chef cherry chest chicken chief child chimney choice choose chronic chuckle chunk churn cigar cinnamon circle citizen city civil " + "claim clap clarify claw clay clean clerk clever click client cliff climb clinic clip clock clog close cloth cloud clown club clump " + "cluster clutch coach coast coconut code coffee coil coin collect color column combine come comfort comic common company concert conduct " + "confirm congress connect consider control convince cook cool copper copy coral core corn correct cost cotton couch country couple course " + "cousin cover coyote crack cradle craft cram crane crash crater crawl crazy cream credit creek crew cricket crime crisp critic crop cross " + "crouch crowd crucial cruel cruise crumble crunch crush cry crystal cube culture cup cupboard curious current curtain curve cushion " + "custom cute cycle dad damage damp dance danger daring dash daughter dawn day deal debate debris decade december decide decline decorate " + "decrease deer defense define defy degree delay deliver demand demise denial dentist deny depart depend deposit depth deputy derive " + "describe desert design desk despair destroy detail detect develop device devote diagram dial diamond diary dice diesel diet differ " + "digital dignity dilemma dinner dinosaur direct dirt disagree discover disease dish dismiss disorder display distance divert divide " + "divorce dizzy doctor document dog doll dolphin domain donate donkey donor door dose double dove draft dragon drama drastic draw dream " + "dress drift drill drink drip drive drop drum dry duck dumb dune during dust dutch duty dwarf dynamic eager eagle early earn earth easily " + "east easy echo ecology economy edge edit educate effort egg eight either elbow elder electric elegant element elephant elevator elite " + "else embark embody embrace emerge emotion employ empower empty enable enact end endless endorse enemy energy enforce engage engine " + "enhance enjoy enlist enough enrich enroll ensure enter entire entry envelope episode equal equip era erase erode erosion error erupt " + "escape essay essence estate eternal ethics evidence evil evoke evolve exact example excess exchange excite exclude excuse execute " + "exercise exhaust exhibit exile exist exit exotic expand expect expire explain expose express extend extra eye eyebrow fabric face " + "faculty fade faint faith fall false fame family famous fan fancy fantasy farm fashion fat fatal father fatigue fault favorite feature " + "february federal fee feed feel female fence festival fetch fever few fiber fiction field figure file film filter final find fine finger " + "finish fire firm first fiscal fish fit fitness fix flag flame flash flat flavor flee flight flip float flock floor flower fluid flush " + "fly foam focus fog foil fold follow food foot force forest forget fork fortune forum forward fossil foster found fox fragile frame " + "frequent fresh friend fringe frog front frost frown frozen fruit fuel fun funny furnace fury future gadget gain galaxy gallery game gap " + "garage garbage garden garlic garment gas gasp gate gather gauge gaze general genius genre gentle genuine gesture ghost giant gift giggle " + "ginger giraffe girl give glad glance glare glass glide glimpse globe gloom glory glove glow glue goat goddess gold good goose gorilla " + "gospel gossip govern gown grab grace grain grant grape grass gravity great green grid grief grit grocery group grow grunt guard guess " + "guide guilt guitar gun gym habit hair half hammer hamster hand happy harbor hard harsh harvest hat have hawk hazard head health heart " + "heavy hedgehog height hello helmet help hen hero hidden high hill hint hip hire history hobby hockey hold hole holiday hollow home honey " + "hood hope horn horror horse hospital host hotel hour hover hub huge human humble humor hundred hungry hunt hurdle hurry hurt husband " + "hybrid ice icon idea identify idle ignore ill illegal illness image imitate immense immune impact impose improve impulse inch include " + "income increase index indicate indoor industry infant inflict inform inhale inherit initial inject injury inmate inner innocent input " + "inquiry insane insect inside inspire install intact interest into invest invite involve iron island isolate issue item ivory jacket " + "jaguar jar jazz jealous jeans jelly jewel job join joke journey joy judge juice jump jungle junior junk just kangaroo keen keep ketchup " + "key kick kid kidney kind kingdom kiss kit kitchen kite kitten kiwi knee knife knock know lab label labor ladder lady lake lamp language " + "laptop large later latin laugh laundry lava law lawn lawsuit layer lazy leader leaf learn leave lecture left leg legal legend leisure " + "lemon lend length lens leopard lesson letter level liar liberty library license life lift light like limb limit link lion liquid list " + "little live lizard load loan lobster local lock logic lonely long loop lottery loud lounge love loyal lucky luggage lumber lunar lunch " + "luxury lyrics machine mad magic magnet maid mail main major make mammal man manage mandate mango mansion manual maple marble march " + "margin marine market marriage mask mass master match material math matrix matter maximum maze meadow mean measure meat mechanic medal " + "media melody melt member memory mention menu mercy merge merit merry mesh message metal method middle midnight milk million mimic mind " + "minimum minor minute miracle mirror misery miss mistake mix mixed mixture mobile model modify mom moment monitor monkey monster month " + "moon moral more morning mosquito mother motion motor mountain mouse move movie much muffin mule multiply muscle museum mushroom music " + "must mutual myself mystery myth naive name napkin narrow nasty nation nature near neck need negative neglect neither nephew nerve nest " + "net network neutral never news next nice night noble noise nominee noodle normal north nose notable note nothing notice novel now " + "nuclear number nurse nut oak obey object oblige obscure observe obtain obvious occur ocean october odor off offer office often oil okay " + "old olive olympic omit once one onion online only open opera opinion oppose option orange orbit orchard order ordinary organ orient " + "original orphan ostrich other outdoor outer output outside oval oven over own owner oxygen oyster ozone pact paddle page pair palace " + "palm panda panel panic panther paper parade parent park parrot party pass patch path patient patrol pattern pause pave payment peace " + "peanut pear peasant pelican pen penalty pencil people pepper perfect permit person pet phone photo phrase physical piano picnic picture " + "piece pig pigeon pill pilot pink pioneer pipe pistol pitch pizza place planet plastic plate play please pledge pluck plug plunge poem " + "poet point polar pole police pond pony pool popular portion position possible post potato pottery poverty powder power practice praise " + "predict prefer prepare present pretty prevent price pride primary print priority prison private prize problem process produce profit " + "program project promote proof property prosper protect proud provide public pudding pull pulp pulse pumpkin punch pupil puppy purchase " + "purity purpose purse push put puzzle pyramid quality quantum quarter question quick quit quiz quote rabbit raccoon race rack radar radio " + "rail rain raise rally ramp ranch random range rapid rare rate rather raven raw razor ready real reason rebel rebuild recall receive " + "recipe record recycle reduce reflect reform refuse region regret regular reject relax release relief rely remain remember remind remove " + "render renew rent reopen repair repeat replace report require rescue resemble resist resource response result retire retreat return " + "reunion reveal review reward rhythm rib ribbon rice rich ride ridge rifle right rigid ring riot ripple risk ritual rival river road " + "roast robot robust rocket romance roof rookie room rose rotate rough round route royal rubber rude rug rule run runway rural sad saddle " + "sadness safe sail salad salmon salon salt salute same sample sand satisfy satoshi sauce sausage save say scale scan scare scatter scene " + "scheme school science scissors scorpion scout scrap screen script scrub sea search season seat second secret section security seed seek " + "segment select sell seminar senior sense sentence series service session settle setup seven shadow shaft shallow share shed shell " + "sheriff shield shift shine ship shiver shock shoe shoot shop short shoulder shove shrimp shrug shuffle shy sibling sick side siege sight " + "sign silent silk silly silver similar simple since sing siren sister situate six size skate sketch ski skill skin skirt skull slab slam " + "sleep slender slice slide slight slim slogan slot slow slush small smart smile smoke smooth snack snake snap sniff snow soap soccer " + "social sock soda soft solar soldier solid solution solve someone song soon sorry sort soul sound soup source south space spare spatial " + "spawn speak special speed spell spend sphere spice spider spike spin spirit split spoil sponsor spoon sport spot spray spread spring spy " + "square squeeze squirrel stable stadium staff stage stairs stamp stand start state stay steak steel stem step stereo stick still sting " + "stock stomach stone stool story stove strategy street strike strong struggle student stuff stumble style subject submit subway success " + "such sudden suffer sugar suggest suit summer sun sunny sunset super supply supreme sure surface surge surprise surround survey suspect " + "sustain swallow swamp swap swarm swear sweet swift swim swing switch sword symbol symptom syrup system table tackle tag tail talent talk " + "tank tape target task taste tattoo taxi teach team tell ten tenant tennis tent term test text thank that theme then theory there they " + "thing this thought three thrive throw thumb thunder ticket tide tiger tilt timber time tiny tip tired tissue title toast tobacco today " + "toddler toe together toilet token tomato tomorrow tone tongue tonight tool tooth top topic topple torch tornado tortoise toss total " + "tourist toward tower town toy track trade traffic tragic train transfer trap trash travel tray treat tree trend trial tribe trick " + "trigger trim trip trophy trouble truck true truly trumpet trust truth try tube tuition tumble tuna tunnel turkey turn turtle twelve " + "twenty twice twin twist two type typical ugly umbrella unable unaware uncle uncover under undo unfair unfold unhappy uniform unique unit " + "universe unknown unlock until unusual unveil update upgrade uphold upon upper upset urban urge usage use used useful useless usual " + "utility vacant vacuum vague valid valley valve van vanish vapor various vast vault vehicle velvet vendor venture venue verb verify " + "version very vessel veteran viable vibrant vicious victory video view village vintage violin virtual virus visa visit visual vital vivid " + "vocal voice void volcano volume vote voyage wage wagon wait walk wall walnut want warfare warm warrior wash wasp waste water wave way " + "wealth weapon wear weasel weather web wedding weekend weird welcome west wet whale what wheat wheel when where whip whisper wide width " + "wife wild will win window wine wing wink winner winter wire wisdom wise wish witness wolf woman wonder wood wool word work world worry " + "worth wrap wreck wrestle wrist write wrong yard year yellow you young youth zebra zero zone zoo"); }); const mnemonicWordCount = [12, 15, 18, 21, 24]; const mnemonicDictionary = [0, 1, 2, 3, 4, 5, 6, 7, 8]; test("crypto: mnemonic_from_random", async () => { const crypto = runner.getClient().crypto; let phrase = await crypto.mnemonic_from_random({}); expect(phrase.phrase.split(" ").length).toEqual(12); for (const dictionary of mnemonicDictionary) { for (const word_count of mnemonicWordCount) { expect((await crypto.mnemonic_from_random({ dictionary, word_count, })).phrase.split(" ").length).toEqual(word_count); } } }); test("crypto: mnemonic_from_entropy", async () => { const crypto = runner.getClient().crypto; const result = await crypto.mnemonic_from_entropy({ entropy: "00112233445566778899AABBCCDDEEFF", dictionary: 1, word_count: 12, }); expect(result.phrase) .toEqual("abandon math mimic master filter design carbon crystal rookie group knife young"); }); test("crypto: mnemonic_verify", async () => { const crypto = runner.getClient().crypto; for (const dictionary of mnemonicDictionary) { for (const word_count of mnemonicWordCount) { expect((await crypto.mnemonic_verify({ dictionary, word_count, phrase: (await crypto.mnemonic_from_random({ dictionary, word_count, })).phrase, })).valid).toBeTruthy(); } } expect((await crypto.mnemonic_verify({ phrase: "one two" })).valid).toBeFalsy(); }); test("crypto: mnemonic_derive_sign_keys", async () => { const crypto = runner.getClient().crypto; const keys = await crypto.mnemonic_derive_sign_keys({ phrase: "unit follow zone decline glare flower crisp vocal adapt magic much mesh cherry teach mechanic rain float vicious solution assume hedgehog rail sort chuckle", dictionary: 0, word_count: 24, }); expect(keys).toEqual({ public: "13bc2b9ffff617869fb88efdd35d31cbd222bae489b0c46d111ab61cd6c3f71f", secret: "a32820391c3fc73ad9d145f9b269f7d93c93dd91ec70f1930b616e63db0ae7ff" }); }); test("crypto: entropy->mnemonic->ton_public_key test", async () => { const crypto = runner.getClient().crypto; const entropy = "2199ebe996f14d9e4e2595113ad1e627"; const phrase = await crypto.mnemonic_from_entropy({ entropy }); const public2 = (await crypto.mnemonic_derive_sign_keys({ phrase: phrase.phrase })).public; const ton_public = await crypto.convert_public_key_to_ton_safe_format({ public_key: public2 }); expect(ton_public.ton_public_key).toEqual("PuZdw_KyXIzo8IksTrERN3_WoAoYTyK7OvM-yaLk711sUIB3"); }); // ------------------------- hdkey ------------------------- test("crypto: hdkey_xprv_from_mnemonic", async () => { const crypto = runner.getClient().crypto; const result = await crypto.hdkey_xprv_from_mnemonic({ dictionary: 1, word_count: 12, phrase: "abuse boss fly battle rubber wasp afraid hamster guide essence vibrant tattoo", }); expect(result.xprv) .toEqual( "xprv9s21ZrQH143K25JhKqEwvJW7QAiVvkmi4WRenBZanA6kxHKtKAQQKwZG65kCyW5jWJ8NY9e3GkRoistUjjcpHNsGBUv94istDPXvqGNuWpC"); }); test("crypto: hdkey_secret_from_xprv", async () => { const crypto = runner.getClient().crypto; const result = await crypto.hdkey_secret_from_xprv({ xprv: "xprv9s21ZrQH143K25JhKqEwvJW7QAiVvkmi4WRenBZanA6kxHKtKAQQKwZG65kCyW5jWJ8NY9e3GkRoistUjjcpHNsGBUv94istDPXvqGNuWpC", }); expect(result.secret).toEqual("0c91e53128fa4d67589d63a6c44049c1068ec28a63069a55ca3de30c57f8b365"); }); test("crypto: hdkey_public_from_xprv", async () => { const crypto = runner.getClient().crypto; const result = await crypto.hdkey_public_from_xprv({ xprv: "xprv9s21ZrQH143K25JhKqEwvJW7QAiVvkmi4WRenBZanA6kxHKtKAQQKwZG65kCyW5jWJ8NY9e3GkRoistUjjcpHNsGBUv94istDPXvqGNuWpC", }); expect(result.public).toEqual("7b70008d0c40992283d488b1046739cf827afeabf647a5f07c4ad1e7e45a6f89"); }); test("crypto: hdkey_derive_from_xprv", async () => { const crypto = runner.getClient().crypto; const result = await crypto.hdkey_derive_from_xprv({ xprv: "xprv9s21ZrQH143K25JhKqEwvJW7QAiVvkmi4WRenBZanA6kxHKtKAQQKwZG65kCyW5jWJ8NY9e3GkRoistUjjcpHNsGBUv94istDPXvqGNuWpC", child_index: 0, hardened: false, }); expect(result.xprv) .toEqual( "xprv9uZwtSeoKf1swgAkVVCEUmC2at6t7MCJoHnBbn1MWJZyxQ4cySkVXPyNh7zjf9VjsP4vEHDDD2a6R35cHubg4WpzXRzniYiy8aJh1gNnBKv"); expect((await crypto.hdkey_secret_from_xprv({xprv: result.xprv})).secret) .toEqual("518afc6489b61d4b738ee9ad9092815fa014ffa6e9a280fa17f84d95f31adb91"); expect((await crypto.hdkey_public_from_xprv({xprv: result.xprv})).public) .toEqual("b45e1297a5e767341a6eaaac9e20f8ccd7556a0106298316f1272e461b6fbe98"); }); test("crypto: hdkey_derive_from_xprv_path", async () => { const crypto = runner.getClient().crypto; const result = await crypto.hdkey_derive_from_xprv_path({ xprv: "xprv9s21ZrQH143K25JhKqEwvJW7QAiVvkmi4WRenBZanA6kxHKtKAQQKwZG65kCyW5jWJ8NY9e3GkRoistUjjcpHNsGBUv94istDPXvqGNuWpC", path: "m/44'/60'/0'/0'", }); expect(result.xprv) .toEqual( "xprvA1KNMo63UcGjmDF1bX39Cw2BXGUwrwMjeD5qvQ3tA3qS3mZQkGtpf4DHq8FDLKAvAjXsYGLHDP2dVzLu9ycta8PXLuSYib2T3vzLf3brVgZ"); expect((await crypto.hdkey_secret_from_xprv({xprv: result.xprv})).secret) .toEqual("1c566ade41169763b155761406d3cef08b29b31cf8014f51be08c0cb4e67c5e1"); expect((await crypto.hdkey_public_from_xprv({xprv: result.xprv})).public) .toEqual("302a832bad9e5c9906422a82c28b39ae465dcd60178480f7309e183ee34b5e83"); }); // ------------------------- encryption ------------------------- test("crypto: chacha20", async () => { const crypto = runner.getClient().crypto; const params = { key: "01".repeat(32), nonce: "ff".repeat(12), data: text2base64("Message"), }; const encrypted = await crypto.chacha20(params); const decrypted = await crypto.chacha20({ ...params, data: encrypted.data }); expect(encrypted.data).toEqual("w5QOGsJodQ=="); expect(decrypted.data).toEqual(text2base64("Message")); }); // ------------------------- boxes ------------------------- test("crypto: signing_box default", async () => { const crypto = runner.getClient().crypto; const keys = { public: "0335e912a6dc50b5727d332aa389d2aeff86c7b7ae5b6483bb0e425f41ee42c0", secret: "6d33449a8b5aeff942789ea69574e8254a52688a3f570590933177b8cbe2b82c", }; const signing_box = await crypto.get_signing_box(keys); const getPublicKeyResult = await crypto.signing_box_get_public_key(signing_box); expect(getPublicKeyResult.pubkey).toEqual(keys.public); const signResult = await crypto.signing_box_sign({ signing_box: signing_box.handle, unsigned: "" }); expect(signResult.signature) .toEqual( "b254a6c54f48790b039bb5621950a11ca9cfc681d685ed019e6826fdbea3ad21c0e92f667d8270b2ba27fcb5fb57991a2c3bb9ced69fc6893aa1e22bd694fa0c"); }); test("crypto: signing_box custom", async () => { const crypto = runner.getClient().crypto; const keys = { public: "0335e912a6dc50b5727d332aa389d2aeff86c7b7ae5b6483bb0e425f41ee42c0", secret: "6d33449a8b5aeff942789ea69574e8254a52688a3f570590933177b8cbe2b82c", }; const signing_box = await crypto.register_signing_box({ get_public_key: () => Promise.resolve({ public_key: keys.public }), sign: async (params) => await crypto.sign({ keys, unsigned: params.unsigned }), }); const getPublicKeyResult = await crypto.signing_box_get_public_key(signing_box); expect(getPublicKeyResult.pubkey).toEqual(keys.public); const signResult = await crypto.signing_box_sign({ signing_box: signing_box.handle, unsigned: text2base64("abc") }); expect(signResult.signature).toEqual((await crypto.sign({keys, unsigned: text2base64("abc") })).signature); }); test("crypto: external encryption box (register_encryption_box, encryption_box_get_info, encryption_box_encrypt, encryption_box_decrypt)", async () => { const crypto = runner.getClient().crypto; const encryption_box: AppEncryptionBox = { get_info: async () => { return { info: { algorithm: "duplicator", } }; }, encrypt: async (params) => { return { data: params.data + params.data, }; }, decrypt: async (params) => { return { data: params.data.substr(0, params.data.length / 2), } } }; const handle: EncryptionBoxHandle = (await crypto.register_encryption_box(encryption_box)).handle; const info: EncryptionBoxInfo = (await crypto.encryption_box_get_info({ encryption_box: handle, })).info; expect(info.algorithm).toEqual("duplicator"); const encrypted: string = (await crypto.encryption_box_encrypt({ encryption_box: handle, data: "12345", })).data; expect(encrypted).toEqual("1234512345"); const decrypted: string = (await crypto.encryption_box_decrypt({ encryption_box: handle, data: encrypted, })).data; expect(decrypted).toEqual("12345"); }); // ------------------------- ---- ------------------------- // Intentionally disabled (was created for react-native, shouldn't go to the master branch) test.skip("crypto: encrypt large blocks", async () => { const client = runner.getClient(); const ourKeys = await client.crypto.nacl_box_keypair(); const theirKeys = await client.crypto.nacl_box_keypair(); async function testBuffer() { const nonce = Buffer.from((await client.crypto.generate_random_bytes({length: 24})).bytes, "base64").toString("hex"); const decrypted = (await client.crypto.generate_random_bytes({ length: 100000000, // 100 MB // @ts-ignore // TODO: response_binary_type: 'base64' | 'blob' | 'as_params' response_binary_type: 'blob' })).bytes; const encrypted = (await client.crypto.nacl_box({ decrypted: decrypted, secret: ourKeys.secret, their_public: theirKeys.public, nonce, })).encrypted; const decrypted2 = (await client.crypto.nacl_box_open({ encrypted, secret: theirKeys.secret, their_public: ourKeys.public, nonce, })).decrypted; if (typeof decrypted2 === 'string') { expect(decrypted2).toEqual(decrypted); } else { // Blob const hash = (await client.crypto.sha512({ data: decrypted, // @ts-ignore // TODO: response_binary_type: 'base64' | 'blob' | 'as_params' response_binary_type: 'base64' })).hash; const hash2 = (await client.crypto.sha512({ data: decrypted2, // @ts-ignore // TODO: response_binary_type: 'base64' | 'blob' | 'as_params' response_binary_type: 'base64' })).hash; expect(hash).toEqual(hash2); } } await Promise.all([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(_ => testBuffer())); });
the_stack
import fs = require('fs'); import path = require('path'); import os = require('os'); import { BufferWriter } from './writer/bufferstream'; class DirentFromStat extends (fs.Dirent || class{}) { constructor(name:string, private readonly stat:fs.Stats) { super(); this.name = name; } isFile(): boolean { return this.stat.isFile(); } isDirectory(): boolean{ return this.stat.isDirectory(); } isBlockDevice(): boolean{ return this.stat.isBlockDevice(); } isCharacterDevice(): boolean{ return this.stat.isCharacterDevice(); } isSymbolicLink(): boolean{ return this.stat.isSymbolicLink(); } isFIFO(): boolean{ return this.stat.isFIFO(); } isSocket(): boolean{ return this.stat.isSocket(); } } export namespace fsutil { export const projectPath = path.resolve(process.cwd(), process.argv[1]); /** @deprecated use fsutil.projectPath */ export function getProjectPath():string { return projectPath; } export function isDirectory(filepath:string):Promise<boolean> { return new Promise((resolve, reject)=>{ fs.stat(filepath, (err, stat)=>{ if (err !== null) { if (err.code === 'ENOENT') resolve(false); else reject(err); } else { resolve(stat.isDirectory()); } }); }); } export function isFile(filepath:string):Promise<boolean> { return new Promise((resolve, reject)=>{ fs.stat(filepath, (err, stat)=>{ if (err !== null) { if (err.code === 'ENOENT') resolve(false); else reject(err); } else { resolve(stat.isFile()); } }); }); } export function isDirectorySync(filepath:string):boolean { try { return fs.statSync(filepath).isDirectory(); } catch (err) { return false; } } export function isFileSync(filepath:string):boolean { try { return fs.statSync(filepath).isFile(); } catch (err) { return false; } } export function checkModified(ori:string, out:string):Promise<boolean>{ return new Promise((resolve, reject)=>{ fs.stat(ori, (err, ostat)=>{ if (err !== null) { reject(err); } else { fs.stat(out, (err, nstat)=>{ if (err !== null) resolve(true); else resolve(ostat.mtimeMs >= nstat.mtimeMs); }); } }); }); } export function checkModifiedSync(ori:string, out:string):boolean{ const ostat = fs.statSync(ori); try{ const nstat = fs.statSync(out); return ostat.mtimeMs >= nstat.mtimeMs; } catch (err){ return true; } } export function readFile(path:string):Promise<string>; export function readFile(path:string, encoding:null):Promise<Buffer>; export function readFile(path:string, encoding:string):Promise<string>; export function readFile(path:string, encoding?:string|null):Promise<string|Buffer> { if (encoding === undefined) encoding = 'utf-8'; return new Promise((resolve, reject)=>{ fs.readFile(path, encoding, (err, data)=>{ if (err !== null) reject(err); else resolve(data); }); }); } export function writeFile(path:string, content:string|Uint8Array):Promise<void> { return new Promise((resolve, reject)=>{ fs.writeFile(path, content, (err)=>{ if (err !== null) reject(err); else resolve(); }); }); } /** * uses system EOL and add a last line */ export function writeJson(path:string, content:unknown):Promise<void> { return new Promise((resolve, reject)=>{ fs.writeFile(path, JSON.stringify(content, null, 2).replace(/\n/g, os.EOL)+os.EOL, 'utf8', (err)=>{ if (err !== null) reject(err); else resolve(); }); }); } /** * uses system EOL and add a last line */ export function writeJsonSync(path:string, content:unknown):void { fs.writeFileSync(path, JSON.stringify(content, null, 2).replace(/\n/g, os.EOL)+os.EOL, 'utf8'); } export function readdir(path:string):Promise<string[]> { return new Promise((resolve, reject)=>{ fs.readdir(path, (err, data)=>{ if (err !== null) { reject(err); } else { resolve(data); } }); }); } export function readdirWithFileTypes(path:string):Promise<fs.Dirent[]> { return new Promise((resolve, reject)=>{ fs.readdir(path, {withFileTypes: true}, (err, data)=>{ if (err !== null) { if (err.code === 'ENOENT') resolve([]); else reject(err); } else { if (data.length !== 0 && typeof data[0] === 'string') { (async()=>{ const stats:fs.Dirent[] = []; for (const d of data) { const stat = await fsutil.stat(d as any); stats.push(new DirentFromStat(d as any, stat)); } resolve(stats); })(); } else { resolve(data); } } }); }); } export function mkdir(path:string):Promise<void> { return new Promise((resolve, reject)=>{ fs.mkdir(path, (err)=>{ if (err !== null) { if (err.code === 'EEXIST') resolve(); else reject(err); } else resolve(); }); }); } export async function mkdirRecursive(dirpath:string, dirhas?:Set<string>):Promise<void> { if (dirhas != null && dirhas.has(dirpath)) return; await mkdirRecursive(path.dirname(dirpath), dirhas); await mkdir(dirpath); } export function rmdir(path:string):Promise<void> { return new Promise((resolve, reject)=>{ fs.rmdir(path, (err)=>{ if (err !== null) reject(err); else resolve(); }); }); } export function stat(path:string):Promise<fs.Stats> { return new Promise((resolve, reject)=>{ fs.stat(path, (err, data)=>{ if (err !== null) reject(err); else resolve(data); }); }); } export function lstat(path:string):Promise<fs.Stats> { return new Promise((resolve, reject)=>{ fs.lstat(path, (err, data)=>{ if (err !== null) reject(err); else resolve(data); }); }); } export function utimes(path:string, atime:string|number|Date, mtime:string|number|Date):Promise<void> { return new Promise((resolve, reject)=>{ fs.utimes(path, atime, mtime, err=>{ if (err !== null) reject(err); else resolve(); }); }); } export function unlink(path:string):Promise<void> { return new Promise((resolve, reject)=>{ fs.unlink(path, (err)=>{ if (err !== null) reject(err); else resolve(); }); }); } export function copyFile(from:string, to:string):Promise<void> { if (fs.copyFile != null) { return new Promise((resolve, reject)=>fs.copyFile(from, to, err=>{ if (err !== null) reject(err); else resolve(); })); } else { return new Promise((resolve, reject)=>{ const rd = fs.createReadStream(from); rd.on("error", reject); const wr = fs.createWriteStream(to); wr.on("error", reject); wr.on("close", ()=>{ resolve(); }); rd.pipe(wr); }); } } export async function exists(path:string):Promise<boolean> { try { await stat(path); return true; } catch (err) { return false; } } export async function del(filepath:string):Promise<void> { const s = await stat(filepath); if (s.isDirectory()) { const files = await readdir(filepath); for (const file of files) { await del(path.join(filepath, file)); } await rmdir(filepath); } else { await unlink(filepath); } } export function unlinkQuiet(path:string):Promise<void> { return new Promise(resolve=>{ fs.unlink(path, ()=>resolve()); }); } export function symlink(target:string, path:string, type?:fs.symlink.Type):Promise<void> { return new Promise((resolve, reject)=>{ fs.symlink(target, path, type, err=>{ if (err !== null) reject(err); else resolve(); }); }); } export function readFirstLineSync(path:string):string { const fd = fs.openSync(path, 'r'); const BUF_SIZE = 4*1024; const writer = new BufferWriter(new Uint8Array(BUF_SIZE), 0); for (;;) { const off = writer.size; writer.resize(off + BUF_SIZE); const readlen = fs.readSync(fd, writer.array, off, BUF_SIZE, null); writer.size = off + readlen; const buf = writer.buffer(); let idx:number; if (readlen !== 0) { idx = buf.indexOf(0x0a, off); // ASCII of \n if (idx === -1) continue; if (writer.array[idx-1] === 0xd) { // ASCII of \r idx --; } } else { idx = buf.length; } fs.closeSync(fd); return Buffer.from(buf.buffer, buf.byteOffset, idx).toString(); } } export class DirectoryMaker { public readonly dirhas = new Set<string>(); async make(pathname:string):Promise<void> { const resolved = path.resolve(pathname); if (this.dirhas.has(resolved)) return; await mkdirRecursive(resolved, this.dirhas); this.dirhas.add(resolved); } del(pathname:string):void { const resolved = path.resolve(pathname); for (const dir of this.dirhas) { if (dir.startsWith(resolved)) { if (dir.length === resolved.length || dir.charAt(resolved.length) === path.sep) { this.dirhas.delete(dir); } } } } } }
the_stack
import { A as arr } from '@ember/array'; import { assert, warn } from '@ember/debug'; import { action, computed } from '@ember/object'; import { capitalize } from '@ember/string'; import moment from 'moment'; import FilterFragment from 'navi-core/models/request/filter'; import { parseDuration } from '@yavin/client/utils/classes/duration'; import { DateTimePeriod, getPeriodForGrain, Grain } from '@yavin/client/utils/date'; import Interval from '@yavin/client/utils/classes/interval'; import BaseFilterBuilderComponent, { FilterValueBuilder } from './base'; import { isEmpty } from '@ember/utils'; import { GrainOrdering } from '@yavin/client/models/metadata/bard/table'; export const MONTHS_IN_QUARTER = 3; export const OPERATORS = <const>{ current: 'current', lookback: 'inPast', since: 'since', before: 'before', dateRange: 'in', advanced: 'advanced', equals: 'eq', }; type InternalOperatorType = typeof OPERATORS[keyof typeof OPERATORS]; interface InteralFilterBuilderOperators extends FilterValueBuilder { internalId: InternalOperatorType; } type TimeFilterValues = [string, string] | [string] | []; type TimeDimensionFilterArgs = BaseFilterBuilderComponent['args'] & { filter: FilterFragment & { values: string[] }; }; /** * Converts a grain into a period usable for the interval class * @param grain - the grain to turn into a period */ type DateGrain = Exclude<DateTimePeriod, 'second' | 'minute' | 'hour'>; export function intervalPeriodForGrain(grain: Grain): DateGrain { if (grain === 'quarter') { return 'month'; } let period = getPeriodForGrain(grain); if (period === 'hour' || period === 'minute' || period === 'second') { period = 'day'; } return period; } type FilterLike = Pick<FilterFragment, 'values' | 'parameters' | 'operator'>; export function findDefaultOperator(type: string): FilterFragment['operator'] { type = type?.toLowerCase(); const opDictionary: Record<string, FilterFragment['operator']> = { time: 'gte', date: 'bet', datetime: 'bet', number: 'eq', default: 'in', }; return opDictionary[type] || opDictionary.default; } export function getDefaultValuesForTimeFilter(filter: FilterLike): TimeFilterValues { const isTime = ['hour', 'minute', 'second'].includes(`${filter.parameters.grain}`); if (isTime) { return valuesForOperator(filter, 'day', OPERATORS.dateRange); } return valuesForOperator(filter, filter.parameters.grain as Grain, OPERATORS.lookback); } /** * Converts an Interval to a format suitable to the newOperator while retaining as much information as possible * e.g. ([P7D, current], day, in) -> [2020-01-01,2020-01-08] * @param prevValues - the previous filter values * @param grain - the time period being requested * @param newOperator - the operator to build values for */ export function valuesForOperator( filter: FilterLike, grain: Grain, newOperator?: InternalOperatorType ): TimeFilterValues { // TODO: Support sub day grain if (grain === 'hour' || grain === 'minute' || grain === 'second') { grain = 'day'; } newOperator = newOperator || internalOperatorForValues(filter); const DEFAULT_START = 'P1D', DEFAULT_END = 'current'; let [startStr = DEFAULT_START, endStr = DEFAULT_END] = filter.values as TimeFilterValues; if (isEmpty(startStr)) { startStr = DEFAULT_START; } if (isEmpty(endStr)) { endStr = DEFAULT_END; } const filterGrain = filter.parameters.grain as Grain; const minGrain = GrainOrdering[filterGrain] < GrainOrdering.day ? 'day' : filterGrain; let interval; try { interval = Interval.parseInclusive(startStr, endStr, minGrain); } catch { interval = Interval.parseInclusive(DEFAULT_START, DEFAULT_END, minGrain); } if (newOperator === OPERATORS.current) { return ['current', 'next']; } else if (newOperator === OPERATORS.lookback) { const currentEnd = Interval.parseFromStrings('P1D', 'current').asMomentsForTimePeriod(grain, false).end; const end = interval.asMomentsForTimePeriod(grain).end; let intervalValue = 1; if (end.isSame(currentEnd)) { // end is 'current', get lookback amount intervalValue = interval.diffForTimePeriod(grain); } intervalValue = Math.max(intervalValue, 1); if (grain === 'quarter') { // round to quarter intervalValue = intervalValue * MONTHS_IN_QUARTER; } const grainLabel = intervalPeriodForGrain(grain)[0].toUpperCase(); return [`P${intervalValue}${grainLabel}`, 'current']; } else if (newOperator === OPERATORS.since) { const { start } = interval.asMomentsInclusive(grain); return [start.toISOString()]; } else if (newOperator === OPERATORS.before) { const { end } = interval.asMomentsInclusive(grain); return [end.toISOString()]; } else if (newOperator === OPERATORS.equals) { const { start } = interval.asMomentsInclusive(grain); return [start.toISOString()]; } else if (newOperator === OPERATORS.dateRange) { const { start, end } = interval.asMomentsInclusive(grain); return [start.toISOString(), end.toISOString()]; } else if (newOperator === OPERATORS.advanced) { const newInterval = interval.asIntervalForTimePeriod(grain); const intervalValue = Math.abs(newInterval.diffForTimePeriod('day')); const end = newInterval.asMomentsForTimePeriod(grain).end.subtract(1, 'day'); return [`P${intervalValue}D`, end.toISOString()]; } warn(`No operator was found for the values '${filter.values.join(',')}'`, { id: 'time-dimension-filter-builder-no-operator', }); return []; } export function internalOperatorForValues(filter: FilterLike): InternalOperatorType { const { values, operator } = filter; const filterGrain = filter.parameters.grain as Grain; const [startStr, endStr] = values as string[]; if (!startStr && !endStr && operator === 'bet') { // there's no values return OPERATORS.dateRange; } else if (!(startStr && endStr)) { // there's only one value if (operator === 'gte') { return OPERATORS.since; } else if (operator === 'lte') { return OPERATORS.before; } else if (operator === 'eq') { return OPERATORS.equals; } } const interval = Interval.parseFromStrings(startStr, endStr); const { start, end } = interval.asStrings(); const [lookbackDuration, lookbackGrain] = parseDuration(start) || []; let internalId: InternalOperatorType; if (start === 'current' && end === 'next') { internalId = OPERATORS.current; } else if ( lookbackDuration && lookbackGrain && ['day', 'week', 'month', 'year'].includes(lookbackGrain) && (lookbackGrain === getPeriodForGrain(filterGrain) || (filterGrain === 'quarter' && lookbackGrain === 'month' && lookbackDuration % MONTHS_IN_QUARTER === 0) || // TODO: Remove once sub day grain is supported (['hour', 'minute', 'second'].includes(filterGrain) && lookbackGrain === 'day')) && end === 'current' ) { internalId = OPERATORS.lookback; } else if (moment.isMoment(interval['_start']) && moment.isMoment(interval['_end'])) { internalId = OPERATORS.dateRange; } else { internalId = OPERATORS.advanced; } assert(`A component for ${operator} [${values.join(',')}] exists`, internalId); return internalId; } export default class TimeDimensionFilterBuilder extends BaseFilterBuilderComponent<TimeDimensionFilterArgs> { @computed('args.filter.parameters.grain') get timeGrainName() { return capitalize(`${this.args.filter.parameters.grain}`); } /** * list of valid operators for a time-dimension filter */ @computed('args.filter.parameters.grain', 'timeGrainName') get valueBuilders(): InteralFilterBuilderOperators[] { return [ { operator: 'bet' as const, internalId: OPERATORS.current, name: `Current ${this.timeGrainName}`, component: 'filter-values/time-dimension/current', }, { operator: 'bet' as const, internalId: OPERATORS.lookback, name: 'In The Past', component: 'filter-values/time-dimension/lookback', }, { operator: 'gte' as const, internalId: OPERATORS.since, name: 'Since', component: 'filter-values/time-dimension/date', }, { operator: 'lte' as const, internalId: OPERATORS.before, name: 'Before', component: 'filter-values/time-dimension/date', }, { operator: 'eq' as const, internalId: OPERATORS.equals, name: 'Equals', component: 'filter-values/time-dimension/date', }, { operator: 'bet' as const, internalId: OPERATORS.dateRange, name: 'Between', component: 'filter-values/time-dimension/range', }, { operator: 'bet' as const, internalId: OPERATORS.advanced, name: 'Advanced', component: 'filter-values/time-dimension/advanced', }, ]; } /** * Finds the appropriate interval operator to modify an existing interval * @returns the best supported operator for this interval */ @computed( // eslint-disable-next-line ember/use-brace-expansion 'args.filter.parameters.grain', 'args.filter.validations.isValid', 'args.filter.{operator,values}', 'supportedOperators', 'valueBuilders' ) get selectedValueBuilder(): InteralFilterBuilderOperators { const internalId = this.args.filter.validations.isValid ? internalOperatorForValues(this.args.filter) : OPERATORS.advanced; const filterValueBuilder = this.valueBuilders.find((f) => f.internalId === internalId); assert(`A filter value component for ${internalId} operator exists`, filterValueBuilder); return filterValueBuilder; } /** * @param operator - a value from supportedOperators that should become the filter's operator */ @action setOperator(newBuilder: InteralFilterBuilderOperators) { const oldOperator = this.selectedValueBuilder; if (oldOperator.internalId === newBuilder.internalId) { return; } const { filter } = this.args; const { grain } = filter.parameters; const newInterval = valuesForOperator(filter, grain as Grain, newBuilder.internalId); this.args.onUpdateFilter({ operator: newBuilder.operator, values: arr(newInterval), }); } }
the_stack
import { PdfStreamWriter } from './../../input-output/pdf-stream-writer'; import { GetResourceEventHandler } from './../pdf-graphics'; import { PdfColorSpace } from './../enum'; import { PdfColor } from './../pdf-color'; import { PdfBrush } from './pdf-brush'; import { IPdfWrapper } from '../../../interfaces/i-pdf-wrapper'; import { PdfDictionary} from '../../primitives/pdf-dictionary'; import { PdfTransformationMatrix } from './../pdf-transformation-matrix'; import { DictionaryProperties } from './../../input-output/pdf-dictionary-properties'; import { PdfBoolean } from './../../primitives/pdf-boolean'; import { PdfArray } from './../../primitives/pdf-array'; import { PdfName } from '../../primitives/pdf-name'; import { PdfNumber} from '../../primitives/pdf-number'; import { PdfReferenceHolder } from '../../primitives/pdf-reference'; import { IPdfPrimitive } from './../../../interfaces/i-pdf-primitives'; import { PdfFunction } from './../../general/functions/pdf-function'; import { PdfResources } from './../pdf-resources'; /** * `PdfGradientBrush` class provides objects used to fill the interiors of graphical shapes such as rectangles, * ellipses, pies, polygons, and paths. * @private */ export abstract class PdfGradientBrush extends PdfBrush implements IPdfWrapper { // Fields /** * Local variable to store the background color. * @private */ private mbackground : PdfColor = new PdfColor(255, 255, 255); /** * Local variable to store the stroking color. * @private */ private mbStroking : boolean = false; /** * Local variable to store the dictionary. * @private */ private mpatternDictionary : PdfDictionary; /** * Local variable to store the shading. * @private */ private mshading : PdfDictionary; /** * Local variable to store the Transformation Matrix. * @private */ private mmatrix: PdfTransformationMatrix; /** * Local variable to store the colorSpace. * @private */ private mcolorSpace: PdfColorSpace; /** * Local variable to store the function. * @private */ private mfunction: PdfFunction = null; /** * Local variable to store the DictionaryProperties. * @private */ private dictionaryProperties : DictionaryProperties = new DictionaryProperties(); //Constructor /** * Initializes a new instance of the `PdfGradientBrush` class. * @public */ /* tslint:disable-next-line:max-line-length */ public constructor(shading: PdfDictionary) { super(); this.mpatternDictionary = new PdfDictionary(); this.mpatternDictionary.items.setValue(this.dictionaryProperties.type, new PdfName(this.dictionaryProperties.pattern)); this.mpatternDictionary.items.setValue(this.dictionaryProperties.patternType, new PdfNumber(2)); this.shading = shading; this.colorSpace = PdfColorSpace.Rgb; } //Properties /** * Gets or sets the background color of the brush. * @public */ public get background(): PdfColor { return this.mbackground; } public set background(value: PdfColor) { this.mbackground = value; let sh: PdfDictionary = this.shading; if (value.isEmpty) { sh.remove(this.dictionaryProperties.background); } else { sh.items.setValue(this.dictionaryProperties.background, value.toArray(this.colorSpace)); } } /** * Gets or sets a value indicating whether use anti aliasing algorithm. * @public */ public get antiAlias(): boolean { let sh: PdfDictionary = this.shading; let aa: PdfBoolean = (<PdfBoolean>(sh.items.getValue(this.dictionaryProperties.antiAlias))); return aa.value; } public set antiAlias(value: boolean) { let sh: PdfDictionary = this.shading; let aa: PdfBoolean = (<PdfBoolean>(sh.items.getValue(this.dictionaryProperties.antiAlias))); if ((aa == null && typeof aa === 'undefined')) { aa = new PdfBoolean(value); sh.items.setValue(this.dictionaryProperties.antiAlias, aa); } else { aa.value = value; } } /** * Gets or sets the function of the brush. * @protected */ protected get function(): PdfFunction { return this.mfunction; } protected set function(value: PdfFunction) { this.mfunction = value; if (value != null && typeof value !== 'undefined') { this.shading.items.setValue(this.dictionaryProperties.function, new PdfReferenceHolder(this.mfunction)); } else { this.shading.remove(this.dictionaryProperties.function); } } /** * Gets or sets the boundary box of the brush. * @protected */ protected get bBox(): PdfArray { let sh: PdfDictionary = this.shading; let box: PdfArray = (<PdfArray>(sh.items.getValue(this.dictionaryProperties.bBox))); return box; } protected set bBox(value: PdfArray) { let sh: PdfDictionary = this.shading; if (value == null && typeof value === 'undefined') { sh.remove(this.dictionaryProperties.bBox); } else { sh.items.setValue(this.dictionaryProperties.bBox, value); } } /** * Gets or sets the color space of the brush. * @public */ public get colorSpace(): PdfColorSpace { return this.mcolorSpace; } public set colorSpace(value: PdfColorSpace) { let colorSpace: IPdfPrimitive = this.shading.items.getValue(this.dictionaryProperties.colorSpace); if ((value !== this.mcolorSpace) || (colorSpace == null)) { this.mcolorSpace = value; let csValue: string = this.colorSpaceToDeviceName(value); this.shading.items.setValue(this.dictionaryProperties.colorSpace, new PdfName(csValue)); } } /** * Gets or sets a value indicating whether this PdfGradientBrush is stroking. * @public */ public get stroking(): boolean { return this.mbStroking; } public set stroking(value: boolean) { this.mbStroking = value; } /** * Gets the pattern dictionary. * @protected */ protected get patternDictionary(): PdfDictionary { if (this.mpatternDictionary == null) { this.mpatternDictionary = new PdfDictionary(); } return this.mpatternDictionary; } /** * Gets or sets the shading dictionary. * @protected */ protected get shading(): PdfDictionary { return this.mshading; } protected set shading(value: PdfDictionary) { if (value == null) { throw new Error('ArgumentNullException : Shading'); } if (value !== this.mshading) { this.mshading = value; this.patternDictionary.items.setValue(this.dictionaryProperties.shading, new PdfReferenceHolder(this.mshading)); } } /** * Gets or sets the transformation matrix. * @public */ public get matrix(): PdfTransformationMatrix { return this.mmatrix; } public set matrix(value: PdfTransformationMatrix) { if (value == null) { throw new Error('ArgumentNullException : Matrix'); } if (value !== this.mmatrix) { this.mmatrix = value.clone(); let m: PdfArray = new PdfArray(this.mmatrix.matrix.elements); this.mpatternDictionary.items.setValue(this.dictionaryProperties.matrix, m); } } //Overrides /** * Monitors the changes of the brush and modify PDF state respectfully. * @param brush The brush. * @param streamWriter The stream writer. * @param getResources The get resources delegate. * @param saveChanges if set to true the changes should be saved anyway. * @param currentColorSpace The current color space. */ /* tslint:disable-next-line:max-line-length */ public monitorChanges(brush: PdfBrush, streamWriter: PdfStreamWriter, getResources: GetResourceEventHandler, saveChanges: boolean, currentColorSpace: PdfColorSpace): boolean { let diff: boolean = false; if (brush instanceof PdfGradientBrush) { if ((this.colorSpace !== currentColorSpace)) { this.colorSpace = currentColorSpace; this.resetFunction(); } // Set the /Pattern colour space. streamWriter.setColorSpace('Pattern', this.mbStroking); // Set the pattern for non-stroking operations. let resources : PdfResources = getResources.getResources(); let name: PdfName = resources.getName(this); streamWriter.setColourWithPattern(null, name, this.mbStroking); diff = true; } return diff; } /** * Resets the changes, which were made by the brush. * In other words resets the state to the initial one. * @param streamWriter The stream writer. */ public resetChanges(streamWriter: PdfStreamWriter): void { // Unable reset. } //Implementation /** * Converts colorspace enum to a PDF name. * @param colorSpace The color space enum value. */ private colorSpaceToDeviceName(colorSpace: PdfColorSpace): string { let result: string; switch (colorSpace) { case PdfColorSpace.Rgb: result = 'DeviceRGB'; break; } return result; } /** * Resets the pattern dictionary. * @param dictionary A new pattern dictionary. */ protected resetPatternDictionary(dictionary: PdfDictionary) : void { this.mpatternDictionary = dictionary; } /** * Resets the function. */ public abstract resetFunction() : void; /** * Clones the anti aliasing value. * @param brush The brush. */ protected cloneAntiAliasingValue(brush: PdfGradientBrush) : void { if ((brush == null)) { throw new Error('ArgumentNullException : brush'); } let sh: PdfDictionary = this.shading; let aa: PdfBoolean = (<PdfBoolean>(sh.items.getValue(this.dictionaryProperties.antiAlias))); if ((aa != null)) { brush.shading.items.setValue(this.dictionaryProperties.antiAlias, new PdfBoolean(aa.value)); } } /** * Clones the background value. * @param brush The brush. */ protected cloneBackgroundValue(brush: PdfGradientBrush) : void { let background: PdfColor = this.background; if (!background.isEmpty) { brush.background = background; } } /* tslint:enable */ // IPdfWrapper Members /** * Gets the `element`. * @private */ public get element() : IPdfPrimitive { return this.patternDictionary; } }
the_stack
import { Athena, GetQueryResultsCommandOutput } from '@aws-sdk/client-athena'; import { S3, GetObjectCommand } from '@aws-sdk/client-s3'; import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; import * as stream from 'stream'; import { BaseDriver, DatabaseStructure, DownloadTableCSVData, DriverInterface, QueryOptions, StreamOptions, StreamTableData, TableName } from '@cubejs-backend/query-orchestrator'; import { checkNonNullable, getEnv, pausePromise, Required } from '@cubejs-backend/shared'; import * as SqlString from 'sqlstring'; import { AthenaClientConfig } from '@aws-sdk/client-athena/dist-types/AthenaClient'; import { URL } from 'url'; interface AthenaDriverOptions extends AthenaClientConfig { readOnly?: boolean accessKeyId?: string secretAccessKey?: string workGroup?: string S3OutputLocation?: string exportBucket?: string pollTimeout?: number pollMaxInterval?: number } type AthenaDriverOptionsInitialized = Required<AthenaDriverOptions, 'pollTimeout' | 'pollMaxInterval'>; export interface AthenaQueryId { QueryExecutionId: string; } function applyParams(query: string, params: any[]): string { return SqlString.format(query, params); } export class AthenaDriver extends BaseDriver implements DriverInterface { private config: AthenaDriverOptionsInitialized; private athena: Athena; public constructor(config: AthenaDriverOptions = {}) { super(); const accessKeyId = config.accessKeyId || process.env.CUBEJS_AWS_KEY; const secretAccessKey = config.secretAccessKey || process.env.CUBEJS_AWS_SECRET; this.config = { ...config, credentials: accessKeyId && secretAccessKey ? { accessKeyId, secretAccessKey } : undefined, region: config.region || process.env.CUBEJS_AWS_REGION, S3OutputLocation: config.S3OutputLocation || process.env.CUBEJS_AWS_S3_OUTPUT_LOCATION, workGroup: config.workGroup || process.env.CUBEJS_AWS_ATHENA_WORKGROUP || 'primary', exportBucket: config.exportBucket || getEnv('dbExportBucket'), pollTimeout: (config.pollTimeout || getEnv('dbPollTimeout') || getEnv('dbQueryTimeout')) * 1000, pollMaxInterval: (config.pollMaxInterval || getEnv('dbPollMaxInterval')) * 1000, }; if (this.config.exportBucket) { this.config.exportBucket = AthenaDriver.normalizeS3Path(this.config.exportBucket); } this.athena = new Athena(this.config); } public readOnly(): boolean { return !!this.config.readOnly; } public async isUnloadSupported() { return this.config.exportBucket !== undefined; } public async testConnection() { await this.athena.getWorkGroup({ WorkGroup: this.config.workGroup }); } public async query<R = unknown>(query: string, values: unknown[], options?: QueryOptions): Promise<R[]> { const qid = await this.startQuery(query, values); await this.waitForSuccess(qid); const rows: R[] = []; for await (const row of this.lazyRowIterator<R>(qid, query)) { rows.push(row); } return rows; } public async stream(query: string, values: unknown[], options: StreamOptions): Promise<StreamTableData> { const qid = await this.startQuery(query, values); await this.waitForSuccess(qid); const rowStream = stream.Readable.from(this.lazyRowIterator(qid, query), { highWaterMark: options.highWaterMark }); return { rowStream }; } public async loadPreAggregationIntoTable( preAggregationTableName: string, loadSql: string, params: any, ): Promise<any> { if (this.config.S3OutputLocation === undefined) { throw new Error('Unload is not configured'); } const qid = await this.startQuery(loadSql, params); await this.waitForSuccess(qid); } public async unload(tableName: string): Promise<DownloadTableCSVData> { if (this.config.exportBucket === undefined) { throw new Error('Unload is not configured'); } const types = await this.tableColumnTypes(tableName); const columns = types.map(t => t.name).join(', '); const path = `${this.config.exportBucket}/${tableName}`; const unloadSql = ` UNLOAD (SELECT ${columns} FROM ${tableName}) TO '${path}' WITH (format = 'TEXTFILE', field_delimiter = ',', compression='GZIP') `; const qid = await this.startQuery(unloadSql, []); await this.waitForSuccess(qid); const client = new S3({ credentials: this.config.credentials, region: this.config.region, }); const { bucket, prefix } = AthenaDriver.splitS3Path(path); const list = await client.listObjectsV2({ Bucket: bucket, // skip leading / Prefix: prefix.slice(1), }); if (list.Contents === undefined) { return { csvFile: [], types, }; } const csvFile = await Promise.all( list.Contents.map(async (file) => { const command = new GetObjectCommand({ Bucket: bucket, Key: file.Key, }); return getSignedUrl(client, command, { expiresIn: 3600 }); }) ); return { csvFile, types, csvNoHeader: true }; } public async tablesSchema(): Promise<DatabaseStructure> { const tablesSchema = await super.tablesSchema(); const viewsSchema = await this.viewsSchema(tablesSchema); return this.mergeSchemas([tablesSchema, viewsSchema]); } protected async startQuery(query: string, values: unknown[]): Promise<AthenaQueryId> { const queryString = applyParams( query, (values || []).map(s => (typeof s === 'string' ? { toSqlString: () => SqlString.escape(s).replace(/\\\\([_%])/g, '\\$1').replace(/\\'/g, '\'\'') } : s)) ); const request = { QueryString: queryString, WorkGroup: this.config.workGroup, ResultConfiguration: { OutputLocation: this.config.S3OutputLocation } }; const { QueryExecutionId } = await this.athena.startQueryExecution(request); return { QueryExecutionId: checkNonNullable('StartQueryExecution', QueryExecutionId) }; } protected async checkStatus(qid: AthenaQueryId): Promise<boolean> { const queryExecution = await this.athena.getQueryExecution(qid); const status = queryExecution.QueryExecution?.Status?.State; if (status === 'FAILED') { throw new Error(queryExecution.QueryExecution?.Status?.StateChangeReason); } if (status === 'CANCELLED') { throw new Error('Query has been cancelled'); } return status === 'SUCCEEDED'; } protected async waitForSuccess(qid: AthenaQueryId): Promise<void> { const startedTime = Date.now(); for (let i = 0; Date.now() - startedTime <= this.config.pollTimeout; i++) { if (await this.checkStatus(qid)) { return; } await pausePromise( Math.min(this.config.pollMaxInterval, 500 * i) ); } throw new Error( `Athena job timeout reached ${this.config.pollTimeout}ms` ); } protected async* lazyRowIterator<R extends unknown>(qid: AthenaQueryId, query: string): AsyncGenerator<R> { let isFirstBatch = true; let columnInfo: { Name: string }[] = []; for ( let results: GetQueryResultsCommandOutput | undefined = await this.athena.getQueryResults(qid); results; results = results.NextToken ? (await this.athena.getQueryResults({ ...qid, NextToken: results.NextToken })) : undefined ) { let rows = results.ResultSet?.Rows ?? []; if (isFirstBatch) { isFirstBatch = false; // Athena returns the columns names in first row, skip it. rows = rows.slice(1); columnInfo = /SHOW COLUMNS/.test(query) // Fix for getColumns method ? [{ Name: 'column' }] : checkNonNullable('ColumnInfo', results.ResultSet?.ResultSetMetadata?.ColumnInfo) .map(info => ({ Name: checkNonNullable('Name', info.Name) })); } for (const row of rows) { const fields: Record<string, any> = {}; columnInfo .forEach((c, j) => { fields[c.Name] = row.Data?.[j].VarCharValue; }); yield fields as R; } } } protected async viewsSchema(tablesSchema: DatabaseStructure): Promise<DatabaseStructure> { const isView = (table: TableName) => !tablesSchema[table.schema] || !tablesSchema[table.schema][table.name]; const allTables = await this.getAllTables(); const arrViewsSchema = await Promise.all( allTables .filter(isView) .map(table => this.getColumns(table)) ); return this.mergeSchemas(arrViewsSchema); } protected async getAllTables(): Promise<TableName[]> { const rows = await this.query( ` SELECT table_schema AS schema, table_name AS name FROM information_schema.tables WHERE tables.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys') `, [] ); return rows as TableName[]; } protected async getColumns(table: TableName): Promise<DatabaseStructure> { const data: { column: string }[] = await this.query(`SHOW COLUMNS IN \`${table.join()}\``, []); return { [table.schema]: { [table.name]: data.map(({ column }) => { const [name, type] = column.split('\t'); return { name, type, attributes: [] }; }) } }; } protected mergeSchemas(arrSchemas: DatabaseStructure[]): DatabaseStructure { const result: DatabaseStructure = {}; arrSchemas.forEach(schemas => { Object.keys(schemas).forEach(schema => { Object.keys(schemas[schema]).forEach((name) => { if (!result[schema]) result[schema] = {}; if (!result[schema][name]) result[schema][name] = schemas[schema][name]; }); }); }); return result; } public static normalizeS3Path(path: string): string { // Remove trailing / path = path.replace(/\/+$/, ''); // Prepend s3:// prefix to plain bucket if (!path.startsWith('s3://')) { return `s3://${path}`; } return path; } public static splitS3Path(path: string) { const url = new URL(path); return { bucket: url.host, prefix: url.pathname }; } }
the_stack
import { Runtime, CausalBroadcastNetwork, CausalTimestamp, VectorClock, } from "compoventuals"; import { WebRtcNetworkMessage } from "../generated/proto_compiled"; import { Buffer } from "buffer"; // NOTE: This WebRTC network layer is just a prototype, which only // two users peer-to-peer connection. // // The webrtc network designed for a two-way peer-to-peer interactive // communication session among two users using WebRTC protocol. // // The whole infrastructure is based-on the WebSocket protocol to // initialize the connection between WebRTC candidates. // // Also ensure the order of delivery with casuality check. /** * Customized message event that travel through * casualbroadcast network. */ class myMessage { /** * Crdt update message. */ message: Uint8Array; /** * Timestamp for casuality/concurrency check. * * Provide basic functions such as : * getSender() / getSenderCounter() / asVectorClock(). */ timestamp: VectorClock; constructor(message: Uint8Array, timestamp: VectorClock) { this.message = message; this.timestamp = timestamp; } /** * Returns a serialized form of the message. * * @returns serialize message */ serialize(): Uint8Array { const vectorMap = Object.fromEntries(this.timestamp.vectorMap); delete vectorMap[this.timestamp.sender]; const message = WebRtcNetworkMessage.create({ message: this.message, sender: this.timestamp.sender, senderCounter: this.timestamp.getSenderCounter(), vectorMap, time: this.timestamp.getTime(), }); return WebRtcNetworkMessage.encode(message).finish(); } /** * Parse serialized data back to myMessage. * * @param data serialized message * @param myReplicaID the local use's replicaID * @returns a deserialized myMessage */ static deserialize(data: Uint8Array, myReplicaID: string): myMessage { let decoded = WebRtcNetworkMessage.decode(data); let vc = new VectorClock( decoded.sender, myReplicaID === decoded.sender, decoded.time as number ); vc.vectorMap = new Map(Object.entries(decoded.vectorMap)); vc.vectorMap.set(decoded.sender, decoded.senderCounter); return new myMessage(decoded.message, vc); } } /** * WebRtcNetwork: * * Process initialization when starting a new user node. * * Communicate with CRDT's runtime and send/receive message via * central server with WebSocket protocol to exchange signals. * Then create channels for peer-to-peer communications by using * the WebRtc. * * Perform casuality check to ensure message ordering. */ export class WebRtcNetwork implements CausalBroadcastNetwork { private onreceive!: ( message: Uint8Array, firstTimestamp: CausalTimestamp ) => CausalTimestamp; /** * Registered Runtime. */ runtime!: Runtime; /** * WebSocket for connection to server. */ ws: WebSocket; /** * WebRtc for connection to another user. */ peerRtc: RTCPeerConnection; /** * Data channel for connection to another user. */ dataChannel: any; /** * Map stores all crdtId with its corresponding vector clock. */ vc!: VectorClock; /** * Message buffer to store received message to ensure casual delivery. */ messageBuffer: Array<[Uint8Array, VectorClock]>; /** * Message waiting to be sent by the WebSocket */ sendBuffer: Array<any>; /** * Message waiting to be sent by the WebRtc */ dataBuffer: Array<string>; /** * User's name that current data channel connected. */ userName: String; private isPendingBatch: boolean = false; constructor(webSocketArgs: string) { this.messageBuffer = []; this.sendBuffer = []; this.dataBuffer = []; this.userName = ""; /** * Open WebSocket connection with server. * Register EventListener with corresponding event handler. */ this.ws = new WebSocket(webSocketArgs); this.ws.addEventListener("open", this.sendWebSocketData); this.ws.addEventListener("message", this.receiveAction); /** * Open WebRtc peer connection. * Register EventListener with corresponding event handler. */ let configuration: RTCConfiguration = { iceServers: [{ urls: "stun:stun2.1.google.com:19302" }], }; this.peerRtc = new RTCPeerConnection(configuration); this.peerRtc.addEventListener("icecandidate", this.handleIceCandidate); this.peerRtc.addEventListener("datachannel", this.peerRtcReceiveMessage); } readonly isCausalBroadcastNetwork: true = true; /** * Send signal message in JSON format by using WebSocket * * @param message the JSON format data send via network */ sendSignalingMessage(message: any): void { message.webRtc = true; if (this.ws.readyState === 1) { this.ws.send(JSON.stringify(message)); } else { this.sendBuffer.push(message); } } /** * Check if the send message buffer has any message waiting to be sent. * If there exist, then send it via WebSocket and remove the item from buffer. * If not, then wait a customized time period and check again. */ sendWebSocketData = () => { let index = 0; while (index < this.sendBuffer.length) { console.log(this.sendBuffer[index]); this.ws.send(JSON.stringify(this.sendBuffer[index])); index++; } this.sendBuffer = new Array<any>(); }; /** * Parse JSON format signal message and check signal message type. * Jump to the corresponding signal handler for further steps to * build WebRtc channel. * * @param msg the JSON format data send via network. */ receiveAction = (msg: any) => { console.log("Got message", msg.data); var data = JSON.parse(msg.data); switch (data.type) { case "register": this.handleRegister(data.success); break; case "connect": this.handleConnect(data.users); break; case "offer": this.handleOffer(data.offer, data.requestName); break; case "answer": this.handleAnswer(data.answer); break; case "candidate": this.handleCandidate(data.candidate); break; case "leave": this.handleLeave(); break; default: break; } }; /** * Handle register signal sent back from the central server. * Check if login successfully or not. * * @param successStatus A register status sent back from the server. */ handleRegister(successStatus: any): void { if (successStatus == false) { console.log("Register failed: duplicate CRDT id."); } else { console.log("Register successfully in server."); } } /** * Handle connect signal sent from the central server. * Create an offer and send it to the requested user. * * @param users An array of users that shared a same CRDTs. */ handleConnect(users: Array<any>): void { // This loop is to check the correct user to connect. // Design for the multiple users. // TODO: Complete multiple users connection built. let index = 0; while (index < users.length) { if (users[index] != this.runtime.replicaID) { this.userName = users[index]; break; } index++; } // Create an offer to build WebRtc connection. // Set offer as the local descrition. this.peerRtc.createOffer().then((offer) => { this.sendSignalingMessage({ type: "offer", name: this.userName, offer: offer, requestName: this.runtime.replicaID, }); this.peerRtc.setLocalDescription(offer); }); } /** * Handle offer signal sent from the server. * Create an answer as a response and send the answer to the server. * * @param offer The offer received from the central server. * @param name The name of a user who sends this offer. */ handleOffer(offer: any, name: string): void { this.userName = name; this.peerRtc.setRemoteDescription(new RTCSessionDescription(offer)); this.peerRtc.createAnswer().then((answer) => { this.sendSignalingMessage({ type: "answer", name: this.userName, answer: answer, }); this.peerRtc.setLocalDescription(answer); }); } /** * Handle answer signal sent from the central server. * Setup remote description by using the answer. * * @param answer The answer received from the central server. */ handleAnswer(answer: any): void { this.peerRtc.setRemoteDescription(new RTCSessionDescription(answer)); } handleCandidate(candidate: any): void { this.peerRtc .addIceCandidate(new RTCIceCandidate(candidate)) .catch((e) => console.error(e)); } handleLeave() { this.peerRtc.close(); this.peerRtc.onicecandidate = null; } /** * Handle icecandidate event when an RTCIceCandidate has been * identified and added to the local peer by a call. * Send signal message to the central server. * * @param event Ice candidate event that should be handled */ handleIceCandidate = (event: any) => { if (event.candidate != null) { this.sendSignalingMessage({ type: "candidate", candidate: event.candidate, name: this.userName, }); } }; peerRtcReceiveMessage = (event: any) => { let receiveChannel = event.channel; console.log(receiveChannel); receiveChannel.addEventListener("message", this.dataChanelReceiveMsg); }; dataChanelReceiveMsg = (event: any) => { console.log(event.data); let parsed = JSON.parse(event.data) as { message: string }; let myPackage = myMessage.deserialize( new Uint8Array(Buffer.from(parsed.message, "base64")), this.runtime.replicaID ); this.messageBuffer.push([myPackage.message, myPackage.timestamp]); this.checkMessageBuffer(); }; sendWebRtcData = () => { console.log("The data channel is open"); let index = 0; while (index < this.dataBuffer.length) { console.log(this.dataBuffer[index]); this.dataChannel.send(this.dataBuffer[index]); index++; } this.dataBuffer = []; }; /** * Implement the function defined in Runtime interfaces. * * @returns This replica's id, used by some CRDTs internally * (e.g., to generate unique identifiers of the form (replica id, counter)). * */ getReplicaID(): any { return this.runtime.replicaID; } /** * Register newly created crdt with its ID and corresponding message * listener on CasualBroadcastNetwork. * * @param crdtMessageListener the message listener of each crdt. * @param crdtId the ID of each crdt. * */ registerRuntime( runtime: Runtime, onreceive: ( message: Uint8Array, firstTimestamp: CausalTimestamp ) => CausalTimestamp ): void { this.runtime = runtime; this.onreceive = onreceive; // TODO: onreceiveblocked this.vc = new VectorClock(this.runtime.replicaID, true, -1); this.sendSignalingMessage({ type: "register", name: this.runtime.replicaID, crdtName: Runtime.name, }); console.log("Create dataChannel"); this.dataChannel = this.peerRtc.createDataChannel("channel1"); this.dataChannel.onerror = function (error: any) { console.log("Errors: ", error); }; this.dataChannel.addEventListener("open", this.sendWebRtcData); this.dataChannel.onclose = function () { console.log("data channel is closed"); }; } beginBatch(): CausalTimestamp { this.isPendingBatch = true; // Return the next timestamp. const next = this.nextTimestamp(this.vc) as VectorClock; next.time = Date.now(); return next; } /** * Send function on casualbroadcast network layer, which called * by crdt's runtime layer. * * The message is wrapped with its corresponding timestamp (basic sender node * info and vector clock). * * Using WebSocket as network transmission protocol. * Using JSON format as message type. * * If the WebSocket Readystate is not Open, then buffer the message and * wait until WebSocket open. * If the WebSocket Readystate is Open, then send it with ws.send(). * * @param message the crdt update message. * @param crdtId the unique ID for each crdt. */ commitBatch( message: Uint8Array, firstTimestamp: CausalTimestamp, lastTimestamp: CausalTimestamp ): void { this.vc = lastTimestamp as VectorClock; let myPackage = new myMessage(message, firstTimestamp as VectorClock); let encoded = Buffer.from(myPackage.serialize()).toString("base64"); let toSend = JSON.stringify({ message: encoded, }); if (this.dataChannel.readyState == "open") { this.dataChannel.send(toSend); } else { this.dataBuffer.push(toSend); } this.isPendingBatch = false; // Deliver any messages received in the meantime, which were previously // blocked by the pending batch. this.checkMessageBuffer(); } /** * Get the next timestamp of the given crdtId in this replica. * * This is passed to CrdtInternal.effect when a replica processes its own * message. * * @param crdtId the crdtId that would like to return. * @returns The timestamp that would be assigned to a CRDT * message sent by this replica and given crdtId right now. * */ nextTimestamp(previous: CausalTimestamp): CausalTimestamp { // Copy a new vector clock. // TODO: can we avoid copying, for efficiency? let vc = previous as CausalTimestamp; let vcCopy = new VectorClock( previous.getSender(), previous.isLocal(), previous.getTime() ); vcCopy.vectorMap = new Map<string, number>(vc.asVectorClock()); // Update the timestamp of this replica with next value. vcCopy.increment(); return vcCopy; } /** * Check the casuality of buffered messages and delivery the * messages back to crdtMessageListener which are ready. * * The checking order is from the lastest to the oldest. * Update the VectorClock entry and MessageBuffer when necessary. * * Send the message back to runtime with corresponding * crdtMessageListener. */ checkMessageBuffer(): void { let index = this.messageBuffer.length - 1; while (index >= 0) { // Don't deliver any messages to the runtime if there is a pending // batch of messages to send. if (this.isPendingBatch) return; let curVectorClock = this.messageBuffer[index][1]; if (this.vc.isReady(curVectorClock)) { /** * Send back the received messages to runtime. */ let lastTimestamp = this.onreceive(...this.messageBuffer[index]); this.vc.mergeSender(lastTimestamp as VectorClock); this.messageBuffer.splice(index, 1); // Set index to the end and try again, in case // this makes more messages ready index = this.messageBuffer.length - 1; } else { if (this.vc.isAlreadyReceived(curVectorClock)) { // Remove the message from the buffer this.messageBuffer.splice(index, 1); console.log("(already received)"); } index--; } } } serialize(value: CausalTimestamp): Uint8Array { // TODO: make reasonable (don't use myMessage) return new myMessage(new Uint8Array(), value as VectorClock).serialize(); } deserialize(message: Uint8Array, runtime: Runtime): CausalTimestamp { return myMessage.deserialize(message, runtime.replicaID).timestamp; } save(): Uint8Array { // TODO return new Uint8Array(); } load(saveData: Uint8Array) { // TODO } }
the_stack
import { ATN } from 'antlr4ts/atn/ATN' import { ATNDeserializer } from 'antlr4ts/atn/ATNDeserializer' import { CharStream } from 'antlr4ts/CharStream' import { Lexer } from 'antlr4ts/Lexer' import { LexerATNSimulator } from 'antlr4ts/atn/LexerATNSimulator' import { Vocabulary } from 'antlr4ts/Vocabulary' import { VocabularyImpl } from 'antlr4ts/VocabularyImpl' import * as Utils from 'antlr4ts/misc/Utils' export class AgtypeLexer extends Lexer { public static readonly T__0 = 1; public static readonly T__1 = 2; public static readonly T__2 = 3; public static readonly T__3 = 4; public static readonly T__4 = 5; public static readonly T__5 = 6; public static readonly T__6 = 7; public static readonly T__7 = 8; public static readonly T__8 = 9; public static readonly T__9 = 10; public static readonly T__10 = 11; public static readonly T__11 = 12; public static readonly T__12 = 13; public static readonly IDENT = 14; public static readonly STRING = 15; public static readonly INTEGER = 16; public static readonly RegularFloat = 17; public static readonly ExponentFloat = 18; public static readonly WS = 19; // tslint:disable:no-trailing-whitespace public static readonly channelNames: string[] = [ 'DEFAULT_TOKEN_CHANNEL', 'HIDDEN' ]; // tslint:disable:no-trailing-whitespace public static readonly modeNames: string[] = [ 'DEFAULT_MODE' ]; public static readonly ruleNames: string[] = [ 'T__0', 'T__1', 'T__2', 'T__3', 'T__4', 'T__5', 'T__6', 'T__7', 'T__8', 'T__9', 'T__10', 'T__11', 'T__12', 'IDENT', 'STRING', 'ESC', 'UNICODE', 'HEX', 'SAFECODEPOINT', 'INTEGER', 'INT', 'RegularFloat', 'ExponentFloat', 'DECIMAL', 'SCIENTIFIC', 'WS' ]; private static readonly _LITERAL_NAMES: Array<string | undefined> = [ undefined, "'true'", "'false'", "'null'", "'{'", "','", "'}'", "':'", "'['", "']'", "'::'", "'-'", "'Infinity'", "'NaN'" ]; private static readonly _SYMBOLIC_NAMES: Array<string | undefined> = [ undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, 'IDENT', 'STRING', 'INTEGER', 'RegularFloat', 'ExponentFloat', 'WS' ]; public static readonly VOCABULARY: Vocabulary = new VocabularyImpl(AgtypeLexer._LITERAL_NAMES, AgtypeLexer._SYMBOLIC_NAMES, []); // @Override // @NotNull public get vocabulary (): Vocabulary { return AgtypeLexer.VOCABULARY } // tslint:enable:no-trailing-whitespace constructor (input: CharStream) { super(input) this._interp = new LexerATNSimulator(AgtypeLexer._ATN, this) } // @Override public get grammarFileName (): string { return 'Agtype.g4' } // @Override public get ruleNames (): string[] { return AgtypeLexer.ruleNames } // @Override public get serializedATN (): string { return AgtypeLexer._serializedATN } // @Override public get channelNames (): string[] { return AgtypeLexer.channelNames } // @Override public get modeNames (): string[] { return AgtypeLexer.modeNames } public static readonly _serializedATN: string = '\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x02\x15\xB9\b\x01' + '\x04\x02\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06\t\x06' + '\x04\x07\t\x07\x04\b\t\b\x04\t\t\t\x04\n\t\n\x04\v\t\v\x04\f\t\f\x04\r' + '\t\r\x04\x0E\t\x0E\x04\x0F\t\x0F\x04\x10\t\x10\x04\x11\t\x11\x04\x12\t' + '\x12\x04\x13\t\x13\x04\x14\t\x14\x04\x15\t\x15\x04\x16\t\x16\x04\x17\t' + '\x17\x04\x18\t\x18\x04\x19\t\x19\x04\x1A\t\x1A\x04\x1B\t\x1B\x03\x02\x03' + '\x02\x03\x02\x03\x02\x03\x02\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03' + '\x03\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x05\x03\x05\x03\x06\x03' + '\x06\x03\x07\x03\x07\x03\b\x03\b\x03\t\x03\t\x03\n\x03\n\x03\v\x03\v\x03' + '\v\x03\f\x03\f\x03\r\x03\r\x03\r\x03\r\x03\r\x03\r\x03\r\x03\r\x03\r\x03' + '\x0E\x03\x0E\x03\x0E\x03\x0E\x03\x0F\x03\x0F\x07\x0Fh\n\x0F\f\x0F\x0E' + '\x0Fk\v\x0F\x03\x10\x03\x10\x03\x10\x07\x10p\n\x10\f\x10\x0E\x10s\v\x10' + '\x03\x10\x03\x10\x03\x11\x03\x11\x03\x11\x05\x11z\n\x11\x03\x12\x03\x12' + '\x03\x12\x03\x12\x03\x12\x03\x12\x03\x13\x03\x13\x03\x14\x03\x14\x03\x15' + '\x05\x15\x87\n\x15\x03\x15\x03\x15\x03\x16\x03\x16\x03\x16\x07\x16\x8E' + '\n\x16\f\x16\x0E\x16\x91\v\x16\x05\x16\x93\n\x16\x03\x17\x05\x17\x96\n' + '\x17\x03\x17\x03\x17\x03\x17\x03\x18\x05\x18\x9C\n\x18\x03\x18\x03\x18' + '\x05\x18\xA0\n\x18\x03\x18\x03\x18\x03\x19\x03\x19\x06\x19\xA6\n\x19\r' + '\x19\x0E\x19\xA7\x03\x1A\x03\x1A\x05\x1A\xAC\n\x1A\x03\x1A\x06\x1A\xAF' + '\n\x1A\r\x1A\x0E\x1A\xB0\x03\x1B\x06\x1B\xB4\n\x1B\r\x1B\x0E\x1B\xB5\x03' + '\x1B\x03\x1B\x02\x02\x02\x1C\x03\x02\x03\x05\x02\x04\x07\x02\x05\t\x02' + '\x06\v\x02\x07\r\x02\b\x0F\x02\t\x11\x02\n\x13\x02\v\x15\x02\f\x17\x02' + '\r\x19\x02\x0E\x1B\x02\x0F\x1D\x02\x10\x1F\x02\x11!\x02\x02#\x02\x02%' + "\x02\x02\'\x02\x02)\x02\x12+\x02\x02-\x02\x13/\x02\x141\x02\x023\x02\x02" + '5\x02\x15\x03\x02\f\x05\x02C\\aac|\x07\x02&&2;C\\aac|\n\x02$$11^^ddhh' + 'ppttvv\x05\x022;CHch\x05\x02\x02!$$^^\x03\x023;\x03\x022;\x04\x02GGgg' + '\x04\x02--//\x05\x02\v\f\x0F\x0F""\x02\xBF\x02\x03\x03\x02\x02\x02\x02' + '\x05\x03\x02\x02\x02\x02\x07\x03\x02\x02\x02\x02\t\x03\x02\x02\x02\x02' + '\v\x03\x02\x02\x02\x02\r\x03\x02\x02\x02\x02\x0F\x03\x02\x02\x02\x02\x11' + '\x03\x02\x02\x02\x02\x13\x03\x02\x02\x02\x02\x15\x03\x02\x02\x02\x02\x17' + '\x03\x02\x02\x02\x02\x19\x03\x02\x02\x02\x02\x1B\x03\x02\x02\x02\x02\x1D' + '\x03\x02\x02\x02\x02\x1F\x03\x02\x02\x02\x02)\x03\x02\x02\x02\x02-\x03' + '\x02\x02\x02\x02/\x03\x02\x02\x02\x025\x03\x02\x02\x02\x037\x03\x02\x02' + '\x02\x05<\x03\x02\x02\x02\x07B\x03\x02\x02\x02\tG\x03\x02\x02\x02\vI\x03' + '\x02\x02\x02\rK\x03\x02\x02\x02\x0FM\x03\x02\x02\x02\x11O\x03\x02\x02' + '\x02\x13Q\x03\x02\x02\x02\x15S\x03\x02\x02\x02\x17V\x03\x02\x02\x02\x19' + 'X\x03\x02\x02\x02\x1Ba\x03\x02\x02\x02\x1De\x03\x02\x02\x02\x1Fl\x03\x02' + "\x02\x02!v\x03\x02\x02\x02#{\x03\x02\x02\x02%\x81\x03\x02\x02\x02\'\x83" + '\x03\x02\x02\x02)\x86\x03\x02\x02\x02+\x92\x03\x02\x02\x02-\x95\x03\x02' + '\x02\x02/\x9B\x03\x02\x02\x021\xA3\x03\x02\x02\x023\xA9\x03\x02\x02\x02' + '5\xB3\x03\x02\x02\x0278\x07v\x02\x0289\x07t\x02\x029:\x07w\x02\x02:;\x07' + 'g\x02\x02;\x04\x03\x02\x02\x02<=\x07h\x02\x02=>\x07c\x02\x02>?\x07n\x02' + '\x02?@\x07u\x02\x02@A\x07g\x02\x02A\x06\x03\x02\x02\x02BC\x07p\x02\x02' + 'CD\x07w\x02\x02DE\x07n\x02\x02EF\x07n\x02\x02F\b\x03\x02\x02\x02GH\x07' + '}\x02\x02H\n\x03\x02\x02\x02IJ\x07.\x02\x02J\f\x03\x02\x02\x02KL\x07\x7F' + '\x02\x02L\x0E\x03\x02\x02\x02MN\x07<\x02\x02N\x10\x03\x02\x02\x02OP\x07' + ']\x02\x02P\x12\x03\x02\x02\x02QR\x07_\x02\x02R\x14\x03\x02\x02\x02ST\x07' + '<\x02\x02TU\x07<\x02\x02U\x16\x03\x02\x02\x02VW\x07/\x02\x02W\x18\x03' + '\x02\x02\x02XY\x07K\x02\x02YZ\x07p\x02\x02Z[\x07h\x02\x02[\\\x07k\x02' + '\x02\\]\x07p\x02\x02]^\x07k\x02\x02^_\x07v\x02\x02_`\x07{\x02\x02`\x1A' + '\x03\x02\x02\x02ab\x07P\x02\x02bc\x07c\x02\x02cd\x07P\x02\x02d\x1C\x03' + '\x02\x02\x02ei\t\x02\x02\x02fh\t\x03\x02\x02gf\x03\x02\x02\x02hk\x03\x02' + '\x02\x02ig\x03\x02\x02\x02ij\x03\x02\x02\x02j\x1E\x03\x02\x02\x02ki\x03' + "\x02\x02\x02lq\x07$\x02\x02mp\x05!\x11\x02np\x05\'\x14\x02om\x03\x02\x02" + '\x02on\x03\x02\x02\x02ps\x03\x02\x02\x02qo\x03\x02\x02\x02qr\x03\x02\x02' + '\x02rt\x03\x02\x02\x02sq\x03\x02\x02\x02tu\x07$\x02\x02u \x03\x02\x02' + '\x02vy\x07^\x02\x02wz\t\x04\x02\x02xz\x05#\x12\x02yw\x03\x02\x02\x02y' + 'x\x03\x02\x02\x02z"\x03\x02\x02\x02{|\x07w\x02\x02|}\x05%\x13\x02}~\x05' + '%\x13\x02~\x7F\x05%\x13\x02\x7F\x80\x05%\x13\x02\x80$\x03\x02\x02\x02' + '\x81\x82\t\x05\x02\x02\x82&\x03\x02\x02\x02\x83\x84\n\x06\x02\x02\x84' + '(\x03\x02\x02\x02\x85\x87\x07/\x02\x02\x86\x85\x03\x02\x02\x02\x86\x87' + '\x03\x02\x02\x02\x87\x88\x03\x02\x02\x02\x88\x89\x05+\x16\x02\x89*\x03' + '\x02\x02\x02\x8A\x93\x072\x02\x02\x8B\x8F\t\x07\x02\x02\x8C\x8E\t\b\x02' + '\x02\x8D\x8C\x03\x02\x02\x02\x8E\x91\x03\x02\x02\x02\x8F\x8D\x03\x02\x02' + '\x02\x8F\x90\x03\x02\x02\x02\x90\x93\x03\x02\x02\x02\x91\x8F\x03\x02\x02' + '\x02\x92\x8A\x03\x02\x02\x02\x92\x8B\x03\x02\x02\x02\x93,\x03\x02\x02' + '\x02\x94\x96\x07/\x02\x02\x95\x94\x03\x02\x02\x02\x95\x96\x03\x02\x02' + '\x02\x96\x97\x03\x02\x02\x02\x97\x98\x05+\x16\x02\x98\x99\x051\x19\x02' + '\x99.\x03\x02\x02\x02\x9A\x9C\x07/\x02\x02\x9B\x9A\x03\x02\x02\x02\x9B' + '\x9C\x03\x02\x02\x02\x9C\x9D\x03\x02\x02\x02\x9D\x9F\x05+\x16\x02\x9E' + '\xA0\x051\x19\x02\x9F\x9E\x03\x02\x02\x02\x9F\xA0\x03\x02\x02\x02\xA0' + '\xA1\x03\x02\x02\x02\xA1\xA2\x053\x1A\x02\xA20\x03\x02\x02\x02\xA3\xA5' + '\x070\x02\x02\xA4\xA6\t\b\x02\x02\xA5\xA4\x03\x02\x02\x02\xA6\xA7\x03' + '\x02\x02\x02\xA7\xA5\x03\x02\x02\x02\xA7\xA8\x03\x02\x02\x02\xA82\x03' + '\x02\x02\x02\xA9\xAB\t\t\x02\x02\xAA\xAC\t\n\x02\x02\xAB\xAA\x03\x02\x02' + '\x02\xAB\xAC\x03\x02\x02\x02\xAC\xAE\x03\x02\x02\x02\xAD\xAF\t\b\x02\x02' + '\xAE\xAD\x03\x02\x02\x02\xAF\xB0\x03\x02\x02\x02\xB0\xAE\x03\x02\x02\x02' + '\xB0\xB1\x03\x02\x02\x02\xB14\x03\x02\x02\x02\xB2\xB4\t\v\x02\x02\xB3' + '\xB2\x03\x02\x02\x02\xB4\xB5\x03\x02\x02\x02\xB5\xB3\x03\x02\x02\x02\xB5' + '\xB6\x03\x02\x02\x02\xB6\xB7\x03\x02\x02\x02\xB7\xB8\b\x1B\x02\x02\xB8' + '6\x03\x02\x02\x02\x11\x02ioqy\x86\x8F\x92\x95\x9B\x9F\xA7\xAB\xB0\xB5' + '\x03\b\x02\x02'; public static __ATN: ATN; public static get _ATN (): ATN { if (!AgtypeLexer.__ATN) { AgtypeLexer.__ATN = new ATNDeserializer().deserialize(Utils.toCharArray(AgtypeLexer._serializedATN)) } return AgtypeLexer.__ATN } }
the_stack
// Subpages import './appearance_page/appearance_fonts_page.js'; import './autofill_page/autofill_section.js'; import './autofill_page/password_check.js'; import './autofill_page/passwords_section.js'; import './autofill_page/passwords_device_section.js'; import './autofill_page/payments_section.js'; import './clear_browsing_data_dialog/clear_browsing_data_dialog.js'; import './search_engines_page/search_engines_page.js'; import './privacy_page/privacy_review/privacy_review_description_item.js'; import './privacy_page/privacy_review/privacy_review_history_sync_fragment.js'; import './privacy_page/privacy_review/privacy_review_msbb_fragment.js'; import './privacy_page/privacy_review/privacy_review_page.js'; import './privacy_page/security_keys_subpage.js'; import './privacy_page/security_page.js'; import './site_settings/all_sites.js'; import './site_settings/site_data_details_subpage.js'; import './site_settings_page/site_settings_page.js'; import './site_settings/category_default_setting.js'; import './site_settings/category_setting_exceptions.js'; import './site_settings/chooser_exception_list.js'; import './site_settings/media_picker.js'; import './site_settings/pdf_documents.js'; import './site_settings/protocol_handlers.js'; import './site_settings/settings_category_default_radio_group.js'; import './site_settings/site_data.js'; import './site_settings/site_details.js'; import './site_settings/zoom_levels.js'; // <if expr="not chromeos and not lacros"> import './people_page/import_data_dialog.js'; // </if> // <if expr="not chromeos"> import './people_page/manage_profile.js'; // </if> import './people_page/signout_dialog.js'; import './people_page/sync_controls.js'; import './people_page/sync_page.js'; // <if expr="use_nss_certs"> import 'chrome://resources/cr_components/certificate_manager/certificate_manager.js'; // </if> // Sections import './a11y_page/a11y_page.js'; import './downloads_page/downloads_page.js'; // <if expr="not chromeos"> import './languages_page/languages_page.js'; // </if> import './reset_page/reset_page.js'; // <if expr="not chromeos and not lacros"> import './system_page/system_page.js'; // </if> // <if expr="not chromeos and not is_macosx"> import './languages_page/edit_dictionary_page.js'; // </if> export {CrCheckboxElement} from 'chrome://resources/cr_elements/cr_checkbox/cr_checkbox.m.js'; export {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; export {CrIconButtonElement} from 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js'; export {CrInputElement} from 'chrome://resources/cr_elements/cr_input/cr_input.m.js'; export {CrSliderElement} from 'chrome://resources/cr_elements/cr_slider/cr_slider.js'; export {getToastManager} from 'chrome://resources/cr_elements/cr_toast/cr_toast_manager.js'; export {SettingsAppearanceFontsPageElement} from './appearance_page/appearance_fonts_page.js'; export {FontsBrowserProxy, FontsBrowserProxyImpl, FontsData} from './appearance_page/fonts_browser_proxy.js'; export {CountryDetailManager, CountryDetailManagerImpl, SettingsAddressEditDialogElement} from './autofill_page/address_edit_dialog.js'; export {SettingsAddressRemoveConfirmationDialogElement} from './autofill_page/address_remove_confirmation_dialog.js'; export {AutofillManagerImpl, AutofillManagerProxy, PersonalDataChangedListener} from './autofill_page/autofill_manager_proxy.js'; export {SettingsAutofillSectionElement} from './autofill_page/autofill_section.js'; // <if expr="chromeos_ash or chromeos_lacros"> export {BlockingRequestManager} from './autofill_page/blocking_request_manager.js'; // </if> export {SettingsCreditCardEditDialogElement} from './autofill_page/credit_card_edit_dialog.js'; export {PasswordEditDialogElement} from './autofill_page/password_edit_dialog.js'; export {PasswordListItemElement} from './autofill_page/password_list_item.js'; export {PasswordMoveMultiplePasswordsToAccountDialogElement} from './autofill_page/password_move_multiple_passwords_to_account_dialog.js'; export {PasswordsExportDialogElement} from './autofill_page/passwords_export_dialog.js'; export {PasswordsSectionElement} from './autofill_page/passwords_section.js'; export {PaymentsManagerImpl, PaymentsManagerProxy} from './autofill_page/payments_manager_proxy.js'; export {SettingsPaymentsSectionElement} from './autofill_page/payments_section.js'; // <if expr="_google_chrome and is_win"> export {ChromeCleanupIdleReason} from './chrome_cleanup_page/chrome_cleanup_page.js'; export {ChromeCleanupProxy, ChromeCleanupProxyImpl} from './chrome_cleanup_page/chrome_cleanup_proxy.js'; export {CHROME_CLEANUP_DEFAULT_ITEMS_TO_SHOW} from './chrome_cleanup_page/items_to_remove_list.js'; // </if> export {ClearBrowsingDataBrowserProxy, ClearBrowsingDataBrowserProxyImpl, ClearBrowsingDataResult, InstalledApp} from './clear_browsing_data_dialog/clear_browsing_data_browser_proxy.js'; export {SettingsClearBrowsingDataDialogElement} from './clear_browsing_data_dialog/clear_browsing_data_dialog.js'; export {SettingsHistoryDeletionDialogElement} from './clear_browsing_data_dialog/history_deletion_dialog.js'; export {SettingsPasswordsDeletionDialogElement} from './clear_browsing_data_dialog/passwords_deletion_dialog.js'; export {ControlledButtonElement} from './controls/controlled_button.js'; export {SettingsCheckboxElement} from './controls/settings_checkbox.js'; export {SettingsRadioGroupElement} from './controls/settings_radio_group.js'; export {SettingsSliderElement} from './controls/settings_slider.js'; export {SettingsTextareaElement} from './controls/settings_textarea.js'; export {DownloadsBrowserProxy, DownloadsBrowserProxyImpl} from './downloads_page/downloads_browser_proxy.js'; export {SettingsDownloadsPageElement} from './downloads_page/downloads_page.js'; // <if expr="_google_chrome and is_win"> export {IncompatibleApplication, IncompatibleApplicationsBrowserProxyImpl} from './incompatible_applications_page/incompatible_applications_browser_proxy.js'; // </if> // <if expr="not chromeos"> export {LanguagesBrowserProxy, LanguagesBrowserProxyImpl} from './languages_page/languages_browser_proxy.js'; export {LanguageSettingsActionType, LanguageSettingsMetricsProxy, LanguageSettingsMetricsProxyImpl, LanguageSettingsPageImpressionType} from './languages_page/languages_settings_metrics_proxy.js'; export {kMenuCloseDelay, SettingsLanguagesSubpageElement} from './languages_page/languages_subpage.js'; export {LanguageHelper, LanguagesModel} from './languages_page/languages_types.js'; // </if> // <if expr="not chromeos and not lacros"> export {ImportDataBrowserProxyImpl, ImportDataStatus} from './people_page/import_data_browser_proxy.js'; // </if> // <if expr="not chromeos"> export {SettingsManageProfileElement} from './people_page/manage_profile.js'; export {ManageProfileBrowserProxy, ManageProfileBrowserProxyImpl, ProfileShortcutStatus} from './people_page/manage_profile_browser_proxy.js'; // </if> export {SettingsSyncControlsElement} from './people_page/sync_controls.js'; export {SettingsSyncEncryptionOptionsElement} from './people_page/sync_encryption_options.js'; export {SettingsSyncPageElement} from './people_page/sync_page.js'; export {SettingsCollapseRadioButtonElement} from './privacy_page/collapse_radio_button.js'; export {SettingsCookiesPageElement} from './privacy_page/cookies_page.js'; export {SettingsDoNotTrackToggleElement} from './privacy_page/do_not_track_toggle.js'; export {SettingsPersonalizationOptionsElement} from './privacy_page/personalization_options.js'; export {PrivacyReviewStep} from './privacy_page/privacy_review/constants.js'; export {PrivacyReviewClearOnExitFragmentElement} from './privacy_page/privacy_review/privacy_review_clear_on_exit_fragment.js'; export {PrivacyReviewDescriptionItemElement} from './privacy_page/privacy_review/privacy_review_description_item.js'; export {PrivacyReviewHistorySyncFragmentElement} from './privacy_page/privacy_review/privacy_review_history_sync_fragment.js'; export {PrivacyReviewMsbbFragmentElement} from './privacy_page/privacy_review/privacy_review_msbb_fragment.js'; export {SettingsPrivacyReviewPageElement} from './privacy_page/privacy_review/privacy_review_page.js'; export {PrivacyReviewWelcomeFragmentElement} from './privacy_page/privacy_review/privacy_review_welcome_fragment.js'; export {SettingsSecureDnsElement} from './privacy_page/secure_dns.js'; export {SecureDnsInputElement} from './privacy_page/secure_dns_input.js'; export {BioEnrollDialogPage, SettingsSecurityKeysBioEnrollDialogElement} from './privacy_page/security_keys_bio_enroll_dialog.js'; export {Ctap2Status, SampleStatus, SecurityKeysBioEnrollProxy, SecurityKeysBioEnrollProxyImpl, SecurityKeysCredentialBrowserProxy, SecurityKeysCredentialBrowserProxyImpl, SecurityKeysPINBrowserProxy, SecurityKeysPINBrowserProxyImpl, SecurityKeysResetBrowserProxy, SecurityKeysResetBrowserProxyImpl} from './privacy_page/security_keys_browser_proxy.js'; export {CredentialManagementDialogPage, SettingsSecurityKeysCredentialManagementDialogElement} from './privacy_page/security_keys_credential_management_dialog.js'; export {ResetDialogPage, SettingsSecurityKeysResetDialogElement} from './privacy_page/security_keys_reset_dialog.js'; export {SetPINDialogPage, SettingsSecurityKeysSetPinDialogElement} from './privacy_page/security_keys_set_pin_dialog.js'; export {SafeBrowsingSetting, SettingsSecurityPageElement} from './privacy_page/security_page.js'; export {SettingsResetPageElement} from './reset_page/reset_page.js'; export {SettingsResetProfileDialogElement} from './reset_page/reset_profile_dialog.js'; export {SettingsOmniboxExtensionEntryElement} from './search_engines_page/omnibox_extension_entry.js'; export {SettingsSearchEngineDialogElement} from './search_engines_page/search_engine_dialog.js'; export {SettingsSearchEngineEntryElement} from './search_engines_page/search_engine_entry.js'; export {SettingsSearchEnginesPageElement} from './search_engines_page/search_engines_page.js'; export {AddSiteDialogElement} from './site_settings/add_site_dialog.js'; export {AllSitesElement} from './site_settings/all_sites.js'; // <if expr="chromeos"> export {AndroidInfoBrowserProxy, AndroidInfoBrowserProxyImpl, AndroidSmsInfo} from './site_settings/android_info_browser_proxy.js'; // </if> export {CategorySettingExceptionsElement} from './site_settings/category_setting_exceptions.js'; export {ChooserExceptionListElement} from './site_settings/chooser_exception_list.js'; export {ChooserExceptionListEntryElement} from './site_settings/chooser_exception_list_entry.js'; export {ChooserType, ContentSetting, ContentSettingsTypes, CookieControlsMode, NotificationSetting, SITE_EXCEPTION_WILDCARD, SiteSettingSource, SortMethod} from './site_settings/constants.js'; export {CookieDetails, cookieInfo} from './site_settings/cookie_info.js'; export {SettingsEditExceptionDialogElement} from './site_settings/edit_exception_dialog.js'; export {LocalDataBrowserProxy, LocalDataBrowserProxyImpl, LocalDataItem} from './site_settings/local_data_browser_proxy.js'; export {AppHandlerEntry, AppProtocolEntry, HandlerEntry, ProtocolEntry, ProtocolHandlersElement} from './site_settings/protocol_handlers.js'; export {SettingsCategoryDefaultRadioGroupElement} from './site_settings/settings_category_default_radio_group.js'; export {SiteDetailsElement} from './site_settings/site_details.js'; export {SiteDetailsPermissionElement} from './site_settings/site_details_permission.js'; export {SiteEntryElement} from './site_settings/site_entry.js'; export {SiteListElement} from './site_settings/site_list.js'; export {SiteListEntryElement} from './site_settings/site_list_entry.js'; export {ChooserException, ContentSettingProvider, CookiePrimarySetting, DefaultContentSetting, OriginInfo, RawChooserException, RawSiteException, RecentSitePermissions, SiteException, SiteGroup, SiteSettingsPrefsBrowserProxy, SiteSettingsPrefsBrowserProxyImpl, ZoomLevelEntry} from './site_settings/site_settings_prefs_browser_proxy.js'; export {WebsiteUsageBrowserProxy, WebsiteUsageBrowserProxyImpl} from './site_settings/website_usage_browser_proxy.js'; export {ZoomLevelsElement} from './site_settings/zoom_levels.js'; export {SettingsRecentSitePermissionsElement} from './site_settings_page/recent_site_permissions.js'; export {defaultSettingLabel} from './site_settings_page/site_settings_list.js'; export {SettingsSiteSettingsPageElement} from './site_settings_page/site_settings_page.js'; // <if expr="not chromeos and not lacros"> export {SettingsSystemPageElement} from './system_page/system_page.js'; export {SystemPageBrowserProxy, SystemPageBrowserProxyImpl} from './system_page/system_page_browser_proxy.js'; // </if>
the_stack
import { BaseCollection, BaseCollectionMixin, BaseCollectionOptions, } from 'detritus-utils'; import { ShardClient } from '../client'; export { BaseCollection, BaseCollectionOptions, }; export class BaseCollectionCache<K, V> extends BaseCollectionMixin<K, V> { readonly caches = new BaseCollection<K, BaseCollection<K, V>>(); readonly options: BaseCollectionOptions = {}; constructor(options?: BaseCollectionOptions) { super(); Object.assign(this.options, options); Object.defineProperties(this, { caches: {enumerable: false}, options: {enumerable: false}, }); } get size(): number { let size = 0; for (let [cacheKey, cache] of this.caches) { size += cache.size; } return size; } clear(): void { for (let [cacheKey, cache] of this.caches) { cache.clear(); } return this.caches.clear(); } delete(cacheKey: K): boolean; delete(cacheKey: K | null | undefined, key: K): boolean; delete(cacheKey?: K | null, key?: K | null): boolean { if (cacheKey) { if (key) { const cache = this.caches.get(cacheKey); if (cache) { return cache.delete(key); } } else { return this.caches.delete(cacheKey); } } else if (key) { let deleted = false; for (let [ck, cache] of this.caches) { if (cache.delete(key)) { deleted = true; } } return deleted; } return false; } forEach(func: (v: V, k: K, map: Map<K, V>) => void, thisArg?: any): void { for (let [cacheKey, cache] of this.caches) { for (let [k, v] of cache) { func.call(thisArg, v, k, cache); } } } get(cacheKey: K): BaseCollection<K, V> | undefined; get(cacheKey: K | null | undefined, key: K): V | undefined; get(cacheKey?: K | null, key?: K | null): BaseCollection<K, V> | V | undefined { if (cacheKey) { const cache = this.caches.get(cacheKey); if (key) { if (cache) { return cache.get(key); } } else { return cache; } } else if (key) { for (let [ck, cache] of this.caches) { if (cache.has(key)) { return cache.get(key); } } } return undefined; } has(cacheKey: K): boolean; has(cacheKey: K | null | undefined, key: K): boolean; has(cacheKey?: K | null, key?: K | null): boolean { if (cacheKey) { if (key) { const cache = this.caches.get(cacheKey); if (cache) { return cache.has(key); } } else { return this.caches.has(cacheKey); } } else if (key) { for (let [ck, cache] of this.caches) { if (cache.has(key)) { return true; } } } return false; } insertCache(cacheKey: K): BaseCollection<K, V> { let cache = this.caches.get(cacheKey); if (!cache) { cache = new BaseCollection(this.options); this.caches.set(cacheKey, cache); } return cache; } set(cacheKey: K, key: K, value: V): this { const cache = this.insertCache(cacheKey); cache.set(key, value); return this; } *keys(): IterableIterator<K> { for (let cache of this.caches.values()) { for (let key of cache.keys()) { yield key; } } } *values(): IterableIterator<V> { for (let cache of this.caches.values()) { for (let value of cache.values()) { yield value; } } } *[Symbol.iterator](): IterableIterator<[K, V]> { for (let [cacheKey, cache] of this.caches) { for (let [key, value] of cache) { yield [key, value]; } } } get [Symbol.toStringTag](): string { return `BaseCollectionCache (${this.caches.size.toLocaleString()} caches, ${this.size.toLocaleString()} items)`; } } export interface BaseClientCollectionOptions extends BaseCollectionOptions { enabled?: boolean, } /** * Basic Client Collection, the ShardClient instance is attached to this * @category Collections */ export class BaseClientCollection<K, V> extends BaseCollection<K, V> { client: ShardClient; enabled: boolean; constructor( client: ShardClient, options: BaseClientCollectionOptions | boolean = {}, ) { if (typeof(options) === 'boolean') { options = {enabled: options}; } super(options); this.client = client; this.enabled = !!(options.enabled || options.enabled === undefined); Object.defineProperties(this, { client: {enumerable: false, writable: false}, enabled: {configurable: true, writable: false}, }); } setEnabled(value: boolean) { Object.defineProperty(this, 'enabled', {value}); } } /** * Basic Client Cache Collection, the ShardClient instance is attached to this * @category Collections */ export class BaseClientCollectionCache<K, V> extends BaseCollectionCache<K, V> { client: ShardClient; enabled: boolean; constructor( client: ShardClient, options: BaseClientCollectionOptions | boolean = {}, ) { if (typeof(options) === 'boolean') { options = {enabled: options}; } super(options); this.client = client; this.enabled = !!(options.enabled || options.enabled === undefined); Object.defineProperties(this, { client: {enumerable: false, writable: false}, enabled: {configurable: true, writable: false}, }); } setEnabled(value: boolean) { Object.defineProperty(this, 'enabled', {value}); } } export class BaseClientGuildReferenceCache<K, V> extends BaseCollectionMixin<K, V> { client: ShardClient; enabled: boolean; key: string = ''; options: BaseCollectionOptions = {}; constructor( client: ShardClient, options: BaseClientCollectionOptions | boolean = {}, ) { super(); if (typeof(options) === 'boolean') { options = {enabled: options}; } Object.assign(this.options, options); this.client = client; this.enabled = !!(options.enabled || options.enabled === undefined); Object.defineProperties(this, { client: {enumerable: false, writable: false}, enabled: {configurable: true, writable: false}, options: {enumerable: false}, }); } get guilds() { return this.client.guilds; } get size(): number { let size = 0; for (let [guildId, guild] of this.guilds) { const cache = (guild as any)[this.key] as BaseCollection<K, V>; size += cache.size; } return size; } setEnabled(value: boolean) { Object.defineProperty(this, 'enabled', {value}); } clear(): void { for (let [guildId, guild] of this.guilds) { const cache = (guild as any)[this.key] as BaseCollection<K, V>; cache.clear(); } } delete(guildId: K | null | undefined, key: K): boolean; delete(guildId?: K | null, key?: K | null): boolean { if (guildId && key) { const guild = this.guilds.get(<string> <unknown> guildId); if (guild) { const cache = (guild as any)[this.key] as BaseCollection<K, V>; return cache.delete(key); } } else if (key) { let deleted = false; for (let [guildId, guild] of this.guilds) { const cache = (guild as any)[this.key] as BaseCollection<K, V>; if (cache.delete(key)) { deleted = true; } } return deleted; } return false; } forEach(func: (v: V, k: K, map: Map<K, V>) => void, thisArg?: any): void { for (let [guildId, guild] of this.guilds) { const cache = (guild as any)[this.key] as BaseCollection<K, V>; for (let [k, v] of cache) { func.call(thisArg, v, k, cache); } } } get(guildId: K | null | undefined, key: K): V | undefined; get(guildId?: K | null, key?: K | null): BaseCollection<K, V> | V | undefined { if (guildId && key) { const guild = this.guilds.get(<string> <unknown> guildId); if (guild) { const cache = (guild as any)[this.key] as BaseCollection<K, V>; return cache.get(key); } } else if (key) { for (let [guildId, guild] of this.guilds) { const cache = (guild as any)[this.key] as BaseCollection<K, V>; if (cache.has(key)) { return cache.get(key); } } } return undefined; } has(guildId: K | null | undefined, key: K): boolean; has(guildId?: K | null, key?: K | null): boolean { if (guildId && key) { const guild = this.guilds.get(<string> <unknown> guildId); if (guild) { const cache = (guild as any)[this.key] as BaseCollection<K, V>; return cache.has(key); } } else if (key) { for (let [guildId, guild] of this.guilds) { const cache = (guild as any)[this.key] as BaseCollection<K, V>; if (cache.has(key)) { return true; } } } return false; } set(guildId: K, key: K, value: V): this { const guild = this.guilds.get(<string> <unknown> guildId); if (guild) { const cache = (guild as any)[this.key] as BaseCollection<K, V>; cache.set(key, value); } return this; } *keys(): IterableIterator<K> { for (let guild of this.guilds.values()) { const cache = (guild as any)[this.key] as BaseCollection<K, V>; for (let key of cache.keys()) { yield key; } } } *values(): IterableIterator<V> { for (let guild of this.guilds.values()) { const cache = (guild as any)[this.key] as BaseCollection<K, V>; for (let value of cache.values()) { yield value; } } } *[Symbol.iterator](): IterableIterator<[K, V]> { for (let [guildId, guild] of this.guilds) { const cache = (guild as any)[this.key] as BaseCollection<K, V>; for (let [key, value] of cache) { yield [key, value]; } } } get [Symbol.toStringTag](): string { return `BaseGuildReferenceCache (${this.guilds.size.toLocaleString()} guilds, ${this.size.toLocaleString()} items)`; } } export class EmptyBaseCollection extends BaseCollection<any, any> { delete(): boolean { return false; } has(): boolean { return false; } set(): this { return this; } get(): any { return undefined; } } const emptyBaseCollection = new EmptyBaseCollection(); Object.freeze(emptyBaseCollection); export { emptyBaseCollection };
the_stack
import { SpreadsheetModel, Spreadsheet, BasicModule } from '../../../src/spreadsheet/index'; import { SpreadsheetHelper } from '../util/spreadsheethelper.spec'; import { defaultData } from '../util/datasource.spec'; import { CellModel, SortEventArgs, SortDescriptor, getCell } from '../../../src/index'; Spreadsheet.Inject(BasicModule); /** * Sorting test cases */ describe('Spreadsheet sorting module ->', () => { let helper: SpreadsheetHelper = new SpreadsheetHelper('spreadsheet'); let model: SpreadsheetModel; let instance: Spreadsheet; describe('UI interaction checking ->', () => { beforeAll((done: Function) => { model = { sheets: [ { ranges: [{ dataSource: defaultData }] } ], created: (): void => { instance = helper.getInstance(); instance.cellFormat({ fontWeight: 'bold', textAlign: 'center' }, 'A1:H1'); } }; helper.initializeSpreadsheet(model, done); }); afterAll(() => { helper.invoke('destroy'); }); it('sort ascending testing', (done: Function) => { helper.invoke('selectRange', ['D2:E5']); helper.setModel('activeCell', 'D2'); helper.invoke('sort', null).then((args: SortEventArgs) => { helper.invoke('getData', [args.range]).then((values: Map<string, CellModel>) => { expect(values.get('D2').value.toString()).toEqual('10'); expect(values.get('E2').value.toString()).toEqual('20'); expect(values.get('D3').value.toString()).toEqual('15'); expect(values.get('E3').value.toString()).toEqual('20'); expect(values.get('D4').value.toString()).toEqual('20'); expect(values.get('E4').value.toString()).toEqual('30'); expect(values.size).toEqual(8); done(); }); }); }); // it('sort undo testing', (done: Function) => { // helper.invoke('undo', null); // expect(getCell(1, 3, instance.getActiveSheet()).value.toString()).toEqual('10'); // expect(getCell(1, 4, instance.getActiveSheet()).value.toString()).toEqual('20'); // expect(getCell(2, 3, instance.getActiveSheet()).value.toString()).toEqual('20'); // expect(getCell(2, 4, instance.getActiveSheet()).value.toString()).toEqual('30'); // expect(getCell(3, 3, instance.getActiveSheet()).value.toString()).toEqual('20'); // expect(getCell(3, 4, instance.getActiveSheet()).value.toString()).toEqual('15'); // done(); // }); it('sort redo testing', (done: Function) => { helper.invoke('redo', null); setTimeout(() => { expect(getCell(1, 3, instance.getActiveSheet()).value.toString()).toEqual('10'); expect(getCell(1, 4, instance.getActiveSheet()).value.toString()).toEqual('20'); expect(getCell(2, 3, instance.getActiveSheet()).value.toString()).toEqual('15'); expect(getCell(2, 4, instance.getActiveSheet()).value.toString()).toEqual('20'); expect(getCell(3, 3, instance.getActiveSheet()).value.toString()).toEqual('20'); expect(getCell(3, 4, instance.getActiveSheet()).value.toString()).toEqual('30'); done(); }, 10); }); it('sort descending testing', (done: Function) => { helper.invoke('selectRange', ['D2:E5']); helper.setModel('activeCell', 'D2'); helper.invoke('sort', [{ sortDescriptors: { order: 'Descending' } }]).then((args: SortEventArgs) => { helper.invoke('getData', [args.range]).then((values: Map<string, CellModel>) => { expect(values.get('D2').value.toString()).toEqual('20'); expect(values.get('E2').value.toString()).toEqual('30'); expect(values.get('D3').value.toString()).toEqual('20'); expect(values.get('E3').value.toString()).toEqual('15'); expect(values.get('D4').value.toString()).toEqual('15'); expect(values.get('E4').value.toString()).toEqual('20'); expect(values.size).toEqual(8); done(); }); }); }); it('sort auto containsHeader testing', (done: Function) => { helper.invoke('selectRange', ['D1:E5']); helper.setModel('activeCell', 'D1'); helper.invoke('sort', null).then((args: SortEventArgs) => { helper.invoke('getData', [args.range]).then((values: Map<string, CellModel>) => { expect(values.get('D1')).toBeUndefined(); //Quantity - skipped expect(values.get('E1')).toBeUndefined(); // Price - skipped expect(values.get('D2').value.toString()).toEqual('10'); expect(values.get('E2').value.toString()).toEqual('20'); expect(values.get('D3').value.toString()).toEqual('15'); expect(values.get('E3').value.toString()).toEqual('20'); expect(values.get('D4').value.toString()).toEqual('20'); expect(values.get('E4').value.toString()).toEqual('30'); expect(values.size).toEqual(8); done(); }); }); }); it('automatic sort range testing', (done: Function) => { helper.invoke('selectRange', ['A1:A1']); //no selection helper.invoke('sort', null).then((args: SortEventArgs) => { expect(args.range).toEqual('Sheet1!A2:H11'); //excluding header done(); }); }); it('catch invalid sort range error testing', (done: Function) => { helper.invoke('selectRange', ['K2:M5']); helper.invoke('sort', null).catch((error: string) => { expect(error).toEqual('Select a cell or range inside the used range and try again.'); done(); }); }); it('custom sort testing', (done: Function) => { helper.invoke('selectRange', ['D1:E11']); //Price - ascending, Quantity - descending let sortDescriptors: SortDescriptor[] = [ { field: 'E', order: 'Ascending' }, { field: 'D', order: 'Descending' } ]; helper.invoke('sort', [{ sortDescriptors: sortDescriptors }]).then((args: SortEventArgs) => { helper.invoke('getData', [args.range]).then((values: Map<string, CellModel>) => { expect(values.get('E2').value.toString()).toEqual('10'); expect(values.get('E3').value.toString()).toEqual('10'); expect(values.get('E4').value.toString()).toEqual('10'); expect(values.get('E5').value.toString()).toEqual('10'); expect(values.get('D2').value.toString()).toEqual('50'); expect(values.get('D3').value.toString()).toEqual('31'); expect(values.get('D4').value.toString()).toEqual('30'); expect(values.get('D5').value.toString()).toEqual('20'); expect(values.size).toEqual(20); done(); }); }); }); it('case sensitive sort testing', (done: Function) => { let td: HTMLTableCellElement = helper.invoke('getCell', [4, 0]); let cellValue: string = td.textContent; helper.invoke('updateCell', [{ value: cellValue.toLowerCase() }, 'A7']); helper.invoke('selectRange', ['A2:B7']); helper.setModel('activeCell', 'A2'); helper.invoke('sort', [{ caseSensitive: true }]).then((args: SortEventArgs) => { helper.invoke('getData', [args.range]).then((values: Map<string, CellModel>) => { // expect(values.get('A5').value.toString()).toEqual(cellValue.toLowerCase());//lowercase first Check this now // expect(values.get('A6').value.toString()).toEqual(cellValue);//uppercase next // expect(values.size).toEqual(12); done(); }); }); }); }); describe('CR-Issues ->', () => { describe('I311230, I311230, I309407, I300737, I315895 ->', () => { beforeAll((done: Function) => { model = { sheets: [{ rows: [{ cells: [{ index: 1, value: 'Amount' }] }, { cells: [{ index: 1, value: 2 }] }, { cells: [{ index: 1, value: 3 }] }, { cells: [{ index: 1, value: 5 }] }, { cells: [{ index: 1, value: 11 }] }, { cells: [{ index: 1, value: 7 }] }, { cells: [{ index: 1, value: 6 }] }, { cells: [{ index: 1, value: 4 }] }] }], created: (): void => { helper.getInstance().hideColumn(0, 10, false); } } as any; helper.initializeSpreadsheet(model, done); }); afterAll(() => { helper.invoke('destroy'); }); it('Try to filter an unsorted number list', (done: Function) => { helper.invoke('numberFormat', ['_-* #,##0_-;-* #,##0_-;_-* "-"_-;_-@_-', 'B1:B8']); const inst: Spreadsheet = helper.getInstance(); expect(inst.sheets[0].rows[1].cells[1].format).toEqual('_-* #,##0_-;-* #,##0_-;_-* "-"_-;_-@_-'); expect(helper.invoke('getCell', [1, 1]).textContent).toEqual('2.00'); helper.invoke('selectRange', ['B1:B8']); setTimeout((): void => { helper.getElement('#' + helper.id + '_sorting').click(); helper.getElement('#' + helper.id + '_applyfilter').click(); expect(!!helper.invoke('getCell', [0, 1]).querySelector('.e-filter-iconbtn')).toBeTruthy(); helper.invoke('selectRange', ['B1']); let filterCell: HTMLElement = helper.invoke('getCell', [0, 1]).querySelector('.e-filter-icon'); helper.triggerMouseAction( 'mousedown', { x: filterCell.getBoundingClientRect().left + 1, y: filterCell.getBoundingClientRect().top + 1 }, null, filterCell); filterCell = helper.invoke('getCell', [0, 1]); helper.triggerMouseAction( 'mouseup', { x: filterCell.getBoundingClientRect().left + 1, y: filterCell.getBoundingClientRect().top + 1 }, document, filterCell); setTimeout((): void => { const sortAsc: HTMLElement = helper.getElement('.e-excelfilter .e-filter-sortasc'); helper.triggerMouseAction( 'mousedown', { x: sortAsc.getBoundingClientRect().left + 1, y: sortAsc.getBoundingClientRect().top + 1 }, null, sortAsc); setTimeout((): void => { expect(inst.sheets[0].rows[3].cells[1].value.toString()).toEqual('4'); expect(helper.invoke('getCell', [3, 1]).textContent).toEqual('4.00'); expect(inst.sheets[0].rows[4].cells[1].value.toString()).toEqual('5'); expect(helper.invoke('getCell', [4, 1]).textContent).toEqual('5.00'); expect(inst.sheets[0].rows[5].cells[1].value.toString()).toEqual('6'); expect(helper.invoke('getCell', [5, 1]).textContent).toEqual('6.00'); expect(inst.sheets[0].rows[6].cells[1].value.toString()).toEqual('7'); expect(helper.invoke('getCell', [6, 1]).textContent).toEqual('7.00'); expect(inst.sheets[0].rows[7].cells[1].value.toString()).toEqual('11'); expect(helper.invoke('getCell', [7, 1]).textContent).toEqual('11.00'); done(); }, 10); }, 10); }); }); it('cut and paste the filtered list', (done: Function) => { helper.invoke('selectRange', ['B1:B8']); setTimeout(() => { helper.invoke('cut').then((): void => { helper.invoke('paste', ['D1']); setTimeout((): void => { expect(!!helper.invoke('getCell', [0, 1]).querySelector('.e-filter-iconbtn')).toBeFalsy(); expect(!!helper.invoke('getCell', [0, 3]).querySelector('.e-filter-iconbtn')).toBeTruthy(); const inst: Spreadsheet = helper.getInstance(); expect(inst.sheets[0].rows[1].cells[1]).toBeNull(); expect(helper.invoke('getCell', [1, 1]).textContent).toEqual(''); expect(inst.sheets[0].rows[7].cells[1]).toBeNull(); expect(helper.invoke('getCell', [7, 1]).textContent).toEqual(''); expect(inst.sheets[0].rows[1].cells[3].value.toString()).toEqual('2'); expect(helper.invoke('getCell', [1, 3]).textContent).toEqual('2.00'); expect(inst.sheets[0].rows[7].cells[3].value.toString()).toEqual('11'); expect(helper.invoke('getCell', [7, 3]).textContent).toEqual('11.00'); done(); }); }, 10); }); }); it('copy the list and paste the list starting from row 2', (done: Function) => { helper.invoke('copy').then(() => { helper.invoke('selectRange', ['D2']); setTimeout((): void => { helper.invoke('paste', ['D2']); setTimeout((): void => { const inst: Spreadsheet = helper.getInstance(); expect(inst.sheets[0].rows[1].cells[3].value.toString()).toEqual('Amount'); expect(helper.invoke('getCell', [1, 3]).textContent).toEqual('Amount'); expect(inst.sheets[0].rows[8].cells[3].value.toString()).toEqual('11'); expect(helper.invoke('getCell', [8, 3]).textContent).toEqual('11.00'); done(); }, 10); }); }); }); }); describe('I309407, I301769 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }] }] }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('sort ascending on a column, the data gets vanished', (done: Function) => { const td: HTMLElement = (helper.getElement('.e-colhdr-table') as HTMLTableElement).tHead.rows[0].cells[3]; helper.triggerMouseAction( 'mousedown', { x: td.getBoundingClientRect().left + 20, y: td.getBoundingClientRect().top + 10 }, null, td); helper.triggerMouseAction( 'mouseup', { x: td.getBoundingClientRect().left + 20, y: td.getBoundingClientRect().top + 10 }, document, td); setTimeout((): void => { const spreadsheet: Spreadsheet = helper.getInstance(); expect(spreadsheet.sheets[0].rows[2].cells[3].value.toString()).toEqual('20'); expect(spreadsheet.sheets[0].rows[6].cells[3].value.toString()).toEqual('40'); expect(spreadsheet.sheets[0].rows[7].cells[3].value.toString()).toEqual('20'); expect(spreadsheet.sheets[0].rows[8].cells[3].value.toString()).toEqual('31'); helper.getElement('#' + helper.id + '_sorting').click(); helper.getElement('#' + helper.id + '_sorting-popup').querySelector('.e-item').click(); setTimeout((): void => { expect(spreadsheet.sheets[0].rows[0].cells[3].value.toString()).toEqual('Quantity'); expect(spreadsheet.sheets[0].rows[2].cells[3].value.toString()).toEqual('15'); expect(spreadsheet.sheets[0].rows[6].cells[3].value.toString()).toEqual('30'); expect(spreadsheet.sheets[0].rows[7].cells[3].value.toString()).toEqual('31'); expect(spreadsheet.sheets[0].rows[8].cells[3].value.toString()).toEqual('40'); done(); }, 10); }, 10); }); }); }); });
the_stack
import {RefCounted} from 'neuroglancer/util/disposable'; import {GL} from 'neuroglancer/webgl/context'; const DEBUG_SHADER = false; export enum ShaderType { VERTEX = WebGL2RenderingContext.VERTEX_SHADER, FRAGMENT = WebGL2RenderingContext.FRAGMENT_SHADER } export interface ShaderErrorMessage { file?: number; line?: number; message: string; } /** * Parses the output of getShaderInfoLog into a list of messages. */ export function parseShaderErrors(log: string) { log = log.replace('\0', ''); let result: ShaderErrorMessage[] = []; for (let line of log.split('\n')) { let m = line.match(/^ERROR:\s*(\d+):(\d+)\s*(.+)$/); if (m !== null) { result.push({message: m[3].trim(), file: parseInt(m[1], 10), line: parseInt(m[2], 10)}); } else { m = line.match(/^ERROR:\s*(.+)$/); if (m !== null) { result.push({message: m[1]}); } else { line = line.trim(); if (line) { result.push({message: line}); } } } } return result; } export class ShaderCompilationError extends Error { shaderType: ShaderType; source: string; log: string; errorMessages: ShaderErrorMessage[]; constructor( shaderType: ShaderType, source: string, log: string, errorMessages: ShaderErrorMessage[]) { const message = `Error compiling ${ShaderType[shaderType].toLowerCase()} shader: ${log}`; super(message); this.name = 'ShaderCompilationError'; this.log = log; this.message = message; this.shaderType = shaderType; this.source = source; this.errorMessages = errorMessages; } } export class ShaderLinkError extends Error { vertexSource: string; fragmentSource: string; log: string; constructor(vertexSource: string, fragmentSource: string, log: string) { const message = `Error linking shader: ${log}`; super(message); this.name = 'ShaderLinkError'; this.log = log; this.message = message; this.vertexSource = vertexSource; this.fragmentSource = fragmentSource; } } export function getShader(gl: WebGL2RenderingContext, source: string, shaderType: ShaderType) { var shader = gl.createShader(shaderType)!; gl.shaderSource(shader, source); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { let log = gl.getShaderInfoLog(shader) || ''; if (DEBUG_SHADER) { let lines = source.replace('<', '&lt;').replace('>', '&gt;').split('\n'); let s = '<pre>'; s += log.replace('<', '&lt;').replace('>', '&gt;') + '\n'; lines.forEach((line, i) => { s += `${i + 1}: ${line}\n`; }); s += `\n</pre>`; console.log(s); let w = window.open('about:blank', '_blank'); if (w !== null) { try { w.document.write(s); } catch (writeError) { } } } throw new ShaderCompilationError(shaderType, source, log, parseShaderErrors(log)); } return shader!; } export type AttributeIndex = number; export type AttributeType = number; export interface VertexShaderInputBinder { enable(divisor: number): void; disable(): void; bind(stride: number, offset: number): void; } let curShader: ShaderProgram|undefined; export class ShaderProgram extends RefCounted { program: WebGLProgram; vertexShader: WebGLShader; fragmentShader: WebGLShader; attributes = new Map<string, AttributeIndex>(); uniforms = new Map<string, WebGLUniformLocation|null>(); textureUnits: Map<any, number>; vertexShaderInputBinders: {[name: string]: VertexShaderInputBinder} = {}; vertexDebugOutputs?: VertexDebugOutput[]; constructor( public gl: GL, public vertexSource: string, public fragmentSource: string, uniformNames?: string[], attributeNames?: string[], vertexDebugOutputs?: VertexDebugOutput[]) { super(); let vertexShader = this.vertexShader = getShader(gl, vertexSource, gl.VERTEX_SHADER); let fragmentShader = this.fragmentShader = getShader(gl, fragmentSource, gl.FRAGMENT_SHADER); let shaderProgram = gl.createProgram()!; gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); if (DEBUG_SHADER && vertexDebugOutputs?.length) { gl.transformFeedbackVaryings( shaderProgram, vertexDebugOutputs.map(x => x.name), WebGL2RenderingContext.INTERLEAVED_ATTRIBS); this.vertexDebugOutputs = vertexDebugOutputs; } gl.linkProgram(shaderProgram); if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { let log = gl.getProgramInfoLog(shaderProgram) || ''; // DEBUG // { // let combinedSource = 'VERTEX SHADER\n\n' + vertexSource + '\n\n\nFRAGMENT SHADER\n\n' + // fragmentSource + '\n'; // let w = window.open("about:blank", "_blank"); // w.document.write('<pre>' + combinedSource.replace('<', '&lt;').replace('>', '&gt;') + // '</pre>'); // } throw new ShaderLinkError(vertexSource, fragmentSource, log); } this.program = shaderProgram!; let {uniforms, attributes} = this; if (uniformNames) { for (let name of uniformNames) { uniforms.set(name, gl.getUniformLocation(shaderProgram, name)); } } if (attributeNames) { for (let name of attributeNames) { attributes.set(name, gl.getAttribLocation(shaderProgram, name)); } } } uniform(name: string): WebGLUniformLocation { return this.uniforms.get(name)!; } attribute(name: string): number { return this.attributes.get(name)!; } textureUnit(symbol: Symbol): number { return this.textureUnits.get(symbol)!; } bind() { curShader = this; this.gl.useProgram(this.program); } disposed() { let {gl} = this; gl.deleteShader(this.vertexShader); this.vertexShader = <any>undefined; gl.deleteShader(this.fragmentShader); this.fragmentShader = <any>undefined; gl.deleteProgram(this.program); this.program = <any>undefined; this.gl = <any>undefined; this.attributes = <any>undefined; this.uniforms = <any>undefined; } } export function drawArraysInstanced( gl: WebGL2RenderingContext, mode: number, first: number, count: number, instanceCount: number) { gl.drawArraysInstanced(mode, first, count, instanceCount); if (!DEBUG_SHADER || !curShader?.vertexDebugOutputs) { return; } const {vertexDebugOutputs} = curShader; let bytesPerVertex = 0; for (const debugOutput of vertexDebugOutputs) { bytesPerVertex += DEBUG_OUTPUT_TYPE_TO_BYTES[debugOutput.typeName]; } const buffer = gl.createBuffer(); const totalBytes = bytesPerVertex * count * instanceCount; gl.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER, buffer); gl.bufferData( WebGL2RenderingContext.ARRAY_BUFFER, totalBytes, WebGL2RenderingContext.DYNAMIC_DRAW); gl.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER, null); gl.bindBufferBase(WebGL2RenderingContext.TRANSFORM_FEEDBACK_BUFFER, 0, buffer); gl.beginTransformFeedback(WebGL2RenderingContext.POINTS); gl.enable(WebGL2RenderingContext.RASTERIZER_DISCARD); gl.drawArraysInstanced(WebGL2RenderingContext.POINTS, first, count, instanceCount); gl.disable(WebGL2RenderingContext.RASTERIZER_DISCARD); gl.endTransformFeedback(); gl.bindBufferBase(WebGL2RenderingContext.TRANSFORM_FEEDBACK_BUFFER, 0, null); gl.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER, buffer); const array = new Uint8Array(totalBytes); gl.getBufferSubData(WebGL2RenderingContext.ARRAY_BUFFER, 0, array, 0, totalBytes); gl.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER, null); gl.deleteBuffer(buffer); let offset = 0; const floatView = new Float32Array(array.buffer); for (let instance = 0; instance < instanceCount; ++instance) { for (let vertex = 0; vertex < count; ++vertex) { let msg = `i=${instance} v=${vertex}:`; for (const debugOutput of vertexDebugOutputs) { msg += ` ${debugOutput.name}=`; switch (debugOutput.typeName) { case 'float': msg += `${floatView[offset++]}`; break; case 'vec2': msg += `${floatView[offset++]},${floatView[offset++]}`; break; case 'vec3': msg += `${floatView[offset++]},${floatView[offset++]},${floatView[offset++]}`; break; case 'vec4': msg += `${floatView[offset++]},${floatView[offset++]},${floatView[offset++]},${ floatView[offset++]}`; break; } } console.log(msg); } } } export type ShaderCodePart = string|ShaderCodePartArray|ShaderCodePartFunction; interface ShaderCodePartFunction { (): ShaderCodePart; } interface ShaderCodePartArray extends Array<ShaderCodePart> {} export class ShaderCode { code = ''; parts = new Set<ShaderCodePart>(); constructor() {} add(x: ShaderCodePart) { if (this.parts.has(x)) { return; } this.parts.add(x); switch (typeof x) { case 'string': this.code += x; break; case 'function': this.add((<ShaderCodePartFunction>x)()); break; default: if (Array.isArray(x)) { for (let y of x) { this.add(y); } } else { console.log('Invalid code type', x); throw new Error('Invalid code type'); } } } toString(): string { return this.code; } } export type ShaderInitializer = ((x: ShaderProgram) => void); export type ShaderModule = ((x: ShaderBuilder) => void); export type ShaderSamplerPrefix = 'i'|'u'|''; export type ShaderSamplerType = 'sampler2D'|'usampler2D'|'isampler2D'|'sampler3D'|'usampler3D'|'isampler3D'; export type ShaderInterpolationMode = ''|'centroid'|'flat centroid'|'smooth centroid'|'flat'|'smooth'; export const textureTargetForSamplerType = { 'sampler2D': WebGL2RenderingContext.TEXTURE_2D, 'isampler2D': WebGL2RenderingContext.TEXTURE_2D, 'usampler2D': WebGL2RenderingContext.TEXTURE_2D, 'sampler3D': WebGL2RenderingContext.TEXTURE_3D, 'isampler3D': WebGL2RenderingContext.TEXTURE_3D, 'usampler3D': WebGL2RenderingContext.TEXTURE_3D, }; export type DebugOutputType = 'float'|'vec2'|'vec3'|'vec4'; const DEBUG_OUTPUT_TYPE_TO_BYTES: Record<DebugOutputType, number> = { 'float': 4, 'vec2': 8, 'vec3': 12, 'vec4': 16, }; interface VertexDebugOutput { typeName: DebugOutputType; name: string; } export class ShaderBuilder { private nextSymbolID = 0; private nextTextureUnit = 0; private uniformsCode = ''; private attributesCode = ''; private varyingsCodeVS = ''; private varyingsCodeFS = ''; private fragmentExtensionsSet = new Set<string>(); private fragmentExtensions = ''; private vertexCode = new ShaderCode(); private vertexMain = ''; private fragmentCode = new ShaderCode(); private outputBufferCode = ''; private fragmentMain = ''; private required = new Set<ShaderModule>(); private uniforms = new Array<string>(); private attributes = new Array<string>(); private initializers: Array<ShaderInitializer> = []; private textureUnits = new Map<Symbol, number>(); private vertexDebugOutputs: VertexDebugOutput[] = []; constructor(public gl: GL) {} addVertexPositionDebugOutput() { this.vertexDebugOutputs.push({typeName: 'vec4', name: 'gl_Position'}); } addVertexDebugOutput(typeName: DebugOutputType, name: string) { this.addVarying(typeName, name); this.vertexDebugOutputs.push({typeName, name}); } allocateTextureUnit(symbol: Symbol, count: number = 1) { if (this.textureUnits.has(symbol)) { throw new Error('Duplicate texture unit symbol: ' + symbol.toString()); } let old = this.nextTextureUnit; this.nextTextureUnit += count; this.textureUnits.set(symbol, old); return old; } addTextureSampler(samplerType: ShaderSamplerType, name: string, symbol: Symbol, extent?: number) { let textureUnit = this.allocateTextureUnit(symbol, extent); this.addUniform(`highp ${samplerType}`, name, extent); this.addInitializer(shader => { if (extent) { let textureUnits = new Int32Array(extent); for (let i = 0; i < extent; ++i) { textureUnits[i] = i + textureUnit; } shader.gl.uniform1iv(shader.uniform(name), textureUnits); } else { shader.gl.uniform1i(shader.uniform(name), textureUnit); } }); return textureUnit; } symbol(name: string) { return name + (this.nextSymbolID++); } addAttribute(typeName: string, name: string, location?: number) { this.attributes.push(name); if (location !== undefined) this.attributesCode += `layout(location = ${location})`; this.attributesCode += `in ${typeName} ${name};\n`; return name; } addVarying(typeName: string, name: string, interpolationMode: ShaderInterpolationMode = '') { this.varyingsCodeVS += `${interpolationMode} out ${typeName} ${name};\n`; this.varyingsCodeFS += `${interpolationMode} in ${typeName} ${name};\n`; } addOutputBuffer(typeName: string, name: string, location: number|null) { if (location !== null) { this.outputBufferCode += `layout(location = ${location}) `; } this.outputBufferCode += `out ${typeName} ${name};\n`; } addUniform(typeName: string, name: string, extent?: number) { this.uniforms.push(name); if (extent != null) { this.uniformsCode += `uniform ${typeName} ${name}[${extent}];\n`; } else { this.uniformsCode += `uniform ${typeName} ${name};\n`; } return name; } addFragmentExtension(name: string) { if (this.fragmentExtensionsSet.has(name)) { return; } this.fragmentExtensionsSet.add(name); this.fragmentExtensions += `#extension ${name} : require\n`; } addVertexCode(code: ShaderCodePart) { this.vertexCode.add(code); } addFragmentCode(code: ShaderCodePart) { this.fragmentCode.add(code); } setVertexMain(code: string) { this.vertexMain = code; } addVertexMain(code: string) { this.vertexMain = (this.vertexMain || '') + code; } setFragmentMain(code: string) { this.fragmentMain = `void main() { ${code} } `; } setFragmentMainFunction(code: string) { this.fragmentMain = code; } addInitializer(f: ShaderInitializer) { this.initializers.push(f); } require(f: ShaderModule): void { if (this.required.has(f)) { return; } this.required.add(f); f(this); } build() { let vertexSource = `#version 300 es precision highp float; precision highp int; ${this.uniformsCode} ${this.attributesCode} ${this.varyingsCodeVS} ${this.vertexCode} void main() { ${this.vertexMain} } `; let fragmentSource = `#version 300 es ${this.fragmentExtensions} precision highp float; precision highp int; ${this.uniformsCode} ${this.varyingsCodeFS} ${this.outputBufferCode} ${this.fragmentCode} ${this.fragmentMain} `; let shader = new ShaderProgram( this.gl, vertexSource, fragmentSource, this.uniforms, this.attributes, this.vertexDebugOutputs); shader.textureUnits = this.textureUnits; let {initializers} = this; if (initializers.length > 0) { shader.bind(); for (let initializer of initializers) { initializer(shader); } } return shader; } } export function shaderContainsIdentifiers(code: string, identifiers: Iterable<string>) { let found = new Set<string>(); for (let identifier of identifiers) { let pattern = new RegExp(`(?:^|[^a-zA-Z0-9_])${identifier}[^a-zA-Z0-9_])`); if (code.match(pattern) !== null) { found.add(identifier); } } return found; }
the_stack
import { FieldDefinitionNode } from 'graphql'; import { compoundExpression, Expression, obj, printBlock, and, equals, notEquals, iff, methodCall, not, ref, str, bool, forEach, list, qref, raw, set, ifElse, } from 'graphql-mapping-template'; import { getIdentityClaimExp, getOwnerClaim, emptyPayload, setHasAuthExpression, iamCheck, iamAdminRoleCheckExpression } from './helpers'; import { COGNITO_AUTH_TYPE, OIDC_AUTH_TYPE, LAMBDA_AUTH_TYPE, RoleDefinition, splitRoles, ConfiguredAuthProviders, IS_AUTHORIZED_FLAG, fieldIsList, API_KEY_AUTH_TYPE, IAM_AUTH_TYPE, } from '../utils'; import { NONE_VALUE } from 'graphql-transformer-common'; const allowedAggFieldsList = 'allowedAggFields'; const aggFieldsFilterMap = 'aggFieldsFilterMap'; const totalFields = 'totalFields'; const apiKeyExpression = (roles: Array<RoleDefinition>): Expression => { const expression = Array<Expression>(); if (roles.length === 0) { expression.push(ref('util.unauthorized()')); } else if (roles[0].allowedFields) { expression.push( set(ref(IS_AUTHORIZED_FLAG), bool(true)), qref(methodCall(ref(`${allowedAggFieldsList}.addAll`), raw(JSON.stringify(roles[0].allowedFields)))), ); } else { expression.push(set(ref(IS_AUTHORIZED_FLAG), bool(true)), set(ref(allowedAggFieldsList), ref(totalFields))); } return iff(equals(ref('util.authType()'), str(API_KEY_AUTH_TYPE)), compoundExpression(expression)); }; const lambdaExpression = (roles: Array<RoleDefinition>): Expression => { const expression = Array<Expression>(); if (roles.length === 0) { expression.push(ref('util.unauthorized()')); } else if (roles[0].allowedFields) { expression.push( set(ref(IS_AUTHORIZED_FLAG), bool(true)), qref(methodCall(ref(`${allowedAggFieldsList}.addAll`), raw(JSON.stringify(roles[0].allowedFields)))), ); } else { expression.push(set(ref(IS_AUTHORIZED_FLAG), bool(true)), set(ref(allowedAggFieldsList), ref(totalFields))); } return iff(equals(ref('util.authType()'), str(LAMBDA_AUTH_TYPE)), compoundExpression(expression)); }; const iamExpression = ( roles: Array<RoleDefinition>, hasAdminRolesEnabled: boolean = false, adminRoles: Array<string> = [], identityPoolId?: string, ) => { const expression = new Array<Expression>(); // allow if using an admin role if (hasAdminRolesEnabled) { expression.push(iamAdminRoleCheckExpression(adminRoles)); } if (roles.length === 0) { expression.push(ref('util.unauthorized()')); } else { for (let role of roles) { const exp: Expression[] = [set(ref(IS_AUTHORIZED_FLAG), bool(true))]; if (role.allowedFields) { exp.push(qref(methodCall(ref(`${allowedAggFieldsList}.addAll`), raw(JSON.stringify(role.allowedFields))))); } else { exp.push(set(ref(allowedAggFieldsList), ref(totalFields))); } expression.push(iff(not(ref(IS_AUTHORIZED_FLAG)), iamCheck(role.claim!, compoundExpression(exp), identityPoolId))); } } return iff(equals(ref('util.authType()'), str(IAM_AUTH_TYPE)), compoundExpression(expression)); }; const generateStaticRoleExpression = (roles: Array<RoleDefinition>): Array<Expression> => { const staticRoleExpression: Array<Expression> = []; let privateRoleIdx = roles.findIndex(r => r.strategy === 'private'); if (privateRoleIdx > -1) { if (roles[privateRoleIdx].allowedFields) { staticRoleExpression.push( qref(methodCall(ref(`${allowedAggFieldsList}.addAll`), raw(JSON.stringify(roles[privateRoleIdx].allowedFields)))), ); } else { staticRoleExpression.push(set(ref(allowedAggFieldsList), ref(totalFields))); } staticRoleExpression.push(set(ref(IS_AUTHORIZED_FLAG), bool(true))); roles.splice(privateRoleIdx, 1); } if (roles.length > 0) { staticRoleExpression.push( iff( not(ref(IS_AUTHORIZED_FLAG)), compoundExpression([ set( ref('staticGroupRoles'), raw( JSON.stringify( roles.map(r => ({ claim: r.claim, entity: r.entity, ...(r.allowedFields ? { allowedFields: r.allowedFields } : {}) })), ), ), ), forEach(ref('groupRole'), ref('staticGroupRoles'), [ set(ref('groupsInToken'), getIdentityClaimExp(ref('groupRole.claim'), list([]))), iff( methodCall(ref('groupsInToken.contains'), ref('groupRole.entity')), compoundExpression([ set(ref(IS_AUTHORIZED_FLAG), bool(true)), ifElse( methodCall(ref('util.isNull'), ref('groupRole.allowedFields')), compoundExpression([set(ref(allowedAggFieldsList), ref(totalFields)), raw(`#break`)]), qref(methodCall(ref(`${allowedAggFieldsList}.addAll`), ref('groupRole.allowedFields'))), ), ]), ), ]), ]), ), ); } return staticRoleExpression; }; const generateAuthFilter = ( roles: Array<RoleDefinition>, fields: ReadonlyArray<FieldDefinitionNode>, allowedAggFields: Array<string>, ): Array<Expression> => { const filterExpression = new Array<Expression>(); const authFilter = new Array<Expression>(); const aggFieldMap: Record<string, Array<string>> = {}; if (!(roles.length > 0)) return []; /** * for opensearch * we create a terms_set where the field (role.entity) has to match at least element in the terms * if the field is a list it will look for a subset of elements in the list which should exist in the terms list * */ roles.forEach((role, idx) => { // for the terms search it's best to go by keyword for non list dynamic auth fields const entityIsList = fieldIsList(fields, role.entity); const roleKey = entityIsList ? role.entity : `${role.entity}.keyword`; if (role.strategy === 'owner') { filterExpression.push( set( ref(`owner${idx}`), obj({ terms_set: obj({ [roleKey]: obj({ terms: list([getOwnerClaim(role.claim!)]), minimum_should_match_script: obj({ source: str('1') }), }), }), }), ), ); authFilter.push(ref(`owner${idx}`)); if (role.allowedFields) { role.allowedFields.forEach(field => { if (!allowedAggFields.includes(field)) { aggFieldMap[field] = [...(aggFieldMap[field] ?? []), `$owner${idx}`]; } }); } } else if (role.strategy === 'groups') { filterExpression.push( set( ref(`group${idx}`), obj({ terms_set: obj({ [roleKey]: obj({ terms: getIdentityClaimExp(str(role.claim!), list([str(NONE_VALUE)])), minimum_should_match_script: obj({ source: str('1') }), }), }), }), ), ); authFilter.push(ref(`group${idx}`)); if (role.allowedFields) { role.allowedFields.forEach(field => { if (!allowedAggFields.includes(field)) { aggFieldMap[field] = [...(aggFieldMap[field] ?? []), `$group${idx}`]; } }); } } }); filterExpression.push( iff( not(ref(IS_AUTHORIZED_FLAG)), qref(methodCall(ref('ctx.stash.put'), str('authFilter'), obj({ bool: obj({ should: list(authFilter) }) }))), ), ); if (Object.keys(aggFieldMap).length > 0) { filterExpression.push( iff( notEquals(ref(`${allowedAggFieldsList}.size()`), ref(`${totalFields}.size()`)), // regex is there so we can remove the quotes from the array values in VTL as they contain objects // ex. "$owner0" to $owner0 qref(methodCall(ref('ctx.stash.put'), str(aggFieldsFilterMap), raw(JSON.stringify(aggFieldMap).replace(/"\$(.*?)"/g, '$$$1')))), ), ); } return filterExpression; }; /* creates the auth expression for searchable - handles object level search query - creates field auth expression for aggregation query */ export const generateAuthExpressionForSearchQueries = ( providers: ConfiguredAuthProviders, roles: Array<RoleDefinition>, fields: ReadonlyArray<FieldDefinitionNode>, allowedAggFields: Array<string>, ): string => { const { cognitoStaticRoles, cognitoDynamicRoles, oidcStaticRoles, oidcDynamicRoles, apiKeyRoles, iamRoles, lambdaRoles } = splitRoles(roles); const totalAuthExpressions: Array<Expression> = [ setHasAuthExpression, set(ref(IS_AUTHORIZED_FLAG), bool(false)), set(ref(totalFields), raw(JSON.stringify(fields.map(f => f.name.value)))), set(ref(allowedAggFieldsList), raw(JSON.stringify(allowedAggFields))), ]; if (providers.hasApiKey) { totalAuthExpressions.push(apiKeyExpression(apiKeyRoles)); } if (providers.hasLambda) { totalAuthExpressions.push(lambdaExpression(lambdaRoles)); } if (providers.hasIAM) { totalAuthExpressions.push(iamExpression(iamRoles, providers.hasAdminRolesEnabled, providers.adminRoles, providers.identityPoolId)); } if (providers.hasUserPools) { totalAuthExpressions.push( iff( equals(ref('util.authType()'), str(COGNITO_AUTH_TYPE)), compoundExpression([ ...generateStaticRoleExpression(cognitoStaticRoles), ...generateAuthFilter(cognitoDynamicRoles, fields, allowedAggFields), ]), ), ); } if (providers.hasOIDC) { totalAuthExpressions.push( iff( equals(ref('util.authType()'), str(OIDC_AUTH_TYPE)), compoundExpression([ ...generateStaticRoleExpression(oidcStaticRoles), ...generateAuthFilter(oidcDynamicRoles, fields, allowedAggFields), ]), ), ); } totalAuthExpressions.push( qref(methodCall(ref('ctx.stash.put'), str(allowedAggFieldsList), ref(allowedAggFieldsList))), iff(and([not(ref(IS_AUTHORIZED_FLAG)), methodCall(ref('util.isNull'), ref('ctx.stash.authFilter'))]), ref('util.unauthorized()')), ); return printBlock('Authorization Steps')(compoundExpression([...totalAuthExpressions, emptyPayload])); };
the_stack
import * as vscode from 'vscode'; import { LoggerWrapper } from './LoggerWrapper'; import { ExecutableConfig } from './ExecutableConfig'; import { SharedVariables } from './SharedVariables'; import { hashString } from './Util'; import { performance } from 'perf_hooks'; import { TestGrouping } from './TestGroupingInterface'; import { AdvancedExecutable, AdvancedExecutableArray, FrameworkSpecific, RunTask, ExecutionWrapper, } from './AdvancedExecutableInterface'; import { platformUtil } from './util/Platform'; type SentryValue = 'question' | 'enable' | 'enabled' | 'disable' | 'disable_1' | 'disable_2' | 'disable_3'; const ConfigSectionBase = 'testMate.cpp'; const enum Section { 'test' = 'test', 'discovery' = 'discovery', 'debug' = 'debug', 'log' = 'log', 'gtest' = 'gtest', } export type Config = | 'test.executables' | 'test.parallelExecutionOfExecutableLimit' | 'test.advancedExecutables' | 'test.workingDirectory' | 'test.randomGeneratorSeed' | 'test.runtimeLimit' | 'test.parallelExecutionLimit' | 'discovery.gracePeriodForMissing' | 'discovery.runtimeLimit' | 'discovery.testListCaching' | 'discovery.strictPattern' | 'debug.configTemplate' | 'debug.breakOnFailure' | 'debug.noThrow' | 'log.logpanel' | 'log.logfile' | 'log.logSentry' | 'log.userId' | 'gtest.treatGmockWarningAs' | 'gtest.gmockVerbose'; class ConfigurationChangeEvent { public constructor(private readonly event: vscode.ConfigurationChangeEvent) {} affectsConfiguration(config: Config, resource?: vscode.Uri): boolean { return this.event.affectsConfiguration(`${ConfigSectionBase}.${config}`, resource); } } /// export class Configurations { private _cfg: vscode.WorkspaceConfiguration; public constructor(public _log: LoggerWrapper, private _workspaceFolderUri: vscode.Uri) { this._cfg = vscode.workspace.getConfiguration(ConfigSectionBase, _workspaceFolderUri); } private _get<T>(section: Config): T | undefined { return this._cfg.get<T>(section); } private _getD<T>(section: string, defaultValue: T): T { return this._cfg.get<T>(section, defaultValue); } // eslint-disable-next-line public getValues(): { test: any; discovery: any; debug: any; log: any; gtest: any } { return { test: this._cfg.get(Section.test), discovery: this._cfg.get(Section.discovery), debug: this._cfg.get(Section.debug), log: this._cfg.get(Section.log), gtest: this._cfg.get(Section.gtest), }; } public static onDidChange(callbacks: (changeEvent: ConfigurationChangeEvent) => void): vscode.Disposable { return vscode.workspace.onDidChangeConfiguration(changeEvent => callbacks(new ConfigurationChangeEvent(changeEvent)), ); } private _hasExtension(id: string): boolean { return vscode.extensions.all.find(e => e.id === id) !== undefined; } public getDebugConfigurationTemplate(): [vscode.DebugConfiguration, string] { const [template, source] = ((): [vscode.DebugConfiguration, string] => { const templateFromConfig = this._getD<vscode.DebugConfiguration | null | 'extensionOnly'>( 'debug.configTemplate', null, ); const template: vscode.DebugConfiguration = { name: '${label} (${suiteLabel})', request: 'launch', type: 'cppdbg', }; if (typeof templateFromConfig === 'object' && templateFromConfig !== null) { Object.assign(template, templateFromConfig); this._log.debug('template', template); return [template, 'userDefined']; } else if (templateFromConfig === null) { const wpLaunchConfigs = vscode.workspace .getConfiguration('launch', this._workspaceFolderUri) .get('configurations'); if (wpLaunchConfigs && Array.isArray(wpLaunchConfigs) && wpLaunchConfigs.length > 0) { for (let i = 0; i < wpLaunchConfigs.length; ++i) { if (wpLaunchConfigs[i].request !== 'launch') continue; const platformProp = platformUtil.getPlatformProperty(wpLaunchConfigs[i]); if (typeof platformProp?.type == 'string') { if ( platformProp.type.startsWith('cpp') || platformProp.type.startsWith('lldb') || platformProp.type.startsWith('gdb') ) { // skip } else { continue; } } else if (typeof wpLaunchConfigs[i].type == 'string') { if ( wpLaunchConfigs[i].type.startsWith('cpp') || wpLaunchConfigs[i].type.startsWith('lldb') || wpLaunchConfigs[i].type.startsWith('gdb') ) { // skip } else { continue; } } else { continue; } // putting as much known properties as much we can and hoping for the best 🤞 Object.assign(template, wpLaunchConfigs[i], { program: '${exec}', target: '${exec}', arguments: '${argsStr}', args: '${argsArray}', cwd: '${cwd}', env: '${envObj}', environment: '${envObjArray}', sourceFileMap: '${sourceFileMapObj}', }); this._log.info( "using debug config from launch.json. If it doesn't work for you please read the manual: https://github.com/matepek/vscode-catch2-test-adapter#or-user-can-manually-fill-it", template, ); return [template, 'fromLaunchJson']; } } } if (this._hasExtension('vadimcn.vscode-lldb')) { Object.assign(template, { type: 'cppdbg', MIMode: 'lldb', program: '${exec}', args: '${argsArray}', cwd: '${cwd}', env: '${envObj}', sourceMap: '${sourceFileMapObj}', }); return [template, 'vadimcn.vscode-lldb']; } else if (this._hasExtension('webfreak.debug')) { Object.assign(template, { type: 'gdb', target: '${exec}', arguments: '${argsStr}', cwd: '${cwd}', env: '${envObj}', valuesFormatting: 'prettyPrinters', pathSubstitutions: '${sourceFileMapObj}', }); if (platformUtil.is('darwin')) { template.type = 'lldb-mi'; // Note: for LLDB you need to have lldb-mi in your PATH // If you are on OS X you can add lldb-mi to your path using ln -s /Applications/Xcode.app/Contents/Developer/usr/bin/lldb-mi /usr/local/bin/lldb-mi if you have Xcode. template.lldbmipath = '/Applications/Xcode.app/Contents/Developer/usr/bin/lldb-mi'; } return [template, 'webfreak.debug']; } else if (this._hasExtension('ms-vscode.cpptools')) { // documentation says debug"environment" = [{...}] but that doesn't work Object.assign(template, { type: 'cppvsdbg', linux: { type: 'cppdbg', MIMode: 'gdb' }, darwin: { type: 'cppdbg', MIMode: 'lldb' }, windows: { type: 'cppvsdbg' }, program: '${exec}', args: '${argsArray}', cwd: '${cwd}', env: '${envObj}', environment: '${envObjArray}', sourceFileMap: '${sourceFileMapObj}', }); return [template, 'ms-vscode.cpptools']; } this._log.info('no debug config'); throw Error( "For debugging 'testMate.cpp.debug.configTemplate' should be set: https://github.com/matepek/vscode-catch2-test-adapter#or-user-can-manually-fill-it", ); })(); const platfromProp = platformUtil.getPlatformProperty(template); if (typeof platfromProp === 'object') Object.assign(template, platfromProp); return [template, source]; } public getOrCreateUserId(): string { let userId = this._get<string>('log.userId'); if (userId) { return userId; } else { let newUserId = (process.env['USER'] || process.env['USERNAME'] || 'user') + process.env['USERDOMAIN']; newUserId += performance.now().toString(); newUserId += process.pid.toString(); newUserId += Date.now().toString(); userId = hashString(newUserId); this._cfg.update('log.userId', userId, vscode.ConfigurationTarget.Global); return userId; } } // public static decrypt(encryptedMsg: string): string { // const buffer = Buffer.from(encryptedMsg, 'base64'); // const decrypted = crypto.privateDecrypt(Configurations.PublicKey, buffer); // return decrypted.toString('utf8'); // } public isSentryEnabled(): boolean { const val = this._get('log.logSentry'); return val === 'enable' || val === 'enabled'; } public askSentryConsent(): void { const envAskSentry = process.env['TESTMATE_CPP_ASKSENTRYCONSENT']; if (envAskSentry === 'disabled_3') { return; //const decrypted = Configurations.decrypt(process.env['TESTMATE_CPP_LOGSENTRY']); //if (decrypted === 'disable_3') return; } const logSentryConfig: Config = 'log.logSentry'; const logSentry = this._getD<SentryValue>(logSentryConfig, 'question'); if (logSentry === 'question' || logSentry === 'disable' || logSentry === 'disable_1' || logSentry === 'disable_2') { const options = [ 'Sure! I love this extension and happy to help.', 'Yes, but exclude current workspace', 'Over my dead body (No)', ]; vscode.window .showInformationMessage( 'Hey there! C++ TestMate has [sentry.io](https://github.com/matepek/vscode-catch2-test-adapter/blob/master/documents/configuration/log.logSentry.md) integration to ' + 'improve the stability and the development. 🤩 For this I want to send logs and errors ' + 'but I would NEVER do it without your consent. ' + 'Please be understandable and allow it. 🙏', ...options, ) .then((value: string | undefined) => { this._log.info('Sentry consent', value); if (value === options[0]) { this._cfg .update(logSentryConfig, 'enable', vscode.ConfigurationTarget.Global) .then(undefined, e => this._log.exceptionS(e)); } else if (value === options[1]) { this._cfg .update(logSentryConfig, 'enable', vscode.ConfigurationTarget.Global) .then(undefined, e => this._log.exceptionS(e)); this._cfg .update(logSentryConfig, 'disable_3', vscode.ConfigurationTarget.WorkspaceFolder) .then(undefined, e => this._log.exceptionS(e)); } else if (value === options[2]) { this._cfg .update(logSentryConfig, 'disable_3', vscode.ConfigurationTarget.Global) .then(undefined, e => this._log.exceptionS(e)); } }); } } public getDebugBreakOnFailure(): boolean { return this._getD<boolean>('debug.breakOnFailure', true); } public getDefaultNoThrow(): boolean { return this._getD<boolean>('debug.noThrow', false); } public getDefaultCwd(): string { const dirname = this._workspaceFolderUri.fsPath; return this._getD<string>('test.workingDirectory', dirname); } public getRandomGeneratorSeed(): 'time' | number | null { const val = this._getD<string>('test.randomGeneratorSeed', 'time'); if (val === 'time') return val; if (val === '') return null; const num = Number(val); if (!Number.isNaN(num)) return num; else return null; } private static _parallelExecutionLimitMetricSent = false; public getParallelExecutionLimit(): number { const res = Math.max(1, this._getD<number>('test.parallelExecutionLimit', 1)); if (typeof res != 'number') return 1; else { if (res > 1 && !Configurations._parallelExecutionLimitMetricSent) { this._log.infoS('Using test.parallelExecutionLimit'); Configurations._parallelExecutionLimitMetricSent = true; } return res; } } public getParallelExecutionOfExecutableLimit(): number { const cfgName: Config = 'test.parallelExecutionOfExecutableLimit'; const res = Math.max(1, this._getD<number>(cfgName, 1)); if (typeof res != 'number' || Number.isNaN(res)) return 1; else { if (res > 1) this._log.infoS(cfgName, res); return res; } } public getExecWatchTimeout(): number { const res = this._getD<number>('discovery.gracePeriodForMissing', 10) * 1000; return res; } public getExecRunningTimeout(): null | number { const r = this._getD<null | number>('test.runtimeLimit', null); return r !== null && r > 0 ? r * 1000 : null; } public getExecParsingTimeout(): number { const r = this._getD<number>('discovery.runtimeLimit', 5); return r * 1000; } public getEnableTestListCaching(): boolean { return this._getD<boolean>('discovery.testListCaching', false); } public getEnableStrictPattern(): boolean { return this._getD<boolean>('discovery.strictPattern', false); } public getGoogleTestTreatGMockWarningAs(): 'nothing' | 'failure' { return this._getD<'nothing' | 'failure'>('gtest.treatGmockWarningAs', 'nothing'); } public getGoogleTestGMockVerbose(): 'default' | 'info' | 'warning' | 'error' { return this._getD<'default' | 'info' | 'warning' | 'error'>('gtest.gmockVerbose', 'default'); } public getExecutables(shared: SharedVariables): ExecutableConfig[] { const defaultCwd = this.getDefaultCwd() || '${absDirpath}'; const defaultParallelExecutionOfExecLimit = this.getParallelExecutionOfExecutableLimit() || 1; const createExecutableConfigFromPattern = (pattern: string): ExecutableConfig => { return new ExecutableConfig( shared, pattern, undefined, undefined, defaultCwd, undefined, undefined, [], { before: [], beforeEach: [], after: [], afterEach: [] }, defaultParallelExecutionOfExecLimit, false, undefined, undefined, undefined, {}, undefined, {}, {}, {}, {}, ); }; const [advanced, simple] = ((): [AdvancedExecutableArray | undefined, string | undefined] => { const advanced = this._cfg.inspect<AdvancedExecutableArray>('test.advancedExecutables'); const simple = this._cfg.inspect<string>('test.executables'); if (advanced === undefined || simple === undefined) { this._log.errorS('advanced === undefined || simple === undefined', advanced, simple); throw Error('Assertion. Please file an issue.'); } if (advanced.workspaceFolderValue !== undefined || simple.workspaceFolderValue !== undefined) return [advanced.workspaceFolderValue, simple.workspaceFolderValue]; if (advanced.workspaceValue !== undefined || simple.workspaceValue !== undefined) return [advanced.workspaceValue, simple.workspaceValue]; if (advanced.globalValue !== undefined || simple.globalValue !== undefined) return [advanced.globalValue, simple.globalValue]; if (advanced.defaultValue !== undefined || simple.defaultValue !== undefined) return [advanced.defaultValue, simple.defaultValue]; else return [undefined, undefined]; })(); if (advanced === undefined || (Array.isArray(advanced) && advanced.length === 0)) { this._log.info('`test.advancedExecutables` is not defined. trying to use `test.executables`'); if (simple === undefined) { return [createExecutableConfigFromPattern('{build,Build,BUILD,out,Out,OUT}/**/*{test,Test,TEST}*')]; } else if (typeof simple === 'string') { if (simple.length === 0) { // disabled return []; } else { return [createExecutableConfigFromPattern(simple)]; } } else { this._log.warn('test.executables should be an string or undefined', simple); throw Error( "`test.executables` couldn't be recognised. It should be a string. For fine-tuning use `test.advancedExecutables`.", ); } } else if (Array.isArray(advanced)) { const executables: ExecutableConfig[] = []; this._log.setContext('executables', advanced); const createExecutableConfigFromObj = (origObj: AdvancedExecutable): ExecutableConfig => { const obj: AdvancedExecutable = Object.assign({}, origObj); // we are cheating here: it will work for other os but that is undocumented const platformSpecificProperty = platformUtil.getPlatformProperty(obj); if (platformSpecificProperty !== undefined) Object.assign(obj, platformSpecificProperty); const name: string | undefined = typeof obj.name === 'string' ? obj.name : undefined; const description: string | undefined = typeof obj.description === 'string' ? obj.description : undefined; let pattern = ''; { if (typeof obj.pattern == 'string') pattern = obj.pattern; else { this._log.warn('pattern property is required', obj); throw Error('"pattern" property is required in advancedExecutables.'); } } const cwd: string = typeof obj.cwd === 'string' ? obj.cwd : defaultCwd; const env: { [prop: string]: string } | undefined = typeof obj.env === 'object' ? obj.env : undefined; const envFile: string | undefined = typeof obj.envFile === 'string' ? obj.envFile : undefined; const dependsOn: string[] = Array.isArray(obj.dependsOn) ? obj.dependsOn.filter(v => typeof v === 'string') : []; const runTask: RunTask = typeof obj.runTask === 'object' ? { before: obj.runTask.before || [], beforeEach: obj.runTask.beforeEach || [], after: obj.runTask.after || [], afterEach: obj.runTask.afterEach || [], } : { before: [], beforeEach: [], after: [], afterEach: [] }; const parallelizationLimit: number = typeof obj.parallelizationLimit === 'number' && !Number.isNaN(obj.parallelizationLimit) ? Math.max(1, obj.parallelizationLimit) : defaultParallelExecutionOfExecLimit; const strictPattern: boolean | undefined = obj.strictPattern; const markAsSkipped: boolean | undefined = obj.markAsSkipped; const waitForBuildProcess: boolean | undefined = obj.waitForBuildProcess; const defaultTestGrouping = obj.testGrouping; const spawnerConfig: ExecutionWrapper | undefined = typeof obj.executionWrapper === 'object' && typeof obj.executionWrapper.path === 'string' && (obj.executionWrapper.args === undefined || (Array.isArray(obj.executionWrapper.args) && obj.executionWrapper.args.every(x => typeof x === 'string'))) ? obj.executionWrapper : undefined; const sourceFileMap: Record<string, string> = typeof obj.sourceFileMap === 'object' && Object.keys(obj.sourceFileMap).every(k => typeof k === 'string' && typeof obj.sourceFileMap![k] === 'string') ? obj.sourceFileMap : {}; const fsWatcher: string | undefined = obj.fsWatcher === 'string' ? obj.fsWatcher : undefined; return new ExecutableConfig( shared, pattern, name, description, cwd, env, envFile, dependsOn, runTask, parallelizationLimit, strictPattern, markAsSkipped, waitForBuildProcess, spawnerConfig, sourceFileMap, fsWatcher, this._getFrameworkSpecificSettings(defaultTestGrouping, obj['catch2']), this._getFrameworkSpecificSettings(defaultTestGrouping, obj['gtest']), this._getFrameworkSpecificSettings(defaultTestGrouping, obj['doctest']), this._getFrameworkSpecificSettings(defaultTestGrouping, obj['gbenchmark']), ); }; for (const conf of advanced) { if (typeof conf === 'string') { // this is not supported in the package.json but working executables.push(createExecutableConfigFromPattern(conf)); } else { executables.push(createExecutableConfigFromObj(conf)); } } return executables; } else { this._log.warn('test.advancedExecutables should be an array or undefined', advanced); throw Error("`test.advancedExecutables` couldn't be recognised"); } } private _getFrameworkSpecificSettings( defaultTestGrouping: TestGrouping | undefined, obj?: FrameworkSpecific, ): FrameworkSpecific { const r: FrameworkSpecific = {}; if (typeof obj === 'object') { if (obj.testGrouping) r.testGrouping = obj.testGrouping; else r.testGrouping = defaultTestGrouping; if (typeof obj.helpRegex === 'string') r.helpRegex = obj['helpRegex']; if (Array.isArray(obj.prependTestRunningArgs) && obj.prependTestRunningArgs.every(x => typeof x === 'string')) r.prependTestRunningArgs = obj.prependTestRunningArgs; if (Array.isArray(obj.prependTestListingArgs) && obj.prependTestListingArgs.every(x => typeof x === 'string')) r.prependTestListingArgs = obj.prependTestListingArgs; if (typeof obj.ignoreTestEnumerationStdErr === 'boolean') r.ignoreTestEnumerationStdErr = obj.ignoreTestEnumerationStdErr; if (typeof obj['debug.enableOutputColouring'] === 'boolean') r['debug.enableOutputColouring'] = obj['debug.enableOutputColouring']; if (typeof obj.failIfExceedsLimitNs === 'number') r.failIfExceedsLimitNs = obj.failIfExceedsLimitNs; } return r; } //public static readonly PublicKey: string = ''; }
the_stack
import zlib from 'zlib'; import type { Readable } from 'stream'; import Koa from 'koa'; import mount from 'koa-mount'; import session from 'koa-session'; import parseBody from 'co-body'; import getRawBody from 'raw-body'; import request from 'supertest'; import type { ASTVisitor, ValidationContext } from 'graphql'; import sinon from 'sinon'; import multer from 'multer'; import { expect } from 'chai'; import { describe, it } from 'mocha'; import { Source, GraphQLError, GraphQLString, GraphQLNonNull, GraphQLObjectType, GraphQLSchema, parse, execute, validate, buildSchema, } from 'graphql'; import { graphqlHTTP } from '../index'; import multerWrapper from './helpers/koa-multer'; declare module 'koa' { interface Request { body?: any; rawBody: string; } } type MulterFile = { /** Name of the form field associated with this file. */ fieldname: string; /** Name of the file on the uploader's computer. */ originalname: string; /** * Value of the `Content-Transfer-Encoding` header for this file. * @deprecated since July 2015 * @see RFC 7578, Section 4.7 */ encoding: string; /** Value of the `Content-Type` header for this file. */ mimetype: string; /** Size of the file in bytes. */ size: number; /** * A readable stream of this file. Only available to the `_handleFile` * callback for custom `StorageEngine`s. */ stream: Readable; /** `DiskStorage` only: Directory to which this file has been uploaded. */ destination: string; /** `DiskStorage` only: Name of this file within `destination`. */ filename: string; /** `DiskStorage` only: Full path to the uploaded file. */ path: string; /** `MemoryStorage` only: A Buffer containing the entire file. */ buffer: Buffer; }; declare module 'http' { interface IncomingMessage { file?: MulterFile | undefined; /** * Array or dictionary of `Multer.File` object populated by `array()`, * `fields()`, and `any()` middleware. */ files?: | { [fieldname: string]: Array<MulterFile>; } | Array<MulterFile> | undefined; } } const QueryRootType = new GraphQLObjectType({ name: 'QueryRoot', fields: { test: { type: GraphQLString, args: { who: { type: GraphQLString }, }, resolve: (_root, args: { who?: string }) => 'Hello ' + (args.who ?? 'World'), }, thrower: { type: GraphQLString, resolve: () => { throw new Error('Throws!'); }, }, }, }); const TestSchema = new GraphQLSchema({ query: QueryRootType, mutation: new GraphQLObjectType({ name: 'MutationRoot', fields: { writeTest: { type: QueryRootType, resolve: () => ({}), }, }, }), }); function stringifyURLParams(urlParams?: { [param: string]: string }): string { return new URLSearchParams(urlParams).toString(); } function urlString(urlParams?: { [param: string]: string }): string { let string = '/graphql'; if (urlParams) { string += '?' + stringifyURLParams(urlParams); } return string; } function server<StateT = Koa.DefaultState, ContextT = Koa.DefaultContext>() { const app = new Koa<StateT, ContextT>(); /* istanbul ignore next Error handler added only for debugging failed tests */ app.on('error', (error) => { // eslint-disable-next-line no-console console.warn('App encountered an error:', error); }); return app; } describe('GraphQL-HTTP tests', () => { describe('GET functionality', () => { it('allows GET with query param', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()).get( urlString({ query: '{test}', }), ); expect(response.text).to.equal('{"data":{"test":"Hello World"}}'); }); it('allows GET with variable values', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()).get( urlString({ query: 'query helloWho($who: String){ test(who: $who) }', variables: JSON.stringify({ who: 'Dolly' }), }), ); expect(response.text).to.equal('{"data":{"test":"Hello Dolly"}}'); }); it('allows GET with operation name', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()).get( urlString({ query: ` query helloYou { test(who: "You"), ...shared } query helloWorld { test(who: "World"), ...shared } query helloDolly { test(who: "Dolly"), ...shared } fragment shared on QueryRoot { shared: test(who: "Everyone") } `, operationName: 'helloWorld', }), ); expect(JSON.parse(response.text)).to.deep.equal({ data: { test: 'Hello World', shared: 'Hello Everyone', }, }); }); it('Reports validation errors', async () => { const app = server(); app.use(mount(urlString(), graphqlHTTP({ schema: TestSchema }))); const response = await request(app.listen()).get( urlString({ query: '{ test, unknownOne, unknownTwo }', }), ); expect(response.status).to.equal(400); expect(JSON.parse(response.text)).to.deep.equal({ errors: [ { message: 'Cannot query field "unknownOne" on type "QueryRoot".', locations: [{ line: 1, column: 9 }], }, { message: 'Cannot query field "unknownTwo" on type "QueryRoot".', locations: [{ line: 1, column: 21 }], }, ], }); }); it('Errors when missing operation name', async () => { const app = server(); app.use(mount(urlString(), graphqlHTTP({ schema: TestSchema }))); const response = await request(app.listen()).get( urlString({ query: ` query TestQuery { test } mutation TestMutation { writeTest { test } } `, }), ); expect(response.status).to.equal(500); expect(JSON.parse(response.text)).to.deep.equal({ errors: [ { message: 'Must provide operation name if query contains multiple operations.', }, ], }); }); it('Errors when sending a mutation via GET', async () => { const app = server(); app.use(mount(urlString(), graphqlHTTP({ schema: TestSchema }))); const response = await request(app.listen()).get( urlString({ query: 'mutation TestMutation { writeTest { test } }', }), ); expect(response.status).to.equal(405); expect(JSON.parse(response.text)).to.deep.equal({ errors: [ { message: 'Can only perform a mutation operation from a POST request.', }, ], }); }); it('Errors when selecting a mutation within a GET', async () => { const app = server(); app.use(mount(urlString(), graphqlHTTP({ schema: TestSchema }))); const response = await request(app.listen()).get( urlString({ operationName: 'TestMutation', query: ` query TestQuery { test } mutation TestMutation { writeTest { test } } `, }), ); expect(response.status).to.equal(405); expect(JSON.parse(response.text)).to.deep.equal({ errors: [ { message: 'Can only perform a mutation operation from a POST request.', }, ], }); }); it('Allows a mutation to exist within a GET', async () => { const app = server(); app.use(mount(urlString(), graphqlHTTP({ schema: TestSchema }))); const response = await request(app.listen()).get( urlString({ operationName: 'TestQuery', query: ` mutation TestMutation { writeTest { test } } query TestQuery { test } `, }), ); expect(response.status).to.equal(200); expect(JSON.parse(response.text)).to.deep.equal({ data: { test: 'Hello World', }, }); }); it('Allows async resolvers', async () => { const schema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'Query', fields: { foo: { type: GraphQLString, resolve: () => Promise.resolve('bar'), }, }, }), }); const app = server(); app.use(mount(urlString(), graphqlHTTP({ schema }))); const response = await request(app.listen()).get( urlString({ query: '{ foo }', }), ); expect(response.status).to.equal(200); expect(JSON.parse(response.text)).to.deep.equal({ data: { foo: 'bar' }, }); }); it('Allows passing in a context', async () => { const schema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'Query', fields: { test: { type: GraphQLString, resolve: (_obj, _args, context) => context, }, }, }), }); const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema, context: 'testValue', }), ), ); const response = await request(app.listen()).get( urlString({ query: '{ test }', }), ); expect(response.status).to.equal(200); expect(JSON.parse(response.text)).to.deep.equal({ data: { test: 'testValue', }, }); }); it('Allows passing in a fieldResolver', async () => { const schema = buildSchema(` type Query { test: String } `); const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema, fieldResolver: () => 'fieldResolver data', }), ), ); const response = await request(app.listen()).get( urlString({ query: '{ test }', }), ); expect(response.status).to.equal(200); expect(JSON.parse(response.text)).to.deep.equal({ data: { test: 'fieldResolver data', }, }); }); it('Allows passing in a typeResolver', async () => { const schema = buildSchema(` type Foo { foo: String } type Bar { bar: String } union UnionType = Foo | Bar type Query { test: UnionType } `); const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema, rootValue: { test: {} }, typeResolver: () => 'Bar', }), ), ); const response = await request(app.listen()).get( urlString({ query: '{ test { __typename } }', }), ); expect(response.status).to.equal(200); expect(JSON.parse(response.text)).to.deep.equal({ data: { test: { __typename: 'Bar' }, }, }); }); it('Uses ctx as context by default', async () => { const schema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'Query', fields: { test: { type: GraphQLString, resolve: (_obj, _args, context) => context.foo, }, }, }), }); const app = server(); // Middleware that adds ctx.foo to every request app.use((ctx, next) => { ctx.foo = 'bar'; return next(); }); app.use( mount( urlString(), graphqlHTTP({ schema, }), ), ); const response = await request(app.listen()).get( urlString({ query: '{ test }', }), ); expect(response.status).to.equal(200); expect(JSON.parse(response.text)).to.deep.equal({ data: { test: 'bar', }, }); }); it('Allows returning an options Promise', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP(() => Promise.resolve({ schema: TestSchema, }), ), ), ); const response = await request(app.listen()).get( urlString({ query: '{test}', }), ); expect(response.text).to.equal('{"data":{"test":"Hello World"}}'); }); it('Provides an options function with arguments', async () => { const app = server(); let seenRequest; let seenResponse; let seenContext; let seenParams; app.use( mount( urlString(), graphqlHTTP((req, res, ctx, params) => { seenRequest = req; seenResponse = res; seenContext = ctx; seenParams = params; return { schema: TestSchema }; }), ), ); const response = await request(app.listen()).get( urlString({ query: '{test}', }), ); expect(response.text).to.equal('{"data":{"test":"Hello World"}}'); expect(seenRequest).to.not.equal(null); expect(seenResponse).to.not.equal(null); expect(seenContext).to.not.equal(null); expect(seenParams).to.deep.equal({ query: '{test}', operationName: null, variables: null, raw: false, }); }); it('Catches errors thrown from options function', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP(() => { throw new Error('I did something wrong'); }), ), ); const response = await request(app.listen()).get( urlString({ query: '{test}', }), ); expect(response.status).to.equal(500); expect(response.text).to.equal( '{"errors":[{"message":"I did something wrong"}]}', ); }); }); describe('POST functionality', () => { it('allows POST with JSON encoding', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()) .post(urlString()) .send({ query: '{test}' }); expect(response.text).to.equal('{"data":{"test":"Hello World"}}'); }); it('Allows sending a mutation via POST', async () => { const app = server(); app.use(mount(urlString(), graphqlHTTP({ schema: TestSchema }))); const response = await request(app.listen()) .post(urlString()) .send({ query: 'mutation TestMutation { writeTest { test } }' }); expect(response.status).to.equal(200); expect(response.text).to.equal( '{"data":{"writeTest":{"test":"Hello World"}}}', ); }); it('allows POST with url encoding', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()) .post(urlString()) .send(stringifyURLParams({ query: '{test}' })); expect(response.text).to.equal('{"data":{"test":"Hello World"}}'); }); it('supports POST JSON query with string variables', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()) .post(urlString()) .send({ query: 'query helloWho($who: String){ test(who: $who) }', variables: JSON.stringify({ who: 'Dolly' }), }); expect(response.text).to.equal('{"data":{"test":"Hello Dolly"}}'); }); it('supports POST JSON query with JSON variables', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()) .post(urlString()) .send({ query: 'query helloWho($who: String){ test(who: $who) }', variables: { who: 'Dolly' }, }); expect(response.text).to.equal('{"data":{"test":"Hello Dolly"}}'); }); it('supports POST url encoded query with string variables', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()) .post(urlString()) .send( stringifyURLParams({ query: 'query helloWho($who: String){ test(who: $who) }', variables: JSON.stringify({ who: 'Dolly' }), }), ); expect(response.text).to.equal('{"data":{"test":"Hello Dolly"}}'); }); it('supports POST JSON query with GET variable values', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()) .post( urlString({ variables: JSON.stringify({ who: 'Dolly' }), }), ) .send({ query: 'query helloWho($who: String){ test(who: $who) }' }); expect(response.text).to.equal('{"data":{"test":"Hello Dolly"}}'); }); it('supports POST url encoded query with GET variable values', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()) .post( urlString({ variables: JSON.stringify({ who: 'Dolly' }), }), ) .send( stringifyURLParams({ query: 'query helloWho($who: String){ test(who: $who) }', }), ); expect(response.text).to.equal('{"data":{"test":"Hello Dolly"}}'); }); it('supports POST raw text query with GET variable values', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()) .post( urlString({ variables: JSON.stringify({ who: 'Dolly' }), }), ) .set('Content-Type', 'application/graphql') .send('query helloWho($who: String){ test(who: $who) }'); expect(response.text).to.equal('{"data":{"test":"Hello Dolly"}}'); }); it('allows POST with operation name', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()) .post(urlString()) .send({ query: ` query helloYou { test(who: "You"), ...shared } query helloWorld { test(who: "World"), ...shared } query helloDolly { test(who: "Dolly"), ...shared } fragment shared on QueryRoot { shared: test(who: "Everyone") } `, operationName: 'helloWorld', }); expect(JSON.parse(response.text)).to.deep.equal({ data: { test: 'Hello World', shared: 'Hello Everyone', }, }); }); it('allows POST with GET operation name', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()) .post( urlString({ operationName: 'helloWorld', }), ) .set('Content-Type', 'application/graphql').send(` query helloYou { test(who: "You"), ...shared } query helloWorld { test(who: "World"), ...shared } query helloDolly { test(who: "Dolly"), ...shared } fragment shared on QueryRoot { shared: test(who: "Everyone") } `); expect(JSON.parse(response.text)).to.deep.equal({ data: { test: 'Hello World', shared: 'Hello Everyone', }, }); }); it('allows other UTF charsets', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const req = request(app.listen()) .post(urlString()) .set('Content-Type', 'application/graphql; charset=utf-16'); req.write(Buffer.from('{ test(who: "World") }', 'utf16le')); const response = await req; expect(JSON.parse(response.text)).to.deep.equal({ data: { test: 'Hello World', }, }); }); it('allows gzipped POST bodies', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const req = request(app.listen()) .post(urlString()) .set('Content-Type', 'application/json') .set('Content-Encoding', 'gzip'); req.write(zlib.gzipSync('{ "query": "{ test }" }')); const response = await req; expect(JSON.parse(response.text)).to.deep.equal({ data: { test: 'Hello World', }, }); }); it('allows deflated POST bodies', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const req = request(app.listen()) .post(urlString()) .set('Content-Type', 'application/json') .set('Content-Encoding', 'deflate'); req.write(zlib.deflateSync('{ "query": "{ test }" }')); const response = await req; expect(JSON.parse(response.text)).to.deep.equal({ data: { test: 'Hello World', }, }); }); // should replace multer with koa middleware it('allows for pre-parsed POST bodies', async () => { // Note: this is not the only way to handle file uploads with GraphQL, // but it is terse and illustrative of using koa-graphql and multer // together. // A simple schema which includes a mutation. const UploadedFileType = new GraphQLObjectType({ name: 'UploadedFile', fields: { originalname: { type: GraphQLString }, mimetype: { type: GraphQLString }, }, }); const TestMutationSchema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'QueryRoot', fields: { test: { type: GraphQLString }, }, }), mutation: new GraphQLObjectType({ name: 'MutationRoot', fields: { uploadFile: { type: UploadedFileType, resolve(rootValue) { // For this test demo, we're just returning the uploaded // file directly, but presumably you might return a Promise // to go store the file somewhere first. return rootValue.request.file; }, }, }, }), }); const app = server(); // Multer provides multipart form data parsing. const storage = multer.memoryStorage(); app.use(mount(urlString(), multerWrapper({ storage }).single('file'))); // Providing the request as part of `rootValue` allows it to // be accessible from within Schema resolve functions. app.use( mount( urlString(), graphqlHTTP((_req, _res, ctx) => { expect(ctx.req.file?.originalname).to.equal('test.txt'); return { schema: TestMutationSchema, rootValue: { request: ctx.req }, }; }), ), ); const response = await request(app.listen()) .post(urlString()) .field( 'query', `mutation TestMutation { uploadFile { originalname, mimetype } }`, ) .attach('file', Buffer.from('test'), 'test.txt'); expect(JSON.parse(response.text)).to.deep.equal({ data: { uploadFile: { originalname: 'test.txt', mimetype: 'text/plain', }, }, }); }); it('allows for pre-parsed POST using application/graphql', async () => { const app = server(); app.use(async (ctx, next) => { if (typeof ctx.is('application/graphql') === 'string') { // eslint-disable-next-line require-atomic-updates ctx.request.body = await parseBody.text(ctx); } return next(); }); app.use(mount(urlString(), graphqlHTTP({ schema: TestSchema }))); const req = request(app.listen()) .post(urlString()) .set('Content-Type', 'application/graphql'); req.write(Buffer.from('{ test(who: "World") }')); const response = await req; expect(JSON.parse(response.text)).to.deep.equal({ data: { test: 'Hello World', }, }); }); it('does not accept unknown pre-parsed POST string', async () => { const app = server(); app.use(async (ctx, next) => { if (typeof ctx.is('*/*') === 'string') { // eslint-disable-next-line require-atomic-updates ctx.request.body = await parseBody.text(ctx); } return next(); }); app.use(mount(urlString(), graphqlHTTP({ schema: TestSchema }))); const req = request(app.listen()).post(urlString()); req.write(Buffer.from('{ test(who: "World") }')); const response = await req; expect(response.status).to.equal(400); expect(JSON.parse(response.text)).to.deep.equal({ errors: [{ message: 'Must provide query string.' }], }); }); it('does not accept unknown pre-parsed POST raw Buffer', async () => { const app = server(); app.use(async (ctx, next) => { if (typeof ctx.is('*/*') === 'string') { const req = ctx.req; // eslint-disable-next-line require-atomic-updates ctx.request.body = await getRawBody(req, { length: req.headers['content-length'], limit: '1mb', encoding: null, }); } return next(); }); app.use(mount(urlString(), graphqlHTTP({ schema: TestSchema }))); const req = request(app.listen()) .post(urlString()) .set('Content-Type', 'application/graphql'); req.write(Buffer.from('{ test(who: "World") }')); const response = await req; expect(response.status).to.equal(400); expect(JSON.parse(response.text)).to.deep.equal({ errors: [{ message: 'Must provide query string.' }], }); }); }); describe('Pretty printing', () => { it('supports pretty printing', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, pretty: true, }), ), ); const response = await request(app.listen()).get( urlString({ query: '{test}', }), ); expect(response.text).to.equal( [ // Pretty printed JSON '{', ' "data": {', ' "test": "Hello World"', ' }', '}', ].join('\n'), ); }); it('supports pretty printing configured by request', async () => { const app = server(); let pretty: boolean | undefined; app.use( mount( urlString(), graphqlHTTP(() => ({ schema: TestSchema, pretty, })), ), ); pretty = undefined; const defaultResponse = await request(app.listen()).get( urlString({ query: '{test}', }), ); expect(defaultResponse.text).to.equal('{"data":{"test":"Hello World"}}'); pretty = true; const prettyResponse = await request(app.listen()).get( urlString({ query: '{test}', pretty: '1', }), ); expect(prettyResponse.text).to.equal( [ // Pretty printed JSON '{', ' "data": {', ' "test": "Hello World"', ' }', '}', ].join('\n'), ); pretty = false; const unprettyResponse = await request(app.listen()).get( urlString({ query: '{test}', pretty: '0', }), ); expect(unprettyResponse.text).to.equal('{"data":{"test":"Hello World"}}'); }); }); it('will send request, response and context when using thunk', async () => { const app = server(); let seenRequest; let seenResponse; let seenContext; app.use( mount( urlString(), graphqlHTTP((req, res, ctx) => { seenRequest = req; seenResponse = res; seenContext = ctx; return { schema: TestSchema }; }), ), ); await request(app.listen()).get(urlString({ query: '{test}' })); expect(seenRequest).to.not.equal(undefined); expect(seenResponse).to.not.equal(undefined); expect(seenContext).to.not.equal(undefined); }); describe('Error handling functionality', () => { it('handles field errors caught by GraphQL', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()).get( urlString({ query: '{thrower}', }), ); expect(response.status).to.equal(200); expect(JSON.parse(response.text)).to.deep.equal({ data: { thrower: null }, errors: [ { message: 'Throws!', locations: [{ line: 1, column: 2 }], path: ['thrower'], }, ], }); }); it('handles query errors from non-null top field errors', async () => { const schema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'Query', fields: { test: { type: new GraphQLNonNull(GraphQLString), resolve() { throw new Error('Throws!'); }, }, }, }), }); const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema, }), ), ); const response = await request(app.listen()).get( urlString({ query: '{ test }', }), ); expect(response.status).to.equal(500); expect(JSON.parse(response.text)).to.deep.equal({ data: null, errors: [ { message: 'Throws!', locations: [{ line: 1, column: 3 }], path: ['test'], }, ], }); }); it('allows for custom error formatting to sanitize', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, customFormatErrorFn(error) { return { message: 'Custom error format: ' + error.message }; }, }), ), ); const response = await request(app.listen()).get( urlString({ query: '{thrower}', }), ); expect(response.status).to.equal(200); expect(JSON.parse(response.text)).to.deep.equal({ data: { thrower: null }, errors: [ { message: 'Custom error format: Throws!', }, ], }); }); it('allows for custom error formatting to elaborate', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, customFormatErrorFn(error) { return { message: error.message, locations: error.locations, stack: 'Stack trace', }; }, }), ), ); const response = await request(app.listen()).get( urlString({ query: '{thrower}', }), ); expect(response.status).to.equal(200); expect(JSON.parse(response.text)).to.deep.equal({ data: { thrower: null }, errors: [ { message: 'Throws!', locations: [{ line: 1, column: 2 }], stack: 'Stack trace', }, ], }); }); it('handles syntax errors caught by GraphQL', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()).get( urlString({ query: 'syntax_error', }), ); expect(response.status).to.equal(400); expect(JSON.parse(response.text)).to.deep.equal({ errors: [ { message: 'Syntax Error: Unexpected Name "syntax_error".', locations: [{ line: 1, column: 1 }], }, ], }); }); it('handles errors caused by a lack of query', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()).get(urlString()); expect(response.status).to.equal(400); expect(JSON.parse(response.text)).to.deep.equal({ errors: [{ message: 'Must provide query string.' }], }); }); it('handles invalid JSON bodies', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()) .post(urlString()) .set('Content-Type', 'application/json') .send('[]'); expect(response.status).to.equal(400); expect(JSON.parse(response.text)).to.deep.equal({ errors: [{ message: 'POST body sent invalid JSON.' }], }); }); it('handles incomplete JSON bodies', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()) .post(urlString()) .set('Content-Type', 'application/json') .send('{"query":'); expect(response.status).to.equal(400); expect(JSON.parse(response.text)).to.deep.equal({ errors: [{ message: 'POST body sent invalid JSON.' }], }); }); it('handles plain POST text', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()) .post( urlString({ variables: JSON.stringify({ who: 'Dolly' }), }), ) .set('Content-Type', 'text/plain') .send('query helloWho($who: String){ test(who: $who) }'); expect(response.status).to.equal(400); expect(JSON.parse(response.text)).to.deep.equal({ errors: [{ message: 'Must provide query string.' }], }); }); it('handles unsupported charset', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()) .post(urlString()) .set('Content-Type', 'application/graphql; charset=ascii') .send('{ test(who: "World") }'); expect(response.status).to.equal(415); expect(JSON.parse(response.text)).to.deep.equal({ errors: [{ message: 'Unsupported charset "ASCII".' }], }); }); it('handles unsupported utf charset', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()) .post(urlString()) .set('Content-Type', 'application/graphql; charset=utf-53') .send('{ test(who: "World") }'); expect(response.status).to.equal(415); expect(JSON.parse(response.text)).to.deep.equal({ errors: [{ message: 'Unsupported charset "UTF-53".' }], }); }); it('handles unknown encoding', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()) .post(urlString()) .set('Content-Encoding', 'garbage') .send('!@#$%^*(&^$%#@'); expect(response.status).to.equal(415); expect(JSON.parse(response.text)).to.deep.equal({ errors: [{ message: 'Unsupported content-encoding "garbage".' }], }); }); it('handles invalid body', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP(() => ({ schema: TestSchema, })), ), ); const response = await request(app.listen()) .post(urlString()) .set('Content-Type', 'application/json') .send(`{ "query": "{ ${new Array(102400).fill('test').join('')} }" }`); expect(response.status).to.equal(413); expect(JSON.parse(response.text)).to.deep.equal({ errors: [{ message: 'Invalid body: request entity too large.' }], }); }); it('handles poorly formed variables', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()).get( urlString({ variables: 'who:You', query: 'query helloWho($who: String){ test(who: $who) }', }), ); expect(response.status).to.equal(400); expect(JSON.parse(response.text)).to.deep.equal({ errors: [{ message: 'Variables are invalid JSON.' }], }); }); it('`formatError` is deprecated', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, formatError(error) { return { message: 'Custom error format: ' + error.message }; }, }), ), ); const spy = sinon.spy(console, 'warn'); const response = await request(app.listen()).get( urlString({ variables: 'who:You', query: 'query helloWho($who: String){ test(who: $who) }', }), ); expect( spy.calledWith( '`formatError` is deprecated and replaced by `customFormatErrorFn`. It will be removed in version 1.0.0.', ), ); expect(response.status).to.equal(400); expect(JSON.parse(response.text)).to.deep.equal({ errors: [ { message: 'Custom error format: Variables are invalid JSON.', }, ], }); spy.restore(); }); it('allows for custom error formatting of poorly formed requests', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, customFormatErrorFn(error) { return { message: 'Custom error format: ' + error.message }; }, }), ), ); const response = await request(app.listen()).get( urlString({ variables: 'who:You', query: 'query helloWho($who: String){ test(who: $who) }', }), ); expect(response.status).to.equal(400); expect(JSON.parse(response.text)).to.deep.equal({ errors: [ { message: 'Custom error format: Variables are invalid JSON.', }, ], }); }); it('allows disabling prettifying poorly formed requests', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, pretty: false, }), ), ); const response = await request(app.listen()).get( urlString({ variables: 'who:You', query: 'query helloWho($who: String){ test(who: $who) }', }), ); expect(response.status).to.equal(400); expect(response.text).to.equal( '{"errors":[{"message":"Variables are invalid JSON."}]}', ); }); it('handles invalid variables', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()) .post(urlString()) .send({ query: 'query helloWho($who: String){ test(who: $who) }', variables: { who: ['John', 'Jane'] }, }); expect(response.status).to.equal(500); expect(JSON.parse(response.text)).to.deep.equal({ errors: [ { locations: [{ column: 16, line: 1 }], message: 'Variable "$who" got invalid value ["John", "Jane"]; String cannot represent a non string value: ["John", "Jane"]', }, ], }); }); it('handles unsupported HTTP methods', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, }), ), ); const response = await request(app.listen()).put( urlString({ query: '{test}' }), ); expect(response.status).to.equal(405); expect(response.get('allow')).to.equal('GET, POST'); expect(JSON.parse(response.text)).to.deep.equal({ errors: [{ message: 'GraphQL only supports GET and POST requests.' }], }); }); }); describe('Built-in GraphiQL support', () => { it('does not renders GraphiQL if no opt-in', async () => { const app = server(); app.use(mount(urlString(), graphqlHTTP({ schema: TestSchema }))); const response = await request(app.listen()) .get(urlString({ query: '{test}' })) .set('Accept', 'text/html'); expect(response.status).to.equal(200); expect(response.type).to.equal('application/json'); expect(response.text).to.equal('{"data":{"test":"Hello World"}}'); }); it('presents GraphiQL when accepting HTML', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, graphiql: true, }), ), ); const response = await request(app.listen()) .get(urlString({ query: '{test}' })) .set('Accept', 'text/html'); expect(response.status).to.equal(200); expect(response.type).to.equal('text/html'); expect(response.text).to.include('graphiql.min.js'); }); it('contains a default query within GraphiQL', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, graphiql: { defaultQuery: 'query testDefaultQuery { hello }' }, }), ), ); const response = await request(app.listen()) .get(urlString()) .set('Accept', 'text/html'); expect(response.status).to.equal(200); expect(response.type).to.equal('text/html'); expect(response.text).to.include( 'defaultQuery: "query testDefaultQuery { hello }"', ); }); it('contains a pre-run response within GraphiQL', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, graphiql: true, }), ), ); const response = await request(app.listen()) .get(urlString({ query: '{test}' })) .set('Accept', 'text/html'); expect(response.status).to.equal(200); expect(response.type).to.equal('text/html'); expect(response.text).to.include( 'response: ' + JSON.stringify( JSON.stringify({ data: { test: 'Hello World' } }, null, 2), ), ); }); it('contains a pre-run operation name within GraphiQL', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, graphiql: true, }), ), ); const response = await request(app.listen()) .get( urlString({ query: 'query A{a:test} query B{b:test}', operationName: 'B', }), ) .set('Accept', 'text/html'); expect(response.status).to.equal(200); expect(response.type).to.equal('text/html'); expect(response.text).to.include( 'response: ' + JSON.stringify( JSON.stringify({ data: { b: 'Hello World' } }, null, 2), ), ); expect(response.text).to.include('operationName: "B"'); }); it('escapes HTML in queries within GraphiQL', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, graphiql: true, }), ), ); const response = await request(app.listen()) .get(urlString({ query: '</script><script>alert(1)</script>' })) .set('Accept', 'text/html'); expect(response.status).to.equal(400); expect(response.type).to.equal('text/html'); expect(response.text).to.not.include( '</script><script>alert(1)</script>', ); }); it('escapes HTML in variables within GraphiQL', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, graphiql: true, }), ), ); const response = await request(app.listen()) .get( urlString({ query: 'query helloWho($who: String) { test(who: $who) }', variables: JSON.stringify({ who: '</script><script>alert(1)</script>', }), }), ) .set('Accept', 'text/html'); expect(response.status).to.equal(200); expect(response.type).to.equal('text/html'); expect(response.text).to.not.include( '</script><script>alert(1)</script>', ); }); it('GraphiQL renders provided variables', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, graphiql: true, }), ), ); const response = await request(app.listen()) .get( urlString({ query: 'query helloWho($who: String) { test(who: $who) }', variables: JSON.stringify({ who: 'Dolly' }), }), ) .set('Accept', 'text/html'); expect(response.status).to.equal(200); expect(response.type).to.equal('text/html'); expect(response.text).to.include( 'variables: ' + JSON.stringify(JSON.stringify({ who: 'Dolly' }, null, 2)), ); }); it('GraphiQL accepts an empty query', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, graphiql: true, }), ), ); const response = await request(app.listen()) .get(urlString()) .set('Accept', 'text/html'); expect(response.status).to.equal(200); expect(response.type).to.equal('text/html'); expect(response.text).to.include('response: undefined'); }); it('GraphiQL accepts a mutation query - does not execute it', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, graphiql: true, }), ), ); const response = await request(app.listen()) .get( urlString({ query: 'mutation TestMutation { writeTest { test } }', }), ) .set('Accept', 'text/html'); expect(response.status).to.equal(200); expect(response.type).to.equal('text/html'); expect(response.text).to.include( 'query: "mutation TestMutation { writeTest { test } }"', ); expect(response.text).to.include('response: undefined'); }); it('returns HTML if preferred', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, graphiql: true, }), ), ); const response = await request(app.listen()) .get(urlString({ query: '{test}' })) .set('Accept', 'text/html,application/json'); expect(response.status).to.equal(200); expect(response.type).to.equal('text/html'); expect(response.text).to.include('{test}'); expect(response.text).to.include('graphiql.min.js'); }); it('returns JSON if preferred', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, graphiql: true, }), ), ); const response = await request(app.listen()) .get(urlString({ query: '{test}' })) .set('Accept', 'application/json,text/html'); expect(response.status).to.equal(200); expect(response.type).to.equal('application/json'); expect(response.text).to.equal('{"data":{"test":"Hello World"}}'); }); it('prefers JSON if unknown accept', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, graphiql: true, }), ), ); const response = await request(app.listen()) .get(urlString({ query: '{test}' })) .set('Accept', 'unknown'); expect(response.status).to.equal(200); expect(response.type).to.equal('application/json'); expect(response.text).to.equal('{"data":{"test":"Hello World"}}'); }); it('prefers JSON if explicitly requested raw response', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, graphiql: true, }), ), ); const response = await request(app.listen()) .get(urlString({ query: '{test}', raw: '' })) .set('Accept', 'text/html'); expect(response.status).to.equal(200); expect(response.type).to.equal('application/json'); expect(response.text).to.equal('{"data":{"test":"Hello World"}}'); }); it('contains subscriptionEndpoint within GraphiQL', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, graphiql: { subscriptionEndpoint: 'ws://localhost' }, }), ), ); const response = await request(app.listen()) .get(urlString()) .set('Accept', 'text/html'); expect(response.status).to.equal(200); expect(response.type).to.equal('text/html'); // should contain the function to make fetcher for subscription or non-subscription expect(response.text).to.include('makeFetcher'); // should contain subscriptions-transport-ws browser client expect(response.text).to.include('SubscriptionsTransportWs'); // should contain the subscriptionEndpoint url expect(response.text).to.include('ws:\\/\\/localhost'); }); it('contains subscriptionEndpoint within GraphiQL with websocketClient option', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, graphiql: { subscriptionEndpoint: 'ws://localhost', websocketClient: 'v1', }, }), ), ); const response = await request(app.listen()) .get(urlString()) .set('Accept', 'text/html'); expect(response.status).to.equal(200); expect(response.type).to.equal('text/html'); // should contain graphql-ws browser client expect(response.text).to.include('graphql-transport-ws'); // should contain the subscriptionEndpoint url expect(response.text).to.include('ws:\\/\\/localhost'); }); }); describe('Custom validate function', () => { it('returns data', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, customValidateFn(schema, documentAST, validationRules) { return validate(schema, documentAST, validationRules); }, }), ), ); const response = await request(app.listen()) .get(urlString({ query: '{test}', raw: '' })) .set('Accept', 'text/html'); expect(response.status).to.equal(200); expect(response.text).to.equal('{"data":{"test":"Hello World"}}'); }); it('returns validation errors', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, customValidateFn(schema, documentAST, validationRules) { const errors = validate(schema, documentAST, validationRules); return [new GraphQLError(`custom error ${errors.length}`)]; }, }), ), ); const response = await request(app.listen()).get( urlString({ query: '{thrower}', }), ); expect(response.status).to.equal(400); expect(JSON.parse(response.text)).to.deep.equal({ errors: [ { message: 'custom error 0', }, ], }); }); }); describe('Custom validation rules', () => { const AlwaysInvalidRule = function ( context: ValidationContext, ): ASTVisitor { return { Document() { context.reportError( new GraphQLError('AlwaysInvalidRule was really invalid!'), ); }, }; }; it('Do not execute a query if it do not pass the custom validation.', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, validationRules: [AlwaysInvalidRule], pretty: true, }), ), ); const response = await request(app.listen()).get( urlString({ query: '{thrower}', }), ); expect(response.status).to.equal(400); expect(JSON.parse(response.text)).to.deep.equal({ errors: [ { message: 'AlwaysInvalidRule was really invalid!', }, ], }); }); }); describe('Session support', () => { it('supports koa-session', async () => { const SessionAwareGraphQLSchema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'MyType', fields: { myField: { type: GraphQLString, resolve(_parentValue, _, sess) { return sess.id; }, }, }, }), }); const app = server(); app.keys = ['some secret hurr']; app.use(session(app)); app.use((ctx, next) => { if (ctx.session !== null) { ctx.session.id = 'me'; } return next(); }); app.use( mount( '/graphql', graphqlHTTP((_req, _res, ctx) => ({ schema: SessionAwareGraphQLSchema, context: ctx.session, })), ), ); const response = await request(app.listen()).get( urlString({ query: '{myField}', }), ); expect(response.text).to.equal('{"data":{"myField":"me"}}'); }); }); describe('Custom execute', () => { it('allow to replace default execute', async () => { const app = server(); let seenExecuteArgs; app.use( mount( urlString(), graphqlHTTP(() => ({ schema: TestSchema, async customExecuteFn(args) { seenExecuteArgs = args; const result = await Promise.resolve(execute(args)); return { ...result, data: { ...result.data, test2: 'Modification', }, }; }, })), ), ); const response = await request(app.listen()) .get(urlString({ query: '{test}', raw: '' })) .set('Accept', 'text/html'); expect(response.text).to.equal( '{"data":{"test":"Hello World","test2":"Modification"}}', ); expect(seenExecuteArgs).to.not.equal(null); }); it('catches errors thrown from custom execute function', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP(() => ({ schema: TestSchema, customExecuteFn() { throw new Error('I did something wrong'); }, })), ), ); const response = await request(app.listen()) .get(urlString({ query: '{test}', raw: '' })) .set('Accept', 'text/html'); expect(response.status).to.equal(400); expect(response.text).to.equal( '{"errors":[{"message":"I did something wrong"}]}', ); }); }); describe('Custom parse function', () => { it('can replace default parse functionality', async () => { const app = server(); let seenParseArgs; app.use( mount( urlString(), graphqlHTTP(() => ({ schema: TestSchema, customParseFn(args) { seenParseArgs = args; return parse(new Source('{test}', 'Custom parse function')); }, })), ), ); const response = await request(app.listen()).get( urlString({ query: '----' }), ); expect(response.status).to.equal(200); expect(response.text).to.equal('{"data":{"test":"Hello World"}}'); expect(seenParseArgs).property('body', '----'); }); it('can throw errors', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP(() => ({ schema: TestSchema, customParseFn() { throw new GraphQLError('my custom parse error'); }, })), ), ); const response = await request(app.listen()).get( urlString({ query: '----' }), ); expect(response.status).to.equal(400); expect(response.text).to.equal( '{"errors":[{"message":"my custom parse error"}]}', ); }); }); describe('Custom result extensions', () => { it('allows for adding extensions', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP(() => ({ schema: TestSchema, context: { foo: 'bar' }, extensions({ context }) { return { contextValue: JSON.stringify(context) }; }, })), ), ); const response = await request(app.listen()) .get(urlString({ query: '{test}', raw: '' })) .set('Accept', 'text/html'); expect(response.status).to.equal(200); expect(response.type).to.equal('application/json'); expect(response.text).to.equal( '{"data":{"test":"Hello World"},"extensions":{"contextValue":"{\\"foo\\":\\"bar\\"}"}}', ); }); it('extensions have access to initial GraphQL result', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, customFormatErrorFn: () => ({ message: 'Some generic error message.', }), extensions({ result }) { return { preservedResult: { ...result } }; }, }), ), ); const response = await request(app.listen()).get( urlString({ query: '{thrower}', }), ); expect(response.status).to.equal(200); expect(JSON.parse(response.text)).to.deep.equal({ data: { thrower: null }, errors: [{ message: 'Some generic error message.' }], extensions: { preservedResult: { data: { thrower: null }, errors: [ { message: 'Throws!', locations: [{ line: 1, column: 2 }], path: ['thrower'], }, ], }, }, }); }); it('extension function may be async', async () => { const app = server(); app.use( mount( urlString(), graphqlHTTP({ schema: TestSchema, extensions() { // Note: you can await arbitrary things here! return Promise.resolve({ eventually: 42 }); }, }), ), ); const response = await request(app.listen()) .get(urlString({ query: '{test}', raw: '' })) .set('Accept', 'text/html'); expect(response.status).to.equal(200); expect(response.type).to.equal('application/json'); expect(response.text).to.equal( '{"data":{"test":"Hello World"},"extensions":{"eventually":42}}', ); }); it('does nothing if extensions function does not return an object', async () => { const app = server(); app.use( mount( urlString(), // @ts-expect-error graphqlHTTP(() => ({ schema: TestSchema, context: { foo: 'bar' }, extensions({ context }) { return () => ({ contextValue: JSON.stringify(context) }); }, })), ), ); const response = await request(app.listen()) .get(urlString({ query: '{test}', raw: '' })) .set('Accept', 'text/html'); expect(response.status).to.equal(200); expect(response.type).to.equal('application/json'); expect(response.text).to.equal('{"data":{"test":"Hello World"}}'); }); }); });
the_stack
import { Endpoints, RequestTypes, } from 'detritus-client-rest'; import { ShardClient, VoiceConnectObject, VoiceConnectOptions, } from '../client'; import { BaseCollection, emptyBaseCollection } from '../collections/basecollection'; import { BaseSet } from '../collections/baseset'; import { DiscordKeys, ChannelTypes, ChannelVideoQualityModes, Permissions, DEFAULT_GROUP_DM_AVATARS } from '../constants'; import { addQuery, getFormatFromHash, PartialBy, PermissionTools, Snowflake, UrlQuery, } from '../utils'; import { BaseStructure, BaseStructureData, } from './basestructure'; import { Guild } from './guild'; import { Member } from './member'; import { Message } from './message'; import { Overwrite } from './overwrite'; import { Role } from './role'; import { StageInstance } from './stageinstance'; import { ThreadMember, ThreadMetadata } from './thread'; import { Typing } from './typing'; import { User } from './user'; import { VoiceState } from './voicestate'; export type Channel = ( ChannelBase | ChannelDM | ChannelGuildVoice | ChannelDMGroup | ChannelGuildType ); export type ChannelGuildType = ( ChannelGuildBase | ChannelGuildCategory | ChannelGuildText | ChannelGuildStore | ChannelGuildThread | ChannelGuildStageVoice ); export type ChannelTextType = ( ChannelDM | ChannelDMGroup | ChannelGuildText | ChannelGuildThread ); export function createChannelFromData( client: ShardClient, data?: BaseStructureData, isClone?: boolean, ): Channel { let Class = ChannelBase; if (data) { switch (data.type) { case ChannelTypes.GUILD_TEXT: { Class = ChannelGuildText; }; break; case ChannelTypes.DM: { Class = ChannelDM; }; break; case ChannelTypes.GUILD_VOICE: { Class = ChannelGuildVoice; }; break; case ChannelTypes.GROUP_DM: { Class = ChannelDMGroup; }; break; case ChannelTypes.GUILD_CATEGORY: { Class = ChannelGuildCategory; }; break; case ChannelTypes.GUILD_NEWS: { Class = ChannelGuildText; }; break; case ChannelTypes.GUILD_STORE: { Class = ChannelGuildStore; }; break; case ChannelTypes.GUILD_NEWS_THREAD: case ChannelTypes.GUILD_PUBLIC_THREAD: case ChannelTypes.GUILD_PRIVATE_THREAD: { Class = ChannelGuildThread; }; break; case ChannelTypes.GUILD_STAGE_VOICE: { Class = ChannelGuildStageVoice; }; break; } } return new Class(client, data, isClone); } const keysChannelBase = new BaseSet<string>([ DiscordKeys.ID, DiscordKeys.IS_PARTIAL, DiscordKeys.NAME, DiscordKeys.TYPE, ]); const keysMergeChannelBase = new BaseSet<string>(); /** * Basic Channel Structure * @category Structure */ export class ChannelBase extends BaseStructure { readonly _keys = keysChannelBase; readonly _keysMerge = keysMergeChannelBase; _name: string = ''; _nicks?: BaseCollection<string, string>; _nsfw?: boolean; _permissionOverwrites?: BaseCollection<string, Overwrite>; _recipients?: BaseCollection<string, User>; applicationId?: string; bitrate?: number; deleted: boolean = false; guildId?: string; id: string = ''; icon?: null | string; isPartial: boolean = false; lastMessageId?: null | string; lastPinTimestampUnix?: number; member?: ThreadMember; memberCount?: number; messageCount?: number; ownerId?: string; parentId?: null | string; position?: number; rateLimitPerUser?: number; rtcRegion?: null | string; threadMetadata?: ThreadMetadata; topic: null | string = null; type: ChannelTypes = ChannelTypes.BASE; userLimit?: number; videoQualityMode?: ChannelVideoQualityModes; constructor( client: ShardClient, data?: BaseStructureData, isClone?: boolean, ) { super(client, undefined, isClone); this.merge(data); } get canAddReactions(): boolean { return this.canMessage; } get canAttachFiles(): boolean { return this.canMessage; } get canDeafenMembers(): boolean { return this.isGuildStageVoice || this.isGuildVoice; } get canEdit(): boolean { return this.isDm; } get canEmbedLinks(): boolean { return this.canMessage; } get canJoin(): boolean { if (this.isDm) { if (this.client.user && this.client.user.bot) { return false; } return true; } return this.isGuildStageVoice || this.isGuildVoice; } get canManageMessages(): boolean { return false; } get canManageWebhooks(): boolean { return false; } get canMentionEveryone(): boolean { return this.isText; } get canMessage(): boolean { return this.isText; } get canManageThreads(): boolean { return false; } get canMoveMembers(): boolean { return this.isGuildStageVoice || this.isGuildVoice; } get canMuteMembers(): boolean { return this.isGuildStageVoice || this.isGuildVoice; } get canPrioritySpeaker(): boolean { return false; } get canSendTTSMessage(): boolean { return this.isText && !this.isDm; } get canSpeak(): boolean { if (this.isDm) { if (this.client.user && this.client.user.bot) { return false; } return true; } return this.isGuildStageVoice || this.isGuildVoice; } get canStream(): boolean { return this.isGuildStageVoice || this.isGuildVoice; } get canReadHistory(): boolean { return this.isText; } get canUseExternalEmojis(): boolean { return this.isDm; } get canUsePrivateThreads(): boolean { return false; } get canUsePublicThreads(): boolean { return false; } get canUseVAD(): boolean { return this.isVoice; } get canView(): boolean { return this.isText; } get children(): BaseCollection<string, ChannelGuildType> { return emptyBaseCollection; } get createdAt(): Date { return new Date(this.createdAtUnix); } get createdAtUnix(): number { return Snowflake.timestamp(this.id); } get defaultIconUrl(): null | string { return null; } get guild(): Guild | null { return null; } get iconUrl(): null | string { return null; } get isDm(): boolean { return this.isDmSingle || this.isDmGroup; } get isDmGroup(): boolean { return this.type === ChannelTypes.GROUP_DM; } get isDmSingle(): boolean { return this.type === ChannelTypes.DM; } get isGuildCategory(): boolean { return this.type === ChannelTypes.GUILD_CATEGORY; } get isGuildChannel(): boolean { return (this.isGuildCategory) || (this.isGuildText) || (this.isGuildVoice) || (this.isGuildNews) || (this.isGuildStore) || (this.isGuildThreadNews) || (this.isGuildThreadPrivate) || (this.isGuildThreadPublic) || (this.isGuildStageVoice); } get isGuildNews(): boolean { return this.type === ChannelTypes.GUILD_NEWS; } get isGuildStageVoice(): boolean { return this.type === ChannelTypes.GUILD_STAGE_VOICE; } get isGuildStore(): boolean { return this.type === ChannelTypes.GUILD_STORE; } get isGuildText(): boolean { return this.type === ChannelTypes.GUILD_TEXT; } get isGuildThread(): boolean { return this.isGuildThreadNews || this.isGuildThreadPrivate || this.isGuildThreadPublic; } get isGuildThreadNews(): boolean { return this.type === ChannelTypes.GUILD_NEWS_THREAD; } get isGuildThreadPrivate(): boolean { return this.type === ChannelTypes.GUILD_PRIVATE_THREAD; } get isGuildThreadPublic(): boolean { return this.type === ChannelTypes.GUILD_PUBLIC_THREAD; } get isGuildVoice(): boolean { return this.type === ChannelTypes.GUILD_VOICE; } get isLive(): boolean { return !!this.stageInstance; } get isManaged(): boolean { return !!this.applicationId; } get isSyncedWithParent(): boolean { return this.isSyncedWith(this.parent); } get isText(): boolean { return this.isDm || this.isGuildText || this.isGuildNews || this.isGuildThread; } get isVoice(): boolean { return this.isDm || this.isGuildVoice || this.isGuildStageVoice; } get joined(): boolean { return false; } get jumpLink(): string { return Endpoints.Routes.URL + Endpoints.Routes.CHANNEL(null, this.id); } get lastMessage(): Message | null { if (this.lastMessageId) { return this.client.messages.get(this.lastMessageId) || null; } return null; } get lastPinTimestamp(): Date | null { if (this.lastPinTimestampUnix) { return new Date(this.lastPinTimestampUnix); } return null; } get members(): BaseCollection<string, Member> { return emptyBaseCollection; } get messages(): BaseCollection<string, Message> { return emptyBaseCollection; } get mention(): string { return `<#${this.id}>`; } get name(): string { return this._name; } get nicks(): BaseCollection<string, string> { if (this._nicks) { return this._nicks; } return emptyBaseCollection; } get nsfw(): boolean { return !!this._nsfw; } get owner(): User | null { if (this.ownerId) { return this.client.users.get(this.ownerId) || null; } return null; } get parent(): ChannelGuildCategory | ChannelGuildText | null { if (this.parentId && this.client.channels.has(this.parentId)) { return this.client.channels.get(this.parentId) as ChannelGuildCategory | ChannelGuildText; } return null; } get permissionOverwrites(): BaseCollection<string, Overwrite> { if (this._permissionOverwrites) { return this._permissionOverwrites; } return emptyBaseCollection; } get stageInstance(): StageInstance | null { if (this.isGuildStageVoice) { const guild = this.guild; if (guild) { for (let [stageId, stage] of guild.stageInstances) { if (stage.channelId === this.id) { return stage; } } } } return null; } get recipients(): BaseCollection<string, User> { if (this._recipients) { return this._recipients; } return emptyBaseCollection; } get typing(): BaseCollection<string, Typing> { if (this.client.typings.has(this.id)) { return <BaseCollection<string, Typing>> this.client.typings.get(this.id); } return emptyBaseCollection; } get voiceStates(): BaseCollection<string, VoiceState> { return emptyBaseCollection; } can( permissions: PermissionTools.PermissionChecks, memberOrRole?: Member | Role, ): boolean { return false; } iconUrlFormat(format?: null | string, query?: UrlQuery): null | string { return null; } isSyncedWith(parent: ChannelGuildCategory | null): boolean { return false; } async addPinnedMessage(messageId: string) { if (!this.isText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.addPinnedMessage(this.id, messageId); } async addMember(userId: string) { if (!this.isGuildThread) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.addThreadMember(this.id, userId); } async addRecipient(userId: string) { if (!this.isDm) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.addRecipient(this.id, userId); } async bulkDelete(messageIds: Array<string>) { if (!this.isGuildText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.bulkDeleteMessages(this.id, messageIds); } async close() { if (!this.isDm) { throw new Error('Channel type doesn\'t support this.'); } return this.delete(); } async createInvite(options: RequestTypes.CreateChannelInvite) { return this.client.rest.createChannelInvite(this.id, options); } async createMessage(options: RequestTypes.CreateMessage | string = {}) { if (!this.isText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.createMessage(this.id, options); } async createReaction(messageId: string, emoji: string) { if (!this.isText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.createReaction(this.id, messageId, emoji); } async createStageInstance(options: PartialBy<RequestTypes.CreateStageInstance, 'channelId'>) { if (!this.isGuildStageVoice) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.createStageInstance({ ...options, channelId: this.id, }); } async createThread(options: RequestTypes.CreateChannelThread) { if (!this.isGuildText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.createChannelThread(this.id, options); } async createWebhook(options: RequestTypes.CreateWebhook) { if (!this.isGuildText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.createWebhook(this.id, options); } async crosspostMessage(messageId: string) { if (!this.isGuildNews) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.crosspostMessage(this.id, messageId); } async delete(options: RequestTypes.DeleteChannel = {}) { return this.client.rest.deleteChannel(this.id, options); } async deleteMessage(messageId: string, options: RequestTypes.DeleteMessage = {}) { if (!this.isText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.deleteMessage(this.id, messageId, options); } async deleteOverwrite(overwriteId: string, options: RequestTypes.DeleteChannelOverwrite = {}) { if (!this.isGuildChannel) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.deleteChannelOverwrite(this.id, overwriteId, options); } async deletePin(messageId: string) { if (!this.isText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.deletePinnedMessage(this.id, messageId); } async deleteReaction(messageId: string, emoji: string, userId: string = '@me') { if (!this.isText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.deleteReaction(this.id, messageId, emoji, userId); } async deleteReactions(messageId: string) { if (!this.isText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.deleteReactions(this.id, messageId); } async deleteStageInstance() { if (!this.isGuildStageVoice) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.deleteStageInstance(this.id); } edit(options: RequestTypes.EditChannel = {}) { return this.client.rest.editChannel(this.id, options); } async editMessage(messageId: string, options: RequestTypes.EditMessage = {}) { if (!this.isText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.editMessage(this.id, messageId, options); } async editOverwrite(overwriteId: string, options: RequestTypes.EditChannelOverwrite = {}) { if (!this.isGuildChannel) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.editChannelOverwrite(this.id, overwriteId, options); } async editStageInstance(options: RequestTypes.EditStageInstance = {}) { if (!this.isGuildStageVoice) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.editStageInstance(this.id, options); } async fetchCallStatus() { if (!this.isDm) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.fetchChannelCall(this.id); } async fetchInvites() { return this.client.rest.fetchChannelInvites(this.id); } async fetchMembers() { if (!this.isGuildThread) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.fetchThreadMembers(this.id); } async fetchMessage(messageId: string) { if (!this.isText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.fetchMessage(this.id, messageId); } async fetchMessages(options: RequestTypes.FetchMessages = {}) { if (!this.isText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.fetchMessages(this.id, options); } async fetchPins() { if (!this.isText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.fetchPinnedMessages(this.id); } async fetchReactions(messageId: string, emoji: string, options: RequestTypes.FetchReactions = {}) { if (!this.isText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.fetchReactions(this.id, messageId, emoji, options); } async fetchStageInstance() { if (!this.isGuildStageVoice) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.fetchStageInstance(this.id); } async fetchStoreListing() { if (!this.isGuildStore) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.fetchChannelStoreListing(this.id); } async fetchThreadsActive() { if (!this.isGuildText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.fetchChannelThreadsActive(this.id); } async fetchThreadsArchivedPrivate(options: RequestTypes.FetchChannelThreadsArchivedPrivate = {}) { if (!this.isGuildText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.fetchChannelThreadsArchivedPrivate(this.id, options); } async fetchThreadsArchivedPrivateJoined(options: RequestTypes.FetchChannelThreadsArchivedPrivateJoined = {}) { if (!this.isGuildText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.fetchChannelThreadsArchivedPrivateJoined(this.id, options); } async fetchThreadsArchivedPublic(options: RequestTypes.FetchChannelThreadsArchivedPublic = {}) { if (!this.isGuildText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.fetchChannelThreadsArchivedPublic(this.id, options); } async fetchWebhooks() { if (!this.isGuildText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.fetchChannelWebhooks(this.id); } async follow(options: RequestTypes.FollowChannel) { if (!this.isGuildNews) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.followChannel(this.id, options); } async grantEntitlement() { if (!this.isGuildStore) { throw new Error('Channel type doesn\'t support this.'); } } async join(): Promise<void>; async join(options?: CallOptions): Promise<VoiceConnectObject | null>; async join(options?: CallOptions): Promise<VoiceConnectObject | null | void> { if (this.isGuildThread) { return this.client.rest.joinThread(this.id); } else if (this.isVoice) { if (options && this.isDm) { if (options.verify || options.verify === undefined) { await this.fetchCallStatus(); } if (options.recipients) { await this.startCallRinging(options.recipients); } } return this.client.voiceConnect(this.guildId || undefined, this.id, options); } else { throw new Error('Channel type doesn\'t support this.'); } } async leave() { if (!this.isGuildThread) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.leaveThread(this.id); } async removeMember(userId: string) { if (!this.isGuildThread) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.removeThreadMember(this.id, userId); } async removeRecipient(userId: string) { if (!this.isDm) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.removeRecipient(this.id, userId); } async search(options: RequestTypes.SearchOptions, retry?: boolean) { if (!this.isText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.searchChannel(this.id, options, retry); } async startCallRinging(recipients?: Array<string>) { if (!this.isDm) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.startChannelCallRinging(this.id, {recipients}); } async stopCallRinging(recipients?: Array<string>) { if (!this.isDm) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.stopChannelCallRinging(this.id, {recipients}); } async triggerTyping() { if (!this.isText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.triggerTyping(this.id); } async turnIntoNewsChannel() { if (!this.isGuildText) { throw new Error('Channel type doesn\'t support this.'); } return this.edit({ type: ChannelTypes.GUILD_NEWS, }); } async turnIntoTextChannel() { if (!this.isGuildText) { throw new Error('Channel type doesn\'t support this.'); } return this.edit({ type: ChannelTypes.GUILD_TEXT, }); } async unack() { if (!this.isText) { throw new Error('Channel type doesn\'t support this.'); } return this.client.rest.unAckChannel(this.id); } mergeValue(key: string, value: any): void { if (value !== undefined) { switch (key) { case DiscordKeys.NAME: { this._name = value; }; return; case DiscordKeys.NSFW: { this._nsfw = value; }; return; } } return super.mergeValue(key, value); } toString(): string { return `#${this.name}`; } } export interface CallOptions extends VoiceConnectOptions { recipients?: Array<string>, verify?: boolean, } const keysChannelDm = new BaseSet<string>([ DiscordKeys.ID, DiscordKeys.IS_PARTIAL, DiscordKeys.LAST_MESSAGE_ID, DiscordKeys.LAST_PIN_TIMESTAMP, DiscordKeys.NICKS, DiscordKeys.RECIPIENTS, DiscordKeys.TYPE, ]); /** * Single DM Channel * @category Structure */ export class ChannelDM extends ChannelBase { readonly _keys = keysChannelDm; type = ChannelTypes.DM; lastMessageId?: null | string; constructor( client: ShardClient, data?: BaseStructureData, isClone?: boolean, ) { super(client, undefined, isClone); this.merge(data); } get iconUrl(): null | string { return this.iconUrlFormat(); } get joined(): boolean { return this.client.voiceConnections.has(this.id); } get messages(): BaseCollection<string, Message> { const collection = new BaseCollection<string, Message>(); for (let [messageId, message] of this.client.messages) { if (message.channelId === this.id) { collection.set(messageId, message); } } return collection; } get name(): string { if (!this._name) { return this.recipients.join(', ') || 'DM Channel'; } return this._name; } get voiceStates(): BaseCollection<string, VoiceState> { if (this.client.voiceStates.has(this.id)) { return this.client.voiceStates.get(this.id)!; } return emptyBaseCollection; } iconUrlFormat(format?: null | string, query?: UrlQuery): null | string { if (this.recipients.size) { const user = this.recipients.first()!; return user.avatarUrlFormat(format, query); } return null; } mergeValue(key: string, value: any): void { if (value !== undefined) { switch (key) { case DiscordKeys.LAST_PIN_TIMESTAMP: { this.lastPinTimestampUnix = (value) ? (new Date(value).getTime()) : 0; }; return; case DiscordKeys.NICKS: { if (Object.keys(value).length) { if (!this._nicks) { this._nicks = new BaseCollection<string, string>(); } this._nicks.clear(); for (let userId in value) { this._nicks.set(userId, value[userId]); } } else { if (this._nicks) { this._nicks.clear(); this._nicks = undefined; } } }; return; case DiscordKeys.RECIPIENTS: { if (value.length) { if (!this._recipients) { this._recipients = new BaseCollection<string, User>(); } this._recipients.clear(); if (this.client.user) { this._recipients.set(this.client.user.id, this.client.user); } for (let raw of value) { let user: User; if (this.isClone) { user = new User(this.client, raw, true); } else { if (this.client.users.has(raw.id)) { user = this.client.users.get(raw.id)!; user.merge(raw); } else { user = new User(this.client, raw); this.client.users.insert(user); } } this._recipients.set(user.id, user); // unsure of this if (DiscordKeys.NICK in raw) { if (!this._nicks) { this._nicks = new BaseCollection<string, string>(); } this._nicks.set(user.id, raw.nick); } } } else { if (this._recipients) { this._recipients.clear(); this._recipients = undefined; } } }; return; } return super.mergeValue(key, value); } } } const keysChannelDmGroup = new BaseSet<string>([ ...keysChannelDm, DiscordKeys.APPLICATION_ID, DiscordKeys.ICON, DiscordKeys.NAME, DiscordKeys.OWNER_ID, ]); /** * Group DM Channel * @category Structure */ export class ChannelDMGroup extends ChannelDM { readonly _keys = keysChannelDmGroup; type = ChannelTypes.GROUP_DM; applicationId?: string; icon: null | string = null; ownerId: string = ''; constructor(client: ShardClient, data?: BaseStructureData, isClone?: boolean) { super(client, undefined, isClone); this.merge(data); } get defaultIconUrl(): string { const hash = DEFAULT_GROUP_DM_AVATARS[this.createdAtUnix % DEFAULT_GROUP_DM_AVATARS.length]; return Endpoints.Assets.URL + Endpoints.Assets.ICON(hash); } get owner(): User | null { if (this._recipients && this._recipients.has(this.ownerId)) { return this._recipients.get(this.ownerId) || null; } return super.owner; } iconUrlFormat(format?: null | string, query?: UrlQuery): string { if (!this.icon) { return this.defaultIconUrl; } const hash = this.icon; format = getFormatFromHash( hash, format, this.client.imageFormat, ); return addQuery( Endpoints.CDN.URL + Endpoints.CDN.DM_ICON(this.id, hash, format), query, ); } isOwner(userId: string): boolean { return this.ownerId === userId; } } const keysChannelGuildBase = new BaseSet<string>([ DiscordKeys.GUILD_ID, DiscordKeys.ID, DiscordKeys.IS_PARTIAL, DiscordKeys.NAME, DiscordKeys.NSFW, DiscordKeys.PARENT_ID, DiscordKeys.PERMISSION_OVERWRITES, DiscordKeys.POSITION, DiscordKeys.RATE_LIMIT_PER_USER, DiscordKeys.TYPE, ]); const keysMergeChannelGuildBase = new BaseSet<string>([ DiscordKeys.GUILD_ID, DiscordKeys.ID, ]); /** * Basic Guild Channel * @category Structure */ export class ChannelGuildBase extends ChannelBase { readonly _keys = keysChannelGuildBase; readonly _keysMerge = keysMergeChannelGuildBase; type = ChannelTypes.BASE; guildId: string = ''; parentId: null | string = null; position: number = -1; rateLimitPerUser: number = 0; constructor( client: ShardClient, data?: BaseStructureData, isClone?: boolean, ) { super(client, undefined, isClone); this.merge(data); } get canAddReactions(): boolean { return this.isText && this.can([ Permissions.VIEW_CHANNEL, Permissions.SEND_MESSAGES, Permissions.ADD_REACTIONS, ]); } get canAttachFiles(): boolean { return this.isText && this.can([ Permissions.VIEW_CHANNEL, Permissions.SEND_MESSAGES, Permissions.ATTACH_FILES, ]); } get canDeafenMembers(): boolean { return this.isVoice && this.can([ Permissions.DEAFEN_MEMBERS, ]); } get canEdit(): boolean { return this.can([ Permissions.MANAGE_CHANNELS, ]); } get canEmbedLinks(): boolean { return this.isText && this.can([ Permissions.VIEW_CHANNEL, Permissions.SEND_MESSAGES, Permissions.EMBED_LINKS, ]); } get canJoin(): boolean { return this.isVoice && this.can([ Permissions.VIEW_CHANNEL, Permissions.CONNECT, ]); } get canManageMessages(): boolean { return this.isText && this.can([ Permissions.MANAGE_MESSAGES, ]); } get canManageWebhooks(): boolean { return this.isText && this.can([ Permissions.MANAGE_WEBHOOKS, ]); } get canManageThreads(): boolean { return this.isText && this.can([ Permissions.MANAGE_THREADS, ]); } get canMentionEveryone(): boolean { return this.isText && this.can([ Permissions.VIEW_CHANNEL, Permissions.SEND_MESSAGES, Permissions.MENTION_EVERYONE, ]); } get canMessage(): boolean { return this.isText && this.can([ Permissions.VIEW_CHANNEL, Permissions.SEND_MESSAGES, ]); } get canMoveMembers(): boolean { return this.isVoice && this.can([ Permissions.MOVE_MEMBERS, ]); } get canMuteMembers(): boolean { return this.isVoice && this.can([ Permissions.MUTE_MEMBERS, ]); } get canPrioritySpeaker(): boolean { return this.isVoice && this.can([ Permissions.PRIORITY_SPEAKER, ]); } get canSendTTSMessage(): boolean { return this.isText && this.can([ Permissions.VIEW_CHANNEL, Permissions.SEND_MESSAGES, Permissions.SEND_TTS_MESSAGES, ]); } get canSpeak(): boolean { return this.isVoice && this.can([ Permissions.SPEAK, ]); } get canStream(): boolean { return this.isVoice && this.can([ Permissions.STREAM, ]); } get canReadHistory(): boolean { return this.isText && this.can([ Permissions.VIEW_CHANNEL, Permissions.READ_MESSAGE_HISTORY, ]); } get canUseExternalEmojis(): boolean { return this.isText && this.can([ Permissions.VIEW_CHANNEL, Permissions.SEND_MESSAGES, Permissions.USE_EXTERNAL_EMOJIS, ]); } get canUsePrivateThreads(): boolean { return this.isText && this.can([ Permissions.VIEW_CHANNEL, Permissions.USE_PRIVATE_THREADS, ]); } get canUsePublicThreads(): boolean { return this.isText && this.can([ Permissions.VIEW_CHANNEL, Permissions.USE_PUBLIC_THREADS, ]); } get canUseVAD(): boolean { return this.isVoice && this.can([ Permissions.USE_VAD, ]); } get canView(): boolean { return this.isText && this.can([ Permissions.VIEW_CHANNEL, ]); } get guild(): Guild | null { return this.client.guilds.get(this.guildId) || null; } get jumpLink(): string { return Endpoints.Routes.URL + Endpoints.Routes.CHANNEL(this.guildId, this.id); } can( permissions: PermissionTools.PermissionChecks, memberOrRole?: Member | Role, {ignoreAdministrator, ignoreOwner}: {ignoreAdministrator?: boolean, ignoreOwner?: boolean} = {}, ): boolean { let total = Permissions.NONE; if (memberOrRole instanceof Role) { total = memberOrRole.permissions; if (!ignoreAdministrator) { if (PermissionTools.checkPermissions(total, Permissions.ADMINISTRATOR)) { return true; } } } else { if (!memberOrRole) { if (!this.client.user) { return false; } if (!this.client.members.has(this.guildId, this.client.user.id)) { return false; } memberOrRole = this.client.members.get(this.guildId, this.client.user.id)!; } if (!ignoreOwner) { const guild = this.guild; if (guild && guild.isOwner(memberOrRole.id)) { return true; } } if (!ignoreAdministrator) { if (PermissionTools.checkPermissions(memberOrRole.permissions, Permissions.ADMINISTRATOR)) { return true; } } total = memberOrRole.permissionsIn(this); } return PermissionTools.checkPermissions(total, permissions); } isSyncedWith(parent: ChannelGuildCategory | null): boolean { if (parent) { const overwrites = this.permissionOverwrites; const parentOverwrites = parent.permissionOverwrites; if (overwrites.length !== parentOverwrites.length) { return false; } return overwrites.every((overwrite) => { if (parentOverwrites.has(overwrite.id)) { const parentOverwrite = parentOverwrites.get(overwrite.id)!; return overwrite.allow === parentOverwrite.allow && overwrite.deny === parentOverwrite.deny; } return false; }); } return false; } mergeValue(key: string, value: any): void { if (value !== undefined) { switch (key) { case DiscordKeys.PERMISSION_OVERWRITES: { if (value.length) { if (!this._permissionOverwrites) { this._permissionOverwrites = new BaseCollection<string, Overwrite>(); } const overwrites: Array<Overwrite> = []; for (let raw of value) { let overwrite: Overwrite; if (this._permissionOverwrites.has(raw.id)) { overwrite = this._permissionOverwrites.get(raw.id)!; overwrite.merge(raw); } else { overwrite = new Overwrite(this, raw); } overwrites.push(overwrite); } this._permissionOverwrites.clear(); for (let overwrite of overwrites) { this._permissionOverwrites.set(overwrite.id, overwrite); } } else { if (this._permissionOverwrites) { this._permissionOverwrites.clear(); this._permissionOverwrites = undefined; } } }; return; } return super.mergeValue(key, value); } } } /** * Guild Category Channel * @category Structure */ export class ChannelGuildCategory extends ChannelGuildBase { readonly _keys = keysChannelGuildBase; type = ChannelTypes.GUILD_CATEGORY; constructor( client: ShardClient, data?: BaseStructureData, isClone?: boolean, ) { super(client, undefined, isClone); this.merge(data); } get children(): BaseCollection<string, ChannelGuildType> { const collection = new BaseCollection<string, ChannelGuildType>(); for (let [channelId, channel] of this.client.channels) { if (channel.isGuildChannel && channel.parentId === this.id) { collection.set(channelId, channel as ChannelGuildType); } } return collection; } } const keysChannelGuildText = new BaseSet<string>([ DiscordKeys.GUILD_ID, DiscordKeys.ID, DiscordKeys.IS_PARTIAL, DiscordKeys.LAST_MESSAGE_ID, DiscordKeys.LAST_PIN_TIMESTAMP, DiscordKeys.NAME, DiscordKeys.NSFW, DiscordKeys.PARENT_ID, DiscordKeys.PERMISSION_OVERWRITES, DiscordKeys.POSITION, DiscordKeys.RATE_LIMIT_PER_USER, DiscordKeys.TOPIC, DiscordKeys.TYPE, ]); /** * Guild Text Channel, it can also be a news channel. * @category Structure */ export class ChannelGuildText extends ChannelGuildBase { readonly _keys = keysChannelGuildText; type = ChannelTypes.GUILD_TEXT; lastMessageId: null | string = null; topic: null | string = null; constructor( client: ShardClient, data?: BaseStructureData, isClone?: boolean, ) { super(client, undefined, isClone); this.merge(data); } get members(): BaseCollection<string, Member> { const collection = new BaseCollection<string, Member>(); const guild = this.guild; if (guild) { for (let [userId, member] of guild.members) { if (this.can(Permissions.VIEW_CHANNEL, member)) { collection.set(userId, member); } } } return collection; } get messages(): BaseCollection<string, Message> { const collection = new BaseCollection<string, Message>(); for (let [messageId, message] of this.client.messages) { if (message.channelId === this.id) { collection.set(messageId, message); } } return collection; } mergeValue(key: string, value: any) { if (value !== undefined) { switch (key) { case DiscordKeys.LAST_PIN_TIMESTAMP: { this.lastPinTimestampUnix = (value) ? (new Date(value).getTime()) : 0; }; return; } return super.mergeValue(key, value); } } } const keysChannelGuildVoice = new BaseSet<string>([ DiscordKeys.BITRATE, DiscordKeys.GUILD_ID, DiscordKeys.ID, DiscordKeys.IS_PARTIAL, DiscordKeys.NAME, DiscordKeys.NSFW, DiscordKeys.PARENT_ID, DiscordKeys.PERMISSION_OVERWRITES, DiscordKeys.POSITION, DiscordKeys.RATE_LIMIT_PER_USER, DiscordKeys.RTC_REGION, DiscordKeys.TOPIC, DiscordKeys.TYPE, DiscordKeys.USER_LIMIT, DiscordKeys.VIDEO_QUALITY_MODE, ]); /** * Guild Voice Channel * @category Structure */ export class ChannelGuildVoice extends ChannelGuildBase { readonly _keys = keysChannelGuildVoice; type = ChannelTypes.GUILD_VOICE; bitrate: number = 64000; rtcRegion: string | null = null; userLimit: number = 0; videoQualityMode: ChannelVideoQualityModes = ChannelVideoQualityModes.AUTO; constructor( client: ShardClient, data?: BaseStructureData, isClone?: boolean, ) { super(client, undefined, isClone); this.merge(data); } get joined(): boolean { if (this.client.voiceConnections.has(this.guildId)) { const voiceConnection = this.client.voiceConnections.get(this.guildId)!; return voiceConnection.guildId === this.id; } return false; } get members(): BaseCollection<string, Member> { const collection = new BaseCollection<string, Member>(); const voiceStates = this.voiceStates; if (voiceStates) { for (let [cacheId, voiceState] of voiceStates) { if (voiceState.member) { collection.set(voiceState.userId, voiceState.member); } } } return collection; } get voiceStates(): BaseCollection<string, VoiceState> { const collection = new BaseCollection<string, VoiceState>(); const voiceStates = this.client.voiceStates.get(this.guildId); if (voiceStates) { for (let [userId, voiceState] of voiceStates) { if (voiceState.channelId === this.id) { collection.set(userId, voiceState); } } } return collection; } } const keysChannelGuildStore = new BaseSet<string>([ DiscordKeys.BITRATE, DiscordKeys.GUILD_ID, DiscordKeys.ID, DiscordKeys.IS_PARTIAL, DiscordKeys.NAME, DiscordKeys.NSFW, DiscordKeys.PARENT_ID, DiscordKeys.PERMISSION_OVERWRITES, DiscordKeys.POSITION, DiscordKeys.RATE_LIMIT_PER_USER, DiscordKeys.TYPE, DiscordKeys.USER_LIMIT, ]); /** * Guild Store Channel * @category Structure */ export class ChannelGuildStore extends ChannelGuildBase { readonly _keys = keysChannelGuildStore; type = ChannelTypes.GUILD_STORE; bitrate: number = 0; userLimit: number = 0; constructor( client: ShardClient, data?: BaseStructureData, isClone?: boolean, ) { super(client, undefined, isClone); this.merge(data); } } const keysChannelGuildStageVoice = new BaseSet<string>([ ...keysChannelGuildVoice, DiscordKeys.TOPIC, ]); /** * Guild Stage Voice Channel * @category Structure */ export class ChannelGuildStageVoice extends ChannelGuildVoice { readonly _keys = keysChannelGuildStageVoice; type = ChannelTypes.GUILD_STAGE_VOICE; topic: null | string = null; constructor( client: ShardClient, data?: BaseStructureData, isClone?: boolean, ) { super(client, undefined, isClone); this.merge(data); } } const keysChannelGuildThread = new BaseSet<string>([ DiscordKeys.GUILD_ID, DiscordKeys.ID, DiscordKeys.IS_PARTIAL, DiscordKeys.LAST_MESSAGE_ID, DiscordKeys.LAST_PIN_TIMESTAMP, DiscordKeys.MEMBER, DiscordKeys.MEMBER_COUNT, DiscordKeys.MESSAGE_COUNT, DiscordKeys.NAME, DiscordKeys.NSFW, DiscordKeys.OWNER_ID, DiscordKeys.PARENT_ID, DiscordKeys.PERMISSION_OVERWRITES, DiscordKeys.POSITION, DiscordKeys.RATE_LIMIT_PER_USER, DiscordKeys.THREAD_METADATA, DiscordKeys.TYPE, ]); /** * Guild Thread Channel * @category Structure */ export class ChannelGuildThread extends ChannelGuildBase { readonly _keys = keysChannelGuildThread; type = ChannelTypes.GUILD_PUBLIC_THREAD; member?: ThreadMember; memberCount: number = 0; messageCount: number = 0; ownerId: string = ''; threadMetadata!: ThreadMetadata; constructor( client: ShardClient, data?: BaseStructureData, isClone?: boolean, ) { super(client, undefined, isClone); this.merge(data); } get nsfw(): boolean { if (this.parent) { return this.parent.nsfw; } return false; } mergeValue(key: string, value: any) { if (value !== undefined) { switch (key) { case DiscordKeys.LAST_PIN_TIMESTAMP: { this.lastPinTimestampUnix = (value) ? (new Date(value).getTime()) : 0; }; return; case DiscordKeys.MEMBER: { value = new ThreadMember(this.client, value); }; break; case DiscordKeys.THREAD_METADATA: { value = new ThreadMetadata(this, value); }; break; } return super.mergeValue(key, value); } } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "../types"; import * as utilities from "../utilities"; import {PolicyDocument} from "./index"; /** * Provides an IAM role. * * > **NOTE:** If policies are attached to the role via the `aws.iam.PolicyAttachment` resource and you are modifying the role `name` or `path`, the `forceDetachPolicies` argument must be set to `true` and applied before attempting the operation otherwise you will encounter a `DeleteConflict` error. The `aws.iam.RolePolicyAttachment` resource does not have this requirement. * * > **NOTE:** If you use this resource's `managedPolicyArns` argument or `inlinePolicy` configuration blocks, this resource will take over exclusive management of the role's respective policy types (e.g., both policy types if both arguments are used). These arguments are incompatible with other ways of managing a role's policies, such as `aws.iam.PolicyAttachment`, `aws.iam.RolePolicyAttachment`, and `aws.iam.RolePolicy`. If you attempt to manage a role's policies by multiple means, you will get resource cycling and/or errors. * * ## Example Usage * ### Basic Example * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const testRole = new aws.iam.Role("testRole", { * assumeRolePolicy: JSON.stringify({ * Version: "2012-10-17", * Statement: [{ * Action: "sts:AssumeRole", * Effect: "Allow", * Sid: "", * Principal: { * Service: "ec2.amazonaws.com", * }, * }], * }), * tags: { * "tag-key": "tag-value", * }, * }); * ``` * ### Example of Using Data Source for Assume Role Policy * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const instance-assume-role-policy = aws.iam.getPolicyDocument({ * statements: [{ * actions: ["sts:AssumeRole"], * principals: [{ * type: "Service", * identifiers: ["ec2.amazonaws.com"], * }], * }], * }); * const instance = new aws.iam.Role("instance", { * path: "/system/", * assumeRolePolicy: instance_assume_role_policy.then(instance_assume_role_policy => instance_assume_role_policy.json), * }); * ``` * ### Example of Exclusive Inline Policies * * This example creates an IAM role with two inline IAM policies. If someone adds another inline policy out-of-band, on the next apply, the provider will remove that policy. If someone deletes these policies out-of-band, the provider will recreate them. * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const inlinePolicy = aws.iam.getPolicyDocument({ * statements: [{ * actions: ["ec2:DescribeAccountAttributes"], * resources: ["*"], * }], * }); * const example = new aws.iam.Role("example", { * assumeRolePolicy: data.aws_iam_policy_document.instance_assume_role_policy.json, * inlinePolicies: [ * { * name: "my_inline_policy", * policy: JSON.stringify({ * Version: "2012-10-17", * Statement: [{ * Action: ["ec2:Describe*"], * Effect: "Allow", * Resource: "*", * }], * }), * }, * { * name: "policy-8675309", * policy: inlinePolicy.then(inlinePolicy => inlinePolicy.json), * }, * ], * }); * ``` * ### Example of Removing Inline Policies * * This example creates an IAM role with what appears to be empty IAM `inlinePolicy` argument instead of using `inlinePolicy` as a configuration block. The result is that if someone were to add an inline policy out-of-band, on the next apply, the provider will remove that policy. * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const example = new aws.iam.Role("example", { * assumeRolePolicy: data.aws_iam_policy_document.instance_assume_role_policy.json, * inlinePolicies: [{}], * }); * ``` * ### Example of Exclusive Managed Policies * * This example creates an IAM role and attaches two managed IAM policies. If someone attaches another managed policy out-of-band, on the next apply, the provider will detach that policy. If someone detaches these policies out-of-band, the provider will attach them again. * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const policyOne = new aws.iam.Policy("policyOne", {policy: JSON.stringify({ * Version: "2012-10-17", * Statement: [{ * Action: ["ec2:Describe*"], * Effect: "Allow", * Resource: "*", * }], * })}); * const policyTwo = new aws.iam.Policy("policyTwo", {policy: JSON.stringify({ * Version: "2012-10-17", * Statement: [{ * Action: [ * "s3:ListAllMyBuckets", * "s3:ListBucket", * "s3:HeadBucket", * ], * Effect: "Allow", * Resource: "*", * }], * })}); * const example = new aws.iam.Role("example", { * assumeRolePolicy: data.aws_iam_policy_document.instance_assume_role_policy.json, * managedPolicyArns: [ * policyOne.arn, * policyTwo.arn, * ], * }); * ``` * ### Example of Removing Managed Policies * * This example creates an IAM role with an empty `managedPolicyArns` argument. If someone attaches a policy out-of-band, on the next apply, the provider will detach that policy. * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const example = new aws.iam.Role("example", { * assumeRolePolicy: data.aws_iam_policy_document.instance_assume_role_policy.json, * managedPolicyArns: [], * }); * ``` * * ## Import * * IAM Roles can be imported using the `name`, e.g. * * ```sh * $ pulumi import aws:iam/role:Role developer developer_name * ``` */ export class Role extends pulumi.CustomResource { /** * Get an existing Role resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: RoleState, opts?: pulumi.CustomResourceOptions): Role { return new Role(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'aws:iam/role:Role'; /** * Returns true if the given object is an instance of Role. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is Role { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Role.__pulumiType; } /** * Amazon Resource Name (ARN) specifying the role. */ public /*out*/ readonly arn!: pulumi.Output<string>; /** * Policy that grants an entity permission to assume the role. */ public readonly assumeRolePolicy!: pulumi.Output<string>; /** * Creation date of the IAM role. */ public /*out*/ readonly createDate!: pulumi.Output<string>; /** * Description of the role. */ public readonly description!: pulumi.Output<string | undefined>; /** * Whether to force detaching any policies the role has before destroying it. Defaults to `false`. */ public readonly forceDetachPolicies!: pulumi.Output<boolean | undefined>; /** * Configuration block defining an exclusive set of IAM inline policies associated with the IAM role. Defined below. If no blocks are configured, the provider will ignore any managing any inline policies in this resource. Configuring one empty block (i.e., `inlinePolicy {}`) will cause the provider to remove _all_ inline policies. */ public readonly inlinePolicies!: pulumi.Output<outputs.iam.RoleInlinePolicy[]>; /** * Set of exclusive IAM managed policy ARNs to attach to the IAM role. If this attribute is not configured, the provider will ignore policy attachments to this resource. When configured, the provider will align the role's managed policy attachments with this set by attaching or detaching managed policies. Configuring an empty set (i.e., `managedPolicyArns = []`) will cause the provider to remove _all_ managed policy attachments. */ public readonly managedPolicyArns!: pulumi.Output<string[]>; /** * Maximum session duration (in seconds) that you want to set for the specified role. If you do not specify a value for this setting, the default maximum of one hour is applied. This setting can have a value from 1 hour to 12 hours. */ public readonly maxSessionDuration!: pulumi.Output<number | undefined>; /** * Name of the role policy. */ public readonly name!: pulumi.Output<string>; /** * Creates a unique friendly name beginning with the specified prefix. Conflicts with `name`. */ public readonly namePrefix!: pulumi.Output<string>; /** * Path to the role. See [IAM Identifiers](https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) for more information. */ public readonly path!: pulumi.Output<string | undefined>; /** * ARN of the policy that is used to set the permissions boundary for the role. */ public readonly permissionsBoundary!: pulumi.Output<string | undefined>; /** * Key-value mapping of tags for the IAM role. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * A map of tags assigned to the resource, including those inherited from the provider . */ public /*out*/ readonly tagsAll!: pulumi.Output<{[key: string]: string}>; /** * Stable and unique string identifying the role. */ public /*out*/ readonly uniqueId!: pulumi.Output<string>; /** * Create a Role resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: RoleArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: RoleArgs | RoleState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as RoleState | undefined; inputs["arn"] = state ? state.arn : undefined; inputs["assumeRolePolicy"] = state ? state.assumeRolePolicy : undefined; inputs["createDate"] = state ? state.createDate : undefined; inputs["description"] = state ? state.description : undefined; inputs["forceDetachPolicies"] = state ? state.forceDetachPolicies : undefined; inputs["inlinePolicies"] = state ? state.inlinePolicies : undefined; inputs["managedPolicyArns"] = state ? state.managedPolicyArns : undefined; inputs["maxSessionDuration"] = state ? state.maxSessionDuration : undefined; inputs["name"] = state ? state.name : undefined; inputs["namePrefix"] = state ? state.namePrefix : undefined; inputs["path"] = state ? state.path : undefined; inputs["permissionsBoundary"] = state ? state.permissionsBoundary : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["tagsAll"] = state ? state.tagsAll : undefined; inputs["uniqueId"] = state ? state.uniqueId : undefined; } else { const args = argsOrState as RoleArgs | undefined; if ((!args || args.assumeRolePolicy === undefined) && !opts.urn) { throw new Error("Missing required property 'assumeRolePolicy'"); } inputs["assumeRolePolicy"] = args ? args.assumeRolePolicy : undefined; inputs["description"] = args ? args.description : undefined; inputs["forceDetachPolicies"] = args ? args.forceDetachPolicies : undefined; inputs["inlinePolicies"] = args ? args.inlinePolicies : undefined; inputs["managedPolicyArns"] = args ? args.managedPolicyArns : undefined; inputs["maxSessionDuration"] = args ? args.maxSessionDuration : undefined; inputs["name"] = args ? args.name : undefined; inputs["namePrefix"] = args ? args.namePrefix : undefined; inputs["path"] = args ? args.path : undefined; inputs["permissionsBoundary"] = args ? args.permissionsBoundary : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["arn"] = undefined /*out*/; inputs["createDate"] = undefined /*out*/; inputs["tagsAll"] = undefined /*out*/; inputs["uniqueId"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Role.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Role resources. */ export interface RoleState { /** * Amazon Resource Name (ARN) specifying the role. */ arn?: pulumi.Input<string>; /** * Policy that grants an entity permission to assume the role. */ assumeRolePolicy?: pulumi.Input<string | PolicyDocument>; /** * Creation date of the IAM role. */ createDate?: pulumi.Input<string>; /** * Description of the role. */ description?: pulumi.Input<string>; /** * Whether to force detaching any policies the role has before destroying it. Defaults to `false`. */ forceDetachPolicies?: pulumi.Input<boolean>; /** * Configuration block defining an exclusive set of IAM inline policies associated with the IAM role. Defined below. If no blocks are configured, the provider will ignore any managing any inline policies in this resource. Configuring one empty block (i.e., `inlinePolicy {}`) will cause the provider to remove _all_ inline policies. */ inlinePolicies?: pulumi.Input<pulumi.Input<inputs.iam.RoleInlinePolicy>[]>; /** * Set of exclusive IAM managed policy ARNs to attach to the IAM role. If this attribute is not configured, the provider will ignore policy attachments to this resource. When configured, the provider will align the role's managed policy attachments with this set by attaching or detaching managed policies. Configuring an empty set (i.e., `managedPolicyArns = []`) will cause the provider to remove _all_ managed policy attachments. */ managedPolicyArns?: pulumi.Input<pulumi.Input<string>[]>; /** * Maximum session duration (in seconds) that you want to set for the specified role. If you do not specify a value for this setting, the default maximum of one hour is applied. This setting can have a value from 1 hour to 12 hours. */ maxSessionDuration?: pulumi.Input<number>; /** * Name of the role policy. */ name?: pulumi.Input<string>; /** * Creates a unique friendly name beginning with the specified prefix. Conflicts with `name`. */ namePrefix?: pulumi.Input<string>; /** * Path to the role. See [IAM Identifiers](https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) for more information. */ path?: pulumi.Input<string>; /** * ARN of the policy that is used to set the permissions boundary for the role. */ permissionsBoundary?: pulumi.Input<string>; /** * Key-value mapping of tags for the IAM role. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * A map of tags assigned to the resource, including those inherited from the provider . */ tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Stable and unique string identifying the role. */ uniqueId?: pulumi.Input<string>; } /** * The set of arguments for constructing a Role resource. */ export interface RoleArgs { /** * Policy that grants an entity permission to assume the role. */ assumeRolePolicy: pulumi.Input<string | PolicyDocument>; /** * Description of the role. */ description?: pulumi.Input<string>; /** * Whether to force detaching any policies the role has before destroying it. Defaults to `false`. */ forceDetachPolicies?: pulumi.Input<boolean>; /** * Configuration block defining an exclusive set of IAM inline policies associated with the IAM role. Defined below. If no blocks are configured, the provider will ignore any managing any inline policies in this resource. Configuring one empty block (i.e., `inlinePolicy {}`) will cause the provider to remove _all_ inline policies. */ inlinePolicies?: pulumi.Input<pulumi.Input<inputs.iam.RoleInlinePolicy>[]>; /** * Set of exclusive IAM managed policy ARNs to attach to the IAM role. If this attribute is not configured, the provider will ignore policy attachments to this resource. When configured, the provider will align the role's managed policy attachments with this set by attaching or detaching managed policies. Configuring an empty set (i.e., `managedPolicyArns = []`) will cause the provider to remove _all_ managed policy attachments. */ managedPolicyArns?: pulumi.Input<pulumi.Input<string>[]>; /** * Maximum session duration (in seconds) that you want to set for the specified role. If you do not specify a value for this setting, the default maximum of one hour is applied. This setting can have a value from 1 hour to 12 hours. */ maxSessionDuration?: pulumi.Input<number>; /** * Name of the role policy. */ name?: pulumi.Input<string>; /** * Creates a unique friendly name beginning with the specified prefix. Conflicts with `name`. */ namePrefix?: pulumi.Input<string>; /** * Path to the role. See [IAM Identifiers](https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) for more information. */ path?: pulumi.Input<string>; /** * ARN of the policy that is used to set the permissions boundary for the role. */ permissionsBoundary?: pulumi.Input<string>; /** * Key-value mapping of tags for the IAM role. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; }
the_stack
export const table = { data: { cols: [ { int64s: { data: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] }, type: "int64s", }, { int64s: { data: [1, 11, 21, 31, 41, 51, 61, 71, 81, 91] }, type: "int64s", }, { int64s: { data: [2, 12, 22, 32, 42, 52, 62, 72, 82, 92] }, type: "int64s", }, { int64s: { data: [3, 13, 23, 33, 43, 53, 63, 73, 83, 93] }, type: "int64s", }, { int64s: { data: [4, 14, 24, 34, 44, 54, 64, 74, 84, 94] }, type: "int64s", }, { int64s: { data: [5, 15, 25, 35, 45, 55, 65, 75, 85, 95] }, type: "int64s", }, { int64s: { data: [6, 16, 26, 36, 46, 56, 66, 76, 86, 96] }, type: "int64s", }, { int64s: { data: [7, 17, 27, 37, 47, 57, 67, 77, 87, 97] }, type: "int64s", }, { int64s: { data: [8, 18, 28, 38, 48, 58, 68, 78, 88, 98] }, type: "int64s", }, { int64s: { data: [9, 19, 29, 39, 49, 59, 69, 79, 89, 99] }, type: "int64s", }, ], }, index: { rangeIndex: { start: 0, stop: 10 }, type: "rangeIndex" }, columns: { rangeIndex: { start: 0, stop: 10 }, type: "rangeIndex" }, style: { cols: [ { styles: [ { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, ], }, { styles: [ { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, ], }, { styles: [ { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, ], }, { styles: [ { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, ], }, { styles: [ { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, ], }, { styles: [ { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, ], }, { styles: [ { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, ], }, { styles: [ { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, ], }, { styles: [ { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, ], }, { styles: [ { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, { css: [], displayValue: "", hasDisplayValue: false }, { css: [], displayValue: "", hasDisplayValue: false, }, ], }, ], }, } export const emptyTable = { data: null, index: { rangeIndex: { start: 0, stop: 1 }, type: "rangeIndex" }, columns: { rangeIndex: { start: 0, stop: 3 }, type: "rangeIndex" }, style: { cols: [ { styles: [{ css: [], displayValue: "", hasDisplayValue: false }], }, { styles: [{ css: [], displayValue: "", hasDisplayValue: false }], }, { styles: [{ css: [], displayValue: "", hasDisplayValue: false }], }, ], }, }
the_stack
import { messageUtil } from "../lib/messageUtil"; import { isFirefox, browserInfo, isNodeTest } from "./browserInfo"; import { SettingsTypeMap, SettingsSignature, RuleDefinition, CleanupType } from "./settingsSignature"; import { browser, Storage } from "webextension-polyfill-ts"; import { getRegExForRule } from "./regexp"; import migrateSettings, { manifestVersion } from "./settingsMigrations"; type Callback = () => void; type SettingsValue = string | boolean | number | (RuleDefinition[]) | { [s: string]: boolean }; export type SettingsMap = { [s: string]: SettingsValue }; export const localStorageDefault: boolean = isNodeTest || (isFirefox && browserInfo.versionAsNumber >= 58); export const defaultSettings: SettingsMap = { "version": manifestVersion, "showUpdateNotification": true, "showCookieRemovalNotification": false, "rules": [], "whitelistNoTLD": false, "whitelistFileSystem": true, "fallbackRule": CleanupType.LEAVE, "domainsToClean": {}, "downloadsToClean": {}, "showBadge": true, "initialTab": "this_tab", "lastTab": "this_tab", "cleanAll.cookies": true, "cleanAll.cookies.applyRules": true, "cleanAll.localStorage": localStorageDefault, "cleanAll.localStorage.applyRules": localStorageDefault, "cleanAll.protectOpenDomains": true, "cleanAll.history": false, "cleanAll.history.applyRules": true, "cleanAll.downloads": true, "cleanAll.downloads.applyRules": true, "cleanAll.formData": false, "cleanAll.passwords": false, "cleanAll.indexedDB": true, "cleanAll.pluginData": true, "cleanAll.serviceWorkers": true, "cleanAll.serverBoundCertificates": false, "cleanAll.cache": false, "cleanThirdPartyCookies.enabled": false, "cleanThirdPartyCookies.delay": 60, "cleanThirdPartyCookies.beforeCreation": false, "domainLeave.enabled": false, "domainLeave.delay": 120, "domainLeave.cookies": true, "domainLeave.localStorage": localStorageDefault, "domainLeave.history": false, "domainLeave.downloads": false, "instantly.enabled": true, "instantly.cookies": true, "instantly.history": false, "instantly.history.applyRules": true, "instantly.downloads": false, "instantly.downloads.applyRules": true, "startup.enabled": false, "startup.cookies": true, "startup.cookies.applyRules": true, "startup.localStorage": localStorageDefault, "startup.localStorage.applyRules": localStorageDefault, "startup.history": false, "startup.history.applyRules": true, "startup.downloads": true, "startup.downloads.applyRules": false, "startup.formData": false, "startup.passwords": false, "startup.indexedDB": true, "startup.pluginData": true, "startup.serviceWorkers": true, "startup.serverBoundCertificates": false, "startup.cache": false, "purgeExpiredCookies": false, "logRAD.enabled": true, "logRAD.limit": 20 }; const isAlNum = /^[a-z0-9]+$/; const isAlNumDash = /^[a-z0-9\-]+$/; const validCookieName = /^[!,#,\$,%,&,',\*,\+,\-,\.,0-9,:,;,A-Z,\\,\^,_,`,a-z,\|,~]+$/i; function isValidExpressionPart(part: string) { if (part.length === 0) return false; if (part === "*") return true; return isAlNum.test(part[0]) && isAlNum.test(part[part.length - 1]) && isAlNumDash.test(part); } function isValidDomainExpression(exp: string) { const parts = exp.split("."); return parts.length > 0 && parts.findIndex((p) => !isValidExpressionPart(p)) === -1; } export function isValidExpression(exp: string) { const parts = exp.split("@"); if (parts.length === 1) return isValidDomainExpression(exp); return parts.length === 2 && validCookieName.test(parts[0]) && isValidDomainExpression(parts[1]); } export function classNameForCleanupType(type: CleanupType) { if (type === CleanupType.NEVER) return "cleanup_type_never"; if (type === CleanupType.STARTUP) return "cleanup_type_startup"; if (type === CleanupType.INSTANTLY) return "cleanup_type_instantly"; return "cleanup_type_leave"; } export function cleanupTypeForElement(element: HTMLElement) { if (element.classList.contains("cleanup_type_never")) return CleanupType.NEVER; if (element.classList.contains("cleanup_type_startup")) return CleanupType.STARTUP; if (element.classList.contains("cleanup_type_leave")) return CleanupType.LEAVE; if (element.classList.contains("cleanup_type_instantly")) return CleanupType.INSTANTLY; return null; } function isValidCleanupType(type: CleanupType) { return type === CleanupType.NEVER || type === CleanupType.STARTUP || type === CleanupType.LEAVE || type === CleanupType.INSTANTLY; } function sanitizeRules(rules: RuleDefinition[], expressionValidator: (value: string) => boolean) { const validRules: RuleDefinition[] = []; for (const ruleDef of rules) { if (typeof (ruleDef.rule) === "string" && expressionValidator(ruleDef.rule) && isValidCleanupType(ruleDef.type)) { validRules.push({ rule: ruleDef.rule, type: ruleDef.type }); } } return validRules; } interface CompiledRuleDefinition { definition: RuleDefinition; regex: RegExp; cookieName?: string; } export class Settings { private rules: CompiledRuleDefinition[] = []; private cookieRules: CompiledRuleDefinition[] = []; private readonly storage: Storage.StorageArea; private map: SettingsMap = {}; private readyCallbacks: Callback[] | null = []; public constructor() { this.storage = browser.storage.local; this.load(); this.load = this.load.bind(this); browser.storage.onChanged.addListener(this.load); } public load(changes?: { [key: string]: Storage.StorageChange }) { this.storage.get(null).then((map) => { this.map = map; const changedKeys = Object.getOwnPropertyNames(changes || map); if (changedKeys.indexOf("rules") >= 0) this.rebuildRules(); if (this.readyCallbacks) { for (const callback of this.readyCallbacks) callback(); this.readyCallbacks = null; } if (typeof (messageUtil) !== "undefined") { messageUtil.send("settingsChanged", changedKeys); // to other background scripts messageUtil.sendSelf("settingsChanged", changedKeys); // since the above does not fire on the same process } }); } public rebuildRules() { this.rules = []; this.cookieRules = []; const rules = this.get("rules"); for (const rule of rules) { const parts = rule.rule.split("@"); const isCookieRule = parts.length === 2; if (isCookieRule) { this.cookieRules.push({ definition: rule, regex: getRegExForRule(parts[1]), cookieName: parts[0].toLowerCase() }); } else { this.rules.push({ definition: rule, regex: getRegExForRule(rule.rule) }); } } } public save() { return this.storage.set(this.map); } public onReady(callback: Callback) { if (this.readyCallbacks) this.readyCallbacks.push(callback); else callback(); } public restoreDefaults() { this.map = {}; this.storage.clear(); this.rebuildRules(); this.save(); } public performUpgrade(previousVersion: string) { migrateSettings(previousVersion, this.map); } public setAll(json: any) { // Validate and throw out anything that is no longer valid if (typeof (json) !== "object") return false; if (json.rules) { if (!Array.isArray(json.rules)) delete json.rules; else (json as any).rules = sanitizeRules((json as any).rules as RuleDefinition[], isValidExpression); } for (const key in json) { if (!json.hasOwnProperty(key)) continue; if (!defaultSettings.hasOwnProperty(key)) { if (!isNodeTest) console.warn("Unknown setting: ", key); delete json[key]; } if (typeof (defaultSettings[key]) !== typeof (json[key])) { if (!isNodeTest) console.warn("Types do not match while importing setting: ", key, typeof (defaultSettings[key]), typeof (json[key])); delete json[key]; } } const keysToRemove = Object.getOwnPropertyNames(this.getAll()).filter((key) => !json.hasOwnProperty(key)); this.storage.remove(keysToRemove); this.map = json; this.performUpgrade(this.get("version")); this.set("version", browser.runtime.getManifest().version); this.rebuildRules(); this.save(); return true; } public getAll() { const result: SettingsMap = {}; for (const key in defaultSettings) { if (this.map.hasOwnProperty(key)) result[key] = this.map[key]; else result[key] = defaultSettings[key]; } return result as SettingsSignature; } public get<K extends keyof SettingsTypeMap>(key: K): SettingsTypeMap[K] { if (this.map.hasOwnProperty(key)) return this.map[key] as SettingsTypeMap[K]; return defaultSettings[key] as SettingsTypeMap[K]; } public set<K extends keyof SettingsTypeMap>(key: K, value: SettingsTypeMap[K]) { this.map[key] = value; if (key === "rules") this.rebuildRules(); } // Convenience methods // fixme: add tests public getExactRuleDefinition(expression: string) { for (const crd of this.rules) { if (crd.definition.rule === expression) return crd.definition; } return null; } public getExactCleanupType(expression: string) { const definition = this.getExactRuleDefinition(expression); return definition && definition.type; } public getMatchingRules(domain: string, cookieName: string | false = false) { const rules = cookieName !== false ? this.cookieRules : this.rules; const lowerCookieName = cookieName && cookieName.toLowerCase(); const matchingRules: RuleDefinition[] = []; for (const rule of rules) { if (rule.regex.test(domain) && (!rule.cookieName || rule.cookieName === lowerCookieName)) matchingRules.push(rule.definition); } return matchingRules; } public hasBlockingRule() { return this.get("fallbackRule") === CleanupType.INSTANTLY || !!this.get("rules").find((r) => r.type === CleanupType.INSTANTLY); } private getCleanupTypeFromMatchingRules(matchingRules: RuleDefinition[]) { if (matchingRules.find((r) => r.type === CleanupType.INSTANTLY)) return CleanupType.INSTANTLY; if (matchingRules.find((r) => r.type === CleanupType.LEAVE)) return CleanupType.LEAVE; if (matchingRules.find((r) => r.type === CleanupType.NEVER)) return CleanupType.NEVER; return CleanupType.STARTUP; } public getCleanupTypeForCookie(domain: string, name: string) { if (this.get("whitelistFileSystem") && domain.length === 0) return CleanupType.NEVER; if (this.get("whitelistNoTLD") && domain.length > 0 && domain.indexOf(".") === -1) return CleanupType.NEVER; const matchingRules = this.getMatchingRules(domain, name); if (matchingRules.length) return this.getCleanupTypeFromMatchingRules(matchingRules); return this.getCleanupTypeForDomain(domain); } public getCleanupTypeForDomain(domain: string) { if (this.get("whitelistFileSystem") && domain.length === 0) return CleanupType.NEVER; if (this.get("whitelistNoTLD") && domain.length > 0 && domain.indexOf(".") === -1) return CleanupType.NEVER; const matchingRules = this.getMatchingRules(domain); if (matchingRules.length) return this.getCleanupTypeFromMatchingRules(matchingRules); return this.get("fallbackRule"); } public isDomainProtected(domain: string, ignoreStartupType: boolean) { const type = this.getCleanupTypeForDomain(domain); return type === CleanupType.NEVER || (type === CleanupType.STARTUP && !ignoreStartupType); } public isDomainBlocked(domain: string) { return this.getCleanupTypeForDomain(domain) === CleanupType.INSTANTLY; } // FIXME: add tests public getRulesForDomain(domain: string) { return this.rules.concat(this.cookieRules) .filter((rule) => rule.regex.test(domain)) .map((rule) => rule.definition); } public getChosenRulesForDomain(domain: string) { if (this.get("whitelistFileSystem") && domain.length === 0) return []; if (this.get("whitelistNoTLD") && domain.length > 0 && domain.indexOf(".") === -1) return []; const matchingRules = this.getMatchingRules(domain); if (matchingRules.length) { const types = [CleanupType.INSTANTLY, CleanupType.LEAVE, CleanupType.NEVER, CleanupType.STARTUP]; for (const type of types) { const rules = matchingRules.filter((r) => r.type === type); if (rules.length) return rules; } } return []; } public setRule(expression: string, type: CleanupType, temporary: boolean) { const rules = this.get("rules").slice(); let ruleDef = rules.find((r) => r.rule === expression); if (ruleDef) ruleDef.type = type; else { ruleDef = { rule: expression, type }; rules.push(ruleDef); } if (temporary) ruleDef.temporary = true; else delete ruleDef.temporary; this.set("rules", rules); this.save(); } public removeRule(expression: string) { const rules = this.get("rules").filter((r) => r.rule !== expression); this.set("rules", rules); this.save(); } public removeRules(rules: string[]) { const remainingRules = this.get("rules").filter((r) => rules.indexOf(r.rule) === -1); this.set("rules", remainingRules); this.save(); this.rebuildRules(); } public getTemporaryRules() { return this.rules.filter((r) => !!r.definition.temporary); } public removeTemporaryRules() { const rules = this.get("rules").filter((r) => !r.temporary); this.set("rules", rules); this.save(); } } export const settings = new Settings();
the_stack
import { ethers, waffle } from "hardhat"; import { expect, use } from "chai"; import { solidity } from "ethereum-waffle"; use(solidity); import { constants, providers, Wallet } from "ethers"; import { ProposedOwnable } from "../typechain"; import { assertReceiptEvent, deployContract, proposeNewOwnerOnContract, setBlockTime, transferOwnershipOnContract, } from "./utils"; const createFixtureLoader = waffle.createFixtureLoader; describe("ProposedOwnable.sol", () => { const [wallet, other] = waffle.provider.getWallets() as Wallet[]; let proposedOwnable: ProposedOwnable; const fixture = async () => { // Deploy transaction manager because it inherits the contract // we want to test proposedOwnable = await deployContract<ProposedOwnable>("TransactionManager", 1337); }; const proposeNewOwner = async (newOwner: string = constants.AddressZero) => { // Propose new owner return await proposeNewOwnerOnContract(newOwner, wallet, proposedOwnable); }; const proposeRouterOwnershipRenunciation = async () => { // Propose new owner const tx = await proposedOwnable.connect(wallet).proposeRouterOwnershipRenunciation(); const receipt: providers.TransactionReceipt = await tx.wait(); const block = await ethers.provider.getBlock(receipt.blockNumber); assertReceiptEvent(receipt, "RouterOwnershipRenunciationProposed", { timestamp: block.timestamp }); expect(await proposedOwnable.routerOwnershipTimestamp()).to.be.eq(block.timestamp); }; const proposeAssetOwnershipRenunciation = async () => { // Propose new owner const tx = await proposedOwnable.connect(wallet).proposeAssetOwnershipRenunciation(); const receipt: providers.TransactionReceipt = await tx.wait(); const block = await ethers.provider.getBlock(receipt.blockNumber); assertReceiptEvent(receipt, "AssetOwnershipRenunciationProposed", { timestamp: block.timestamp }); expect(await proposedOwnable.assetOwnershipTimestamp()).to.be.eq(block.timestamp); return receipt; }; const transferOwnership = async (newOwner: string = constants.AddressZero, caller = other) => { await transferOwnershipOnContract(newOwner, caller, proposedOwnable, wallet); }; const renounceAssetOwnership = async () => { await proposeAssetOwnershipRenunciation(); // Advance block time const eightDays = 8 * 24 * 60 * 60; const { timestamp } = await ethers.provider.getBlock("latest"); await setBlockTime(timestamp + eightDays); const tx = await proposedOwnable.connect(wallet).renounceAssetOwnership(); const receipt = await tx.wait(); assertReceiptEvent(receipt, "AssetOwnershipRenounced", { renounced: true }); }; const renounceRouterOwnership = async () => { await proposeRouterOwnershipRenunciation(); // Advance block time const eightDays = 8 * 24 * 60 * 60; const { timestamp } = await ethers.provider.getBlock("latest"); await setBlockTime(timestamp + eightDays); const tx = await proposedOwnable.connect(wallet).renounceRouterOwnership(); const receipt = await tx.wait(); assertReceiptEvent(receipt, "RouterOwnershipRenounced", { renounced: true }); expect(await proposedOwnable.routerOwnershipTimestamp()).to.be.eq(constants.Zero); }; let loadFixture: ReturnType<typeof createFixtureLoader>; before("create fixture loader", async () => { loadFixture = createFixtureLoader([wallet, other]); }); beforeEach(async () => { await loadFixture(fixture); }); describe("owner", () => { it("should work", async () => { expect(await proposedOwnable.owner()).to.be.eq(wallet.address); }); }); describe("proposed", () => { it("should work", async () => { expect(await proposedOwnable.proposed()).to.be.eq(constants.AddressZero); await proposeNewOwner(other.address); expect(await proposedOwnable.proposed()).to.be.eq(other.address); }); }); describe("proposedTimestamp", () => { it("should work", async () => { expect(await proposedOwnable.proposedTimestamp()).to.be.eq(constants.Zero); const receipt = await proposeNewOwner(other.address); const block = await ethers.provider.getBlock(receipt.blockNumber); expect(await proposedOwnable.proposedTimestamp()).to.be.eq(block.timestamp); }); }); describe("routerOwnershipTimestamp", () => { it("should work", async () => { expect(await proposedOwnable.routerOwnershipTimestamp()).to.be.eq(constants.Zero); await proposeRouterOwnershipRenunciation(); }); }); describe("assetOwnershipTimestamp", () => { it("should work", async () => { expect(await proposedOwnable.assetOwnershipTimestamp()).to.be.eq(constants.Zero); await proposeAssetOwnershipRenunciation(); }); }); describe("delay", () => { it("should work", async () => { expect(await proposedOwnable.delay()).to.be.eq(7 * 24 * 60 * 60); }); }); describe("isRouterOwnershipRenounced", () => { it("should work if renounced", async () => { await transferOwnership(constants.AddressZero, wallet); expect(await proposedOwnable.renounced()).to.be.true; expect(await proposedOwnable.isRouterOwnershipRenounced()).to.be.true; }); it("should work if asset ownership renounced", async () => { await renounceRouterOwnership(); expect(await proposedOwnable.renounced()).to.be.false; expect(await proposedOwnable.isRouterOwnershipRenounced()).to.be.true; }); }); describe("proposeRouterOwnershipRenunciation", () => { it("should fail if router ownership is already renounced", async () => { await renounceRouterOwnership(); await expect(proposedOwnable.connect(wallet).proposeRouterOwnershipRenunciation()).to.be.revertedWith( "#PROR:038", ); }); it("should work", async () => { await proposeRouterOwnershipRenunciation(); }); }); describe("renounceRouterOwnership", () => { it("should fail if router ownership is already renounced", async () => { await renounceRouterOwnership(); await expect(proposedOwnable.connect(wallet).renounceRouterOwnership()).to.be.revertedWith("#RRO:038"); }); it("should fail if there is no proposal in place", async () => { await expect(proposedOwnable.connect(wallet).renounceRouterOwnership()).to.be.revertedWith("#RRO:037"); }); it("should fail if delay has not elapsed", async () => { await proposeRouterOwnershipRenunciation(); await expect(proposedOwnable.connect(wallet).renounceRouterOwnership()).to.be.revertedWith("#RRO:030"); }); it("should work", async () => { await renounceRouterOwnership(); }); }); describe("isAssetOwnershipRenounced", () => { it("should work if renounced", async () => { await transferOwnership(constants.AddressZero, wallet); expect(await proposedOwnable.renounced()).to.be.true; expect(await proposedOwnable.isAssetOwnershipRenounced()).to.be.true; }); it("should work if asset ownership renounced", async () => { await renounceAssetOwnership(); expect(await proposedOwnable.renounced()).to.be.false; expect(await proposedOwnable.isAssetOwnershipRenounced()).to.be.true; }); }); describe("proposeAssetOwnershipRenunciation", () => { it("should fail if asset ownership already renounced", async () => { await renounceAssetOwnership(); await expect(proposedOwnable.connect(wallet).proposeAssetOwnershipRenunciation()).to.be.revertedWith("#PAOR:038"); }); it("should work", async () => { await proposeAssetOwnershipRenunciation(); }); }); describe("renounceAssetOwnership", () => { it("should fail if asset ownership is already renounced", async () => { await renounceAssetOwnership(); await expect(proposedOwnable.connect(wallet).renounceAssetOwnership()).to.be.revertedWith("#RAO:038"); }); it("should fail if no proposal was made", async () => { await expect(proposedOwnable.connect(wallet).renounceAssetOwnership()).to.be.revertedWith("#RAO:037"); }); it("should fail if delay has not elapsed", async () => { await proposeAssetOwnershipRenunciation(); await expect(proposedOwnable.connect(wallet).renounceAssetOwnership()).to.be.revertedWith("#RAO:030"); }); it("should work", async () => { await renounceAssetOwnership(); }); }); describe("renounced", () => { it("should return false if owner is not renounced", async () => { expect(await proposedOwnable.renounced()).to.be.false; }); it("should return true if owner is renounced", async () => { // Propose new owner of address(0) await transferOwnership(constants.AddressZero, wallet); // Check renounced expect(await proposedOwnable.renounced()).to.be.true; }); }); describe("proposeNewOwner", () => { it("should fail if not called by owner", async () => { await expect(proposedOwnable.connect(other).proposeNewOwner(constants.AddressZero)).to.be.revertedWith("#OO:029"); }); it("should fail if proposing the same address as what is already proposed", async () => { await proposeNewOwner(other.address); await expect(proposedOwnable.connect(wallet).proposeNewOwner(other.address)).to.be.revertedWith("#PNO:036"); }); it("should fail if proposing the owner", async () => { await expect(proposedOwnable.connect(wallet).proposeNewOwner(wallet.address)).to.be.revertedWith("#PNO:038"); }); it("should work", async () => { await proposeNewOwner(other.address); }); }); describe("renounceOwnership", () => { it("should fail if there was no proposal", async () => { await expect(proposedOwnable.connect(wallet).renounceOwnership()).to.be.revertedWith("#RO:037"); }); it("should fail if the delay hasnt elapsed", async () => { await proposeNewOwner(constants.AddressZero); await expect(proposedOwnable.connect(wallet).renounceOwnership()).to.be.revertedWith("#RO:030"); }); it("should fail if the proposed != address(0)", async () => { await proposeNewOwner(Wallet.createRandom().address); // Advance block time const eightDays = 8 * 24 * 60 * 60; const { timestamp } = await ethers.provider.getBlock("latest"); await setBlockTime(timestamp + eightDays); await expect(proposedOwnable.connect(wallet).renounceOwnership()).to.be.revertedWith("#RO:036"); }); it("should fail if not called by owner", async () => { await proposeNewOwner(constants.AddressZero); await expect(proposedOwnable.connect(other).renounceOwnership()).to.be.revertedWith("#OO:029"); }); it("should work", async () => { await transferOwnership(constants.AddressZero, wallet); }); }); describe("acceptProposedOwner", () => { it("should fail if not called by proposed", async () => { await proposeNewOwner(other.address); await expect(proposedOwnable.connect(wallet).acceptProposedOwner()).to.be.revertedWith("#OP:035"); }); it("should fail if there is no effective change in ownership", async () => { // First make and accept a new owner await transferOwnership(other.address); // Then try again await expect(proposedOwnable.connect(other).acceptProposedOwner()).to.be.revertedWith("#APO:038"); }); it("should fail if delay has not elapsed", async () => { await proposeNewOwner(other.address); await expect(proposedOwnable.connect(other).acceptProposedOwner()).to.be.revertedWith("#APO:030"); }); it("should work", async () => { await transferOwnership(other.address, other); }); }); });
the_stack
import { assert } from 'chai'; import { TestResult, TestStatus, TestVariant, TestVariantStatus } from '../services/resultdb'; import { parseSearchQuery, suggestSearchQuery } from './search_query'; const variant1: TestVariant = { testId: 'invocation-a/test-suite-a/test-1', variant: { def: { key1: 'val1' } }, variantHash: 'key1:val1', testMetadata: { name: 'test-name-1', }, status: TestVariantStatus.UNEXPECTED, results: [ { result: { status: TestStatus.Fail, tags: [{ key: 'tag-key-1', value: 'tag-val-1' }], duration: '10s', } as TestResult, }, { result: { status: TestStatus.Fail, tags: [{ key: 'tag-key-1', value: 'tag-val-1=1' }], duration: '15s', } as TestResult, }, { result: { status: TestStatus.Skip, tags: [{ key: 'tag-key-2', value: 'tag-val-2' }], duration: '20s', } as TestResult, }, ], }; const variant2: TestVariant = { testId: 'invocation-a/test-suite-a/test-2', variant: { def: { key1: 'val2' } }, variantHash: 'key1:val2', testMetadata: { name: 'test-name-2', }, status: TestVariantStatus.UNEXPECTED, results: [ { result: { tags: [{ key: 'tag-key-1', value: 'unknown-val' }], status: TestStatus.Fail, duration: '30s', } as TestResult, }, { result: { status: TestStatus.Fail, tags: [ { key: 'duplicated-tag-key', value: 'first-tag-val' }, { key: 'duplicated-tag-key', value: 'second-tag-val' }, ], } as TestResult, }, ], }; const variant3: TestVariant = { testId: 'invocation-a/test-suite-b/test-3', variant: { def: { key1: 'val3' } }, variantHash: 'key1:val3', testMetadata: { name: 'test', }, status: TestVariantStatus.FLAKY, results: [ { result: { status: TestStatus.Pass, } as TestResult, }, { result: { status: TestStatus.Fail, } as TestResult, }, ], }; const variant4: TestVariant = { testId: 'invocation-a/test-suite-B/test-4', variant: { def: { key1: 'val2' } }, variantHash: 'key1:val2', status: TestVariantStatus.EXONERATED, }; const variant5: TestVariant = { testId: 'invocation-a/test-suite-B/test-5', variant: { def: { key1: 'val2', key2: 'val1' } }, variantHash: 'key1:val2|key2:val1', status: TestVariantStatus.EXPECTED, results: [ { result: { status: TestStatus.Pass, } as TestResult, }, ], }; const variant6: TestVariant = { testId: 'invocation-a/test-suite-b/test-5', variant: { def: { key1: 'val2', key2: 'val3' } }, variantHash: 'key1:val2|key2:val3', testMetadata: { name: 'sub', }, status: TestVariantStatus.EXPECTED, results: [ { result: { status: TestStatus.Skip, } as TestResult, }, ], }; const variant7: TestVariant = { testId: 'invocation-a/test-suite-b/test-5/sub', variant: { def: { key1: 'val2', key2: 'val3=val' } }, variantHash: 'key1:val2|key2:val3=val', status: TestVariantStatus.EXPECTED, results: [ { result: { status: TestStatus.Skip, } as TestResult, }, ], }; const variants = [variant1, variant2, variant3, variant4, variant5, variant6, variant7]; describe('parseSearchQuery', () => { describe('query with no type', () => { it('should match either test ID or test name', () => { const filter = parseSearchQuery('sub'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant6, variant7]); }); it('should be case insensitive', () => { const filter = parseSearchQuery('SuB'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant6, variant7]); }); }); describe('ID query', () => { it("should filter out variants whose test ID doesn't match the search text", () => { const filter = parseSearchQuery('ID:test-suite-a'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant1, variant2]); }); it('should be case insensitive', () => { const filter = parseSearchQuery('id:test-suite-b'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant3, variant4, variant5, variant6, variant7]); }); it('should work with negation', () => { const filter = parseSearchQuery('-id:test-5'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant1, variant2, variant3, variant4]); }); }); describe('RSTATUS query', () => { it('should filter out variants with no matching status', () => { const filter = parseSearchQuery('rstatus:pass'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant3, variant5]); }); it('supports multiple statuses', () => { const filter = parseSearchQuery('rstatus:pass,fail'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant1, variant2, variant3, variant5]); }); it('should work with negation', () => { const filter = parseSearchQuery('-rstatus:pass'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant1, variant2, variant4, variant6, variant7]); }); }); describe('ExactID query', () => { it('should only keep tests with the same ID', () => { const filter = parseSearchQuery('ExactID:invocation-a/test-suite-b/test-5'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant6]); }); it('should be case sensitive', () => { const filter = parseSearchQuery('ExactID:invocation-a/test-suite-B/test-5'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant5]); }); it('should work with negation', () => { const filter = parseSearchQuery('-ExactID:invocation-a/test-suite-b/test-5'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant1, variant2, variant3, variant4, variant5, variant7]); }); }); describe('V query', () => { it('should filter out variants with no matching variant key-value pair', () => { const filter = parseSearchQuery('v:key1=val1'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant1]); }); it("should support variant value with '=' in it", () => { const filter = parseSearchQuery('v:key2=val3=val'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant7]); }); it('should support filter with only variant key', () => { const filter = parseSearchQuery('v:key2'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant5, variant6, variant7]); }); it('should work with negation', () => { const filter = parseSearchQuery('-v:key1=val1'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant2, variant3, variant4, variant5, variant6, variant7]); }); }); describe('VHash query', () => { it('should filter out variants with no matching variant hash', () => { const filter = parseSearchQuery('vhash:key1:val1'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant1]); }); it('should work with negation', () => { const filter = parseSearchQuery('-vhash:key1:val1'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant2, variant3, variant4, variant5, variant6, variant7]); }); }); describe('Tag query', () => { it('should filter out variants with no matching tag key-value pair', () => { const filter = parseSearchQuery('tag:tag-key-1=tag-val-1'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant1]); }); it("should support tag value with '=' in it", () => { const filter = parseSearchQuery('tag:tag-key-1=tag-val-1=1'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant1]); }); it('should support filter with only tag key', () => { const filter = parseSearchQuery('tag:tag-key-1'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant1, variant2]); }); it('should work with negation', () => { const filter = parseSearchQuery('-tag:tag-key-1=tag-val-1'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant2, variant3, variant4, variant5, variant6, variant7]); }); it('should support duplicated tag key', () => { const filter = parseSearchQuery('-tag:duplicated-tag-key=second-tag-val'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant1, variant3, variant4, variant5, variant6, variant7]); }); }); describe('Name query', () => { it("should filter out variants whose test name doesn't match the search text", () => { const filter = parseSearchQuery('Name:test-name'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant1, variant2]); }); it('should be case insensitive', () => { const filter = parseSearchQuery('Name:test-NAME'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant1, variant2]); }); it('should work with negation', () => { const filter = parseSearchQuery('-Name:test-name-1'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant2, variant3, variant4, variant5, variant6, variant7]); }); }); describe('Duration query', () => { it('should filter out variants with no run that has the specified duration', () => { const filter = parseSearchQuery('Duration:5-10'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant1]); }); it('should support decimals', () => { const filter = parseSearchQuery('Duration:5.5-10.5'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant1]); }); it('should support omitting max duration', () => { const filter = parseSearchQuery('Duration:5-'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant1, variant2]); }); it('should work with negation', () => { const filter = parseSearchQuery('-Duration:5-10'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant2, variant3, variant4, variant5, variant6, variant7]); }); }); describe('ExactName query', () => { it('should only keep tests with the same name', () => { const filter = parseSearchQuery('ExactName:test'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant3]); }); it('should be case sensitive', () => { const filter = parseSearchQuery('ExactName:tesT'); const filtered = variants.filter(filter); assert.deepEqual(filtered, []); }); it('should work with negation', () => { const filter = parseSearchQuery('-ExactName:test'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant1, variant2, variant4, variant5, variant6, variant7]); }); }); describe('multiple queries', () => { it('should be able to combine different types of query', () => { const filter = parseSearchQuery('rstatus:pass id:test-3'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant3]); }); it('should be able to combine normal and negative queries', () => { const filter = parseSearchQuery('rstatus:pass -rstatus:fail'); const filtered = variants.filter(filter); assert.deepEqual(filtered, [variant5]); }); }); }); describe('suggestSearchQuery', () => { it('should give user some suggestions when the query is empty', () => { const suggestions1 = suggestSearchQuery(''); assert.notStrictEqual(suggestions1.length, 0); }); it('should not give suggestions when the sub-query is empty', () => { const suggestions1 = suggestSearchQuery('Status:UNEXPECTED '); assert.strictEqual(suggestions1.length, 0); }); it('should give user suggestions based on the last sub-query', () => { const suggestions1 = suggestSearchQuery('unexpected Pass'); assert.isDefined(suggestions1.find((s) => s.value === 'RStatus:Pass')); assert.isDefined(suggestions1.find((s) => s.value === '-RStatus:Pass')); assert.isUndefined(suggestions1.find((s) => s.value === 'Status:UNEXPECTED')); assert.isUndefined(suggestions1.find((s) => s.value === '-Status:UNEXPECTED')); }); it('should suggest run status query with matching status', () => { const suggestions1 = suggestSearchQuery('Pass'); assert.isDefined(suggestions1.find((s) => s.value === 'RStatus:Pass')); assert.isDefined(suggestions1.find((s) => s.value === '-RStatus:Pass')); const suggestions2 = suggestSearchQuery('Fail'); assert.isDefined(suggestions2.find((s) => s.value === 'RStatus:Fail')); assert.isDefined(suggestions2.find((s) => s.value === '-RStatus:Fail')); const suggestions3 = suggestSearchQuery('Crash'); assert.isDefined(suggestions3.find((s) => s.value === 'RStatus:Crash')); assert.isDefined(suggestions3.find((s) => s.value === '-RStatus:Crash')); const suggestions4 = suggestSearchQuery('Abort'); assert.isDefined(suggestions4.find((s) => s.value === 'RStatus:Abort')); assert.isDefined(suggestions4.find((s) => s.value === '-RStatus:Abort')); const suggestions5 = suggestSearchQuery('Skip'); assert.isDefined(suggestions5.find((s) => s.value === 'RStatus:Skip')); assert.isDefined(suggestions5.find((s) => s.value === '-RStatus:Skip')); }); it('should not suggest run status query with a different status', () => { const suggestions1 = suggestSearchQuery('Pass'); assert.isUndefined(suggestions1.find((s) => s.value === 'RStatus:Fail')); assert.isUndefined(suggestions1.find((s) => s.value === '-RStatus:Fail')); assert.isUndefined(suggestions1.find((s) => s.value === 'RStatus:Crash')); assert.isUndefined(suggestions1.find((s) => s.value === '-RStatus:Crash')); assert.isUndefined(suggestions1.find((s) => s.value === 'RStatus:Abort')); assert.isUndefined(suggestions1.find((s) => s.value === '-RStatus:Abort')); assert.isUndefined(suggestions1.find((s) => s.value === 'RStatus:Skip')); assert.isUndefined(suggestions1.find((s) => s.value === '-RStatus:Skip')); }); it('should suggest variant status query with matching status', () => { const suggestions1 = suggestSearchQuery('unexpected'); assert.isDefined(suggestions1.find((s) => s.value === 'Status:UNEXPECTED')); assert.isDefined(suggestions1.find((s) => s.value === '-Status:UNEXPECTED')); const suggestions2 = suggestSearchQuery('flaky'); assert.isDefined(suggestions2.find((s) => s.value === 'Status:FLAKY')); assert.isDefined(suggestions2.find((s) => s.value === '-Status:FLAKY')); const suggestions3 = suggestSearchQuery('exonerated'); assert.isDefined(suggestions3.find((s) => s.value === 'Status:EXONERATED')); assert.isDefined(suggestions3.find((s) => s.value === '-Status:EXONERATED')); const suggestions4 = suggestSearchQuery('expected'); assert.isDefined(suggestions4.find((s) => s.value === 'Status:EXPECTED')); assert.isDefined(suggestions4.find((s) => s.value === '-Status:EXPECTED')); }); it('should not suggest variant status query with a different status', () => { const suggestions1 = suggestSearchQuery('UNEXPECTED'); assert.isUndefined(suggestions1.find((s) => s.value === 'Status:FLAKY')); assert.isUndefined(suggestions1.find((s) => s.value === '-Status:FLAKY')); assert.isUndefined(suggestions1.find((s) => s.value === 'Status:EXONERATED')); assert.isUndefined(suggestions1.find((s) => s.value === '-Status:EXONERATED')); assert.isUndefined(suggestions1.find((s) => s.value === 'Status:EXPECTED')); assert.isUndefined(suggestions1.find((s) => s.value === '-Status:EXPECTED')); }); it('suggestion should be case insensitive', () => { const suggestions1 = suggestSearchQuery('PASS'); assert.isDefined(suggestions1.find((s) => s.value === 'RStatus:Pass')); assert.isDefined(suggestions1.find((s) => s.value === '-RStatus:Pass')); const suggestions2 = suggestSearchQuery('fail'); assert.isDefined(suggestions2.find((s) => s.value === 'RStatus:Fail')); assert.isDefined(suggestions2.find((s) => s.value === '-RStatus:Fail')); const suggestions3 = suggestSearchQuery('CrAsH'); assert.isDefined(suggestions3.find((s) => s.value === 'RStatus:Crash')); assert.isDefined(suggestions3.find((s) => s.value === '-RStatus:Crash')); const suggestions4 = suggestSearchQuery('Abort'); assert.isDefined(suggestions4.find((s) => s.value === 'RStatus:Abort')); assert.isDefined(suggestions4.find((s) => s.value === '-RStatus:Abort')); const suggestions5 = suggestSearchQuery('sKIP'); assert.isDefined(suggestions5.find((s) => s.value === 'RStatus:Skip')); assert.isDefined(suggestions5.find((s) => s.value === '-RStatus:Skip')); }); it('should suggest ID query', () => { const suggestions1 = suggestSearchQuery('ranDom'); assert.isDefined(suggestions1.find((s) => s.value === 'ID:ranDom')); assert.isDefined(suggestions1.find((s) => s.value === '-ID:ranDom')); }); it('should suggest ID query when the query prefix is ID:', () => { const suggestions1 = suggestSearchQuery('ID:pass'); assert.isDefined(suggestions1.find((s) => s.value === 'ID:pass')); assert.isDefined(suggestions1.find((s) => s.value === '-ID:pass')); const suggestions2 = suggestSearchQuery('-ID:pass'); // When user explicitly typed negative query, don't suggest positive query. assert.isUndefined(suggestions2.find((s) => s.value === 'ID:pass')); assert.isDefined(suggestions2.find((s) => s.value === '-ID:pass')); }); it('should suggest ID query when the query type is a substring of ID:', () => { const suggestions1 = suggestSearchQuery('i'); assert.isDefined(suggestions1.find((s) => s.value === 'ID:')); assert.isDefined(suggestions1.find((s) => s.value === '-ID:')); }); it('should suggest ID query even when there are other matching queries', () => { const suggestions1 = suggestSearchQuery('fail'); assert.isDefined(suggestions1.find((s) => s.value === 'RStatus:Fail')); assert.isDefined(suggestions1.find((s) => s.value === '-RStatus:Fail')); assert.isDefined(suggestions1.find((s) => s.value === 'ID:fail')); assert.isDefined(suggestions1.find((s) => s.value === '-ID:fail')); }); it('should suggest ExactID query when the query prefix is ExactID:', () => { const suggestions1 = suggestSearchQuery('ExactID:pass'); assert.isDefined(suggestions1.find((s) => s.value === 'ExactID:pass')); assert.isDefined(suggestions1.find((s) => s.value === '-ExactID:pass')); const suggestions2 = suggestSearchQuery('-ExactID:pass'); // When user explicitly typed negative query, don't suggest positive query. assert.isUndefined(suggestions2.find((s) => s.value === 'ExactID:pass')); assert.isDefined(suggestions2.find((s) => s.value === '-ExactID:pass')); }); it('should suggest ExactID query when the query type is a substring of ExactID:', () => { const suggestions1 = suggestSearchQuery('xact'); assert.isDefined(suggestions1.find((s) => s.value === 'ExactID:')); assert.isDefined(suggestions1.find((s) => s.value === '-ExactID:')); }); it('should suggest V query when the query prefix is V:', () => { const suggestions1 = suggestSearchQuery('V:test_suite'); assert.isDefined(suggestions1.find((s) => s.value === 'V:test_suite')); assert.isDefined(suggestions1.find((s) => s.value === '-V:test_suite')); const suggestions2 = suggestSearchQuery('-V:test_suite'); // When user explicitly typed negative query, don't suggest positive query. assert.isUndefined(suggestions2.find((s) => s.value === 'V:test_suite')); assert.isDefined(suggestions2.find((s) => s.value === '-V:test_suite')); }); it('should suggest Tag query when the query prefix is Tag:', () => { const suggestions1 = suggestSearchQuery('Tag:tag_key'); assert.isDefined(suggestions1.find((s) => s.value === 'Tag:tag_key')); assert.isDefined(suggestions1.find((s) => s.value === '-Tag:tag_key')); const suggestions2 = suggestSearchQuery('-Tag:tag_key'); // When user explicitly typed negative query, don't suggest positive query. assert.isUndefined(suggestions2.find((s) => s.value === 'Tag:tag_key')); assert.isDefined(suggestions2.find((s) => s.value === '-Tag:tag_key')); }); it('should suggest Duration query when the query prefix is Duration:', () => { const suggestions1 = suggestSearchQuery('Duration:10'); assert.isDefined(suggestions1.find((s) => s.value === 'Duration:10')); assert.isDefined(suggestions1.find((s) => s.value === '-Duration:10')); const suggestions2 = suggestSearchQuery('-Duration:10'); // When user explicitly typed negative query, don't suggest positive query. assert.isUndefined(suggestions2.find((s) => s.value === 'Duration:10')); assert.isDefined(suggestions2.find((s) => s.value === '-Duration:10')); }); it('should suggest VHash query when the query prefix is VHash:', () => { const suggestions1 = suggestSearchQuery('VHash:pass'); assert.isDefined(suggestions1.find((s) => s.value === 'VHash:pass')); assert.isDefined(suggestions1.find((s) => s.value === '-VHash:pass')); const suggestions2 = suggestSearchQuery('-VHash:pass'); // When user explicitly typed negative query, don't suggest positive query. assert.isUndefined(suggestions2.find((s) => s.value === 'VHash:pass')); assert.isDefined(suggestions2.find((s) => s.value === '-VHash:pass')); }); it('should suggest VHash query when the query type is a substring of VHash:', () => { const suggestions1 = suggestSearchQuery('hash'); assert.isDefined(suggestions1.find((s) => s.value === 'VHash:')); assert.isDefined(suggestions1.find((s) => s.value === '-VHash:')); }); });
the_stack
import { expect } from "chai"; import { shallow } from "enzyme"; import * as React from "react"; import * as sinon from "sinon"; import * as moq from "typemoq"; import { StagePanelLocation, WidgetState } from "@itwin/appui-abstract"; import { SplitterPaneTarget as NZ_SplitterPaneTarget } from "@itwin/appui-layout-react"; import { ConfigurableCreateInfo, ConfigurableUiManager, CoreTools, FrameworkStagePanel, Frontstage, FrontstageComposer, FrontstageManager, FrontstageProps, FrontstageProvider, SplitterPaneTarget, StagePanel, Widget, WidgetControl, WidgetDef, } from "../../appui-react"; import { StagePanelRuntimeProps } from "../../appui-react/stagepanels/StagePanel"; import { StagePanelDef, StagePanelState } from "../../appui-react/stagepanels/StagePanelDef"; import { UiFramework } from "../../appui-react/UiFramework"; import { UiShowHideManager } from "../../appui-react/utils/UiShowHideManager"; import TestUtils, { mount } from "../TestUtils"; /* eslint-disable react/jsx-key */ describe("StagePanel", () => { class TestWidget extends WidgetControl { constructor(info: ConfigurableCreateInfo, options: any) { super(info, options); this.reactNode = <div />; } } before(async () => { await TestUtils.initializeUiFramework(); }); after(() => { TestUtils.terminateUiFramework(); }); it("should initialize stage panel def location", () => { const sut = new StagePanelDef(); StagePanel.initializeStagePanelDef(sut, { resizable: true, }, StagePanelLocation.BottomMost); sut.location.should.eq(StagePanelLocation.BottomMost); }); it("should add widget definitions", () => { const sut = new StagePanelDef(); StagePanel.initializeStagePanelDef(sut, { resizable: false, widgets: [ <div />, ], }, StagePanelLocation.BottomMost); sut.widgetDefs.length.should.eq(1); }); it("should mount", () => { mount(<StagePanel />); }); it("should not render w/o runtime props", () => { shallow(<StagePanel />).should.matchSnapshot(); }); it("should not render pane that is not visible", () => { const runtimeProps = moq.Mock.ofType<StagePanelRuntimeProps>(); const panel = moq.Mock.ofType<StagePanelRuntimeProps["panel"]>(); const panelDef = moq.Mock.ofType<StagePanelRuntimeProps["panelDef"]>(); const widgetDef0 = moq.Mock.ofType<typeof panelDef.object["widgetDefs"][number]>(); runtimeProps.setup((x) => x.panel).returns(() => panel.object); runtimeProps.setup((x) => x.panelDef).returns(() => panelDef.object); panel.setup((x) => x.panes).returns(() => []); panelDef.setup((x) => x.widgetCount).returns(() => 1); panelDef.setup((x) => x.widgetDefs).returns(() => [widgetDef0.object]); widgetDef0.setup((x) => x.isVisible).returns(() => false); const sut = shallow(<StagePanel runtimeProps={runtimeProps.object} />); const frameworkStagePanel = sut.find(FrameworkStagePanel); const pane = frameworkStagePanel.prop("renderPane")("w1"); (pane === null).should.true; }); it("should not render pane w/o runtimeProps", () => { const runtimeProps = moq.Mock.ofType<StagePanelRuntimeProps>(); const panel = moq.Mock.ofType<StagePanelRuntimeProps["panel"]>(); const panelDef = moq.Mock.ofType<StagePanelRuntimeProps["panelDef"]>(); const widgetDef0 = moq.Mock.ofType<typeof panelDef.object["widgetDefs"][number]>(); runtimeProps.setup((x) => x.panel).returns(() => panel.object); runtimeProps.setup((x) => x.panelDef).returns(() => panelDef.object); panel.setup((x) => x.panes).returns(() => []); panelDef.setup((x) => x.widgetCount).returns(() => 1); panelDef.setup((x) => x.widgetDefs).returns(() => [widgetDef0.object]); widgetDef0.setup((x) => x.isVisible).returns(() => true); const sut = shallow<StagePanel>(<StagePanel runtimeProps={runtimeProps.object} />); const frameworkStagePanel = sut.find(FrameworkStagePanel); sut.setProps({ runtimeProps: undefined }); const pane = frameworkStagePanel.prop("renderPane")("w1"); (pane === null).should.true; }); it("should render collapsed pane", () => { const runtimeProps = moq.Mock.ofType<StagePanelRuntimeProps>(); const panel = moq.Mock.ofType<StagePanelRuntimeProps["panel"]>(); const panelDef = new StagePanelDef(); const widgetDef0 = new WidgetDef({ id: "w0" }); runtimeProps.setup((x) => x.panel).returns(() => panel.object); runtimeProps.setup((x) => x.panelDef).returns(() => panelDef); panel.setup((x) => x.panes).returns(() => []); panel.setup((x) => x.isCollapsed).returns(() => true); sinon.stub(panelDef, "findWidgetDef").returns(widgetDef0); const sut = shallow<StagePanel>(<StagePanel runtimeProps={runtimeProps.object} />); const frameworkStagePanel = sut.find(FrameworkStagePanel); const pane = frameworkStagePanel.prop("renderPane")("w0") as React.ReactElement; shallow(pane).should.matchSnapshot(); }); it("should pass down maxSize number property", () => { const runtimeProps = moq.Mock.ofType<StagePanelRuntimeProps>(); const panel = new StagePanelDef(); runtimeProps.setup((x) => x.panelDef).returns(() => panel); const sut = shallow<StagePanel>(<StagePanel runtimeProps={runtimeProps.object} maxSize={200} />); sut.should.matchSnapshot(); }); it("Panels should render in a Frontstage", async () => { class Frontstage1 extends FrontstageProvider { public static stageId = "Test1"; public get id(): string { return Frontstage1.stageId; } public get frontstage(): React.ReactElement<FrontstageProps> { return ( <Frontstage id="Test1" defaultTool={CoreTools.selectElementCommand} contentGroup={TestUtils.TestContentGroup1} topMostPanel={ <StagePanel widgets={[ <Widget id="stagePanelWidget" control={TestWidget} />, ]} /> } topPanel={ <StagePanel widgets={[ <Widget element={<h3>Top panel</h3>} />, ]} /> } leftPanel={ <StagePanel widgets={[ <Widget element={<h3>Left panel</h3>} />, ]} /> } rightPanel={ <StagePanel defaultState={StagePanelState.Open} resizable={true} applicationData={{ key: "value" }} widgets={[ <Widget element={<h3>Right panel</h3>} />, ]} /> } bottomPanel={ <StagePanel widgets={[ <Widget element={<h3>Bottom panel</h3>} />, ]} /> } bottomMostPanel={ <StagePanel widgets={[ <Widget element={<h3>BottomMost panel</h3>} />, ]} /> } /> ); } } const frontstageProvider = new Frontstage1(); ConfigurableUiManager.addFrontstageProvider(frontstageProvider); const frontstageDef = await FrontstageManager.getFrontstageDef(Frontstage1.stageId); expect(frontstageDef).to.not.be.undefined; await FrontstageManager.setActiveFrontstageDef(frontstageDef); if (frontstageDef) { const widgetDef = frontstageDef.findWidgetDef("stagePanelWidget"); expect(widgetDef).to.not.be.undefined; } const wrapper = mount(<FrontstageComposer />); expect(wrapper.find("div.uifw-stagepanel").length).to.eq(6); expect(wrapper.find("div.uifw-stagepanel.nz-panel-top").length).to.eq(2); expect(wrapper.find("div.uifw-stagepanel.nz-panel-left").length).to.eq(1); expect(wrapper.find("div.uifw-stagepanel.nz-panel-right").length).to.eq(1); expect(wrapper.find("div.uifw-stagepanel.nz-panel-bottom").length).to.eq(2); UiFramework.setIsUiVisible(false); UiShowHideManager.showHidePanels = true; wrapper.update(); expect(wrapper.find("div.uifw-stagepanel").length).to.eq(0); UiShowHideManager.showHidePanels = false; }); it("should update stagePanelWidgets", () => { const runtimeProps = moq.Mock.ofType<StagePanelRuntimeProps>(); const panel = moq.Mock.ofType<StagePanelRuntimeProps["panel"]>(); const panelDef = new StagePanelDef(); const w1 = new WidgetDef({ id: "w1" }); const w2 = new WidgetDef({ id: "w2" }); const w3 = new WidgetDef({ id: "w3" }); runtimeProps.setup((x) => x.panel).returns(() => panel.object); runtimeProps.setup((x) => x.panelDef).returns(() => panelDef); panel.setup((x) => x.panes).returns(() => []); sinon.stub(panelDef, "widgetDefs").get(() => [w1, w2, w3]); const sut = mount<StagePanel>(<StagePanel runtimeProps={runtimeProps.object} />); w2.setWidgetState(WidgetState.Hidden); sut.state("stagePanelWidgets").should.eql(["w1", "w3"]); }); describe("SplitterPaneTarget", () => { it("should render", () => { shallow(<SplitterPaneTarget onTargetChanged={sinon.spy()} paneIndex={0} />).should.matchSnapshot(); }); it("should handle target changed", () => { const spy = sinon.spy(); const sut = shallow<SplitterPaneTarget>(<SplitterPaneTarget onTargetChanged={spy} paneIndex={0} />); const nzSplitterPaneTarget = sut.find(NZ_SplitterPaneTarget); nzSplitterPaneTarget.prop("onTargetChanged")!(true); spy.calledOnceWithExactly(0).should.true; }); it("should handle target changed (untarget)", () => { const spy = sinon.spy(); const sut = shallow<SplitterPaneTarget>(<SplitterPaneTarget onTargetChanged={spy} paneIndex={0} />); const nzSplitterPaneTarget = sut.find(NZ_SplitterPaneTarget); nzSplitterPaneTarget.prop("onTargetChanged")!(false); spy.calledOnceWithExactly(undefined).should.true; }); }); });
the_stack
import MicroModal from 'micromodal'; import { base64_json_parse, base64_json_stringify } from '../base64'; import { Audio, SOUND_ENABLED_OPTION } from './audio'; import DriveLights from './drive_lights'; import { byte, includes, word } from '../types'; import { BLOCK_FORMATS, MassStorage, NIBBLE_FORMATS } from '../formats/types'; import { DISK_FORMATS, DriveNumber, DRIVE_NUMBERS, JSONDisk } from '../formats/types'; import { initGamepad } from './gamepad'; import KeyBoard from './keyboard'; import Tape, { TAPE_TYPES } from './tape'; import type { GamepadConfiguration } from './types'; import ApplesoftDump from '../applesoft/decompiler'; import ApplesoftCompiler from '../applesoft/compiler'; import { debug } from '../util'; import { Apple2, Stats } from '../apple2'; import DiskII from '../cards/disk2'; import CPU6502 from '../cpu6502'; import { VideoModes } from '../videomodes'; import Apple2IO from '../apple2io'; import Printer from './printer'; import { OptionsModal } from './options_modal'; import { Screen, SCREEN_FULL_PAGE } from './screen'; import { JoyStick } from './joystick'; import { System } from './system'; let paused = false; let startTime = Date.now(); let lastCycles = 0; let lastFrames = 0; let lastRenderedFrames = 0; let hashtag = document.location.hash; const optionsModal = new OptionsModal(); interface DiskDescriptor { name: string; disk?: number; filename: string; e?: boolean; category: string; } type DiskCollection = { [name: string]: DiskDescriptor[] }; const CIDERPRESS_EXTENSION = /#([0-9a-f]{2})([0-9a-f]{4})$/i; const BIN_TYPES = ['bin']; const KNOWN_FILE_TYPES = [ ...DISK_FORMATS, ...TAPE_TYPES, ...BIN_TYPES, ] as readonly string[]; const disk_categories: DiskCollection = { 'Local Saves': [] }; const disk_sets: DiskCollection = {}; // Disk names const disk_cur_name: string[] = []; // Disk categories const disk_cur_cat: string[] = []; let _apple2: Apple2; let cpu: CPU6502; let stats: Stats; let vm: VideoModes; let tape: Tape; let _disk2: DiskII; let _massStorage: MassStorage; let _printer: Printer; let audio: Audio; let screen: Screen; let joystick: JoyStick; let system: System; let keyboard: KeyBoard; let io: Apple2IO; let _currentDrive: DriveNumber = 1; let _e: boolean; let ready: Promise<[void, void]>; export const driveLights = new DriveLights(); export function dumpAppleSoftProgram() { const dumper = new ApplesoftDump(cpu); debug(dumper.toString()); } export function compileAppleSoftProgram(program: string) { const compiler = new ApplesoftCompiler(cpu); compiler.compile(program); dumpAppleSoftProgram(); } export function openLoad(driveString: string, event: MouseEvent) { const drive = parseInt(driveString, 10) as DriveNumber; _currentDrive = drive; if (event.metaKey && includes(DRIVE_NUMBERS, drive)) { openLoadHTTP(); } else { if (disk_cur_cat[drive]) { const element = document.querySelector<HTMLSelectElement>('#category_select')!; element.value = disk_cur_cat[drive]; selectCategory(); } MicroModal.show('load-modal'); } } export function openSave(driveString: string, event: MouseEvent) { const drive = parseInt(driveString, 10) as DriveNumber; const mimeType = 'application/octet-stream'; const data = _disk2.getBinary(drive); const a = document.querySelector<HTMLAnchorElement>('#local_save_link')!; if (!data) { alert('No data from drive ' + drive); return; } const blob = new Blob([data], { 'type': mimeType }); a.href = window.URL.createObjectURL(blob); a.download = driveLights.label(drive) + '.dsk'; if (event.metaKey) { dumpDisk(drive); } else { const saveName = document.querySelector<HTMLInputElement>('#save_name')!; saveName.value = driveLights.label(drive); MicroModal.show('save-modal'); } } export function openAlert(msg: string) { const el = document.querySelector<HTMLDivElement>('#alert-modal .message')!; el.innerText = msg; MicroModal.show('alert-modal'); } /******************************************************************** * * Drag and Drop */ export function handleDragOver(_drive: number, event: DragEvent) { event.preventDefault(); event.dataTransfer!.dropEffect = 'copy'; } export function handleDragEnd(_drive: number, event: DragEvent) { const dt = event.dataTransfer!; if (dt.items) { for (let i = 0; i < dt.items.length; i++) { dt.items.remove(i); } } else { dt.clearData(); } } export function handleDrop(drive: number, event: DragEvent) { event.preventDefault(); event.stopPropagation(); if (drive < 1) { if (!_disk2.getMetadata(1)) { drive = 1; } else if (!_disk2.getMetadata(2)) { drive = 2; } else { drive = 1; } } const dt = event.dataTransfer!; if (dt.files.length == 1) { const runOnLoad = event.shiftKey; doLoadLocal(drive as DriveNumber, dt.files[0], { runOnLoad }); } else if (dt.files.length == 2) { doLoadLocal(1, dt.files[0]); doLoadLocal(2, dt.files[1]); } else { for (let idx = 0; idx < dt.items.length; idx++) { if (dt.items[idx].type === 'text/uri-list') { dt.items[idx].getAsString(function (url) { const parts = hup().split('|'); parts[drive - 1] = url; document.location.hash = parts.join('|'); }); } } } } function loadingStart() { const meter = document.querySelector<HTMLDivElement>('#loading-modal .meter')!; meter.style.display = 'none'; MicroModal.show('loading-modal'); } function loadingProgress(current: number, total: number) { if (total) { const meter = document.querySelector<HTMLDivElement>('#loading-modal .meter')!; const progress = document.querySelector<HTMLDivElement>('#loading-modal .progress')!; meter.style.display = 'block'; progress.style.width = current / total * meter.clientWidth + 'px'; } } function loadingStop() { MicroModal.close('loading-modal'); if (!paused) { ready.then(() => { _apple2.run(); }).catch(console.error); } } interface JSONBinaryImage { type: 'binary', start: word, length: word, data: byte[], gamepad?: GamepadConfiguration, } export function loadAjax(drive: DriveNumber, url: string) { loadingStart(); fetch(url).then(function (response: Response) { if (response.ok) { return response.json(); } else { throw new Error('Error loading: ' + response.statusText); } }).then(function (data: JSONDisk | JSONBinaryImage) { if (data.type === 'binary') { loadBinary(data as JSONBinaryImage); } else if (includes(DISK_FORMATS, data.type)) { loadDisk(drive, data); } initGamepad(data.gamepad); loadingStop(); }).catch(function (error) { loadingStop(); openAlert(error.message); console.error(error); }); } export function doLoad(event: MouseEvent|KeyboardEvent) { MicroModal.close('load-modal'); const select = document.querySelector<HTMLSelectElement>('#disk_select')!; const urls = select.value; let url; if (urls && urls.length) { if (typeof (urls) == 'string') { url = urls; } else { url = urls[0]; } } const localFile = document.querySelector<HTMLInputElement>('#local_file')!; const files = localFile.files; if (files && files.length == 1) { const runOnLoad = event.shiftKey; doLoadLocal(_currentDrive, files[0], { runOnLoad }); } else if (url) { let filename; MicroModal.close('load-modal'); if (url.substr(0, 6) == 'local:') { filename = url.substr(6); if (filename == '__manage') { openManage(); } else { loadLocalStorage(_currentDrive, filename); } } else { const r1 = /json\/disks\/(.*).json$/.exec(url); if (r1) { filename = r1[1]; } else { filename = url; } const parts = hup().split('|'); parts[_currentDrive - 1] = filename; document.location.hash = parts.join('|'); } } } export function doSave() { const saveName = document.querySelector<HTMLInputElement>('#save_name')!; const name = saveName.value; saveLocalStorage(_currentDrive, name); MicroModal.close('save-modal'); window.setTimeout(() => openAlert('Saved'), 0); } export function doDelete(name: string) { if (window.confirm('Delete ' + name + '?')) { deleteLocalStorage(name); } } interface LoadOptions { address?: word, runOnLoad?: boolean, } function doLoadLocal(drive: DriveNumber, file: File, options: Partial<LoadOptions> = {}) { const parts = file.name.split('.'); const ext = parts[parts.length - 1].toLowerCase(); const matches = file.name.match(CIDERPRESS_EXTENSION); let type, aux; if (matches && matches.length === 3) { [, type, aux] = matches; } if (includes(DISK_FORMATS, ext)) { doLoadLocalDisk(drive, file); } else if (includes(TAPE_TYPES, ext)) { tape.doLoadLocalTape(file); } else if (BIN_TYPES.includes(ext) || type === '06' || options.address) { const address = aux !== undefined ? parseInt(aux, 16) : undefined; doLoadBinary(file, { address, ...options }); } else { const addressInput = document.querySelector<HTMLInputElement>('#local_file_address'); const addressStr = addressInput?.value; if (addressStr) { const address = parseInt(addressStr, 16); if (isNaN(address)) { openAlert('Invalid address: ' + addressStr); return; } doLoadBinary(file, { address, ...options }); } else { openAlert('Unknown file type: ' + ext); } } } function doLoadBinary(file: File, options: LoadOptions) { loadingStart(); const fileReader = new FileReader(); fileReader.onload = function () { const result = this.result as ArrayBuffer; let { address } = options; address = address ?? 0x2000; const bytes = new Uint8Array(result); for (let idx = 0; idx < result.byteLength; idx++) { cpu.write(address >> 8, address & 0xff, bytes[idx]); address++; } if (options.runOnLoad) { cpu.reset(); cpu.setPC(address); } loadingStop(); }; fileReader.readAsArrayBuffer(file); } function doLoadLocalDisk(drive: DriveNumber, file: File) { loadingStart(); const fileReader = new FileReader(); fileReader.onload = function () { const result = this.result as ArrayBuffer; const parts = file.name.split('.'); const ext = parts.pop()!.toLowerCase(); const name = parts.join('.'); // Remove any json file reference const files = hup().split('|'); files[drive - 1] = ''; document.location.hash = files.join('|'); if (includes(DISK_FORMATS, ext)) { if (result.byteLength >= 800 * 1024) { if ( includes(BLOCK_FORMATS, ext) && _massStorage.setBinary(drive, name, ext, result) ) { initGamepad(); } else { openAlert(`Unable to load ${name}`); } } else { if ( includes(NIBBLE_FORMATS, ext) && _disk2.setBinary(drive, name, ext, result) ) { initGamepad(); } else { openAlert(`Unable to load ${name}`); } } } loadingStop(); }; fileReader.readAsArrayBuffer(file); } export function doLoadHTTP(drive: DriveNumber, url?: string) { if (!url) { MicroModal.close('http-modal'); } loadingStart(); const input = document.querySelector<HTMLInputElement>('#http_url')!; url = url || input.value; if (url) { fetch(url).then(function (response) { if (response.ok) { const reader = response!.body!.getReader(); let received = 0; const chunks: Uint8Array[] = []; const contentLength = parseInt(response.headers.get('content-length')!, 10); return reader.read().then( function readChunk(result): Promise<ArrayBufferLike> { if (result.done) { const data = new Uint8Array(received); let offset = 0; for (let idx = 0; idx < chunks.length; idx++) { data.set(chunks[idx], offset); offset += chunks[idx].length; } return Promise.resolve(data.buffer); } received += result.value.length; if (contentLength) { loadingProgress(received, contentLength); } chunks.push(result.value); return reader.read().then(readChunk); }); } else { throw new Error('Error loading: ' + response.statusText); } }).then(function (data) { const urlParts = url!.split('/'); const file = urlParts.pop()!; const fileParts = file.split('.'); const ext = fileParts.pop()!.toLowerCase(); const name = decodeURIComponent(fileParts.join('.')); if (includes(DISK_FORMATS, ext)) { if (data.byteLength >= 800 * 1024) { if ( includes(BLOCK_FORMATS, ext) && _massStorage.setBinary(drive, name, ext, data) ) { initGamepad(); } } else { if ( includes(NIBBLE_FORMATS, ext) && _disk2.setBinary(drive, name, ext, data) ) { initGamepad(); } } } else { throw new Error(`Extension ${ext} not recognized.`); } loadingStop(); }).catch(function (error) { loadingStop(); openAlert(error.message); console.error(error); }); } } function openLoadHTTP() { MicroModal.show('http-modal'); } function openManage() { MicroModal.show('manage-modal'); } let showStats = 0; export function updateKHz() { const now = Date.now(); const ms = now - startTime; const cycles = cpu.getCycles(); let delta; let fps; let khz; const kHzElement = document.querySelector<HTMLDivElement>('#khz')!; switch (showStats) { case 0: { delta = cycles - lastCycles; khz = Math.trunc(delta / ms); kHzElement.innerText = khz + ' kHz'; break; } case 1: { delta = stats.renderedFrames - lastRenderedFrames; fps = Math.trunc(delta / (ms / 1000)); kHzElement.innerText = fps + ' rps'; break; } default: { delta = stats.frames - lastFrames; fps = Math.trunc(delta / (ms / 1000)); kHzElement.innerText = fps + ' fps'; } } startTime = now; lastCycles = cycles; lastRenderedFrames = stats.renderedFrames; lastFrames = stats.frames; } export function toggleShowFPS() { showStats = ++showStats % 3; } export function toggleSound() { const on = !audio.isEnabled(); optionsModal.setOption(SOUND_ENABLED_OPTION, on); updateSoundButton(on); } function initSoundToggle() { updateSoundButton(audio.isEnabled()); } function updateSoundButton(on: boolean) { const label = document.querySelector<HTMLDivElement>('#toggle-sound i')!; if (on) { label.classList.remove('fa-volume-off'); label.classList.add('fa-volume-up'); } else { label.classList.remove('fa-volume-up'); label.classList.add('fa-volume-off'); } } function dumpDisk(drive: DriveNumber) { const wind = window.open('', '_blank')!; wind.document.title = driveLights.label(drive); wind.document.write('<pre>'); wind.document.write(_disk2.getJSON(drive, true)); wind.document.write('</pre>'); wind.document.close(); } export function reset() { _apple2.reset(); } function loadBinary(bin: JSONBinaryImage) { const maxLen = Math.min(bin.length, 0x10000 - bin.start); for (let idx = 0; idx < maxLen; idx++) { const pos = bin.start + idx; cpu.write(pos, bin.data[idx]); } cpu.reset(); cpu.setPC(bin.start); } export function selectCategory() { const diskSelect = document.querySelector<HTMLSelectElement>('#disk_select')!; const categorySelect = document.querySelector<HTMLSelectElement>('#category_select')!; diskSelect.innerHTML = ''; const cat = disk_categories[categorySelect.value]; if (cat) { for (let idx = 0; idx < cat.length; idx++) { const file = cat[idx]; let name = file.name; if (file.disk) { name += ' - ' + file.disk; } const option = document.createElement('option'); option.value = file.filename; option.innerText = name; diskSelect.append(option); if (disk_cur_name[_currentDrive] === name) { option.selected = true; } } } } export function selectDisk() { const localFile = document.querySelector<HTMLInputElement>('#local_file')!; localFile.value = ''; } export function clickDisk(event: MouseEvent|KeyboardEvent) { doLoad(event); } /** Called to load disks from the local catalog. */ function loadDisk(drive: DriveNumber, disk: JSONDisk) { let name = disk.name; const category = disk.category!; // all disks in the local catalog have a category if (disk.disk) { name += ' - ' + disk.disk; } disk_cur_cat[drive] = category; disk_cur_name[drive] = name; _disk2.setDisk(drive, disk); initGamepad(disk.gamepad); } /* * LocalStorage Disk Storage */ function updateLocalStorage() { const diskIndex = JSON.parse(window.localStorage.diskIndex || '{}'); const names = Object.keys(diskIndex); const cat: DiskDescriptor[] = disk_categories['Local Saves'] = []; const contentDiv = document.querySelector<HTMLDivElement>('#manage-modal-content')!; contentDiv.innerHTML = ''; names.forEach(function (name) { cat.push({ 'category': 'Local Saves', 'name': name, 'filename': 'local:' + name }); contentDiv.innerHTML = '<span class="local_save">' + name + ' <a href="#" onclick="Apple2.doDelete(\'' + name + '\')">Delete</a><br /></span>'; }); cat.push({ 'category': 'Local Saves', 'name': 'Manage Saves...', 'filename': 'local:__manage' }); } type LocalDiskIndex = { [name: string]: string, } function saveLocalStorage(drive: DriveNumber, name: string) { const diskIndex = JSON.parse(window.localStorage.diskIndex || '{}') as LocalDiskIndex; const json = _disk2.getJSON(drive); diskIndex[name] = json; window.localStorage.diskIndex = JSON.stringify(diskIndex); driveLights.label(drive, name); driveLights.dirty(drive, false); updateLocalStorage(); } function deleteLocalStorage(name: string) { const diskIndex = JSON.parse(window.localStorage.diskIndex || '{}') as LocalDiskIndex; if (diskIndex[name]) { delete diskIndex[name]; openAlert('Deleted'); } window.localStorage.diskIndex = JSON.stringify(diskIndex); updateLocalStorage(); } function loadLocalStorage(drive: DriveNumber, name: string) { const diskIndex = JSON.parse(window.localStorage.diskIndex || '{}') as LocalDiskIndex; if (diskIndex[name]) { _disk2.setJSON(drive, diskIndex[name]); driveLights.label(drive, name); driveLights.dirty(drive, false); } } if (window.localStorage !== undefined) { const nodes = document.querySelectorAll<HTMLElement>('.disksave'); nodes.forEach(function (el) { el.style.display = 'inline-block'; }); } const categorySelect = document.querySelector<HTMLSelectElement>('#category_select')!; declare global { interface Window { disk_index: DiskDescriptor[]; } } function buildDiskIndex() { let oldCat = ''; let option; for (let idx = 0; idx < window.disk_index.length; idx++) { const file = window.disk_index[idx]; const cat = file.category; const name = file.name; const disk = file.disk; if (file.e && !_e) { continue; } if (cat != oldCat) { option = document.createElement('option'); option.value = cat; option.innerText = cat; categorySelect.append(option); disk_categories[cat] = []; oldCat = cat; } disk_categories[cat].push(file); if (disk) { if (!disk_sets[name]) { disk_sets[name] = []; } disk_sets[name].push(file); } } option = document.createElement('option'); option.innerText = 'Local Saves'; categorySelect.append(option); updateLocalStorage(); } /** * Processes the URL fragment. It is expected to be of the form: * `disk1|disk2` where each disk is the name of a local image OR * a URL. */ function processHash(hash: string) { const files = hash.split('|'); for (let idx = 0; idx < Math.min(2, files.length); idx++) { const drive = idx + 1; if (!includes(DRIVE_NUMBERS, drive)) { break; } const file = files[idx]; if (file.indexOf('://') > 0) { const parts = file.split('.'); const ext = parts[parts.length - 1].toLowerCase(); if (ext == 'json') { loadAjax(drive, file); } else { doLoadHTTP(drive, file); } } else if (file) { loadAjax(drive, 'json/disks/' + file + '.json'); } } } export function updateUI() { if (document.location.hash != hashtag) { hashtag = document.location.hash; const hash = hup(); if (hash) { processHash(hash); } } } export function pauseRun() { const label = document.querySelector<HTMLElement>('#pause-run i')!; if (paused) { ready.then(() => { _apple2.run(); }).catch(console.error); label.classList.remove('fa-play'); label.classList.add('fa-pause'); } else { _apple2.stop(); label.classList.remove('fa-pause'); label.classList.add('fa-play'); } paused = !paused; } export function openOptions() { optionsModal.openModal(); } export function openPrinterModal() { const mimeType = 'application/octet-stream'; const data = _printer.getRawOutput(); const a = document.querySelector<HTMLAnchorElement>('#raw_printer_output')!; const blob = new Blob([data], { 'type': mimeType }); a.href = window.URL.createObjectURL(blob); a.download = 'raw_printer_output.bin'; MicroModal.show('printer-modal'); } export function clearPrinterPaper() { _printer.clear(); } declare global { interface Window { clipboardData?: DataTransfer; } interface Event { clipboardData?: DataTransfer; } interface Navigator { standalone?: boolean; } } /** * Returns the value of a query parameter or the empty string if it does not * exist. * @param name the parameter name. Note that `name` must not have any RegExp * meta-characters except '[' and ']' or it will fail. */ function gup(name: string) { const params = new URLSearchParams(window.location.search); return params.get(name); } /** Returns the URL fragment. */ function hup() { const regex = new RegExp('#(.*)'); const hash = decodeURIComponent(window.location.hash); const results = regex.exec(hash); if (!results) return ''; else return results[1]; } function onLoaded(apple2: Apple2, disk2: DiskII, massStorage: MassStorage, printer: Printer, e: boolean) { _apple2 = apple2; cpu = _apple2.getCPU(); io = _apple2.getIO(); stats = apple2.getStats(); vm = apple2.getVideoModes(); tape = new Tape(io); _disk2 = disk2; _massStorage = massStorage; _printer = printer; _e = e; system = new System(io, e); optionsModal.addOptions(system); joystick = new JoyStick(io); optionsModal.addOptions(joystick); screen = new Screen(vm); optionsModal.addOptions(screen); audio = new Audio(io); optionsModal.addOptions(audio); initSoundToggle(); ready = Promise.all([audio.ready, apple2.ready]); MicroModal.init(); keyboard = new KeyBoard(cpu, io, e); keyboard.create('#keyboard'); keyboard.setFunction('F1', () => cpu.reset()); keyboard.setFunction('F2', (event) => { if (event.shiftKey) { // Full window, but not full screen optionsModal.setOption( SCREEN_FULL_PAGE, !optionsModal.getOption(SCREEN_FULL_PAGE) ); } else { screen.enterFullScreen(); } }); keyboard.setFunction('F3', () => io.keyDown(0x1b)); // Escape keyboard.setFunction('F4', optionsModal.openModal); keyboard.setFunction('F6', () => { window.localStorage.state = base64_json_stringify(_apple2.getState()); }); keyboard.setFunction('F9', () => { if (window.localStorage.state) { _apple2.setState(base64_json_parse(window.localStorage.state)); } }); buildDiskIndex(); /* * Input Handling */ window.addEventListener('paste', (event: Event) => { const paste = (event.clipboardData || window.clipboardData)!.getData('text'); io.setKeyBuffer(paste); event.preventDefault(); }); window.addEventListener('copy', (event: Event) => { event.clipboardData!.setData('text/plain', vm.getText()); event.preventDefault(); }); if (navigator.standalone) { document.body.classList.add('standalone'); } cpu.reset(); setInterval(updateKHz, 1000); initGamepad(); // Check for disks in hashtag const hash = gup('disk') || hup(); if (hash) { _apple2.stop(); processHash(hash); } else { ready.then(() => { _apple2.run(); }).catch(console.error); } document.querySelector<HTMLInputElement>('#local_file')?.addEventListener( 'change', (event: Event) => { const target = event.target as HTMLInputElement; const address = document.querySelector<HTMLInputElement>('#local_file_address_input')!; const parts = target.value.split('.'); const ext = parts[parts.length - 1]; if (KNOWN_FILE_TYPES.includes(ext)) { address.style.display = 'none'; } else { address.style.display = 'inline-block'; } } ); } export function initUI(apple2: Apple2, disk2: DiskII, massStorage: MassStorage, printer: Printer, e: boolean) { window.addEventListener('load', () => { onLoaded(apple2, disk2, massStorage, printer, e); }); }
the_stack
import * as React from "react"; import { showMessage, getCurrentEventIsBoardEvent } from "../app/appControl"; import { includeEventInBoard } from "../boards"; import { getEventFromLibrary, addEventToLibrary } from "../events/EventLibrary"; import { createCustomEvent, validateCustomEvent } from "../events/customevents"; import { Game, EventExecutionType, EventParameterType, EventCodeLanguage } from "../types"; import { CustomAsmHelper } from "../events/customevents"; import { IEventParameter } from "../events/events"; import { ToggleGroup, Button, ToggleButton } from "../controls"; import deleteImage from "../img/events/delete.png"; import "../css/createevent.scss"; export interface ICreateEventView { getEventName(): string; getSupportedGames(): Game[]; getEventCode(): string; getLanguage(): EventCodeLanguage; updateLastSavedCode(code: string): void; promptExit(): Promise<boolean>; } let _createEventViewInstance: ICreateEventView | null = null; export function updateCreateEventViewInstance(instance: ICreateEventView | null): void { _createEventViewInstance = instance; } export async function saveEvent(): Promise<void> { const eventName = _createEventViewInstance!.getEventName(); const supportedGames = _createEventViewInstance!.getSupportedGames(); const code = _createEventViewInstance!.getEventCode(); if (!eventName) { showMessage("An event name must be specified."); return; } const existingEvent = getEventFromLibrary(eventName); if (existingEvent && !existingEvent.custom) { showMessage("The event name collides with a reserved event name from the original boards."); return; } if (!supportedGames.length) { showMessage("At least one game must be supported."); return; } if (!code) { showMessage("No assembly code was provided."); return; } const language = _createEventViewInstance!.getLanguage(); const event = createCustomEvent(language, code); try { await validateCustomEvent(event); } catch (e) { showMessage(e.toString()); } if (getCurrentEventIsBoardEvent()) { includeEventInBoard(event); } else { addEventToLibrary(event); // Add globally. } if (_createEventViewInstance) { // Ensure we don't prompt for unsaved changes. _createEventViewInstance.updateLastSavedCode(code); } } export function createEventPromptExit(): Promise<boolean> { if (_createEventViewInstance) { return _createEventViewInstance.promptExit(); } return Promise.resolve(true); } /** * Get the supported games for the event currently being edited. */ export function getActiveEditorSupportedGames(): Game[] { if (_createEventViewInstance) { return _createEventViewInstance.getSupportedGames(); } return []; } interface IEventDetailsFormProps { name: string; supportedGames: Game[]; executionType: EventExecutionType; language: EventCodeLanguage; parameters: IEventParameter[]; onGameToggleClicked(id: any, pressed: boolean): any; onExecTypeToggleClicked(id: any, pressed: boolean): any; onAddEventParameter(parameter: IEventParameter): any; onRemoveEventParameter(parameter: IEventParameter): any; onEventNameChange(name: string): any; } export class EventDetailsForm extends React.Component<IEventDetailsFormProps> { render() { const gameToggles = [ { id: Game.MP1_USA, text: "MP1 USA", selected: this._gameSupported(Game.MP1_USA) }, { id: Game.MP2_USA, text: "MP2 USA", selected: this._gameSupported(Game.MP2_USA) }, { id: Game.MP3_USA, text: "MP3 USA", selected: this._gameSupported(Game.MP3_USA) }, { id: Game.MP1_JPN, text: "MP1 JPN", selected: this._gameSupported(Game.MP1_JPN) }, { id: Game.MP2_JPN, text: "MP2 JPN", selected: this._gameSupported(Game.MP2_JPN) }, { id: Game.MP3_JPN, text: "MP3 JPN", selected: this._gameSupported(Game.MP3_JPN) }, { id: Game.MP1_PAL, text: "MP1 PAL", selected: this._gameSupported(Game.MP1_PAL) }, { id: Game.MP2_PAL, text: "MP2 PAL", selected: this._gameSupported(Game.MP2_PAL) }, { id: Game.MP3_PAL, text: "MP3 PAL", selected: this._gameSupported(Game.MP3_PAL) }, ]; const execTypeToggles = [ { id: 1, text: "Direct", title: "The game will execute the event function directly", selected: this.props.executionType === EventExecutionType.DIRECT }, { id: 2, text: "Process", title: "The game will use its process system when executing the event function", selected: this.props.executionType === EventExecutionType.PROCESS }, ]; return ( <div className="createEventForm"> <label>Name:</label> <input value={this.props.name} onChange={this.onEventNameChange} /> <br /><br /> <label>Supported Games:</label> <ToggleGroup items={gameToggles} groupCssClass="createEventGameToggles" onToggleClick={this.props.onGameToggleClicked} /> <br /> <label>Execution Type:</label> <ToggleGroup items={execTypeToggles} allowDeselect={false} onToggleClick={this.props.onExecTypeToggleClicked} /> <br /> <label>Parameters:</label> <EventParametersList language={this.props.language} parameters={this.props.parameters} onAddEventParameter={this.props.onAddEventParameter} onRemoveEventParameter={this.props.onRemoveEventParameter} /> </div> ); } onEventNameChange = (event: any) => { this.props.onEventNameChange(event.target.value); } _gameSupported = (game: Game) => { return this.props.supportedGames.indexOf(game) >= 0; } } interface IEventParametersListProps { language: EventCodeLanguage; parameters: IEventParameter[]; onAddEventParameter(entry: IEventParameter): any; onRemoveEventParameter(entry: IEventParameter): any; } class EventParametersList extends React.Component<IEventParametersListProps> { render() { const entries = this.props.parameters.map(entry => { return ( <EventParametersEntry entry={entry} key={entry.name} onRemoveEntry={this.props.onRemoveEventParameter}/> ); }); return ( <div className="eventParametersList"> <table> <tbody> {entries} </tbody> </table> <EventParametersAddNewEntry language={this.props.language} onAddEntry={this.props.onAddEventParameter} /> </div> ); } } interface IEventParametersEntryProps { entry: IEventParameter; onRemoveEntry(entry: IEventParameter): any; } class EventParametersEntry extends React.Component<IEventParametersEntryProps> { render() { const { type, name } = this.props.entry; return ( <tr className="eventParameterEntry"> <td className="eventParameterEntryType">{type}</td> <td className="eventParameterEntryName" title={name}>{name}</td> <td className="eventParameterEntryDelete"> <img src={deleteImage} alt="Delete" onClick={this.onDeleteClick}></img> </td> </tr> ); } onDeleteClick = () => { this.props.onRemoveEntry(this.props.entry); } } interface IEventParametersAddNewEntryProps { language: EventCodeLanguage; onAddEntry(entry: IEventParameter): any; } class EventParametersAddNewEntry extends React.Component<IEventParametersAddNewEntryProps> { state = { selectedType: "", name: "", } render() { return ( <div className="eventParameterAddNewEntry"> <select value={this.state.selectedType} onChange={this.onTypeChange}> <option></option> <option value={EventParameterType.Boolean}>Boolean</option> <option value={EventParameterType.Number}>Number</option> <option value={EventParameterType.PositiveNumber}>Positive Number</option> <option value={EventParameterType.Space}>Space</option> <option value={EventParameterType.SpaceArray}>Space Array</option> </select> <input type="text" placeholder="Name" value={this.state.name} onChange={this.onNameChange} /> <Button onClick={this.onAddClick}>Add</Button> </div> ); } onNameChange = (event: any) => { const newName = event.target.value; // Can only contain valid characters for a assembler label if (!newName.match(CustomAsmHelper.validParameterNameRegex)) return; this.setState({ name: newName }); } onTypeChange = (event: any) => { this.setState({ selectedType: event.target.value }); } onAddClick = () => { if (!this.state.name || !this.state.selectedType) return; this.props.onAddEntry({ name: this.state.name, type: this.state.selectedType as EventParameterType, }); this.setState({ name: "", selectedType: "", }); } } interface INewEventDropdownProps { onAccept(language: EventCodeLanguage): void; } export class NewEventDropdown extends React.Component<INewEventDropdownProps> { state = { language: EventCodeLanguage.C } onLanguageChange = (language: EventCodeLanguage) => { this.setState({ language }); } submit = () => { let fn = this.props.onAccept; if (fn) fn(this.state.language); } render() { return ( <div className="createEventDropdownContainer"> <NewEventLanguageSelect language={this.state.language} onLanguageChange={this.onLanguageChange} /> <Button onClick={this.submit} css="nbCreate">Create</Button> </div> ); } }; interface INewEventLanguageSelect { language: EventCodeLanguage; onLanguageChange(language: EventCodeLanguage): void; } class NewEventLanguageSelect extends React.Component<INewEventLanguageSelect> { onLanguageChange = (language: EventCodeLanguage) => { this.props.onLanguageChange(language); } render() { return ( <div className="newBoardVersionSelect"> <label className="nbLabel">Code Language</label> <br /> <ToggleButton id={EventCodeLanguage.C} allowDeselect={false} onToggled={this.onLanguageChange} pressed={this.props.language === EventCodeLanguage.C}> <span className="newBoardVersion" title="C programming language">C</span> </ToggleButton> <ToggleButton id={EventCodeLanguage.MIPS} allowDeselect={false} onToggled={this.onLanguageChange} pressed={this.props.language === EventCodeLanguage.MIPS}> <span className="newBoardVersion" title="MIPS assembly language">MIPS</span> </ToggleButton> </div> ); } };
the_stack
import { ParserSymbol } from './parsertokens/ParserSymbol'; import { PrimitiveElement } from './PrimitiveElement'; import { Expression } from './Expression'; import { java } from 'j4ts/j4ts'; import { javaemul } from 'j4ts/j4ts'; import { HeadEqBody } from './Miscellaneous'; import { Function } from './Function'; import { Constant } from './Constant'; import { mXparserConstants } from './mXparserConstants'; import { ArgumentExtension } from './ArgumentExtension'; import { ArgumentConstants } from './ArgumentConstants'; import { ExpressionConstants } from './ExpressionConstants'; /** * Default constructor - creates argument based on the argument definition string. * * @param {string} argumentDefinitionString Argument definition string, i.e.: * <ul> * <li>'x' - only argument name * <li>'x=5' - argument name and argument value * <li>'x=2*5' - argument name and argument value given as simple expression * <li>'x=2*y' - argument name and argument expression (dependent argument 'x' on argument 'y') * </ul> * * @param {boolean} forceDependent If true parser will try to create dependent argument * @param {org.mariuszgromada.math.mxparser.PrimitiveElement[]} elements Optional parameters (comma separated) such as Arguments, Constants, Functions * @class * @extends PrimitiveElement */ export class Argument extends PrimitiveElement { /** * Argument with body based on the extended code. * * @see ArgumentExtension * @see Argument#getArgumentBodyType() */ public static BODY_EXTENDED: number = 2; public static createArgumentWithExpression(argumentExpression: string) : Argument { return Argument.createArgumentWithExpressionArgumentAndValue(argumentExpression, null, null); } public static createArgumentWithName(argumentName: string) : Argument { return Argument.createArgumentWithExpressionArgumentAndValue(null, argumentName, null); } public static createArgumentWithNameAndValue(argumentName: string, argumentValue: number) : Argument { return Argument.createArgumentWithExpressionArgumentAndValue(null, argumentName, argumentValue); } private static createArgumentWithExpressionArgumentAndValue(argumentExpression: string, argumentName: string, argumentValue: number) : Argument { let x : Argument = new Argument(null, null, null); if(argumentExpression !== null) { x.setArgumentExpressionString(argumentExpression); } else if(argumentName !== null && argumentValue !== null) { x.setArgumentName(argumentName); x.setArgumentValue(argumentValue); } else if(argumentName !== null && argumentValue === null) { x.setArgumentName(argumentName); } x.argumentType = ArgumentConstants.FREE_ARGUMENT; return x; } /** * Argument body type. * * @see Argument#BODY_RUNTIME * @see Argument#BODY_EXTENDED * @see Argument#getArgumentBodyType() */ /*private*/ argumentBodyType: number; /** * Argument extension (body based in code) * * @see ArgumentExtension * @see Argument#Argument(String, ArgumentExtension) */ /*private*/ argumentExtension: ArgumentExtension; /** * Description of the argument. */ /*private*/ description: string; /** * Argument expression for dependent and recursive * arguments. */ argumentExpression: Expression; /** * Argument name (x, y, arg1, my_argument, etc...) */ /*private*/ argumentName: string; /** * Argument type (free, dependent) */ argumentType: number; /** * Argument value (for free arguments). */ argumentValue: number; /** * Index argument. * * @see RecursiveArgument */ n: Argument; public constructor(argumentName?: any, argumentExpressionString?: any, ...elements: any[]) { if (((typeof argumentName === 'string') || argumentName === null) && ((typeof argumentExpressionString === 'string') || argumentExpressionString === null) && ((elements != null && elements instanceof <any>Array && (elements.length == 0 || elements[0] == null ||(elements[0] != null && elements[0] instanceof <any>PrimitiveElement))) || elements === null)) { let __args = arguments; super(ArgumentConstants.TYPE_ID); if (this.argumentBodyType === undefined) { this.argumentBodyType = 0; } if (this.argumentExtension === undefined) { this.argumentExtension = null; } if (this.description === undefined) { this.description = null; } if (this.argumentExpression === undefined) { this.argumentExpression = null; } if (this.argumentName === undefined) { this.argumentName = null; } if (this.argumentType === undefined) { this.argumentType = 0; } if (this.argumentValue === undefined) { this.argumentValue = 0; } if (this.n === undefined) { this.n = null; } if (argumentName !== null && mXparserConstants.regexMatch(argumentName, ParserSymbol.nameOnlyTokenRegExp)){ this.argumentName = argumentName; this.argumentValue = ArgumentConstants.ARGUMENT_INITIAL_VALUE_$LI$(); this.argumentExpression = <any>new Expression(argumentExpressionString,elements); this.argumentExpression.setDescription(argumentName); this.argumentType = ArgumentConstants.DEPENDENT_ARGUMENT; } else { this.argumentValue = ArgumentConstants.ARGUMENT_INITIAL_VALUE_$LI$(); this.argumentExpression = Expression.create(); this.argumentExpression.setSyntaxStatus(ArgumentConstants.SYNTAX_ERROR_OR_STATUS_UNKNOWN_$LI$(), "[" + argumentName + "] Invalid argument name, pattern not match: " + ParserSymbol.nameOnlyTokenRegExp); } this.argumentBodyType = ArgumentConstants.BODY_RUNTIME; this.setSilentMode(); this.description = ""; } else if (((typeof argumentName === 'string') || argumentName === null) && ((typeof argumentExpressionString === 'boolean') || argumentExpressionString === null) && ((elements != null && elements instanceof <any>Array && (elements.length == 0 || elements[0] == null ||(elements[0] != null && elements[0] instanceof <any>PrimitiveElement))) || elements === null)) { let __args = arguments; let argumentDefinitionString: any = __args[0]; let forceDependent: any = __args[1]; super(ArgumentConstants.TYPE_ID); if (this.argumentBodyType === undefined) { this.argumentBodyType = 0; } if (this.argumentExtension === undefined) { this.argumentExtension = null; } if (this.description === undefined) { this.description = null; } if (this.argumentExpression === undefined) { this.argumentExpression = null; } if (this.argumentName === undefined) { this.argumentName = null; } if (this.argumentType === undefined) { this.argumentType = 0; } if (this.argumentValue === undefined) { this.argumentValue = 0; } if (this.n === undefined) { this.n = null; } if (mXparserConstants.regexMatch(argumentDefinitionString, ParserSymbol.nameOnlyTokenRegExp)){ this.argumentName = argumentDefinitionString; this.argumentValue = ArgumentConstants.ARGUMENT_INITIAL_VALUE_$LI$(); this.argumentType = ArgumentConstants.FREE_ARGUMENT; this.argumentExpression = <any>new Expression(null, elements); } else if (mXparserConstants.regexMatch(argumentDefinitionString, ParserSymbol.constArgDefStrRegExp_$LI$())){ const headEqBody: HeadEqBody = new HeadEqBody(argumentDefinitionString); this.argumentName = headEqBody.headTokens.get(0).tokenStr; const bodyExpr: Expression = new Expression(headEqBody.bodyStr); if (forceDependent === true){ this.argumentExpression = bodyExpr; this.addDefinitions.apply(this, elements); this.argumentType = ArgumentConstants.DEPENDENT_ARGUMENT; } else { const bodyValue: number = bodyExpr.calculate(); if ((bodyExpr.getSyntaxStatus() === ExpressionConstants.NO_SYNTAX_ERRORS) && (bodyValue !== javaemul.internal.DoubleHelper.NaN)){ this.argumentExpression = new Expression(); this.argumentValue = bodyValue; this.argumentType = ArgumentConstants.FREE_ARGUMENT; } else { this.argumentExpression = bodyExpr; this.addDefinitions.apply(this, elements); this.argumentType = ArgumentConstants.DEPENDENT_ARGUMENT; } } } else if (mXparserConstants.regexMatch(argumentDefinitionString, ParserSymbol.functionDefStrRegExp_$LI$())){ const headEqBody: HeadEqBody = new HeadEqBody(argumentDefinitionString); this.argumentName = headEqBody.headTokens.get(0).tokenStr; this.argumentExpression = <any>new Expression(headEqBody.bodyStr, elements); this.argumentExpression.setDescription(headEqBody.headStr); this.argumentValue = ArgumentConstants.ARGUMENT_INITIAL_VALUE_$LI$(); this.argumentType = ArgumentConstants.DEPENDENT_ARGUMENT; this.n = new Argument(headEqBody.headTokens.get(2).tokenStr); } else { this.argumentValue = ArgumentConstants.ARGUMENT_INITIAL_VALUE_$LI$(); this.argumentType = ArgumentConstants.FREE_ARGUMENT; this.argumentExpression = new Expression(); this.argumentExpression.setSyntaxStatus(ArgumentConstants.SYNTAX_ERROR_OR_STATUS_UNKNOWN_$LI$(), "[" + argumentDefinitionString + "] Invalid argument definition (patterns: \'x\', \'x=5\', \'x=5+3/2\', \'x=2*y\')."); } this.argumentBodyType = ArgumentConstants.BODY_RUNTIME; this.setSilentMode(); this.description = ""; } else if (((typeof argumentName === 'string') || argumentName === null) && ((argumentExpressionString != null && argumentExpressionString instanceof <any>Array && (argumentExpressionString.length == 0 || argumentExpressionString[0] == null ||(argumentExpressionString[0] != null && argumentExpressionString[0] instanceof <any>PrimitiveElement))) || argumentExpressionString === null) && elements === undefined || elements.length === 0) { let __args = arguments; let argumentDefinitionString: any = __args[0]; let elements: any[] = __args[1]; super(ArgumentConstants.TYPE_ID); if (this.argumentBodyType === undefined) { this.argumentBodyType = 0; } if (this.argumentExtension === undefined) { this.argumentExtension = null; } if (this.description === undefined) { this.description = null; } if (this.argumentExpression === undefined) { this.argumentExpression = null; } if (this.argumentName === undefined) { this.argumentName = null; } if (this.argumentType === undefined) { this.argumentType = 0; } if (this.argumentValue === undefined) { this.argumentValue = 0; } if (this.n === undefined) { this.n = null; } if (mXparserConstants.regexMatch(argumentDefinitionString, ParserSymbol.nameOnlyTokenRegExp)){ this.argumentName = argumentDefinitionString; this.argumentValue = ArgumentConstants.ARGUMENT_INITIAL_VALUE_$LI$(); this.argumentType = ArgumentConstants.FREE_ARGUMENT; this.argumentExpression = <any>new Expression(null, elements); } else if (mXparserConstants.regexMatch(argumentDefinitionString, ParserSymbol.constArgDefStrRegExp_$LI$())){ const headEqBody: HeadEqBody = new HeadEqBody(argumentDefinitionString); this.argumentName = headEqBody.headTokens.get(0).tokenStr; const bodyExpr: Expression = new Expression(headEqBody.bodyStr); const bodyValue: number = bodyExpr.calculate(); if ((bodyExpr.getSyntaxStatus() === ExpressionConstants.NO_SYNTAX_ERRORS) && (bodyValue !== javaemul.internal.DoubleHelper.NaN)){ this.argumentExpression = new Expression(); this.argumentValue = bodyValue; this.argumentType = ArgumentConstants.FREE_ARGUMENT; } else { this.argumentExpression = bodyExpr; this.addDefinitions.apply(this, elements); this.argumentType = ArgumentConstants.DEPENDENT_ARGUMENT; } } else if (mXparserConstants.regexMatch(argumentDefinitionString, ParserSymbol.functionDefStrRegExp_$LI$())){ const headEqBody: HeadEqBody = new HeadEqBody(argumentDefinitionString); this.argumentName = headEqBody.headTokens.get(0).tokenStr; this.argumentExpression = <any>new Expression(headEqBody.bodyStr, elements); this.argumentExpression.setDescription(headEqBody.headStr); this.argumentValue = ArgumentConstants.ARGUMENT_INITIAL_VALUE_$LI$(); this.argumentType = ArgumentConstants.DEPENDENT_ARGUMENT; this.n = new Argument(headEqBody.headTokens.get(2).tokenStr); } else { this.argumentValue = ArgumentConstants.ARGUMENT_INITIAL_VALUE_$LI$(); this.argumentType = ArgumentConstants.FREE_ARGUMENT; this.argumentExpression = new Expression(); this.argumentExpression.setSyntaxStatus(ArgumentConstants.SYNTAX_ERROR_OR_STATUS_UNKNOWN_$LI$(), "[" + argumentDefinitionString + "] Invalid argument definition (patterns: \'x\', \'x=5\', \'x=5+3/2\', \'x=2*y\')."); } this.argumentBodyType = ArgumentConstants.BODY_RUNTIME; this.setSilentMode(); this.description = ""; } else if (((typeof argumentName === 'string') || argumentName === null) && ((argumentExpressionString != null && (argumentExpressionString.constructor != null && argumentExpressionString.constructor["__interfaces"] != null && argumentExpressionString.constructor["__interfaces"].indexOf("org.mariuszgromada.math.mxparser.ArgumentExtension") >= 0)) || argumentExpressionString === null) && elements === undefined || elements.length === 0) { let __args = arguments; let argumentExtension: any = __args[1]; super(ArgumentConstants.TYPE_ID); if (this.argumentBodyType === undefined) { this.argumentBodyType = 0; } if (this.argumentExtension === undefined) { this.argumentExtension = null; } if (this.description === undefined) { this.description = null; } if (this.argumentExpression === undefined) { this.argumentExpression = null; } if (this.argumentName === undefined) { this.argumentName = null; } if (this.argumentType === undefined) { this.argumentType = 0; } if (this.argumentValue === undefined) { this.argumentValue = 0; } if (this.n === undefined) { this.n = null; } this.argumentExpression = new Expression(); if (mXparserConstants.regexMatch(argumentName, ParserSymbol.nameOnlyTokenRegExp)){ this.argumentName = argumentName; this.argumentExtension = argumentExtension; this.argumentType = ArgumentConstants.FREE_ARGUMENT; this.argumentBodyType = Argument.BODY_EXTENDED; } else { this.argumentValue = ArgumentConstants.ARGUMENT_INITIAL_VALUE_$LI$(); this.argumentExpression.setSyntaxStatus(ArgumentConstants.SYNTAX_ERROR_OR_STATUS_UNKNOWN_$LI$(), "[" + argumentName + "] Invalid argument name, pattern not match: " + ParserSymbol.nameOnlyTokenRegExp); this.argumentBodyType = ArgumentConstants.BODY_RUNTIME; } this.setSilentMode(); this.description = ""; } else if (((typeof argumentName === 'string') || argumentName === null) && ((typeof argumentExpressionString === 'number') || argumentExpressionString === null) && elements === undefined || elements.length === 0) { let __args = arguments; let argumentValue: any = __args[1]; super(ArgumentConstants.TYPE_ID); if (this.argumentBodyType === undefined) { this.argumentBodyType = 0; } if (this.argumentExtension === undefined) { this.argumentExtension = null; } if (this.description === undefined) { this.description = null; } if (this.argumentExpression === undefined) { this.argumentExpression = null; } if (this.argumentName === undefined) { this.argumentName = null; } if (this.argumentType === undefined) { this.argumentType = 0; } if (this.argumentValue === undefined) { this.argumentValue = 0; } if (this.n === undefined) { this.n = null; } this.argumentExpression = new Expression(); if (mXparserConstants.regexMatch(argumentName, ParserSymbol.nameOnlyTokenRegExp)){ this.argumentName = argumentName; this.argumentValue = argumentValue; this.argumentType = ArgumentConstants.FREE_ARGUMENT; } else { this.argumentValue = ArgumentConstants.ARGUMENT_INITIAL_VALUE_$LI$(); this.argumentExpression.setSyntaxStatus(ArgumentConstants.SYNTAX_ERROR_OR_STATUS_UNKNOWN_$LI$(), "[" + argumentName + "] Invalid argument name, pattern not match: " + ParserSymbol.nameOnlyTokenRegExp); } this.argumentBodyType = ArgumentConstants.BODY_RUNTIME; this.setSilentMode(); this.description = ""; } else throw new Error('invalid overload'); } /** * Sets argument description. * * @param {string} description the argument description. */ public setDescription(description: string) { this.description = description; } /** * Gets argument description. * * @return {string} The argument description string. */ public getDescription(): string { return this.description; } /** * Enables argument verbose mode */ public setVerboseMode() { this.argumentExpression.setVerboseMode(); } /** * Disables argument verbose mode (sets default silent mode) */ public setSilentMode() { this.argumentExpression.setSilentMode(); } /** * Returns verbose mode status * * @return {boolean} true if verbose mode is on, * otherwise returns false. */ public getVerboseMode(): boolean { return this.argumentExpression.getVerboseMode(); } /** * Gets recursive mode status * * @return {boolean} true if recursive mode is enabled, * otherwise returns false */ public getRecursiveMode(): boolean { return this.argumentExpression.getRecursiveMode(); } /** * Gets computing time * * @return {number} Computing time in seconds. */ public getComputingTime(): number { return this.argumentExpression.getComputingTime(); } /** * Sets (modifies) argument name. * Each expression / function / dependent argument associated * with this argument will be marked as modified * (requires new syntax checking). * * @param {string} argumentName the argument name */ public setArgumentName(argumentName: string) { if (mXparserConstants.regexMatch(argumentName, ParserSymbol.nameOnlyTokenRegExp)){ this.argumentName = argumentName; this.setExpressionModifiedFlags(); } else if (this.argumentExpression != null)this.argumentExpression.setSyntaxStatus(ArgumentConstants.SYNTAX_ERROR_OR_STATUS_UNKNOWN_$LI$(), "[" + argumentName + "] Invalid argument name, pattern not match: " + ParserSymbol.nameOnlyTokenRegExp); } /** * Sets argument expression string. * Each expression / function / dependent argument associated * with this argument will be marked as modified * (requires new syntax checking). * If BODY_EXTENDED argument then BODY_RUNTIME is set. * * @param {string} argumentExpressionString the argument expression string * * @see Expression */ public setArgumentExpressionString(argumentExpressionString: string) { this.argumentExpression.setExpressionString(argumentExpressionString); if (this.argumentType === ArgumentConstants.FREE_ARGUMENT)this.argumentType = ArgumentConstants.DEPENDENT_ARGUMENT; this.argumentBodyType = ArgumentConstants.BODY_RUNTIME; } /** * Gets argument name * * @return {string} the argument name as string */ public getArgumentName(): string { return this.argumentName; } /** * Gets argument expression string * * @return {string} the argument expression string */ public getArgumentExpressionString(): string { return this.argumentExpression.getExpressionString(); } /** * Gets argument type * * @return {number} Argument type: ArgumentConstants.FREE_ARGUMENT, * ArgumentConstants.DEPENDENT_ARGUMENT, * ArgumentConstants.RECURSIVE_ARGUMENT */ public getArgumentType(): number { return this.argumentType; } /** * Sets argument value, if DEPENDENT_ARGUMENT then argument type * is set to FREE_ARGUMENT. * If BODY_EXTENDED argument the BODY_RUNTIME argument is set. * * @param {number} argumentValue the value of argument */ public setArgumentValue(argumentValue: number) { if (this.argumentType === ArgumentConstants.DEPENDENT_ARGUMENT){ this.argumentType = ArgumentConstants.FREE_ARGUMENT; this.argumentExpression.setExpressionString(""); } this.argumentBodyType = ArgumentConstants.BODY_RUNTIME; this.argumentValue = argumentValue; } /** * Returns argument body type: {@link Argument#BODY_RUNTIME} {@link Argument#BODY_EXTENDED} * @return {number} Returns argument body type: {@link Argument#BODY_RUNTIME} {@link Argument#BODY_EXTENDED} */ public getArgumentBodyType(): number { return this.argumentBodyType; } /** * Checks argument syntax * * @return {boolean} syntax status: ArgumentConstants.NO_SYNTAX_ERRORS, * ArgumentConstants.SYNTAX_ERROR_OR_STATUS_UNKNOWN */ public checkSyntax(): boolean { if (this.argumentBodyType === Argument.BODY_EXTENDED)return ArgumentConstants.NO_SYNTAX_ERRORS_$LI$(); if (this.argumentType === ArgumentConstants.FREE_ARGUMENT)return ArgumentConstants.NO_SYNTAX_ERRORS_$LI$(); else return this.argumentExpression.checkSyntax$(); } /** * Returns error message after checking the syntax * * @return {string} Error message as string. */ public getErrorMessage(): string { return this.argumentExpression.getErrorMessage(); } /** * Gets argument value. * * @return {number} direct argument value for free argument, * otherwise returns calculated argument value * based on the argument expression. */ public getArgumentValue(): number { if (this.argumentBodyType === Argument.BODY_EXTENDED)return this.argumentExtension.getArgumentValue(); if (this.argumentType === ArgumentConstants.FREE_ARGUMENT)return this.argumentValue; else return this.argumentExpression.calculate(); } /** * Adds user defined elements (such as: Arguments, Constants, Functions) * to the argument expressions. * * @param {org.mariuszgromada.math.mxparser.PrimitiveElement[]} elements Elements list (variadic - comma separated) of types: Argument, Constant, Function * * @see PrimitiveElement */ public addDefinitions(...elements: PrimitiveElement[]) { (o => o.addDefinitions.apply(o, elements))(this.argumentExpression); } /** * Removes user defined elements (such as: Arguments, Constants, Functions) * from the argument expressions. * * @param {org.mariuszgromada.math.mxparser.PrimitiveElement[]} elements Elements list (variadic - comma separated) of types: Argument, Constant, Function * * @see PrimitiveElement */ public removeDefinitions(...elements: PrimitiveElement[]) { (o => o.removeDefinitions.apply(o, elements))(this.argumentExpression); } /** * Adds arguments (variadic) to the argument expression definition. * * @param {org.mariuszgromada.math.mxparser.Argument[]} arguments the arguments list * (comma separated list) * @see Argument * @see RecursiveArgument */ public addArguments(...__arguments: Argument[]) { (o => o.addArguments.apply(o, __arguments))(this.argumentExpression); } /** * Enables to define the arguments (associated with * the argument expression) based on the given arguments names. * * @param {java.lang.String[]} argumentsNames the arguments names (variadic) * comma separated list * * @see Argument * @see RecursiveArgument */ public defineArguments(...argumentsNames: string[]) { (o => o.defineArguments.apply(o, argumentsNames))(this.argumentExpression); } /** * Enables to define the argument (associated with the argument expression) * based on the argument name and the argument value. * * @param {string} argumentName the argument name * @param {number} argumentValue the the argument value * * @see Argument * @see RecursiveArgument */ public defineArgument(argumentName: string, argumentValue: number) { this.argumentExpression.defineArgument(argumentName, argumentValue); } /** * Gets argument index from the argument expression. * * @param {string} argumentName the argument name * * @return {number} The argument index if the argument name was found, * otherwise returns ArgumentConstants.NOT_FOUND * * @see Argument * @see RecursiveArgument */ public getArgumentIndex(argumentName: string): number { return this.argumentExpression.getArgumentIndex(argumentName); } public getArgument$java_lang_String(argumentName: string): Argument { return this.argumentExpression.getArgument$java_lang_String(argumentName); } /** * Gets argument from the argument expression. * * * @param {string} argumentName the argument name * * @return {Argument} The argument if the argument name was found, * otherwise returns null. * * @see Argument * @see RecursiveArgument */ public getArgument(argumentName?: any): any { if (((typeof argumentName === 'string') || argumentName === null)) { return <any>this.getArgument$java_lang_String(argumentName); } else if (((typeof argumentName === 'number') || argumentName === null)) { return <any>this.getArgument$int(argumentName); } else throw new Error('invalid overload'); } public getArgument$int(argumentIndex: number): Argument { return this.argumentExpression.getArgument$int(argumentIndex); } /** * Gets number of arguments associated with the argument expression. * * @return {number} The number of arguments (int &gt;= 0) * * @see Argument * @see RecursiveArgument */ public getArgumentsNumber(): number { return this.argumentExpression.getArgumentsNumber(); } public removeArguments$java_lang_String_A(...argumentsNames: string[]) { (o => o.removeArguments.apply(o, argumentsNames))(this.argumentExpression); } /** * Removes first occurrences of the arguments * associated with the argument expression. * * @param {java.lang.String[]} argumentsNames the arguments names * (variadic parameters) comma separated * list * * @see Argument * @see RecursiveArgument */ public removeArguments(...argumentsNames: any[]) { if (((argumentsNames != null && argumentsNames instanceof <any>Array && (argumentsNames.length == 0 || argumentsNames[0] == null ||(typeof argumentsNames[0] === 'string'))) || argumentsNames === null)) { return <any>this.removeArguments$java_lang_String_A(...argumentsNames); } else if (((argumentsNames != null && argumentsNames instanceof <any>Array && (argumentsNames.length == 0 || argumentsNames[0] == null ||(argumentsNames[0] != null && argumentsNames[0] instanceof <any>Argument))) || argumentsNames === null)) { return <any>this.removeArguments$org_mariuszgromada_math_mxparser_Argument_A(...argumentsNames); } else throw new Error('invalid overload'); } public removeArguments$org_mariuszgromada_math_mxparser_Argument_A(...__arguments: Argument[]) { (o => o.removeArguments.apply(o, __arguments))(this.argumentExpression); } /** * Removes all arguments associated with the argument expression. * * @see Argument * @see RecursiveArgument */ public removeAllArguments() { this.argumentExpression.removeAllArguments(); } public addConstants$org_mariuszgromada_math_mxparser_Constant_A(...constants: Constant[]) { (o => o.addConstants.apply(o, constants))(this.argumentExpression); } /** * Adds constants (variadic parameters) to the argument expression definition. * * @param {org.mariuszgromada.math.mxparser.Constant[]} constants the constants * (comma separated list) * * @see Constant */ public addConstants(...constants: any[]) { if (((constants != null && constants instanceof <any>Array && (constants.length == 0 || constants[0] == null ||(constants[0] != null && constants[0] instanceof <any>Constant))) || constants === null)) { return <any>this.addConstants$org_mariuszgromada_math_mxparser_Constant_A(...constants); } else if (((constants != null && (constants.constructor != null && constants.constructor["__interfaces"] != null && constants.constructor["__interfaces"].indexOf("java.util.List") >= 0)) || constants === null)) { return <any>this.addConstants$java_util_List(<any>constants); } else throw new Error('invalid overload'); } public addConstants$java_util_List(constantsList: java.util.List<Constant>) { this.argumentExpression.addConstants$java_util_List(constantsList); } /** * Enables to define the constant (associated with * the argument expression) based on the constant name and * constant value. * * @param {string} constantName the constant name * @param {number} constantValue the constant value * * @see Constant */ public defineConstant(constantName: string, constantValue: number) { this.argumentExpression.defineConstant(constantName, constantValue); } /** * Gets constant index associated with the argument expression. * * @param {string} constantName the constant name * * @return {number} Constant index if constant name was found, * otherwise return Constant.NOT_FOUND. * * @see Constant */ public getConstantIndex(constantName: string): number { return this.argumentExpression.getConstantIndex(constantName); } public getConstant$java_lang_String(constantName: string): Constant { return this.argumentExpression.getConstant$java_lang_String(constantName); } /** * Gets constant associated with the argument expression. * * @param {string} constantName the constant name * * @return {Constant} Constant if constant name was found, * otherwise return null. * * @see Constant */ public getConstant(constantName?: any): any { if (((typeof constantName === 'string') || constantName === null)) { return <any>this.getConstant$java_lang_String(constantName); } else if (((typeof constantName === 'number') || constantName === null)) { return <any>this.getConstant$int(constantName); } else throw new Error('invalid overload'); } public getConstant$int(constantIndex: number): Constant { return this.argumentExpression.getConstant$int(constantIndex); } /** * Gets number of constants associated with the argument expression. * * @return {number} number of constants (int &gt;= 0) * * @see Constant */ public getConstantsNumber(): number { return this.argumentExpression.getConstantsNumber(); } public removeConstants$java_lang_String_A(...constantsNames: string[]) { (o => o.removeConstants.apply(o, constantsNames))(this.argumentExpression); } /** * Removes first occurrences of the constants * associated with the argument expression. * * @param {java.lang.String[]} constantsNames the constants names (variadic parameters) * comma separated list * * @see Constant */ public removeConstants(...constantsNames: any[]) { if (((constantsNames != null && constantsNames instanceof <any>Array && (constantsNames.length == 0 || constantsNames[0] == null ||(typeof constantsNames[0] === 'string'))) || constantsNames === null)) { return <any>this.removeConstants$java_lang_String_A(...constantsNames); } else if (((constantsNames != null && constantsNames instanceof <any>Array && (constantsNames.length == 0 || constantsNames[0] == null ||(constantsNames[0] != null && constantsNames[0] instanceof <any>Constant))) || constantsNames === null)) { return <any>this.removeConstants$org_mariuszgromada_math_mxparser_Constant_A(...constantsNames); } else throw new Error('invalid overload'); } public removeConstants$org_mariuszgromada_math_mxparser_Constant_A(...constants: Constant[]) { (o => o.removeConstants.apply(o, constants))(this.argumentExpression); } /** * Removes all constants * associated with the argument expression * * @see Constant */ public removeAllConstants() { this.argumentExpression.removeAllConstants(); } /** * Adds functions (variadic parameters) to the argument expression definition. * * @param {org.mariuszgromada.math.mxparser.Function[]} functions the functions * (variadic parameters) comma separated list * * @see Function */ public addFunctions(...functions: Function[]) { (o => o.addFunctions.apply(o, functions))(this.argumentExpression); } /** * Enables to define the function (associated with * the argument expression) based on the function name, * function expression string and arguments names (variadic parameters). * * @param {string} functionName the function name * @param {string} functionExpressionString the expression string * @param {java.lang.String[]} argumentsNames the function arguments names * (variadic parameters) * comma separated list * * @see Function */ public defineFunction(functionName: string, functionExpressionString: string, ...argumentsNames: string[]) { (o => o.defineFunction.apply(o, [functionName, functionExpressionString].concat(<any[]>argumentsNames)))(this.argumentExpression); } /** * Gets index of function associated with the argument expression. * * @param {string} functionName the function name * * @return {number} Function index if function name was found, * otherwise returns Function.NOT_FOUND * * @see Function */ public getFunctionIndex(functionName: string): number { return this.argumentExpression.getFunctionIndex(functionName); } public getFunction$java_lang_String(functionName: string): Function { return this.argumentExpression.getFunction$java_lang_String(functionName); } /** * Gets function associated with the argument expression. * * @param {string} functionName the function name * * @return {Function} Function if function name was found, * otherwise returns null. * * @see Function */ public getFunction(functionName?: any): any { if (((typeof functionName === 'string') || functionName === null)) { return <any>this.getFunction$java_lang_String(functionName); } else if (((typeof functionName === 'number') || functionName === null)) { return <any>this.getFunction$int(functionName); } else throw new Error('invalid overload'); } public getFunction$int(functionIndex: number): Function { return this.argumentExpression.getFunction$int(functionIndex); } /** * Gets number of functions associated with the argument expression. * * @return {number} number of functions (int &gt;= 0) * * @see Function */ public getFunctionsNumber(): number { return this.argumentExpression.getFunctionsNumber(); } public removeFunctions$java_lang_String_A(...functionsNames: string[]) { (o => o.removeFunctions.apply(o, functionsNames))(this.argumentExpression); } /** * Removes first occurrences of the functions * associated with the argument expression. * * @param {java.lang.String[]} functionsNames the functions names (variadic parameters) * comma separated list * * @see Function */ public removeFunctions(...functionsNames: any[]) { if (((functionsNames != null && functionsNames instanceof <any>Array && (functionsNames.length == 0 || functionsNames[0] == null ||(typeof functionsNames[0] === 'string'))) || functionsNames === null)) { return <any>this.removeFunctions$java_lang_String_A(...functionsNames); } else if (((functionsNames != null && functionsNames instanceof <any>Array && (functionsNames.length == 0 || functionsNames[0] == null ||(functionsNames[0] != null && functionsNames[0] instanceof <any>Function))) || functionsNames === null)) { return <any>this.removeFunctions$org_mariuszgromada_math_mxparser_Function_A(...functionsNames); } else throw new Error('invalid overload'); } public removeFunctions$org_mariuszgromada_math_mxparser_Function_A(...functions: Function[]) { (o => o.removeFunctions.apply(o, functions))(this.argumentExpression); } /** * Removes all functions * associated with the argument expression. * * @see Function */ public removeAllFunctions() { this.argumentExpression.removeAllFunctions(); } /** * Adds related expression to the argumentExpression * * @param {Expression} expression the related expression * @see Expression */ addRelatedExpression(expression: Expression) { this.argumentExpression.addRelatedExpression(expression); } /** * Adds related expression form the argumentExpression * * @param {Expression} expression related expression * * @see Expression */ removeRelatedExpression(expression: Expression) { this.argumentExpression.removeRelatedExpression(expression); } /** * Sets expression was modified flag to all related expressions * to the argumentExpression. * * @see Expression */ setExpressionModifiedFlags() { this.argumentExpression.setExpressionModifiedFlag(); } /** * Creates cloned object of the this argument.'' * * @return {Argument} clone of the argument. */ public clone(): Argument { const newArg: Argument = new Argument(this.argumentName); newArg.argumentExpression = this.argumentExpression; newArg.argumentType = this.argumentType; newArg.argumentBodyType = this.argumentBodyType; newArg.argumentValue = this.argumentValue; newArg.description = this.description; newArg.n = this.n; if (this.argumentExtension != null)newArg.argumentExtension = /* clone */((o: any) => { if (o.clone != undefined) { return (<any>o).clone(); } else { let clone = Object.create(o); for(let p in o) { if (o.hasOwnProperty(p)) clone[p] = o[p]; } return clone; } })(this.argumentExtension); else newArg.argumentExtension = null; return newArg; } } Argument["__class"] = "org.mariuszgromada.math.mxparser.Argument"; var __Function = Function;
the_stack
import { ConcreteComponent, PropType, RendererElement, RendererNode, VNode, createTextVNode, defineComponent, h, ref, reactive, resolveComponent, watchEffect, watch, Ref, getCurrentInstance, } from 'vue' import { has, isPojo } from '@formkit/utils' import { FormKitSchemaAttributes, FormKitSchemaNode, isDOM, isConditional, isComponent, compile, FormKitSchemaCondition, FormKitSchemaAttributesCondition, FormKitAttributeValue, FormKitCompilerOutput, getNode, warn, watchRegistry, isNode, sugar, } from '@formkit/core' /** * A library of components available to the schema (in addition to globally * registered ones) */ interface FormKitComponentLibrary { [index: string]: ConcreteComponent } /** * Defines the structure a parsed node. */ type RenderContent = [ condition: false | (() => boolean | number | string), element: string | ConcreteComponent | null, attrs: () => FormKitSchemaAttributes, children: RenderChildren | null, alternate: RenderChildren | null, iterator: | null | [ getNodeValues: () => | number | string | boolean | any[] | Record<string, any>, valueName: string, keyName: string | null ], resolve: boolean ] /** * The actual signature of a VNode in Vue. */ type VirtualNode = VNode<RendererNode, RendererElement, { [key: string]: any }> /** * The types of values that can be rendered by Vue. */ type Renderable = null | string | number | boolean | VirtualNode /** * A list of renderable items. */ type RenderableList = Renderable | Renderable[] | (Renderable | Renderable[])[] /** * An object of slots */ type RenderableSlots = Record<string, RenderableSlot> /** * A slot function that can be rendered. */ type RenderableSlot = ( data?: Record<string, any>, key?: symbol ) => RenderableList /** * Describes renderable children. */ interface RenderChildren { (iterationData?: Record<string, unknown>): RenderableList | RenderableSlots slot?: boolean } /** * The format children elements can be in. */ interface RenderNodes { (iterationData?: Record<string, unknown>): Renderable | Renderable[] } type SchemaProvider = ( providerCallback: SchemaProviderCallback, instanceKey: symbol ) => RenderChildren type SchemaProviderCallback = ( requirements: string[], hints?: Record<string, boolean> ) => Record<string, () => any> type ProviderRegistry = (( providerCallback: SchemaProviderCallback, key: symbol ) => void)[] /** * A registry of memoized schemas (in JSON) to their respective render function * and provider registry. */ const memo: Record<string, [RenderChildren, ProviderRegistry]> = {} /** * This symbol represents the current component instance during render. It is * critical for linking the current instance to the data required for render. */ let instanceKey: symbol /** * A registry of scoped data produced during runtime that is keyed by the * instance symbol. For example data from: for-loop instances and slot data. */ const instanceScopes = new Map<symbol, Record<string, any>[]>() /** * Indicates the a section of the schema is raw. */ const raw = '__raw__' /** * Is a class prop. */ const isClassProp = /[a-zA-Z0-9\-][cC]lass$/ /** * Returns a reference as a placeholder to a specific location on an object. * @param data - A reactive data object * @param token - A dot-syntax string representing the object path * @returns */ function getRef(token: string, data: Record<string, any>): Ref<unknown> { const value = ref<any>(null) if (token === 'get') { const nodeRefs: Record<string, Ref<unknown>> = {} value.value = get.bind(null, nodeRefs) return value } const path = token.split('.') watchEffect(() => (value.value = getValue(data, path))) return value } /** * Returns a value inside a set of data objects. * @param sets - An array of objects to search through * @param path - A array of string paths easily produced by split() * @returns */ function getValue( set: (false | Record<string, any>)[] | Record<string, any>, path: string[] ): any { if (Array.isArray(set)) { for (const subset of set) { const value = subset !== false && getValue(subset, path) if (value !== undefined) return value } return undefined } let foundValue: any = undefined path.reduce( (obj: Record<string, any> | undefined, segment: string, i, arr) => { if (typeof obj !== 'object') { foundValue = undefined return arr.splice(1) // Forces an exit } const currentValue = obj[segment] if (i === path.length - 1 && currentValue !== undefined) { foundValue = currentValue } return obj[segment] }, set ) return foundValue } /** * Get the node from the global registry * @param id - A dot-syntax string where the node is located. */ function get(nodeRefs: Record<string, Ref<unknown>>, id?: string) { if (typeof id !== 'string') return warn(650) if (!(id in nodeRefs)) nodeRefs[id] = ref<unknown>(undefined) if (nodeRefs[id].value === undefined) { nodeRefs[id].value = null const root = getNode(id) if (root) nodeRefs[id].value = root.context watchRegistry(id, ({ payload: node }) => { nodeRefs[id].value = isNode(node) ? node.context : node }) } return nodeRefs[id].value } /** * * @param library - A library of concrete components to use * @param schema - * @returns */ function parseSchema( library: FormKitComponentLibrary, schema: FormKitSchemaNode | FormKitSchemaNode[] ): SchemaProvider { /** * Given an if/then/else schema node, pre-compile the node and return the * artifacts for the render function. * @param data - The schema context object * @param library - The available components * @param node - The node to parse */ function parseCondition( library: FormKitComponentLibrary, node: FormKitSchemaCondition ): [RenderContent[0], RenderContent[3], RenderContent[4]] { const condition = provider(compile(node.if), { if: true }) const children = createElements(library, node.then) const alternate = node.else ? createElements(library, node.else) : null return [condition, children, alternate] } /** * Parses a conditional if/then/else attribute statement. * @param data - The data object * @param attr - The attribute * @param _default - The default value * @returns */ function parseConditionAttr( attr: FormKitSchemaAttributesCondition, _default: FormKitAttributeValue ): () => FormKitAttributeValue | FormKitSchemaAttributes { const condition = provider(compile(attr.if)) let b: () => FormKitAttributeValue = () => _default let a: () => FormKitAttributeValue = () => _default if (typeof attr.then === 'object') { a = parseAttrs(attr.then, undefined) } else if (typeof attr.then === 'string' && attr.then?.startsWith('$')) { a = provider(compile(attr.then)) } else { a = () => attr.then } if (has(attr, 'else')) { if (typeof attr.else === 'object') { b = parseAttrs(attr.else) } else if (typeof attr.else === 'string' && attr.else?.startsWith('$')) { b = provider(compile(attr.else)) } else { b = () => attr.else } } return () => (condition() ? a() : b()) } /** * Parse attributes for dynamic content. * @param attrs - Object of attributes * @returns */ function parseAttrs( unparsedAttrs?: FormKitSchemaAttributes | FormKitSchemaAttributesCondition, bindExp?: string, _default = {} ): () => FormKitSchemaAttributes { const explicitAttrs = new Set(Object.keys(unparsedAttrs || {})) const boundAttrs = bindExp ? provider(compile(bindExp)) : () => ({}) const staticAttrs: FormKitSchemaAttributes = {} const setters: Array<(obj: Record<string, any>) => void> = [ (attrs) => { const bound: Record<string, any> = boundAttrs() for (const attr in bound) { if (!explicitAttrs.has(attr)) { attrs[attr] = bound[attr] } } }, ] if (unparsedAttrs) { if (isConditional(unparsedAttrs)) { // This is a root conditional object that must produce an object of // attributes. const condition = parseConditionAttr( unparsedAttrs, _default ) as () => FormKitSchemaAttributes return condition } // Some attributes are explicitly bound, we need to parse those ones // using the compiler and create a dynamic "setter". for (let attr in unparsedAttrs) { const value = unparsedAttrs[attr] let getValue: () => any const isStr = typeof value === 'string' if (attr.startsWith(raw)) { // attributes prefixed with __raw__ should not be parsed attr = attr.substring(7) getValue = () => value } else if ( isStr && value.startsWith('$') && value.length > 1 && !(value.startsWith('$reset') && isClassProp.test(attr)) ) { // Most attribute values starting with $ should be compiled // -class attributes starting with `$reset` should not be compiled getValue = provider(compile(value)) } else if (typeof value === 'object' && isConditional(value)) { // Conditional attrs require further processing getValue = parseConditionAttr(value, undefined) } else if (typeof value === 'object' && isPojo(value)) { // Sub-parse pojos getValue = parseAttrs(value) } else { // In all other cases, the value is static getValue = () => value staticAttrs[attr] = value } setters.push((attrs) => { attrs[attr] = getValue() }) } } return () => { const attrs = {} setters.forEach((setter) => setter(attrs)) return attrs } } /** * Given a single schema node, parse it and extract the value. * @param data - A state object provided to each node * @param node - The schema node being parsed * @returns */ function parseNode( library: FormKitComponentLibrary, _node: FormKitSchemaNode ): RenderContent { let element: RenderContent[1] = null let attrs: () => FormKitSchemaAttributes = () => null let condition: false | (() => boolean | number | string) = false let children: RenderContent[3] = null let alternate: RenderContent[4] = null let iterator: RenderContent[5] = null let resolve = false const node = sugar(_node) if (isDOM(node)) { // This is an actual HTML DOM element element = node.$el attrs = node.$el !== 'text' ? parseAttrs(node.attrs, node.bind) : () => null } else if (isComponent(node)) { // This is a Vue Component if (typeof node.$cmp === 'string') { if (has(library, node.$cmp)) { element = library[node.$cmp] } else { element = node.$cmp resolve = true } } else { // in this case it must be an actual component element = node.$cmp } attrs = parseAttrs(node.props, node.bind) } else if (isConditional(node)) { // This is an if/then schema statement ;[condition, children, alternate] = parseCondition(library, node) } // This is the same as a "v-if" statement — not an if/else statement if (!isConditional(node) && 'if' in node) { condition = provider(compile(node.if as string)) } else if (!isConditional(node) && element === null) { // In this odd case our element is actually a partial and // we only want to render the children. condition = () => true } // Compile children down to a function if ('children' in node && node.children) { if (typeof node.children === 'string') { // We are dealing with a raw string value if (node.children.startsWith('$slots.')) { // this is a lone text node, turn it into a slot element = element === 'text' ? 'slot' : element children = provider(compile(node.children)) } else if (node.children.startsWith('$') && node.children.length > 1) { const value = provider(compile(node.children)) children = () => String(value()) } else { children = () => String(node.children) } } else if (Array.isArray(node.children)) { // We are dealing with node sub-children children = createElements(library, node.children) } else { // This is a conditional if/else clause const [childCondition, c, a] = parseCondition(library, node.children) children = (iterationData?: Record<string, unknown>) => childCondition && childCondition() ? c && c(iterationData) : a && a(iterationData) } } if (isComponent(node)) { if (children) { // Children of components need to be provided as an object of slots // so we provide an object with the default slot provided as children. // We also create a new scope for this default slot, and then on each // render pass the scoped slot props to the scope. const produceChildren = children children = (iterationData?: Record<string, unknown>) => { return { default( slotData?: Record<string, any>, key?: symbol ): RenderableList { // We need to switch the current instance key back to the one that // originally called this component's render function. const currentKey = instanceKey if (key) instanceKey = key if (slotData) instanceScopes.get(instanceKey)?.unshift(slotData) if (iterationData) instanceScopes.get(instanceKey)?.unshift(iterationData) const c = produceChildren(iterationData) // Ensure our instance key never changed during runtime if (slotData) instanceScopes.get(instanceKey)?.shift() if (iterationData) instanceScopes.get(instanceKey)?.shift() instanceKey = currentKey return c as RenderableList }, } } children.slot = true } else { // If we dont have any children, we still need to provide an object // instead of an empty array (which raises a warning in vue) children = () => ({}) } } // Compile the for loop down if ('for' in node && node.for) { const values = node.for.length === 3 ? node.for[2] : node.for[1] const getValues = typeof values === 'string' && values.startsWith('$') ? provider(compile(values)) : () => values iterator = [ getValues, node.for[0], node.for.length === 3 ? String(node.for[1]) : null, ] } return [condition, element, attrs, children, alternate, iterator, resolve] } /** * Given a particular function that produces children, ensure that the second * argument of all these slots is the original instance key being used to * render the slots. * @param children - The children() function that will produce slots */ function createSlots( children: RenderChildren, iterationData?: Record<string, unknown> ): RenderableSlots | null { const slots = children(iterationData) as RenderableSlots const currentKey = instanceKey return Object.keys(slots).reduce((allSlots, slotName) => { const slotFn = slots && slots[slotName] allSlots[slotName] = (data?: Record<string, any>) => { return (slotFn && slotFn(data, currentKey)) || null } return allSlots }, {} as RenderableSlots) } /** * Creates an element * @param data - The context data available to the node * @param node - The schema node to render * @returns */ function createElement( library: FormKitComponentLibrary, node: FormKitSchemaNode ): RenderNodes { // Parses the schema node into pertinent parts const [condition, element, attrs, children, alternate, iterator, resolve] = parseNode(library, node) // This is a sub-render function (called within a render function). It must // only use pre-compiled features, and be organized in the most efficient // manner possible. let createNodes: RenderNodes = (( iterationData?: Record<string, unknown> ) => { if (condition && element === null && children) { // Handle conditional if/then statements return condition() ? children(iterationData) : alternate && alternate(iterationData) } if (element && (!condition || condition())) { // handle text nodes if (element === 'text' && children) { return createTextVNode(String(children())) } // Handle lone slots if (element === 'slot' && children) return children(iterationData) // Handle resolving components const el = resolve ? resolveComponent(element as string) : element // If we are rendering slots as children, ensure their instanceKey is properly added const slots: RenderableSlots | null = children?.slot ? createSlots(children, iterationData) : null // Handle dom elements and components return h( el, attrs(), (slots || (children ? children(iterationData) : [])) as Renderable[] ) } return typeof alternate === 'function' ? alternate(iterationData) : alternate }) as RenderNodes if (iterator) { const repeatedNode = createNodes const [getValues, valueName, keyName] = iterator createNodes = (() => { const _v = getValues() const values = !isNaN(_v as number) ? Array(Number(_v)) .fill(0) .map((_, i) => i) : _v const fragment = [] if (typeof values !== 'object') return null const instanceScope = instanceScopes.get(instanceKey) || [] for (const key in values) { const iterationData: Record<string, unknown> = Object.defineProperty( { ...instanceScope.reduce( ( previousIterationData: Record<string, undefined>, scopedData: Record<string, undefined> ) => { if (previousIterationData.__idata) { return { ...previousIterationData, ...scopedData } } return scopedData }, {} as Record<string, undefined> ), [valueName]: values[key], ...(keyName !== null ? { [keyName]: key } : {}), }, '__idata', { enumerable: false, value: true } ) instanceScope.unshift(iterationData) fragment.push(repeatedNode.bind(null, iterationData)()) instanceScope.shift() } return fragment }) as RenderNodes } return createNodes as RenderNodes } /** * Given a schema, parse it and return the resulting renderable nodes. * @param data - The schema context object * @param library - The available components * @param node - The node to parse * @returns */ function createElements( library: FormKitComponentLibrary, schema: FormKitSchemaNode | FormKitSchemaNode[] ): RenderChildren { if (Array.isArray(schema)) { const els = schema.map(createElement.bind(null, library)) return (iterationData?: Record<string, unknown>) => els.map((element) => element(iterationData)) } // Single node to render const element = createElement(library, schema) return (iterationData?: Record<string, unknown>) => element(iterationData) } /** * Data providers produced as a result of the compiler. */ const providers: ProviderRegistry = [] /** * Append the requisite compiler provider and return the compiled function. * @param compiled - A compiled function * @returns */ function provider( compiled: FormKitCompilerOutput, hints: Record<string, boolean> = {} ) { const compiledFns: Record<symbol, FormKitCompilerOutput> = {} providers.push((callback: SchemaProviderCallback, key: symbol) => { compiledFns[key] = compiled.provide((tokens) => callback(tokens, hints)) }) return () => compiledFns[instanceKey]() } /** * Creates a new instance of a given schema — this either comes from a * memoized copy of the parsed schema or a freshly parsed version. An symbol * instance key, and dataProvider functions are passed in. * @param providerCallback - A function that is called for each required provider * @param key - a symbol representing the current instance */ return function createInstance( providerCallback: SchemaProviderCallback, key ) { const memoKey = JSON.stringify(schema) const [render, compiledProviders] = has(memo, memoKey) ? memo[memoKey] : [createElements(library, schema), providers] memo[memoKey] = [render, compiledProviders] compiledProviders.forEach((compiledProvider) => { compiledProvider(providerCallback, key) }) return () => { instanceKey = key return render() } } } /** * Checks the current runtime scope for data. * @param token - The token to lookup in the current scope * @param defaultValue - The default ref value to use if no scope is found. */ function useScope(token: string, defaultValue: any) { const scopedData = instanceScopes.get(instanceKey) || [] let scopedValue: any = undefined if (scopedData.length) { scopedValue = getValue(scopedData, token.split('.')) } return scopedValue === undefined ? defaultValue : scopedValue } /** * Get the current scoped data and flatten it. */ function slotData(data: Record<string, any>, key: symbol) { return new Proxy(data, { get(...args) { let data: any = undefined const property = args[1] if (typeof property === 'string') { const prevKey = instanceKey instanceKey = key data = useScope(property, undefined) instanceKey = prevKey } return data !== undefined ? data : Reflect.get(...args) }, }) } /** * Provides data to a parsed schema. * @param provider - The SchemaProvider (output of calling parseSchema) * @param data - Data to fetch values from * @returns */ function createRenderFn( instanceCreator: SchemaProvider, data: Record<string, any>, instanceKey: symbol ) { return instanceCreator( (requirements, hints: Record<string, boolean> = {}) => { return requirements.reduce((tokens, token) => { if (token.startsWith('slots.')) { const slot = token.substring(6) const hasSlot = data.slots && has(data.slots, slot) if (hints.if) { // If statement — dont render the slot, check if it exists tokens[token] = () => hasSlot } else if (data.slots && hasSlot) { // Render the slot with current scope data const scopedData = slotData(data, instanceKey) tokens[token] = () => data.slots[slot](scopedData) return tokens } } const value = getRef(token, data) tokens[token] = () => useScope(token, value.value) return tokens }, {} as Record<string, any>) }, instanceKey ) } let i = 0 /** * The FormKitSchema vue component: * @public */ export const FormKitSchema = defineComponent({ name: 'FormKitSchema', props: { schema: { type: [Array, Object] as PropType< FormKitSchemaNode[] | FormKitSchemaCondition >, required: true, }, data: { type: Object as PropType<Record<string, any>>, default: () => ({}), }, library: { type: Object as PropType<FormKitComponentLibrary>, default: () => ({}), }, }, setup(props, context) { const instance = getCurrentInstance() let instanceKey = Symbol(String(i++)) instanceScopes.set(instanceKey, []) let provider = parseSchema(props.library, props.schema) let render: RenderChildren let data: Record<string, any> // Re-parse the schema if it changes: watch( () => props.schema, (newSchema, oldSchema) => { instanceKey = Symbol(String(i++)) provider = parseSchema(props.library, props.schema) render = createRenderFn(provider, data, instanceKey) if (newSchema === oldSchema) { // In this edge case, someone pushed/modified something in the schema // and we've successfully re-parsed, but since the schema is not // referenced in the render function it technically isnt a dependency // and we need to force a re-render since we swapped out the render // function completely. ;(instance?.proxy?.$forceUpdate as unknown as CallableFunction)() } }, { deep: true } ) // Watch the data object explicitly watchEffect(() => { data = Object.assign(reactive(props.data), { slots: context.slots, }) render = createRenderFn(provider, data, instanceKey) }) return () => render() }, }) export default FormKitSchema
the_stack
import type { IncomingMessage } from 'http' import type { Assert } from '@japa/assert' import type { CorsConfig } from '@ioc:Adonis/Core/Cors' const corsConfig = { enabled: true, origin: true, methods: ['GET', 'PUT', 'POST'], headers: true, credentials: true, maxAge: 90, exposeHeaders: [], } const CORS_HEADERS = [ 'access-control-allow-origin', 'access-control-allow-credentials', 'access-control-expose-headers', 'access-control-allow-headers', 'access-control-allow-methods', 'access-control-max-age', ] /** * Fixtures that tests the cors functionality as * per https://www.w3.org/TR/cors/ RFC. */ export const specFixtures = [ { title: 'do not set any headers when origin is not defined', configureOptions(): CorsConfig { return Object.assign({}, corsConfig) }, configureRequest() {}, assertNormal(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, }, { title: 'do not set any headers when origin mis-matches', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: 'adonisjs.com', }) }, configureRequest(req: IncomingMessage) { req.headers = { origin: 'foo.com', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, }, { title: 'do not set any headers when all origins are dis-allowed', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: false, }) }, configureRequest(req: IncomingMessage) { req.headers = { origin: 'foo.com', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, }, { title: 'do not set headers when origin case sensitive match fails', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: 'foo.com', }) }, configureRequest(req: IncomingMessage) { req.headers = { origin: 'FOO.com', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, }, { title: "do not set headers when current origin isn't inside array of allowed origins", configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: ['foo.com'], }) }, configureRequest(req: IncomingMessage) { req.headers = { origin: 'bar.com', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, }, { title: 'allow all origins when origin is set to true', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: true, }) }, configureRequest(req: IncomingMessage) { req.headers = { origin: 'foo.com', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ( ['access-control-allow-origin', 'access-control-allow-credentials'].indexOf(key) === -1 ) }) ) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, }, { title: 'allow origin when current origin is in allowed array list', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: ['foo.com', 'bar.com'], }) }, configureRequest(req: IncomingMessage) { req.headers = { origin: 'foo.com', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ( ['access-control-allow-origin', 'access-control-allow-credentials'].indexOf(key) === -1 ) }) ) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, }, { title: 'allow origin when current origin is in allowed comma seperated list', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: 'foo.com,bar.com', }) }, configureRequest(req: IncomingMessage) { req.headers = { origin: 'foo.com', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ( ['access-control-allow-origin', 'access-control-allow-credentials'].indexOf(key) === -1 ) }) ) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, }, { title: 'allow origin when config function returns true', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: () => true, }) }, configureRequest(req: IncomingMessage) { req.headers = { origin: 'foo.com', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ( ['access-control-allow-origin', 'access-control-allow-credentials'].indexOf(key) === -1 ) }) ) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, }, { title: 'set current origin when using wildcard identifier with credentails=true', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: '*', }) }, configureRequest(req: IncomingMessage) { req.headers = { origin: 'foo.com', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ( ['access-control-allow-origin', 'access-control-allow-credentials'].indexOf(key) === -1 ) }) ) assert.equal(res.headers['access-control-allow-origin'], 'foo.com') }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, }, { title: 'set wildcard when using wildcard identifier with credentails=false', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: '*', credentials: false, }) }, configureRequest(req: IncomingMessage) { req.headers = { origin: 'foo.com', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return key !== 'access-control-allow-origin' }) ) assert.equal(res.headers['access-control-allow-origin'], '*') }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, }, { title: 'set expose headers when defined', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: '*', exposeHeaders: ['X-Adonis'], }) }, configureRequest(req: IncomingMessage) { req.headers = { origin: 'foo.com', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ( [ 'access-control-allow-origin', 'access-control-allow-credentials', 'access-control-expose-headers', ].indexOf(key) === -1 ) }) ) assert.equal(res.headers['access-control-allow-origin'], 'foo.com') assert.equal(res.headers['access-control-expose-headers'], 'x-adonis') }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, }, { title: 'set required preflight headers when request method exists', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: true, }) }, configureRequest(req: IncomingMessage) { req.headers = { 'origin': 'foo.com', 'access-control-request-method': 'GET', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ( ['access-control-allow-origin', 'access-control-allow-credentials'].indexOf(key) === -1 ) }) ) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ['access-control-expose-headers'].indexOf(key) > -1 }) ) }, }, { title: "do not set preflight headers when request method isn't allowed", configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: true, }) }, configureRequest(req: IncomingMessage) { req.headers = { 'origin': 'foo.com', 'access-control-request-method': 'DELETE', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ( ['access-control-allow-origin', 'access-control-allow-credentials'].indexOf(key) === -1 ) }) ) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, }, { title: 'do not set preflight headers when all of the request headers are not allowed', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: true, headers: false, }) }, configureRequest(req: IncomingMessage) { req.headers = { 'origin': 'foo.com', 'access-control-request-method': 'GET', 'access-control-request-headers': 'X-Adonis', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ( ['access-control-allow-origin', 'access-control-allow-credentials'].indexOf(key) === -1 ) }) ) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, }, { title: 'do not set preflight headers when any of the request headers are not allowed', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: true, headers: ['cache-control'], }) }, configureRequest(req: IncomingMessage) { req.headers = { 'origin': 'foo.com', 'access-control-request-method': 'GET', 'access-control-request-headers': 'X-Adonis', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ( ['access-control-allow-origin', 'access-control-allow-credentials'].indexOf(key) === -1 ) }) ) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, }, { title: 'set preflight headers when all of the request headers are allowed', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: true, headers: true, }) }, configureRequest(req: IncomingMessage) { req.headers = { 'origin': 'foo.com', 'access-control-request-method': 'GET', 'access-control-request-headers': 'X-Adonis', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ( ['access-control-allow-origin', 'access-control-allow-credentials'].indexOf(key) === -1 ) }) ) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ['access-control-expose-headers'].indexOf(key) > -1 }) ) assert.equal(res.headers['access-control-allow-headers'], 'x-adonis') }, }, { title: 'set preflight headers when request headers is in the list of allowed headers', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: true, headers: ['X-Adonis'], }) }, configureRequest(req: IncomingMessage) { req.headers = { 'origin': 'foo.com', 'access-control-request-method': 'GET', 'access-control-request-headers': 'X-Adonis', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ( ['access-control-allow-origin', 'access-control-allow-credentials'].indexOf(key) === -1 ) }) ) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ['access-control-expose-headers'].indexOf(key) > -1 }) ) assert.equal(res.headers['access-control-allow-headers'], 'x-adonis') }, }, { title: 'set preflight headers when request headers is in the list of comma seperated list', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: true, headers: 'X-Adonis,X-Time', }) }, configureRequest(req: IncomingMessage) { req.headers = { 'origin': 'foo.com', 'access-control-request-method': 'GET', 'access-control-request-headers': 'origin,X-Adonis', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ( ['access-control-allow-origin', 'access-control-allow-credentials'].indexOf(key) === -1 ) }) ) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ['access-control-expose-headers'].indexOf(key) > -1 }) ) assert.equal(res.headers['access-control-allow-headers'], 'x-adonis,x-time') }, }, { title: 'set preflight headers when case insensitive match passes', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: true, headers: ['x-adonis'], }) }, configureRequest(req: IncomingMessage) { req.headers = { 'origin': 'foo.com', 'access-control-request-method': 'GET', 'access-control-request-headers': 'X-Adonis', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ( ['access-control-allow-origin', 'access-control-allow-credentials'].indexOf(key) === -1 ) }) ) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ['access-control-expose-headers'].indexOf(key) > -1 }) ) assert.equal(res.headers['access-control-allow-headers'], 'x-adonis') }, }, { title: 'set all allow headers when request header match passes', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: true, headers: ['x-adonis', 'x-foo', 'x-bar'], }) }, configureRequest(req: IncomingMessage) { req.headers = { 'origin': 'foo.com', 'access-control-request-method': 'GET', 'access-control-request-headers': 'X-Adonis', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ( ['access-control-allow-origin', 'access-control-allow-credentials'].indexOf(key) === -1 ) }) ) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ['access-control-expose-headers'].indexOf(key) > -1 }) ) assert.equal(res.headers['access-control-allow-headers'], 'x-adonis,x-foo,x-bar') }, }, { title: 'set allow headers when headers config function returns true', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: true, headers: () => true, }) }, configureRequest(req: IncomingMessage) { req.headers = { 'origin': 'foo.com', 'access-control-request-method': 'GET', 'access-control-request-headers': 'X-Adonis', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ( ['access-control-allow-origin', 'access-control-allow-credentials'].indexOf(key) === -1 ) }) ) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ['access-control-expose-headers'].indexOf(key) > -1 }) ) assert.equal(res.headers['access-control-allow-headers'], 'x-adonis') }, }, { title: 'set max age when defined', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: true, headers: () => true, maxAge: 10, }) }, configureRequest(req: IncomingMessage) { req.headers = { 'origin': 'foo.com', 'access-control-request-method': 'GET', 'access-control-request-headers': 'X-Adonis', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ( ['access-control-allow-origin', 'access-control-allow-credentials'].indexOf(key) === -1 ) }) ) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ['access-control-expose-headers'].indexOf(key) > -1 }) ) assert.equal(res.headers['access-control-max-age'], '10') }, }, { title: 'set expose headers when defined', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { origin: true, headers: () => true, exposeHeaders: ['x-response-time'], maxAge: 10, }) }, configureRequest(req: IncomingMessage) { req.headers = { 'origin': 'foo.com', 'access-control-request-method': 'GET', 'access-control-request-headers': 'X-Adonis', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties( res.headers, CORS_HEADERS.filter((key) => { return ( [ 'access-control-allow-origin', 'access-control-allow-credentials', 'access-control-expose-headers', ].indexOf(key) === -1 ) }) ) }, assertOptions(assert: Assert, res: any) { assert.properties(res.headers, CORS_HEADERS) assert.equal(res.headers['access-control-expose-headers'], 'x-response-time') }, }, { title: 'do not set any headers when cors is disabled', configureOptions(): CorsConfig { return Object.assign({}, corsConfig, { enabled: false, }) }, configureRequest(req: IncomingMessage) { req.headers = { origin: 'foo.com', } }, assertNormal(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, assertOptions(assert: Assert, res: any) { assert.notAnyProperties(res.headers, CORS_HEADERS) }, }, ]
the_stack
declare module "@luma.gl/gltools/polyfill/polyfill-vertex-array-object" { export function polyfillVertexArrayObject(gl: any): void; } declare module "@luma.gl/gltools/utils/utils" { export function assert(condition: any, message: any): void; export function isObjectEmpty(object: any): boolean; export function deepArrayEqual(x: any, y: any): boolean; } declare module "@luma.gl/gltools/utils/device-pixels" { export function cssToDeviceRatio(gl: any): number; export function cssToDevicePixels( gl: any, cssPixel: any, yInvert?: boolean ): { x: number; y: number; width: number; height: number; }; /** * Calulates device pixel ratio, used during context creation * * @param {boolean or Number} useDevicePixels - boolean or a Number * @return {Number} - device pixel ratio */ export function getDevicePixelRatio(useDevicePixels: any): any; } declare module "@luma.gl/gltools/utils/webgl-checks" { export const ERR_CONTEXT = "Invalid WebGLRenderingContext"; export const ERR_WEBGL = "Invalid WebGLRenderingContext"; export const ERR_WEBGL2 = "Requires WebGL2"; export function isWebGL(gl: any): boolean; export function isWebGL2(gl: any): boolean; export function assertWebGLContext(gl: any): void; export function assertWebGL2Context(gl: any): void; } declare module "@luma.gl/gltools/utils" { export { assert, deepArrayEqual, isObjectEmpty, } from "@luma.gl/gltools/utils/utils"; export { cssToDevicePixels, cssToDeviceRatio, getDevicePixelRatio, } from "@luma.gl/gltools/utils/device-pixels"; export { isWebGL, isWebGL2 } from "@luma.gl/gltools/utils/webgl-checks"; export const log: any; } declare module "@luma.gl/gltools/polyfill/get-parameter-polyfill" { export function getParameterPolyfill( gl: any, originalGetParameter: any, pname: any ): any; } declare module "@luma.gl/gltools/polyfill/polyfill-table" { import { getParameterPolyfill } from "@luma.gl/gltools/polyfill/get-parameter-polyfill"; export const WEBGL2_CONTEXT_POLYFILLS: { OES_vertex_array_object: { meta: { suffix: string; }; createVertexArray: () => void; deleteVertexArray: () => void; bindVertexArray: () => void; isVertexArray: () => boolean; }; ANGLE_instanced_arrays: { meta: { suffix: string; }; vertexAttribDivisor(location: any, divisor: any): void; drawElementsInstanced: () => void; drawArraysInstanced: () => void; }; WEBGL_draw_buffers: { meta: { suffix: string; }; drawBuffers: () => void; }; EXT_disjoint_timer_query: { meta: { suffix: string; }; createQuery: () => void; deleteQuery: () => void; beginQuery: () => void; endQuery: () => void; getQuery(handle: any, pname: any): any; getQueryParameter(handle: any, pname: any): any; getQueryObject: () => void; }; }; export const WEBGL2_CONTEXT_OVERRIDES: { readBuffer: (gl: any, originalFunc: any, attachment: any) => void; getVertexAttrib: ( gl: any, originalFunc: any, location: any, pname: any ) => any; getProgramParameter: ( gl: any, originalFunc: any, program: any, pname: any ) => any; getInternalformatParameter: ( gl: any, originalFunc: any, target: any, format: any, pname: any ) => any; getTexParameter(gl: any, originalFunc: any, target: any, pname: any): any; getParameter: typeof getParameterPolyfill; hint(gl: any, originalFunc: any, pname: any, value: any): any; }; } declare module "@luma.gl/gltools/polyfill/polyfill-context" { export default function polyfillContext(gl: any): any; } declare module "@luma.gl/gltools/state-tracker/webgl-parameter-tables" { export const GL_PARAMETER_DEFAULTS: { [x: number]: any; }; export const GL_PARAMETER_SETTERS: { [x: number]: | string | ((gl: any, value: any, key: any) => any) | ((gl: any, value: any) => any); framebuffer: (gl: any, framebuffer: any) => any; blend: (gl: any, value: any) => any; blendColor: (gl: any, value: any) => any; blendEquation: (gl: any, args: any) => void; blendFunc: (gl: any, args: any) => void; clearColor: (gl: any, value: any) => any; clearDepth: (gl: any, value: any) => any; clearStencil: (gl: any, value: any) => any; colorMask: (gl: any, value: any) => any; cull: (gl: any, value: any) => any; cullFace: (gl: any, value: any) => any; depthTest: (gl: any, value: any) => any; depthFunc: (gl: any, value: any) => any; depthMask: (gl: any, value: any) => any; depthRange: (gl: any, value: any) => any; dither: (gl: any, value: any) => any; derivativeHint: (gl: any, value: any) => void; frontFace: (gl: any, value: any) => any; mipmapHint: (gl: any, value: any) => any; lineWidth: (gl: any, value: any) => any; polygonOffsetFill: (gl: any, value: any) => any; polygonOffset: (gl: any, value: any) => any; sampleCoverage: (gl: any, value: any) => any; scissorTest: (gl: any, value: any) => any; scissor: (gl: any, value: any) => any; stencilTest: (gl: any, value: any) => any; stencilMask: (gl: any, value: any) => void; stencilFunc: (gl: any, args: any) => void; stencilOp: (gl: any, args: any) => void; viewport: (gl: any, value: any) => any; }; export const GL_COMPOSITE_PARAMETER_SETTERS: { blendEquation: (gl: any, values: any, cache: any) => any; blendFunc: (gl: any, values: any, cache: any) => any; polygonOffset: (gl: any, values: any, cache: any) => any; sampleCoverage: (gl: any, values: any, cache: any) => any; stencilFuncFront: (gl: any, values: any, cache: any) => any; stencilFuncBack: (gl: any, values: any, cache: any) => any; stencilOpFront: (gl: any, values: any, cache: any) => any; stencilOpBack: (gl: any, values: any, cache: any) => any; }; export const GL_HOOKED_SETTERS: { enable: (update: any, capability: any) => any; disable: (update: any, capability: any) => any; pixelStorei: (update: any, pname: any, value: any) => any; hint: (update: any, pname: any, hint: any) => any; bindFramebuffer: (update: any, target: any, framebuffer: any) => any; blendColor: (update: any, r: any, g: any, b: any, a: any) => any; blendEquation: (update: any, mode: any) => any; blendEquationSeparate: (update: any, modeRGB: any, modeAlpha: any) => any; blendFunc: (update: any, src: any, dst: any) => any; blendFuncSeparate: ( update: any, srcRGB: any, dstRGB: any, srcAlpha: any, dstAlpha: any ) => any; clearColor: (update: any, r: any, g: any, b: any, a: any) => any; clearDepth: (update: any, depth: any) => any; clearStencil: (update: any, s: any) => any; colorMask: (update: any, r: any, g: any, b: any, a: any) => any; cullFace: (update: any, mode: any) => any; depthFunc: (update: any, func: any) => any; depthRange: (update: any, zNear: any, zFar: any) => any; depthMask: (update: any, mask: any) => any; frontFace: (update: any, face: any) => any; lineWidth: (update: any, width: any) => any; polygonOffset: (update: any, factor: any, units: any) => any; sampleCoverage: (update: any, value: any, invert: any) => any; scissor: (update: any, x: any, y: any, width: any, height: any) => any; stencilMask: (update: any, mask: any) => any; stencilMaskSeparate: (update: any, face: any, mask: any) => any; stencilFunc: (update: any, func: any, ref: any, mask: any) => any; stencilFuncSeparate: ( update: any, face: any, func: any, ref: any, mask: any ) => any; stencilOp: (update: any, fail: any, zfail: any, zpass: any) => any; stencilOpSeparate: ( update: any, face: any, fail: any, zfail: any, zpass: any ) => any; viewport: (update: any, x: any, y: any, width: any, height: any) => any; }; export const GL_PARAMETER_GETTERS: { [x: number]: (gl: any, key: any) => any; }; } declare module "@luma.gl/gltools/state-tracker/track-context-state" { /** * Initialize WebGL state caching on a context * can be called multiple times to enable/disable * @param {WebGLRenderingContext} - context */ export default function trackContextState( gl: any, { enable, copyState, }?: { enable?: boolean; copyState: any; } ): any; export function pushContextState(gl: any): void; export function popContextState(gl: any): void; } declare module "@luma.gl/gltools/state-tracker/unified-parameter-api" { export function setParameters(gl: any, values: any): void; export function getParameters(gl: any, parameters: any): any; export function resetParameters(gl: any): void; export function withParameters(gl: any, parameters: any, func: any): any; } declare module "@luma.gl/gltools/context/context" { export const ERR_CONTEXT = "Invalid WebGLRenderingContext"; export const ERR_WEBGL = "Invalid WebGLRenderingContext"; export const ERR_WEBGL2 = "Requires WebGL2"; export function createGLContext(options?: {}): any; export function instrumentGLContext(gl: any, options?: {}): any; /** * Provides strings identifying the GPU vendor and driver. * https://www.khronos.org/registry/webgl/extensions/WEBGL_debug_renderer_info/ * @param {WebGLRenderingContext} gl - context * @return {Object} - 'vendor' and 'renderer' string fields. */ export function getContextDebugInfo( gl: any ): { vendor: any; renderer: any; vendorMasked: any; rendererMasked: any; version: any; shadingLanguageVersion: any; }; /** * Resize the canvas' drawing buffer. * * Can match the canvas CSS size, and optionally also consider devicePixelRatio * Can be called every frame * * Regardless of size, the drawing buffer will always be scaled to the viewport, but * for best visual results, usually set to either: * canvas CSS width x canvas CSS height * canvas CSS width * devicePixelRatio x canvas CSS height * devicePixelRatio * See http://webgl2fundamentals.org/webgl/lessons/webgl-resizing-the-canvas.html * * resizeGLContext(gl, {width, height, useDevicePixels}) */ export function resizeGLContext(gl: any, options?: {}): void; } declare module "@luma.gl/gltools" { export { default as polyfillContext } from "@luma.gl/gltools/polyfill/polyfill-context"; export { getParameters, setParameters, resetParameters, withParameters, } from "@luma.gl/gltools/state-tracker/unified-parameter-api"; export { default as trackContextState, pushContextState, popContextState, } from "@luma.gl/gltools/state-tracker/track-context-state"; export { createGLContext, resizeGLContext, instrumentGLContext, getContextDebugInfo, } from "@luma.gl/gltools/context/context"; export { log, cssToDeviceRatio, cssToDevicePixels, isWebGL, isWebGL2, } from "@luma.gl/gltools/utils"; }
the_stack
import axios from "axios"; import { autobind } from "core-decorators"; import * as _ from "lodash"; import { inject, observer } from "mobx-react"; import * as React from "react"; import { Button, Dropdown, Form, Header, Icon, Image, Input, Message, Modal, Popup, Radio, Reveal, Segment, } from "semantic-ui-react"; import { allowedItunesCategories } from "../../../lib/constants"; import { IPodcast } from "../../../lib/interfaces"; import { colors, globalStyles } from "../../../lib/styles"; import { RootState } from "../../../state/RootState"; import AvatarEditor from "../generic/AvatarEditor"; import { Link } from "react-router-dom"; interface IPodcastEditFormProps { onSubmit: (formState: IPodcastEditFormFields, noRedirect: boolean) => Promise<void>; getUploadPolicy: (file: File) => Promise<{ uploadUrl: string, publicFileUrl: string }>; uploadFile: (file: File, policyUrl: string) => Promise<void>; onSendInvite: (email: string) => Promise<void>; onRemoveCollaborators: (collaborators: any[]) => Promise<void>; currentPodcast?: IPodcast; rootState?: RootState; } export interface IPodcastEditFormFields { title: string; subtitle: string; author: string; keywords: string; categories: string; imageUrl: string; email: string; advertisingEnabled: boolean; socialNetEnabled: boolean; } export interface IPodcastEditFormState { fields: IPodcastEditFormFields; uploading: boolean; imagePreviewUrl: string; error: string; categoryWarning?: string; addCollaboratorModal: boolean; removeCollaboratorModal: boolean; invitationEmail?: string; inviteError?: string; collaborators: any[]; removedCollaborators: any[]; loadingCollaborators: boolean; isCropping: boolean; isSocialSubscriptionActive: boolean; socialNetStatusChange: boolean; file?: any; } function getBaseUrl() { const re = new RegExp(/^.*\//); return re.exec(window.location.href)[0].replace("/#/", "/"); } function validateEmail(email) { const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } const options = [ { key: "Technology", text: "Technology", value: "Technology" }, { key: "Entertainment", text: "Entertainment", value: "Entertainment" }, { key: "Design", text: "Design", value: "Design" }, ]; @inject("rootState") @observer export default class PodcastEditForm extends React.Component<IPodcastEditFormProps, IPodcastEditFormState> { public state: IPodcastEditFormState = { uploading: false, imagePreviewUrl: null, error: null, categoryWarning: null, fields: { title: "", subtitle: "", author: "", keywords: "", categories: "", imageUrl: "", email: "", advertisingEnabled: false, socialNetEnabled: false }, addCollaboratorModal: false, removeCollaboratorModal: false, collaborators: [], removedCollaborators: [], loadingCollaborators: false, isCropping: false, isSocialSubscriptionActive: false, socialNetStatusChange: false, }; constructor(props: IPodcastEditFormProps) { super(); if (props.currentPodcast) { const userEmail = _.get(props, "rootState.me.email", ""); const { title, subtitle, author, keywords, categories, imageUrl, email, advertisingEnabled, socialNetEnabled } = props.currentPodcast; this.state = { fields: { title, subtitle, author, keywords, categories, imageUrl, email: (email || userEmail || ""), advertisingEnabled: advertisingEnabled || false, socialNetEnabled: socialNetEnabled || false, }, uploading: false, imagePreviewUrl: null, error: null, addCollaboratorModal: false, removeCollaboratorModal: false, collaborators: [], loadingCollaborators: false, removedCollaborators: [], isCropping: false, socialNetStatusChange: false, isSocialSubscriptionActive: props.currentPodcast.subscription ? props.currentPodcast.subscription.storageLimit === 1000 : false, }; } } @autobind public render() { const userEmail = _.get(this.props, "rootState.me.email", ""); return ( <Segment style={{ width: "75%", paddingBottom: 100, paddingLeft: 0 }} basic clearing> {this.renderError()} <Form loading={this.state.uploading}> <Header as="h2" style={globalStyles.title}> Settings <div style={{ display: "flex", flex: 1, justifyContent: "center", }}> <Popup trigger={ <Form.Button onClick={(e) => this.toggleAddCollab(e)} style={styles.actionIcon} icon> <Icon size="small" name="add user" /> </Form.Button>} style={styles.tooltip} basic size="tiny" content="Add collaborator" /> {this.props.currentPodcast.owner.length > 1 ? <Popup trigger={ <Form.Button onClick={(e) => this.toggleRemoveCollab(e)} style={styles.actionIcon} icon> <Icon size="small" name="remove user" /> </Form.Button> } style={styles.tooltip} basic size="tiny" content="Remove collaborator" /> : null } </div> </Header> <p style={{ ...globalStyles.workspaceContentText, marginBottom: "2em" }}> The podcast information on this page will publish to iTunes and Google Play. </p> {/* {this.props.rootState.env.AD_PLACEMENT === "true" ? <div style={{ display: "flex", flexDirection: "row", flex: 1, }}> <Radio onClick={(e) => { const fields = this.state.fields; this.setState({ fields: { ...fields, advertisingEnabled: !fields.advertisingEnabled, }, }); }} checked={this.state.fields.advertisingEnabled} toggle /> <div style={{ marginLeft: 15, display: "flex", flex: 1, color: colors.mainDark, }}> {this.state.fields.advertisingEnabled ? "Disable" : "Enable"} Advertising </div> </div> : null } */} <p style={{ color: colors.mainDark, fontSize: "120%", marginBottom: 5, fontWeight: 600, }}>Cover Art</p> <p> <div style={{ display: "flex", flexDirection: "row" }}> <div style={styles.imagePreview} > <Reveal animated="fade" onClick={this.onFileUploadClick}> <Reveal.Content visible> <Image src={ this.state.imagePreviewUrl || this.state.fields.imageUrl || "/assets/image.png" } size="small" /> </Reveal.Content> <Reveal.Content hidden> <Icon name="upload" size="massive" style={styles.uploadIcon} /> </Reveal.Content> </Reveal> </div> </div> <input ref="podcastImgRef" onChange={this.onFileInput} type="file" style={styles.hidenInput} /> <p style={globalStyles.workspaceContentText}> Image must be between 1400 X 1400 and 3000 X 3000 </p> </p> <div style={{ display: "flex", flexDirection: "column", justifyContent: "flex-end", paddingTop: "20px", }}> <p style={{ color: colors.mainDark, fontSize: "120%", marginBottom: 5, fontWeight: 600, }}>RSS</p> <a href={getBaseUrl() + `p/${this.props.rootState.podcast.slug}/rss.xml`} target="_blank" style={{ color: colors.mainDark, fontSize: "120%", }}>{getBaseUrl() + `p/${this.props.rootState.podcast.slug}/rss.xml`}</a> </div> <Form.Field className="formInput" required> <div style={styles.formLabel}>Title</div> <Input style={styles.formInput} name="title" value={this.state.fields.title} onChange={this.onChangeInputField} required /> </Form.Field> <Form.Field className="formInput" required> <div style={styles.formLabel}>Subtitle</div> <Input style={styles.formInput} name="subtitle" value={this.state.fields.subtitle} onChange={this.onChangeInputField} required /> </Form.Field> <Form.Field className="formInput" required> <div style={styles.formLabel}>Author</div> <Input style={styles.formInput} name="author" value={this.state.fields.author} onChange={this.onChangeInputField} required /> </Form.Field> <Form.Field className="formInput"> <div style={styles.formLabel}>Email</div> <Input style={styles.formInput} name="email" value={this.state.fields.email || userEmail} onChange={this.onChangeInputField} required /> </Form.Field> <Form.Field className="formInput" required> <div style={styles.formLabel}>Keywords</div> <Input style={styles.formInput} name="keywords" value={this.state.fields.keywords} onChange={this.onChangeInputField} required /> </Form.Field> <Form.Field className="formInput" required> <div style={styles.formLabel}>Categories {this.state.categoryWarning ? <span style={styles.categoryErrorContainer}> {this.state.categoryWarning} <div onClick={() => this.setState({ categoryWarning: "" })} style={{ position: "absolute", top: 4, right: 4, cursor: "pointer", }}> <Icon name="delete" style={{ fontSize: "120%", }} /> </div> </span> : null } </div> <p style={globalStyles.workspaceContentText}> Although you can specify more than one category in your feed, the iTunes Store only recognizes the first category. </p> <Dropdown value={this.state.fields.categories ? this.state.fields.categories.split(",").map(x => x.trim()) : null} floating placeholder="Technology" fluid multiple selection options={this.getCategories()} onChange={(e, input) => { const categories = this.state.fields.categories.split(","); input.value = _.filter((input.value as string[]), (val) => { return !!val; }); if ((input.value as string[]).length > 3) { this.setState({ categoryWarning: "Only 3 categories are allowed." }); } else { this.setState({ categoryWarning: "", fields: { ...this.state.fields, categories: (input.value as string[]).join(","), }, }); } }} /> </Form.Field> <Button onClick={(e) => this.onSubmit(e)} style={{...styles.buttonStyle, backgroundColor: "#F4CB10"}}> Save </Button> </Form> <Modal open={this.state.addCollaboratorModal} closeOnEscape={true} closeOnRootNodeClick={true} size={"tiny" as "small"} > <Modal.Header style={{color: colors.mainDark}}> Add Collaborator </Modal.Header> <Modal.Content> {!!this.state.inviteError ? <Message color="red" content={this.state.inviteError} /> : null } <Input fluid type="email" onChange={(e, content) => this.onInvEmailChange(content)} placeholder="user@example.com" /> </Modal.Content> <Modal.Actions> <Button onClick={(e) => this.toggleAddCollab(e)} basic color="red">Cancel</Button> <Button onClick={(e) => this.sendInvite(e)} color="violet" labelPosition="right" icon="add" content="Add" /> </Modal.Actions> </Modal> <Modal open={this.state.removeCollaboratorModal} closeOnEscape={true} closeOnRootNodeClick={true} size={"tiny" as "small"} > <Icon style={styles.modalCloseButton} onClick={(e) => this.toggleRemoveCollab(e)} name="close" /> <Modal.Header> Remove User </Modal.Header> <Modal.Content> {this.state.collaborators.filter((user) => { return !(this.state.removedCollaborators as any).includes(user._id); }).length > 0 ? this.state.collaborators. filter((user) => { return !(this.state.removedCollaborators as any).includes(user._id); }) .map((user) => { return ( <div style={{ display: "flex", flexDirection: "row", flex: 1, }}> <span style={{ display: "flex", flex: 1, }}>{user.email}</span> <Icon onClick={() => this.addRemovable(user)} size="large" style={styles.removeIcon} name="remove" /> </div> ); }) : <span> You don't have any collaborators left to remove </span> } </Modal.Content> <Modal.Actions> <Button onClick={(e) => this.removeCollaborators(e)} positive style={styles.doneButton} content="Done" /> </Modal.Actions> </Modal> <AvatarEditor onFile={(file) => this.onEditedFile(file)} onClose={() => this.setState({ isCropping: false })} file={this.state.file} isOpen={this.state.isCropping} /> </Segment> ); } @autobind protected onEditedFile(file) { this.setState({ uploading: true, isCropping: false }); const reader = new FileReader(); reader.readAsDataURL(file); reader.onloadend = () => { this.setState({ imagePreviewUrl: reader.result, error: null }); const img = document.createElement("img"); this.props.getUploadPolicy(file).then(async (policyData) => { const { uploadUrl, publicFileUrl } = policyData; await this.props.uploadFile(file, uploadUrl); // tslint:disable-next-line:prefer-object-spread const fields = Object.assign({}, this.state.fields, { imageUrl: publicFileUrl }); this.setState({ fields, uploading: false }); }).catch((err: Error) => { alert(err.message); this.setState({ uploading: false }); }); img.src = reader.result; }; } @autobind protected addRemovable(user) { const removedCollaborators = this.state.removedCollaborators; removedCollaborators.push(user._id); this.setState({ removedCollaborators }); } @autobind protected toggleAddCollab(e) { e.preventDefault(); this.setState({ addCollaboratorModal: !this.state.addCollaboratorModal }); } @autobind protected toggleRemoveCollab(e) { e.preventDefault(e); if (!this.state.removeCollaboratorModal) { this.getCollaborators(); } this.setState({ removeCollaboratorModal: !this.state.removeCollaboratorModal, removedCollaborators: [], }); } @autobind protected async getCollaborators() { try { const response = await axios.post("/get-collaborators"); this.setState({ collaborators: response.data.collaborators }); } catch (e) { this.setState({ removeCollaboratorModal: false, inviteError: "Could not load collaborators, please try again later", }); } } @autobind protected onInvEmailChange(content) { this.setState({ invitationEmail: content.value }); } @autobind protected sendInvite(e) { e.preventDefault(e); const isValidEmail = validateEmail(this.state.invitationEmail); if (isValidEmail) { this.toggleAddCollab(e); this.props.onSendInvite(this.state.invitationEmail); } else { this.setState({ inviteError: "Invalid Email, please make sure you entered everything correctly" }); } } @autobind protected removeCollaborators(e) { e.preventDefault(); this.toggleRemoveCollab(e); if (this.state.removedCollaborators.length > 0) { this.props.onRemoveCollaborators(this.state.removedCollaborators); } } @autobind protected onFileUploadClick(e: MouseEvent) { const inputField: any = this.refs.podcastImgRef; inputField.click(); } @autobind protected onFileInput(e: React.ChangeEvent<HTMLInputElement>) { e.preventDefault(); if (e.target && e.target.files && e.target.files.length) { const file = e.target.files[0]; const reader = new FileReader(); reader.onloadend = () => { this.setState({ imagePreviewUrl: reader.result, error: null }); const img = document.createElement("img"); img.onload = () => { // Check if width and height are between 1400X1400 and 3000X3000 if ((this as any).width < 1400 || (this as any).width > 3000 || (this as any).height < 1400 || (this as any).height > 3000) { // We only check the width since we know that the width and height are equal return this.setState({ uploading: false, imagePreviewUrl: null, error: "Invalid image dimensions, width and height must" + " be between 1400 X 1400 and 3000 X 3000.", }); } this.setState({ isCropping: true, file }); }; img.src = reader.result; }; reader.readAsDataURL(file); } } protected renderError() { if (!this.state.error) { return null; } return ( <Message error header="Error" content={this.state.error} /> ); } @autobind protected onChangeInputField(e: React.ChangeEvent<HTMLInputElement>, input: any) { if (input && input.name) { // tslint:disable-next-line:prefer-object-spread const fields = Object.assign({}, this.state.fields, { [input.name]: input.value }); this.setState({ fields }); } } @autobind protected async onSubmit(e: any) { e.preventDefault(); const fields = JSON.parse(JSON.stringify({...this.state.fields, socialNetStatusChange: this.state.socialNetStatusChange})); if (!fields.email) { const userEmail = _.get(this.props, "rootState.me.email", ""); fields.email = userEmail; } await this.props.onSubmit(fields, true); } private getCategories(): Array<{ key: string, text: string, value: string }> { const result: Array<{ key: string, text: string, value: string, }> = []; Object.keys(allowedItunesCategories).forEach(category => { result.push({ key: category, text: category, value: category, }); allowedItunesCategories[category].forEach(subCategory => { result.push({ key: `${category} - ${subCategory}`, text: `${category} - ${subCategory}`, value: `${category} - ${subCategory}`, }); }); }); return result; } } const styles = { buttonStyle: { marginTop: "1em", fontWeight: 550, fontSize: "120%", color: "black", }, formLabel: { display: "flex", minWidth: 80, textAlign: "left", fontSize: "120%" as "120%", color: colors.mainDark, fontWeight: 600, marginBottom: 15, marginTop: 40, } as React.CSSProperties, formInput: { minWidth: "75%", color: colors.mainLight, }, hidenInput: { display: "none", visibility: "hidden", }, imagePreview: { width: 150, height: 150, backgroundColor: "#ffffff", cursor: "pointer", padding: "5px", border: "solid", borderColor: "#f1efef", borderWidth: "1px", }, uploadIcon: { margin: 10 }, actionIcon: { fontSize: "160%", backgroundColor: "transparent", paddingLeft: 0, paddingRight: 0, paddingTop: 5, alignSelf: "flex-end", }, tooltip: { ...globalStyles.tooltip, margin: 0, marginBottom: -10, marginLeft: 15, }, header: { color: colors.mainDark, display: "flex", flexDirection: "row", }, categoryErrorContainer: { backgroundColor: "#E7C2CB", color: "#E37A8C", padding: 5, paddingLeft: 15, paddingRight: 60, marginLeft: 15, marginTop: -4, display: "flex", flexDirection: "row" as "row", fontSize: "80%", position: "relative" as "relative", borderRadius: 3, borderColor: "lightgray", borderWidth: 1, borderStyle: "solid", }, modalCloseButton: { position: "absolute", top: 12.5, right: 5, color: colors.mainDark, }, doneButton: { backgroundColor: colors.mainDark, }, removeIcon: { color: "gray", cursor: "pointer", }, };
the_stack
import * as cdk from "@aws-cdk/core"; import * as eventLambda from "@aws-solutions-constructs/aws-events-rule-lambda"; import * as lambda from "@aws-cdk/aws-lambda"; import * as s3 from "@aws-cdk/aws-s3"; import * as iam from "@aws-cdk/aws-iam"; import * as events from "@aws-cdk/aws-events"; import { PolicyDocument, PolicyStatement, Effect } from "@aws-cdk/aws-iam"; import { Aws, CfnResource, CfnStack } from "@aws-cdk/core"; import { LimitMonitorStackProps } from '../bin/limit-monitor'; export class LimitMonitorSpokeStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props: LimitMonitorStackProps) { super(scope, id, props) const primaryAccount = new cdk.CfnParameter(this, 'MasterAccount', { description: 'Account Id for the master account, eg. 111111111111', type: 'String', allowedPattern: '^\\d{12}$' }) const metricsMap = new cdk.CfnMapping(this, 'MetricsMap') metricsMap.setValue('Send-Data', 'SendAnonymousData', 'Yes') const refreshRate = new cdk.CfnMapping(this, 'RefreshRate') refreshRate.setValue('CronSchedule', 'Default', 'rate(1 day)') const eventsMap = new cdk.CfnMapping(this, 'EventsMap') eventsMap.setValue('Checks', 'Services', '"AutoScaling","CloudFormation","DynamoDB","EBS","EC2","ELB","IAM","Kinesis","RDS","Route53","SES","VPC"') const eventBusTarget = `arn:${cdk.Aws.PARTITION}:events:us-east-1:${primaryAccount.valueAsString}:event-bus/default` const eventOkTarget: events.IRuleTarget = { bind: () => ({ id: 'SpokeOkTarget', arn: eventBusTarget }) } const eventOkRule = new events.Rule(this, 'TAOkRule', { description: 'Limit Monitor Solution - Spoke - Rule for TA OK events', enabled: true, schedule: events.Schedule.expression('rate(24 hours)'), targets: [eventOkTarget] }) const eventOKRule_cfn_ref = eventOkRule.node.defaultChild as events.CfnRule eventOKRule_cfn_ref.overrideLogicalId('TAOkRule') eventOKRule_cfn_ref.addOverride('Properties.EventPattern', { "Fn::Join": [ "", [ "{\"account\":[\"", { "Ref": "AWS::AccountId" }, "\"],", "\"source\":[\"aws.trustedadvisor\", \"limit-monitor-solution\"],", "\"detail-type\":[\"Trusted Advisor Check Item Refresh Notification\", \"Limit Monitor Checks\"],", "\"detail\":{", "\"status\":[", "\"OK\"", "],", "\"check-item-detail\":{", "\"Service\":[", { "Fn::FindInMap": [ "EventsMap", "Checks", "Services" ] }, "]", "}", "}", "}" ] ] }) eventOKRule_cfn_ref.addPropertyDeletionOverride('ScheduleExpression') const eventWarnTarget: events.IRuleTarget = { bind: () => ({ id: 'SpokeWarnTarget', arn: eventBusTarget }) } const eventWarnRule = new events.Rule(this, 'TAWarnRule', { description: 'Limit Monitor Solution - Spoke - Rule for TA WARN events', enabled: true, schedule: events.Schedule.expression('rate(24 hours)'), targets: [eventWarnTarget] }) const eventWarnRule_cfn_ref = eventWarnRule.node.defaultChild as events.CfnRule eventWarnRule_cfn_ref.overrideLogicalId('TAWarnRule') eventWarnRule_cfn_ref.addOverride('Properties.EventPattern', { "Fn::Join": [ "", [ "{\"account\":[\"", { "Ref": "AWS::AccountId" }, "\"],", "\"source\":[\"aws.trustedadvisor\", \"limit-monitor-solution\"],", "\"detail-type\":[\"Trusted Advisor Check Item Refresh Notification\", \"Limit Monitor Checks\"],", "\"detail\":{", "\"status\":[", "\"WARN\"", "],", "\"check-item-detail\":{", "\"Service\":[", { "Fn::FindInMap": [ "EventsMap", "Checks", "Services" ] }, "]", "}", "}", "}" ] ] }) eventWarnRule_cfn_ref.addPropertyDeletionOverride('ScheduleExpression') const eventErrorTarget: events.IRuleTarget = { bind: () => ({ id: 'SpokeErrorTarget', arn: eventBusTarget }) } const eventErrorRule = new events.Rule(this, 'TASErrorRule', { description: 'Limit Monitor Solution - Spoke - Rule for TA ERROR events', enabled: true, schedule: events.Schedule.expression('rate(24 hours)'), targets: [eventErrorTarget] }) const eventErrorRule_cfn_ref = eventErrorRule.node.defaultChild as events.CfnRule eventErrorRule_cfn_ref.overrideLogicalId('TASErrorRule') eventErrorRule_cfn_ref.addOverride('Properties.EventPattern', { "Fn::Join": [ "", [ "{\"account\":[\"", { "Ref": "AWS::AccountId" }, "\"],", "\"source\":[\"aws.trustedadvisor\", \"limit-monitor-solution\"],", "\"detail-type\":[\"Trusted Advisor Check Item Refresh Notification\", \"Limit Monitor Checks\"],", "\"detail\":{", "\"status\":[", "\"ERROR\"", "],", "\"check-item-detail\":{", "\"Service\":[", { "Fn::FindInMap": [ "EventsMap", "Checks", "Services" ] }, "]", "}", "}", "}" ] ] }) eventErrorRule_cfn_ref.addPropertyDeletionOverride('ScheduleExpression') const solutionsLambdaCodeBucket = s3.Bucket.fromBucketAttributes(this, 'SolutionsBucket', { bucketName: props.solutionBucket + '-' + Aws.REGION }); const eventRuleLambda = new eventLambda.EventsRuleToLambda(this, 'TARefreshSchedule', { eventRuleProps: { description: 'Schedule to refresh TA checks', schedule: events.Schedule.expression(refreshRate.findInMap('CronSchedule', 'Default')), enabled: true, }, lambdaFunctionProps: { runtime: lambda.Runtime.NODEJS_12_X, code: lambda.Code.fromBucket(solutionsLambdaCodeBucket, props.solutionName + '/' + props.solutionVersion + '/limtr-refresh-service.zip'), description: 'Serverless Limit Monitor - Lambda function to summarize service limits', timeout: cdk.Duration.seconds(300), handler: 'index.handler', environment: { LOG_LEVEL: 'INFO', AWS_SERVICES: eventsMap.findInMap('Checks', 'Services') } } }) const logsPolicy: PolicyStatement = new PolicyStatement({ actions: [ 'logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:PutLogEvents' ], effect: Effect.ALLOW, resources: [ `arn:${cdk.Aws.PARTITION}:logs:${this.region}:${this.account}:log-group:/aws/lambda/*` ] }) const supportPolicy: PolicyStatement = new PolicyStatement({ actions: [ 'support:*' ], effect: Effect.ALLOW, resources: [ '*' ] }) const serviceQuotasPolicy: PolicyStatement = new PolicyStatement({ actions: [ 'servicequotas:GetAWSDefaultServiceQuota' ], effect: Effect.ALLOW, resources: ['*'] }) eventRuleLambda.lambdaFunction.addToRolePolicy(logsPolicy) eventRuleLambda.lambdaFunction.addToRolePolicy(supportPolicy) eventRuleLambda.lambdaFunction.addToRolePolicy(serviceQuotasPolicy) const cfnLambdaFunctionDefPolicy = eventRuleLambda.lambdaFunction.role?.node.tryFindChild('DefaultPolicy')?.node.findChild('Resource') as iam.CfnPolicy; const cfnLambdaFunction = eventRuleLambda.lambdaFunction.node.findChild("Resource") as CfnResource; // Add the CFN NAG suppress to allow for "Resource": "*" for AWS X-Ray and support * actions. cfnLambdaFunctionDefPolicy.cfnOptions.metadata = { cfn_nag: { rules_to_suppress: [{ id: 'W12', reason: `Lambda needs the following minimum required permissions to send trace data to X-Ray.` }, { id: 'F4', reason: `Lambda needs the support * to perform the functions for monitoring resources.` } ]}}; cfnLambdaFunction.cfnOptions.metadata = { cfn_nag: { rules_to_suppress: [ { id: "W89", reason: "Not a valid use case to deploy in VPC", }, { id: "W92", reason: "ReservedConcurrentExecutions not needed", } ], }, }; //End TARefresherLambda and Event Rule Resource. //START Limit Monitor Helper Lambda and Role. const limtrHelperRole = new iam.Role(this, 'LimtrHelperRole', { assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'), path: '/', inlinePolicies: { 'Custom_Limtr_Helper_Permissions': new PolicyDocument({ statements: [ logsPolicy ] }) } }) const cfn_ref_limtrHelperRole = limtrHelperRole.node.defaultChild as iam.CfnRole cfn_ref_limtrHelperRole.overrideLogicalId('LimtrHelperRole') const limtrHelperFunction = new lambda.Function(this, 'LimtrHelperFunction', { runtime: lambda.Runtime.NODEJS_12_X, description: 'This function generates UUID, establishes cross account trust on CloudWatch Event Bus and sends anonymous metric', handler: 'index.handler', code: lambda.Code.fromBucket(solutionsLambdaCodeBucket, props.solutionName + '/' + props.solutionVersion + '/limtr-helper-service.zip'), timeout: cdk.Duration.seconds(300), environment: { LOG_LEVEL: 'INFO' }, role: limtrHelperRole }) //END Limit Monitor Helper Lambda and Role const cfn_ref_limtrFunction = limtrHelperFunction.node.defaultChild as lambda.CfnFunction cfn_ref_limtrFunction.overrideLogicalId('LimtrHelperFunction') cfn_ref_limtrFunction.cfnOptions.metadata = { cfn_nag: { rules_to_suppress: [ { id: "W89", reason: "Not a valid use case to deploy in VPC", }, { id: "W92", reason: "ReservedConcurrentExecutions not needed", } ], }, }; const customUUID = new cdk.CustomResource(this, 'CreateUUID', { resourceType: 'Custom::UUID', serviceToken: limtrHelperFunction.functionArn }) new cdk.CustomResource(this, 'DeploymentData', { resourceType: 'Custom::DeploymentData', serviceToken: limtrHelperFunction.functionArn, properties: { SOLUTION: props.solutionId + 's', UUID: customUUID.getAtt('UUID'), VERSION: props.solutionVersion, ANONYMOUS_DATA: metricsMap.findInMap('Send-Data', 'SendAnonymousData') } }) new CfnStack(this, 'limitCheckStack', { templateUrl: 'https://s3.amazonaws.com/' + props.solutionTemplateBucket + '/' + props.solutionName + '/' + props.solutionVersion + '/' + 'service-quotas-checks.template' }) //stack outputs new cdk.CfnOutput(this, 'ServiceChecks', { value: eventsMap.findInMap('Checks', 'Services'), description: 'service limit checks monitored in the account' }) } }
the_stack
import * as React from 'react'; import { Box as ReakitBox, DialogOptions as ReakitDialogOptions } from 'reakit'; import { Palette, Flexible } from '../types'; import { bindFns, useClassName, createComponent, createElement, createHook, omitCSSProps, useUniqueId } from '../utils'; import { ActionButtons, ActionButtonsProps } from '../ActionButtons'; import { Box, BoxProps } from '../Box'; import { Button, ButtonProps } from '../Button'; import { Flex, FlexProps } from '../Flex'; import { Icon, IconProps } from '../Icon'; import { Modal, ModalContext, ModalProps } from '../Modal'; import { Text, TextProps } from '../Text'; import * as styles from './Dialog.styles'; export type LocalDialogProps = { /** Indicates the type of dialog. */ type?: string; /** Sets the title of the dialog. */ title?: string | React.ReactElement<any>; /** Sets the footer of the dialog. */ footer?: string | React.ReactElement<any>; /** Sets the color of the dialog action buttons. */ palette?: Palette; /** Sets the visibility of the dialog action buttons. */ showActionButtons?: boolean; /** Sets the visibility of the close buttons. */ showCloseButton?: boolean; /** Function to invoke when the close button is clicked. */ onClickClose?: ButtonProps['onClick']; /** Props to spread onto the action buttons. */ actionButtonsProps?: ActionButtonsProps; /** Props to spread onto the close button. */ closeButtonProps?: Omit<ButtonProps, 'children'>; /** Props to spread on the icon. */ iconProps?: IconProps; standalone?: boolean; }; export type DialogProps = BoxProps & LocalDialogProps; export type DialogContextOptions = DialogProps & { descriptionId?: string; titleId?: string; themeKey?: string; }; export const DialogContext = React.createContext<DialogContextOptions>({}); const useProps = createHook<DialogProps>( (props, { themeKey }) => { const { actionButtonsProps = {}, closeButtonProps = {}, footer, iconProps = {}, onClickClose, overrides, palette, showActionButtons, showCloseButton, standalone, title, type, ...restProps } = props; const boxProps = Box.useProps(restProps); const className = useClassName({ style: styles.Dialog, styleProps: props, themeKey, prevClassName: boxProps.className, }); const dialogCloseClassName = useClassName({ style: styles.DialogClose, styleProps: props, themeKey, themeKeySuffix: 'Close', prevClassName: closeButtonProps.className, }); const titleId = useUniqueId(); const descriptionId = useUniqueId(); const context = React.useMemo(() => ({ descriptionId, titleId, ...props }), [descriptionId, props, titleId]); const children = ( <DialogContext.Provider value={context}> {standalone ? ( props.children ) : ( <React.Fragment> <DialogContent overrides={overrides}> {type && <DialogIcon iconProps={iconProps} overrides={overrides} />} <Box width="100%"> {title && ( <DialogHeader overrides={overrides}> {typeof title === 'string' ? <DialogTitle overrides={overrides}>{title}</DialogTitle> : title} {showCloseButton && ( <Button.Close className={dialogCloseClassName} onClick={onClickClose} size={title ? undefined : 'small'} {...closeButtonProps} /> )} </DialogHeader> )} {props.children} </Box> </DialogContent> {(footer || showActionButtons) && ( <DialogFooter overrides={overrides}> {footer} {showActionButtons && <ActionButtons palette={palette} {...actionButtonsProps} />} </DialogFooter> )} </React.Fragment> )} </DialogContext.Provider> ); return { 'aria-describedby': props.children ? descriptionId : undefined, 'aria-labelledby': props.title ? titleId : undefined, ...boxProps, className, children, }; }, { themeKey: 'Dialog' } ); export const Dialog = createComponent<DialogProps>( (props) => { const dialogProps = useProps(props); return createElement({ children: props.children, component: ReakitBox, use: props.use, htmlProps: dialogProps, }); }, { attach: { useProps, displayName: 'Dialog', }, themeKey: 'Dialog', } ); ////////////////////////////// export type LocalDialogContentProps = {}; export type DialogContentProps = FlexProps & LocalDialogContentProps; const useDialogContentProps = createHook<DialogContentProps>( (props, { themeKey }) => { const flexProps = Flex.useProps(props); const contextProps = React.useContext(DialogContext); const className = useClassName({ style: styles.DialogContent, styleProps: { ...contextProps, ...props }, themeKey, prevClassName: flexProps.className, }); return { id: props.id || contextProps.descriptionId, ...flexProps, className, }; }, { themeKey: 'Dialog.Content' } ); export const DialogContent = createComponent<DialogContentProps>( (props) => { const calloutContentProps = useDialogContentProps(props); return createElement({ children: props.children, component: ReakitBox, use: props.use, htmlProps: calloutContentProps, }); }, { attach: { useProps: useDialogContentProps, displayName: 'Dialog.Content' }, themeKey: 'Dialog.Content', } ); ////////////////////////////// export type LocalDialogHeaderProps = {}; export type DialogHeaderProps = BoxProps & LocalDialogHeaderProps; const useDialogHeaderProps = createHook<DialogHeaderProps>( (props, { themeKey }) => { const boxProps = Box.useProps(props); const contextProps = React.useContext(DialogContext); const className = useClassName({ style: styles.DialogHeader, styleProps: { ...contextProps, ...props }, themeKey, prevClassName: boxProps.className, }); return { ...boxProps, className }; }, { themeKey: 'Dialog.Header' } ); export const DialogHeader = createComponent<DialogHeaderProps>( (props) => { const calloutHeaderProps = useDialogHeaderProps(props); return createElement({ children: props.children, component: ReakitBox, use: props.use, htmlProps: calloutHeaderProps, }); }, { attach: { useProps: useDialogHeaderProps, displayName: 'Dialog.Header' }, themeKey: 'Dialog.Header', } ); ////////////////////////////// export type LocalDialogTitleProps = {}; export type DialogTitleProps = TextProps & LocalDialogTitleProps; const useDialogTitleProps = createHook<DialogTitleProps>( (props, { themeKey }) => { const textProps = Text.useProps(props); const contextProps = React.useContext(DialogContext); const className = useClassName({ style: styles.DialogTitle, styleProps: { ...contextProps, ...props }, themeKey, prevClassName: textProps.className, }); return { id: contextProps.titleId, ...textProps, className }; }, { themeKey: 'Dialog.Title' } ); export const DialogTitle = createComponent<DialogTitleProps>( (props) => { const calloutTitleProps = useDialogTitleProps(props); return createElement({ children: props.children, component: ReakitBox, use: props.use, htmlProps: calloutTitleProps, }); }, { attach: { useProps: useDialogTitleProps, displayName: 'Dialog.Title' }, defaultProps: { use: 'span', }, themeKey: 'Dialog.Title', } ); ////////////////////////////// export type LocalDialogFooterProps = {}; export type DialogFooterProps = FlexProps & LocalDialogFooterProps; const useDialogFooterProps = createHook<DialogFooterProps>( (props, { themeKey }) => { const flexProps = Flex.useProps(props); const contextProps = React.useContext(DialogContext); const className = useClassName({ style: styles.DialogFooter, styleProps: { ...contextProps, ...props }, themeKey, prevClassName: flexProps.className, }); return { ...flexProps, className }; }, { themeKey: 'Dialog.Footer' } ); export const DialogFooter = createComponent<DialogFooterProps>( (props) => { const calloutFooterProps = useDialogFooterProps(props); return createElement({ children: props.children, component: ReakitBox, use: props.use, htmlProps: calloutFooterProps, }); }, { attach: { useProps: useDialogFooterProps, displayName: 'Dialog.Footer' }, themeKey: 'Dialog.Footer', } ); ////////////////////////////// export type LocalDialogIconProps = { iconProps?: Omit<IconProps, 'icon'>; }; export type DialogIconProps = TextProps & LocalDialogIconProps; const useDialogIconProps = createHook<DialogIconProps>( (props, { themeKey }) => { const { iconProps, ...restProps } = props; const textProps = Text.useProps(restProps); const contextProps = React.useContext(DialogContext); const className = useClassName({ style: styles.DialogIconWrapper, styleProps: { ...contextProps, ...props }, themeKey, prevClassName: textProps.className, }); const icon = ( <Icon aria-hidden color={contextProps.type} fontSize={!contextProps.title ? '300' : undefined} icon={contextProps.type} {...iconProps} /> ); let children = icon; if (contextProps.title) { children = ( <DialogHeader> <DialogTitle id={undefined}>{icon}</DialogTitle> </DialogHeader> ); } return { ...textProps, className, children }; }, { themeKey: 'Dialog.IconWrapper' } ); export const DialogIcon = createComponent<DialogIconProps>( (props) => { const DialogIconProps = useDialogIconProps(props); return createElement({ children: props.children, component: ReakitBox, use: props.use, htmlProps: DialogIconProps, }); }, { attach: { useProps: useDialogIconProps, displayName: 'Dialog.IconWrapper' }, defaultProps: { use: 'span', }, themeKey: 'Dialog.IconWrapper', } ); ////////////////////////////// export type LocalDialogModalProps = { variant?: Flexible<'alert', string>; hasScroll?: boolean; wrap?: (children: React.ReactNode) => React.ReactNode; }; export type DialogModalProps = DialogProps & ModalProps & LocalDialogModalProps; const useDialogModalProps = createHook<DialogModalProps>( (props, { themeKey }) => { const { modal } = React.useContext(ModalContext); const { wrap, variant, ...restProps } = { ...modal, ...props }; const dialogProps = Dialog.useProps({ ...restProps, onClickClose: bindFns(restProps.hide, props.onClickClose), actionButtonsProps: { ...restProps.actionButtonsProps, onClickCancel: bindFns(restProps.hide, restProps.actionButtonsProps?.onClickCancel), }, wrapElement: (children) => ( // @ts-ignore <Modal hideOnEsc={variant !== 'alert'} hideOnClickOutside={variant !== 'alert'} role={variant === 'alert' ? 'alertdialog' : 'dialog'} {...omitCSSProps(restProps)} > {children} </Modal> ), }); const contextProps = React.useContext(DialogContext); const className = useClassName({ style: styles.DialogModal, styleProps: { ...contextProps, ...props }, themeKey, prevClassName: dialogProps.className, }); return { ...dialogProps, className, children: typeof wrap === 'function' ? wrap(dialogProps.children) : dialogProps.children, }; }, { defaultProps: { hasScroll: true }, themeKey: 'Dialog.Modal' } ); export const DialogModal = createComponent<DialogModalProps>( (props) => { const DialogModalProps = useDialogModalProps(props); return createElement({ children: props.children, component: ReakitBox, use: props.use, htmlProps: DialogModalProps, }); }, { attach: { useProps: useDialogModalProps, displayName: 'Dialog.Modal' }, themeKey: 'Dialog.Modal', } );
the_stack
import { text } from "@core"; import { formatDate, generateID } from "@utils"; import { computed, observable } from "mobx"; import { Model, observeModel, SubModel } from "pouchx"; import { OrthoCaseSchema, patients, PhotoSchema, setting, VisitSchema, } from "@modules"; export const Lips = { competent: "competent lips", incompetent: "incompetent lips", potentially_competent: "potentially competent lips", }; export const FacialProfile = { brachycephalic: "brachycephalic profile", dolichocephalic: "dolichocephalic profile", mesocephalic: "mesocephalic profile", }; export const OralHygiene = { good: "good oral hygiene", bad: "bad oral hygiene", moderate: "moderate oral hygiene", }; export class Photo extends SubModel<PhotoSchema> implements PhotoSchema { @observable id: string = generateID(); @observable photoID: string = ""; @observable comment: string = ""; fromJSON(json: PhotoSchema) { this.id = json.id; this.photoID = json.photoID; this.comment = json.comment; return this; } toJSON(): PhotoSchema { return { id: this.id, photoID: this.photoID, comment: this.comment, }; } } export class Visit extends SubModel<VisitSchema> implements VisitSchema { @observable id: string = generateID(); @observable visitNumber: number = 1; @observable photos: Photo[] = [ new Photo(), // 1 Labial new Photo(), // 2 Right new Photo(), // 3 Left new Photo(), // 4 Lingual new Photo(), // 5 Palatal ]; @observable date: number = new Date().getTime(); @observable appliance: string = ""; @observable target: string = ""; withVisitNumber(visitNumber: number) { this.visitNumber = visitNumber; return this; } fromJSON(json: VisitSchema) { this.id = json.id; this.visitNumber = json.visitNumber; this.date = json.date; this.appliance = json.appliance; this.target = json.target || ""; this.photos = json.photos.map((x) => new Photo().fromJSON(x)); return this; } toJSON(): VisitSchema { return { id: this.id, visitNumber: this.visitNumber, date: this.date, appliance: this.appliance, target: this.target, photos: this.photos.map((x) => x.toJSON()), }; } } @observeModel export class OrthoCase extends Model<OrthoCaseSchema> implements OrthoCaseSchema { @observable _id: string = generateID(); @observable startedDate: number = 0; @observable patientID: string = ""; @computed get patient() { return patients!.docs.find((x) => x._id === this.patientID); } /** * Extra-oral observations */ @observable lips: keyof typeof Lips = "competent"; @observable facialProfile: keyof typeof FacialProfile = "mesocephalic"; @observable nasioLabialAngle: number = 90; @observable oralHygiene: keyof typeof OralHygiene = "moderate"; /** * jaw to jaw relationship */ @observable skeletalRelationship: number = 1; @observable molarsRelationship: number = 1; @observable canineRelationship: number = 1; /** * Anterior teeth relationship */ @observable overJet: number = 2; @observable overBite: number = 3; @observable crossScissorBite: number[] = []; /** * Space analysis: upper jaw */ @observable u_spaceAvailable: number = 0; @observable u_spaceNeeded: number = 0; @computed get u_spacing() { return this.u_spaceAvailable - this.u_spaceNeeded; } @computed get u_crowding() { return this.u_spaceNeeded - this.u_spaceAvailable; } /** * Space analysis: lower jaw */ @observable l_spaceAvailable: number = 0; @observable l_spaceNeeded: number = 0; @computed get l_spacing() { return this.l_spaceAvailable - this.l_spaceNeeded; } @computed get l_crowding() { return this.l_spaceNeeded - this.l_spaceAvailable; } /** * conclusions */ @observable problemsList: string[] = []; @observable treatmentPlan_appliance: string[] = []; @observable isFinished: boolean = false; @observable isStarted: boolean = false; @observable finishedDate: number = 0; @observable nextVisitNotes: string[] = []; @observable visits: Visit[] = []; @computed get computedProblems() { const computedProblemsArr: string[] = []; if (this.lips !== "competent") { computedProblemsArr.push(text(Lips[this.lips] as any).r); } if (this.facialProfile !== "mesocephalic") { computedProblemsArr.push( text(FacialProfile[this.facialProfile] as any).r ); } if (this.oralHygiene === "bad") { computedProblemsArr.push( text(OralHygiene[this.oralHygiene] as any).r ); } if (this.nasioLabialAngle < 90 || this.nasioLabialAngle > 93) { computedProblemsArr.push( `${text("nasio-labial angle")}: ${this.nasioLabialAngle} ${text( "degrees" )}` ); } if (this.skeletalRelationship !== 1) { computedProblemsArr.push( `${text("skeletal relationship")} ${text("class")}: ${ this.skeletalRelationship }` ); } if (this.molarsRelationship !== 1) { computedProblemsArr.push( `${text("molars relationship")} ${text("class")}: ${ this.molarsRelationship }` ); } if (this.canineRelationship !== 1) { computedProblemsArr.push( `${text("canine relationship")} ${text("class")}: ${ this.canineRelationship }` ); } if (this.overJet > 3 || this.overJet < 1) { computedProblemsArr.push( `${text("overjet")} :${this.overJet} ${text("mm")}` ); } if (this.overBite > 4 || this.overBite < 2) { computedProblemsArr.push( `${text("overbite")} :${this.overBite} ${text("mm")}` ); } if (this.crossScissorBite.length) { computedProblemsArr.push( `${text("cross/scissors bite")}: ${this.crossScissorBite.join( ", " )}` ); } if (this.u_crowding > 0) { computedProblemsArr.push( `${text("upper arch crowding by")} ${this.u_crowding}${text( "mm" )}` ); } if (this.u_spacing > 0) { computedProblemsArr.push( `${text("upper arch spacing by")} ${this.u_spacing}${text( "mm" )}` ); } if (this.l_crowding > 0) { computedProblemsArr.push( `${text("lower arch crowding by")} ${this.l_crowding}${text( "mm" )}` ); } if (this.l_spacing > 0) { computedProblemsArr.push( `${text("lower arch spacing by")} ${this.l_spacing}${text( "mm" )}` ); } return computedProblemsArr; } @computed get searchableString() { return !this.patient ? "" : ` ${this.patient.age} ${this.patient.birthYear} ${this.patient.phone} ${this.patient.email} ${this.patient.address} ${ this.patient.gender } ${this.patient.name} ${this.patient.labels .map((x) => x.text) .join(" ")} ${this.patient.medicalHistory.join(" ")} ${this.patient.teeth.map((x) => x.notes.join(" ")).join(" ")} ${ this.patient.nextAppointment ? (this.patient.nextAppointment.treatment || { type: "" }) .type : "" } ${ this.patient.nextAppointment ? formatDate( this.patient.nextAppointment.date, setting!.getSetting("date_format") ) : "" } ${ this.patient.lastAppointment ? (this.patient.lastAppointment.treatment || { type: "" }) .type : "" } ${ this.patient.lastAppointment ? formatDate( this.patient.lastAppointment.date, setting!.getSetting("date_format") ) : "" } ${ this.patient.differenceAmount < 0 ? "outstanding " + this.patient.outstandingAmount : "" } ${ this.patient.differenceAmount > 0 ? "Overpaid " + this.patient.overpaidAmount : "" } ${this.computedProblems} `.toLowerCase(); } toJSON(): OrthoCaseSchema { return { _id: this._id, patientID: this.patientID, startedDate: this.startedDate, isStarted: this.isStarted, canineRelationship: this.canineRelationship, facialProfile: this.facialProfile.charAt(0), l_spaceAvailable: this.l_spaceAvailable, l_spaceNeeded: this.l_spaceNeeded, lips: this.lips.charAt(0), molarsRelationship: this.molarsRelationship, nasioLabialAngle: this.nasioLabialAngle, oralHygiene: this.oralHygiene.charAt(0), overBite: this.overBite, overJet: this.overJet, problemsList: Array.from(this.problemsList), skeletalRelationship: this.skeletalRelationship, treatmentPlan_appliance: Array.from(this.treatmentPlan_appliance), u_spaceAvailable: this.u_spaceAvailable, u_spaceNeeded: this.u_spaceNeeded, crossScissorBite: Array.from(this.crossScissorBite), isFinished: this.isFinished, finishedDate: this.finishedDate, nextVisitNotes: Array.from(this.nextVisitNotes), visits: Array.from(this.visits).map((x) => x.toJSON()), }; } fromJSON(json: OrthoCaseSchema) { this._id = json._id; this.startedDate = json.startedDate || 0; this.patientID = json.patientID; this.canineRelationship = json.canineRelationship; this.facialProfile = json.facialProfile.charAt(0) === "b" ? "brachycephalic" : json.facialProfile.charAt(0) === "d" ? "dolichocephalic" : "mesocephalic"; this.l_spaceAvailable = json.l_spaceAvailable; this.l_spaceNeeded = json.l_spaceNeeded; this.lips = json.lips.charAt(0) === "i" ? "incompetent" : json.lips.charAt(0) === "p" ? "potentially_competent" : "competent"; this.molarsRelationship = json.molarsRelationship; this.nasioLabialAngle = json.nasioLabialAngle; this.oralHygiene = json.oralHygiene.charAt(0) === "g" ? "good" : json.oralHygiene.charAt(0) === "b" ? "bad" : "moderate"; this.overBite = json.overBite; this.overJet = json.overJet; this.problemsList = json.problemsList; this.skeletalRelationship = json.skeletalRelationship; this.treatmentPlan_appliance = json.treatmentPlan_appliance; this.u_spaceAvailable = json.u_spaceAvailable; this.u_spaceNeeded = json.u_spaceNeeded; this.crossScissorBite = json.crossScissorBite; this.isFinished = !!json.isFinished; this.finishedDate = json.finishedDate || 0; this.nextVisitNotes = json.nextVisitNotes || []; this.visits = json.visits ? json.visits.map((x) => new Visit().fromJSON(x)) : []; this.isFinished = !!json.isFinished; this.isStarted = !!json.isStarted; return this; } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/proximityPlacementGroupsMappers"; import * as Parameters from "../models/parameters"; import { ComputeManagementClientContext } from "../computeManagementClientContext"; /** Class representing a ProximityPlacementGroups. */ export class ProximityPlacementGroups { private readonly client: ComputeManagementClientContext; /** * Create a ProximityPlacementGroups. * @param {ComputeManagementClientContext} client Reference to the service client. */ constructor(client: ComputeManagementClientContext) { this.client = client; } /** * Create or update a proximity placement group. * @param resourceGroupName The name of the resource group. * @param proximityPlacementGroupName The name of the proximity placement group. * @param parameters Parameters supplied to the Create Proximity Placement Group operation. * @param [options] The optional parameters * @returns Promise<Models.ProximityPlacementGroupsCreateOrUpdateResponse> */ createOrUpdate(resourceGroupName: string, proximityPlacementGroupName: string, parameters: Models.ProximityPlacementGroup, options?: msRest.RequestOptionsBase): Promise<Models.ProximityPlacementGroupsCreateOrUpdateResponse>; /** * @param resourceGroupName The name of the resource group. * @param proximityPlacementGroupName The name of the proximity placement group. * @param parameters Parameters supplied to the Create Proximity Placement Group operation. * @param callback The callback */ createOrUpdate(resourceGroupName: string, proximityPlacementGroupName: string, parameters: Models.ProximityPlacementGroup, callback: msRest.ServiceCallback<Models.ProximityPlacementGroup>): void; /** * @param resourceGroupName The name of the resource group. * @param proximityPlacementGroupName The name of the proximity placement group. * @param parameters Parameters supplied to the Create Proximity Placement Group operation. * @param options The optional parameters * @param callback The callback */ createOrUpdate(resourceGroupName: string, proximityPlacementGroupName: string, parameters: Models.ProximityPlacementGroup, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProximityPlacementGroup>): void; createOrUpdate(resourceGroupName: string, proximityPlacementGroupName: string, parameters: Models.ProximityPlacementGroup, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProximityPlacementGroup>, callback?: msRest.ServiceCallback<Models.ProximityPlacementGroup>): Promise<Models.ProximityPlacementGroupsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, proximityPlacementGroupName, parameters, options }, createOrUpdateOperationSpec, callback) as Promise<Models.ProximityPlacementGroupsCreateOrUpdateResponse>; } /** * Update a proximity placement group. * @param resourceGroupName The name of the resource group. * @param proximityPlacementGroupName The name of the proximity placement group. * @param parameters Parameters supplied to the Update Proximity Placement Group operation. * @param [options] The optional parameters * @returns Promise<Models.ProximityPlacementGroupsUpdateResponse> */ update(resourceGroupName: string, proximityPlacementGroupName: string, parameters: Models.ProximityPlacementGroupUpdate, options?: msRest.RequestOptionsBase): Promise<Models.ProximityPlacementGroupsUpdateResponse>; /** * @param resourceGroupName The name of the resource group. * @param proximityPlacementGroupName The name of the proximity placement group. * @param parameters Parameters supplied to the Update Proximity Placement Group operation. * @param callback The callback */ update(resourceGroupName: string, proximityPlacementGroupName: string, parameters: Models.ProximityPlacementGroupUpdate, callback: msRest.ServiceCallback<Models.ProximityPlacementGroup>): void; /** * @param resourceGroupName The name of the resource group. * @param proximityPlacementGroupName The name of the proximity placement group. * @param parameters Parameters supplied to the Update Proximity Placement Group operation. * @param options The optional parameters * @param callback The callback */ update(resourceGroupName: string, proximityPlacementGroupName: string, parameters: Models.ProximityPlacementGroupUpdate, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProximityPlacementGroup>): void; update(resourceGroupName: string, proximityPlacementGroupName: string, parameters: Models.ProximityPlacementGroupUpdate, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProximityPlacementGroup>, callback?: msRest.ServiceCallback<Models.ProximityPlacementGroup>): Promise<Models.ProximityPlacementGroupsUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, proximityPlacementGroupName, parameters, options }, updateOperationSpec, callback) as Promise<Models.ProximityPlacementGroupsUpdateResponse>; } /** * Delete a proximity placement group. * @param resourceGroupName The name of the resource group. * @param proximityPlacementGroupName The name of the proximity placement group. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(resourceGroupName: string, proximityPlacementGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>; /** * @param resourceGroupName The name of the resource group. * @param proximityPlacementGroupName The name of the proximity placement group. * @param callback The callback */ deleteMethod(resourceGroupName: string, proximityPlacementGroupName: string, callback: msRest.ServiceCallback<void>): void; /** * @param resourceGroupName The name of the resource group. * @param proximityPlacementGroupName The name of the proximity placement group. * @param options The optional parameters * @param callback The callback */ deleteMethod(resourceGroupName: string, proximityPlacementGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, proximityPlacementGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { resourceGroupName, proximityPlacementGroupName, options }, deleteMethodOperationSpec, callback); } /** * Retrieves information about a proximity placement group . * @param resourceGroupName The name of the resource group. * @param proximityPlacementGroupName The name of the proximity placement group. * @param [options] The optional parameters * @returns Promise<Models.ProximityPlacementGroupsGetResponse> */ get(resourceGroupName: string, proximityPlacementGroupName: string, options?: Models.ProximityPlacementGroupsGetOptionalParams): Promise<Models.ProximityPlacementGroupsGetResponse>; /** * @param resourceGroupName The name of the resource group. * @param proximityPlacementGroupName The name of the proximity placement group. * @param callback The callback */ get(resourceGroupName: string, proximityPlacementGroupName: string, callback: msRest.ServiceCallback<Models.ProximityPlacementGroup>): void; /** * @param resourceGroupName The name of the resource group. * @param proximityPlacementGroupName The name of the proximity placement group. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, proximityPlacementGroupName: string, options: Models.ProximityPlacementGroupsGetOptionalParams, callback: msRest.ServiceCallback<Models.ProximityPlacementGroup>): void; get(resourceGroupName: string, proximityPlacementGroupName: string, options?: Models.ProximityPlacementGroupsGetOptionalParams | msRest.ServiceCallback<Models.ProximityPlacementGroup>, callback?: msRest.ServiceCallback<Models.ProximityPlacementGroup>): Promise<Models.ProximityPlacementGroupsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, proximityPlacementGroupName, options }, getOperationSpec, callback) as Promise<Models.ProximityPlacementGroupsGetResponse>; } /** * Lists all proximity placement groups in a subscription. * @param [options] The optional parameters * @returns Promise<Models.ProximityPlacementGroupsListBySubscriptionResponse> */ listBySubscription(options?: msRest.RequestOptionsBase): Promise<Models.ProximityPlacementGroupsListBySubscriptionResponse>; /** * @param callback The callback */ listBySubscription(callback: msRest.ServiceCallback<Models.ProximityPlacementGroupListResult>): void; /** * @param options The optional parameters * @param callback The callback */ listBySubscription(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProximityPlacementGroupListResult>): void; listBySubscription(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProximityPlacementGroupListResult>, callback?: msRest.ServiceCallback<Models.ProximityPlacementGroupListResult>): Promise<Models.ProximityPlacementGroupsListBySubscriptionResponse> { return this.client.sendOperationRequest( { options }, listBySubscriptionOperationSpec, callback) as Promise<Models.ProximityPlacementGroupsListBySubscriptionResponse>; } /** * Lists all proximity placement groups in a resource group. * @param resourceGroupName The name of the resource group. * @param [options] The optional parameters * @returns Promise<Models.ProximityPlacementGroupsListByResourceGroupResponse> */ listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.ProximityPlacementGroupsListByResourceGroupResponse>; /** * @param resourceGroupName The name of the resource group. * @param callback The callback */ listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.ProximityPlacementGroupListResult>): void; /** * @param resourceGroupName The name of the resource group. * @param options The optional parameters * @param callback The callback */ listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProximityPlacementGroupListResult>): void; listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProximityPlacementGroupListResult>, callback?: msRest.ServiceCallback<Models.ProximityPlacementGroupListResult>): Promise<Models.ProximityPlacementGroupsListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec, callback) as Promise<Models.ProximityPlacementGroupsListByResourceGroupResponse>; } /** * Lists all proximity placement groups in a subscription. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.ProximityPlacementGroupsListBySubscriptionNextResponse> */ listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ProximityPlacementGroupsListBySubscriptionNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listBySubscriptionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ProximityPlacementGroupListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listBySubscriptionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProximityPlacementGroupListResult>): void; listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProximityPlacementGroupListResult>, callback?: msRest.ServiceCallback<Models.ProximityPlacementGroupListResult>): Promise<Models.ProximityPlacementGroupsListBySubscriptionNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listBySubscriptionNextOperationSpec, callback) as Promise<Models.ProximityPlacementGroupsListBySubscriptionNextResponse>; } /** * Lists all proximity placement groups in a resource group. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.ProximityPlacementGroupsListByResourceGroupNextResponse> */ listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ProximityPlacementGroupsListByResourceGroupNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ProximityPlacementGroupListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProximityPlacementGroupListResult>): void; listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProximityPlacementGroupListResult>, callback?: msRest.ServiceCallback<Models.ProximityPlacementGroupListResult>): Promise<Models.ProximityPlacementGroupsListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByResourceGroupNextOperationSpec, callback) as Promise<Models.ProximityPlacementGroupsListByResourceGroupNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const createOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/proximityPlacementGroups/{proximityPlacementGroupName}", urlParameters: [ Parameters.resourceGroupName, Parameters.proximityPlacementGroupName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.ProximityPlacementGroup, required: true } }, responses: { 200: { bodyMapper: Mappers.ProximityPlacementGroup }, 201: { bodyMapper: Mappers.ProximityPlacementGroup }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/proximityPlacementGroups/{proximityPlacementGroupName}", urlParameters: [ Parameters.resourceGroupName, Parameters.proximityPlacementGroupName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.ProximityPlacementGroupUpdate, required: true } }, responses: { 200: { bodyMapper: Mappers.ProximityPlacementGroup }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const deleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/proximityPlacementGroups/{proximityPlacementGroupName}", urlParameters: [ Parameters.resourceGroupName, Parameters.proximityPlacementGroupName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/proximityPlacementGroups/{proximityPlacementGroupName}", urlParameters: [ Parameters.resourceGroupName, Parameters.proximityPlacementGroupName, Parameters.subscriptionId ], queryParameters: [ Parameters.includeColocationStatus, Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ProximityPlacementGroup }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listBySubscriptionOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/providers/Microsoft.Compute/proximityPlacementGroups", urlParameters: [ Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ProximityPlacementGroupListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listByResourceGroupOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/proximityPlacementGroups", urlParameters: [ Parameters.resourceGroupName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ProximityPlacementGroupListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listBySubscriptionNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ProximityPlacementGroupListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listByResourceGroupNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ProximityPlacementGroupListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
import { KnexRecord, ResourceTypeAttributes } from "@ebryn/jsonapi-ts"; import knex from "knex"; import { Log } from "logepi"; import { v4 as generateUuid } from "uuid"; import Errors from "./errors"; import User, { MatchedUser } from "./resources/user/resource"; const DATABASE_URL = (process.env.DATABASE_URL as string) || (process.env.DB_CONNECTION_STRING as string); const DATABASE_CONFIGURATION: knex.Config = { client: process.env.DB_ENGINE as string, connection: DATABASE_URL || { filename: process.env.DB_FILE as string }, searchPath: DATABASE_URL ? ["playground_db", "public"] : [], useNullAsDefault: process.env.DB_FILE ? true : false }; async function runMigration() { const db = getDatabase(); await db.schema.createTable("users", table => { table.uuid("id"); table.string("username"); table.string("email"); table.string("eth_address"); table.string("multisig_address"); table.string("node_address"); table.string("transaction_hash"); table.unique(["username"], "uk_users__username"); }); } export async function detectDBAndSchema() { const relation = "users"; const db = getDatabase(); try { if (!(await db.schema.hasTable(relation))) { await runMigration(); } } catch (e) { if (e.code === "ECONNREFUSED") { Log.error("Failed to connect to database", { tags: { connection: DATABASE_CONFIGURATION.connection } }); Log.error( "Spin up a database at the connection string or specify an existing database via exporting the DB_CONNECTION_STRING environment variable", {} ); } else { Log.error("Failed to determine if schema is correct", { tags: { error: e } }); } process.exit(1); } } export function getDatabase() { Log.debug("Connected to database", {}); return knex(DATABASE_CONFIGURATION); } export async function ethAddressAlreadyRegistered( address: string ): Promise<boolean> { const db = getDatabase(); const query = db("users") .select("id") .where("eth_address", address); const userId: { id: string }[] = await query; Log.debug("Executed ethAddressAlreadyRegistered query", { tags: { query: query.toSQL().sql } }); await db.destroy(); return userId.length > 0; } export async function usernameAlreadyRegistered( username: string ): Promise<boolean> { const db = getDatabase(); const query = db("users") .select("id") .where("username", username); const userId: { id: string }[] = await query; Log.debug("Executed usernameAlreadyRegistered query", { tags: { query: query.toSQL().sql } }); await db.destroy(); return userId.length > 0; } export async function matchmakeUser(userToMatch: User): Promise<MatchedUser> { const db = getDatabase(); if (!userToMatch) { throw Errors.UserAddressRequired(); } const query = db("users") .columns({ id: "id", username: "username", ethAddress: "eth_address", nodeAddress: "node_address" }) .select() .where("eth_address", "!=", userToMatch.attributes.ethAddress); const matchmakeResults: { id: string; username: string; ethAddress: string; nodeAddress: string; }[] = await query; Log.debug("Executed matchmakeUser query", { tags: { query: query.toSQL().sql } }); await db.destroy(); if (matchmakeResults.length === 1) { // If there is only one user, just select that one. Log.info("Matchmade completed with only user available", { tags: { nodes: [ userToMatch.attributes.nodeAddress, matchmakeResults[0].nodeAddress ] } }); const [user] = matchmakeResults; return new MatchedUser({ id: user.id, attributes: { username: user.username, ethAddress: user.ethAddress, nodeAddress: user.nodeAddress } }); } if (matchmakeResults.length === 0) { // If there are no users, throw an error. Log.warn("Cannot matchmake, no users available", { tags: { node: userToMatch.attributes.nodeAddress } }); throw Errors.NoUsersAvailable(); } // We do the random selection of the user outside of the DB // to avoid engine coupling; could've been solved using `.orderBy("RANDOM()")`. const randomIndex = Math.floor(Math.random() * matchmakeResults.length); const matchedUser = matchmakeResults[randomIndex]; Log.info("Matchmade completed via random index selection", { tags: { users: [userToMatch.attributes.nodeAddress, matchedUser.nodeAddress] } }); return new MatchedUser({ id: matchedUser.id, attributes: { username: matchedUser.username, ethAddress: matchedUser.ethAddress, nodeAddress: matchedUser.nodeAddress } }); } export async function getUsers( filters: {}, fields: string[] = [] ): Promise<User[]> { const db = getDatabase(); let returnFields = fields; if (!returnFields.length) { returnFields = [ "username", "email", "ethAddress", "multisigAddress", "nodeAddress" ]; } const users: KnexRecord[] = await db("users") .columns({ id: "id", username: "username", email: "email", ethAddress: "eth_address", multisigAddress: "multisig_address", nodeAddress: "node_address" }) .where(compactObject(filters)) .select(); await db.destroy(); return users.map( (user: KnexRecord) => new User({ id: user.id, attributes: returnFields .map(field => ({ [field]: user[field] })) .reduce((fieldA, fieldB) => ({ ...fieldA, ...fieldB }), {}) }) ); } export async function getUser(userToFind: Partial<User>): Promise<User> { const db = getDatabase(); const { ethAddress } = userToFind.attributes as ResourceTypeAttributes; const query = db("users") .columns({ id: "id", username: "username", email: "email", ethAddress: "eth_address", multisigAddress: "multisig_address", nodeAddress: "node_address" }) .select() .where("eth_address", "=", userToFind.attributes!.ethAddress); const users: ({ id: string; username: string; email: string; ethAddress: string; multisigAddress: string; nodeAddress: string; })[] = await query; Log.debug("Executed getUser query", { tags: { query: query.toSQL().sql } }); await db.destroy(); if (users.length === 0) { Log.info("No user found with provided address", { tags: { user: ethAddress } }); throw Errors.UserNotFound(); } const [user] = users; return new User({ id: user.id, attributes: { username: user.username, email: user.email, ethAddress: user.ethAddress, multisigAddress: user.multisigAddress, nodeAddress: user.nodeAddress } }); } export async function deleteAccount(userId: string) { const db = getDatabase(); const query = db("users") .select() .where("id", "=", userId) .del(); await query; await db.destroy(); } export async function getUsernameFromMultisigAddress( multisigAddress: string ): Promise<string> { const db = getDatabase(); const query = db("users") .columns({ username: "username", multisigAddress: "multisig_address" }) .select() .where("multisig_address", "=", multisigAddress); const users: ({ username: string; multisigAddress: string; })[] = await query; await db.destroy(); if (users.length === 0) { throw Errors.UserNotFound(); } const [user] = users; return user.username; } export async function userExists(user: User): Promise<boolean> { const db = getDatabase(); const query = db("users") .select() .where({ username: user.attributes.username, email: user.attributes.email, eth_address: user.attributes.ethAddress, multisig_address: user.attributes.multisigAddress, node_address: user.attributes.nodeAddress }) .limit(1); const users = await query; Log.debug("Executed userExists query", { tags: { query: query.toSQL().sql } }); await db.destroy(); return users.length === 1; } export async function updateUser(user: User): Promise<User> { const db = getDatabase(); const query = db("users") .update({ email: user.attributes.email }) .where({ id: user.id }); try { await query; Log.debug("Executed updateUser query", { tags: { query: query.toSQL().sql } }); await db.destroy(); return getUser(user); } catch (e) { throw e; } finally { await db.destroy(); } } export async function createUser(user: User): Promise<User> { const db = getDatabase(); const id = generateUuid(); const query = db("users").insert({ id, username: user.attributes.username, email: user.attributes.email, eth_address: user.attributes.ethAddress, multisig_address: user.attributes.multisigAddress, node_address: user.attributes.nodeAddress, transaction_hash: "" }); try { await query; Log.debug("Executed createUser query", { tags: { query: query.toSQL().sql } }); await db.destroy(); return new User({ id, attributes: user.attributes }); } catch (e) { const error = e as Error; if (error.message.match(/unique constraint/i)) { throw Errors.UsernameAlreadyExists(); } else { throw e; } } } export async function bindMultisigToUser( nodeAddress: string, multisigAddress: string ): Promise<boolean> { const db = getDatabase(); const query = db("users") .where({ node_address: nodeAddress }) .update("multisig_address", multisigAddress); try { await query; Log.debug("Executed createUser query", { tags: { query: query.toSQL().sql } }); return true; } catch (e) { throw e; } finally { await db.destroy(); } } export async function bindTransactionHashToUser( user: User, transactionHash: string ): Promise<boolean> { const db = getDatabase(); const query = db("users") .where({ id: user.id }) .update("transaction_hash", transactionHash); try { await query; Log.debug("Executed bindTransactionHashToUser query", { tags: { query: query.toSQL().sql } }); return true; } catch (e) { throw e; } finally { await db.destroy(); } } export async function storePlaygroundSnapshot(snapshot: any): Promise<boolean> { const db = getDatabase(); const query = db("playground_snapshot") .delete() .insert({ snapshot: Buffer.from(JSON.stringify(snapshot)) }); try { await query; Log.debug("Executed storePlaygroundSnapshot query", { tags: { query: query.toSQL().sql } }); return true; } catch (e) { throw e; } finally { await db.destroy(); } } export async function getPlaygroundSnapshot(): Promise<any> { const db = getDatabase(); const query = db("playground_snapshot").select("snapshot"); try { const snapshot = await query; Log.debug("Executed getPlaygroundSnapshot query", { tags: { query: query.toSQL().sql } }); if (!snapshot[0]) { return null; } const rawJSON = snapshot[0].snapshot.toString(); return JSON.parse(rawJSON); } catch (e) { throw e; } finally { await db.destroy(); } } function compactObject(filters: {}): {} { Object.keys(filters).forEach( key => filters[key] === undefined && delete filters[key] ); return filters; }
the_stack
import { build as buildProject } from "snowpack"; import { dirname, resolve } from "path"; import glob from "globby"; import arg from "arg"; import { GetModuleInfo, rollup, RenderedChunk, Plugin } from "rollup"; import { visit } from "recast"; import { performance } from "perf_hooks"; import { green, dim } from "kleur/colors"; import styles from "rollup-plugin-styles"; import esbuild from "esbuild"; import module from "module"; const { createRequire, builtinModules: builtins } = module; const require = createRequire(import.meta.url); import { STAGING_DIR, SSR_DIR, OUT_DIR_NO_BASE, OUT_DIR, importDataMethods, applyDataMethods, preactImportTransformer, proxyImportTransformer, getFileNameFromPath, hashContentSync, emitFile, renderPage, emitFinalAsset, copyAssetToFinal, stripWithHydrate, preactToCDN, setBasePath, CACHE_DIR, } from "../utils/build.js"; import type { ManifestEntry, RouteDataEntry } from "../utils/build"; import { rmdir, mkdir, copyDir, copyFile } from "../utils/fs.js"; import { statSync } from "fs"; import { resolveNormalizedBasePath, loadConfiguration, } from "../utils/command.js"; function parseArgs(argv: string[]) { return arg( { "--debug-hydration": Boolean, "--no-clean": Boolean, "--no-open": Boolean, "--serve": Boolean, "--base-path": String, }, { permissive: true, argv } ); } export default async function build( argvOrParsedArgs: string[] | ReturnType<typeof parseArgs> ) { const args = Array.isArray(argvOrParsedArgs) ? parseArgs(argvOrParsedArgs) : argvOrParsedArgs; let basePath = resolveNormalizedBasePath(args); setBasePath(basePath); const config = await loadConfiguration("build"); const buildStart = performance.now(); await Promise.all([prepare(), buildProject({ config, lockfile: null })]); let pages = await glob(resolve(STAGING_DIR, "src/pages/**/*.js")); let globalEntryPoint = resolve(STAGING_DIR, "src/global/index.js"); let globalStyle = resolve(STAGING_DIR, "src/global/index.css"); try { globalEntryPoint = statSync(globalEntryPoint) ? globalEntryPoint : null; } catch (e) { globalEntryPoint = null; } try { globalStyle = statSync(globalStyle) ? globalStyle : null; } catch (e) { globalStyle = null; } pages = pages.filter((page) => !page.endsWith(".proxy.js")); let [manifest, routeData] = await Promise.all([ bundlePagesForSSR(globalEntryPoint ? [...pages, globalEntryPoint] : pages), fetchRouteData(pages.filter((page) => !page.endsWith("_document.js"))), ]); if (globalStyle) { manifest = manifest.map((entry) => ({ ...entry, hydrateStyleBindings: [ "_static/styles/_global.css", ...(entry.hydrateStyleBindings || []), ], })); } await Promise.all([ ssr(manifest, routeData, { basePath, debug: args["--debug-hydration"], hasGlobalScript: globalEntryPoint !== null, }), copyHydrateAssets(manifest, globalStyle), ]); const buildEnd = performance.now(); console.log( `${green("✔")} build complete ${dim( `[${((buildEnd - buildStart) / 1000).toFixed(2)}s]` )}` ); // TODO: print tree of generated files if (!args["--no-clean"]) await cleanup(); if (args["--serve"]) { const toForward = ["--base-path", "--no-open"]; let forwardArgs = {} as any; for (const arg of toForward) { forwardArgs[arg] = args[arg]; } return import("./microsite-serve.js").then(({ default: serve }) => serve(forwardArgs) ); } process.exit(0); } async function prepare() { const paths = [SSR_DIR]; await Promise.all([...paths, OUT_DIR_NO_BASE].map((p) => rmdir(p))); await Promise.all([...paths].map((p) => mkdir(p))); await copyDir( resolve(process.cwd(), "./public"), resolve(process.cwd(), `./${OUT_DIR}`) ); } async function copyHydrateAssets( manifest: ManifestEntry[], globalStyle?: string | null ) { let tasks: any = []; const transform = async (source: string) => { source = stripWithHydrate(source); source = await preactToCDN(source); const result = await esbuild.transform(source, { minify: true, minifyIdentifiers: false, }); return result.code; }; if (globalStyle) { tasks.push( copyFile(globalStyle, resolve(OUT_DIR, "_static/styles/_global.css")) ); } if ( manifest.some( (entry) => entry.hydrateBindings && Object.keys(entry.hydrateBindings).length > 0 ) ) { const transformInit = async (source: string) => { source = await preactToCDN(source); const result = await esbuild.transform(source, { minify: true, }); return result.code; }; tasks.push( copyFile( require.resolve("microsite/runtime"), resolve(OUT_DIR, "_static/vendor/microsite.js"), { transform: transformInit } ) ); } const jsAssets = await glob([ resolve(SSR_DIR, "_hydrate/**/*.js"), resolve(SSR_DIR, "_static/**/*.js"), ]); const hydrateStyleAssets = await glob([ resolve(SSR_DIR, "_hydrate/**/*.css"), resolve(SSR_DIR, "_static/**/*.css"), ]); await Promise.all([ ...tasks, ...jsAssets.map((asset) => copyAssetToFinal(asset, transform)), ...hydrateStyleAssets.map((asset) => copyAssetToFinal(asset)), ]); return; } async function fetchRouteData(paths: string[]) { let routeData: RouteDataEntry[] = []; await Promise.all( paths.map((path) => importDataMethods(path) .then((handlers) => applyDataMethods( path.replace( resolve(process.cwd(), `./${STAGING_DIR}/src/pages`), "" ), handlers ) ) .then((entry) => { routeData = routeData.concat(...entry); }) ) ); return routeData; } type ModuleInfo = ReturnType<GetModuleInfo>; /** * This function runs rollup on Snowpack's output to * extract the hydrated chunks and prepare the pages to be * server-side rendered. */ async function bundlePagesForSSR(paths: string[]) { const bundle = await rollup({ input: paths.reduce((acc, page) => { if (/pages\//.test(page)) { return { ...acc, [page.slice(page.indexOf("pages/"), -3)]: page, }; } if (/global\/index\.js/.test(page)) { return { ...acc, "_static/chunks/_global": page, }; } }, {}), external: (source: string) => { return ( builtins.includes(source) || (source.startsWith("microsite") && !source.startsWith("microsite/runtime")) || source.startsWith("preact") ); }, plugins: [ rewriteSnowpackPreact(), rewriteCssProxies(), rewritePreact(), collecHydrateMap(), styles({ config: true, mode: "extract", minimize: true, autoModules: true, modules: { generateScopedName: `[local]_[hash:5]`, }, sourceMap: false, }), ], onwarn(warning, handler) { // unresolved import happens for anything just called server-side if (warning.code === "UNRESOLVED_IMPORT") return; handler(warning); }, }); let entries = new Set<string>(); let entryHydrations: Record<string, Set<string>> = {}; let sharedModuleCssProxyEntries = new Set<string>(); const { output } = await bundle.generate({ dir: SSR_DIR, format: "esm", sourcemap: false, hoistTransitiveImports: false, minifyInternalExports: false, chunkFileNames: "[name].js", assetFileNames: "[name][extname]", /** * This is where most of the magic happens... * We loop through all the modules and group any hydrated components * based on the entryPoint which imported them. * * Components reused for multiple routes are placed in a shared chunk. * * All code from '_snowpack/pkg' is placed in a vendor chunk. */ manualChunks(id, { getModuleInfo }) { const info = getModuleInfo(id); if (id.endsWith(".css") && !id.endsWith(".module.css")) return; if (info.importers.length === 1) { // If we only import this module in global/index.js, inline to _global chunk if (/global\/index\.js$/.test(info.importers[0])) return `_static/vendor/global`; } if (/_snowpack\/pkg/.test(info.id)) return `_static/vendor/index`; const dependentStaticEntryPoints = []; const dependentHydrateEntryPoints = []; const target = info.importedIds.includes("microsite/hydrate") ? dependentHydrateEntryPoints : dependentStaticEntryPoints; const idsToHandle = new Set([ ...info.importers, ...info.dynamicImporters, ]); let moduleInfoById: Record<string, ModuleInfo> = {}; for (const moduleId of idsToHandle) { const moduleInfo = getModuleInfo(moduleId); moduleInfoById[moduleId] = moduleInfo; for (const importerId of moduleInfo.importers) idsToHandle.add(importerId); } for (const moduleId of idsToHandle) { const moduleInfo = moduleInfoById[moduleId]; const { isEntry, dynamicImporters, importers } = moduleInfo; // TODO: naive check to see if module is a "facade" to only export sub-modules (something like `/components/index.ts`) // const isFacade = (basename(moduleId, extname(moduleId)) === 'index') && !isEntry && importedIds.every(m => dirname(m).startsWith(dirname(moduleId))); if (isEntry || [...importers, ...dynamicImporters].length > 0) target.push(moduleId); if (isEntry) { entries.add(moduleId); } } let manualChunkId: string; if (dependentHydrateEntryPoints.length > 1) { // All shared components should go in the same chunk (for now) // Eventually this could be optimized to split into a few chunks based on how many entry points rely on them manualChunkId = `_hydrate/chunks/_shared`; } if (dependentStaticEntryPoints.length > 1) { if (id.endsWith(".module.css")) { dependentStaticEntryPoints.forEach((entry) => sharedModuleCssProxyEntries.add( entry.replace(/^.*\/pages\//gim, "pages/") ) ); manualChunkId = `_static/chunks/_classnames`; } manualChunkId = "_static/chunks/_shared"; } if (dependentHydrateEntryPoints.length === 1) { const { code } = getModuleInfo(dependentHydrateEntryPoints[0]); const hash = hashContentSync(code, 8); const filename = `${getFileNameFromPath( dependentHydrateEntryPoints[0] ).replace(/^pages\//, "")}-${hash}`; manualChunkId = `_hydrate/chunks/${filename}`; } for (const moduleId of dependentHydrateEntryPoints) { if (entries.has(moduleId)) { if (!(moduleId in entryHydrations)) { entryHydrations[moduleId] = new Set(); } entryHydrations[moduleId].add(manualChunkId); } } return manualChunkId; }, }); const hydrationExports = output.reduce((acc, chunkOrAsset) => { if ( chunkOrAsset.type !== "asset" && chunkOrAsset.name.startsWith("_hydrate/") ) { return { ...acc, [chunkOrAsset.name]: chunkOrAsset.exports, }; } return acc; }, {}); const manifest: ManifestEntry[] = []; let hydrateMap: Record<string, Record<string, string>> = {}; /** * Here we're manually emitting the files so we have a chance * to generate a manifest detailing any dependent styles or * hydrated chunks per entry-point. * * Later, we'll pass the manifest to the SSR function. */ await Promise.all( output.map((chunkOrAsset) => { if (chunkOrAsset.type === "asset") { if (chunkOrAsset.name === "hydrateMap.json") { hydrateMap = JSON.parse(chunkOrAsset.source.toString()); } if (chunkOrAsset.name.startsWith("_hydrate")) { const finalAssetName = chunkOrAsset.name.replace( /\bchunks\b/, "styles" ); manifest.forEach((entry) => { let binding = chunkOrAsset.name.replace(/\.css$/, ".js"); if (entry.hydrateBindings && entry.hydrateBindings[binding]) { entry.hydrateStyleBindings = Array.from( new Set([...entry.hydrateStyleBindings, finalAssetName]) ); } }); return emitFile(finalAssetName, chunkOrAsset.source); } else if (chunkOrAsset.name.endsWith("_classnames.css")) { const finalAssetName = "_static/styles/_modules.css"; for (const entryName of sharedModuleCssProxyEntries.values()) { const inManifest = manifest.find( (entry) => entry.name === entryName ); if (inManifest) { manifest.forEach((entry) => { if (entry.name === entryName) { entry.hydrateStyleBindings = Array.from( new Set([ ...entry.hydrateStyleBindings, `${finalAssetName}?m=${hashContentSync( chunkOrAsset.source.toString(), 8 )}`, ]) ); } }); } else { manifest.push({ name: entryName, hydrateStyleBindings: [ `${finalAssetName}?m=${hashContentSync( chunkOrAsset.source.toString(), 8 )}`, ], hydrateBindings: {}, }); } } return emitFile(finalAssetName, chunkOrAsset.source); } else { let entryName = chunkOrAsset.name.replace(/\.css$/, ".js"); let finalAssetName = chunkOrAsset.name .replace(/^pages/, "_hydrate/styles") .replace(/\bchunks\b/, "styles"); const inManifest = manifest.find((entry) => entry.name === entryName); if (inManifest) { manifest.forEach((entry) => { if (entry.name === entryName) { entry.hydrateStyleBindings = Array.from( new Set([ ...entry.hydrateStyleBindings, `${finalAssetName}?m=${hashContentSync( chunkOrAsset.source.toString(), 8 )}`, ]) ); } }); } else { manifest.push({ name: entryName, hydrateStyleBindings: [], hydrateBindings: {}, }); } return emitFile(finalAssetName, chunkOrAsset.source); } } else { if ( chunkOrAsset.name.startsWith("_hydrate/") || chunkOrAsset.name.startsWith("_static/") ) { return emitFile(`${chunkOrAsset.name}.js`, chunkOrAsset.code); } else if (chunkOrAsset.isEntry) { let hydrateBindings = {}; for (const [file, exports] of Object.entries( chunkOrAsset.importedBindings )) { if (file.startsWith("_hydrate/")) { hydrateBindings = Object.assign(hydrateBindings, { [file]: exports.reduce((acc, name) => { return Object.assign(acc, { [name]: name }); }, {}), }); } } const id = chunkOrAsset.facadeModuleId; if (id in entryHydrations) { for (const hydration of entryHydrations[id]) { const exports = hydrationExports[hydration] ?? []; const file = `${hydration}.js`; hydrateBindings = Object.assign(hydrateBindings, { [file]: exports.reduce((acc, name) => { return Object.assign(acc, { [name]: name }); }, {}), }); } } const entryName = `${chunkOrAsset.name}.js`; const inManifest = manifest.find((entry) => entry.name === entryName); if (inManifest) { manifest.forEach((entry) => { if (entry.name === entryName) { entry.hydrateBindings = Object.assign( entry.hydrateBindings || {}, hydrateBindings ); } }); } else { manifest.push({ name: entryName, hydrateStyleBindings: [], hydrateBindings, }); } emitFile(entryName, chunkOrAsset.code); } else { console.log( `Unexpected chunk: ${chunkOrAsset.name}`, chunkOrAsset.code ); } } }) ); return manifest .filter(({ name }) => name !== "pages/_document.js") .map((entry) => { if (Object.keys(entry.hydrateBindings).length === 0) entry.hydrateBindings = null; if (entry.hydrateStyleBindings.length === 0) entry.hydrateStyleBindings = null; if (entry.hydrateBindings) { for (const [file, exports] of Object.entries(entry.hydrateBindings)) { const hydrated = hydrateMap[file.replace(/\.js$/, "")]; entry.hydrateBindings[file] = Object.keys(exports).reduce( (acc, key) => { return Object.assign(acc, { [hydrated[key] || key]: key }); }, {} ); } } return entry; }); } const collecHydrateMap = (): Plugin => { let withHydrateMap: Record<string, Record<string, string>> = {}; return { name: "@microsite/rollup-collec-hydrate-map", renderChunk(code: string, chunk: RenderedChunk) { if (chunk.name.startsWith("_hydrate/")) { const ast = this.parse(code); visit(ast, { visitCallExpression(path) { if (path.get("callee").getValueProperty("name") === "withHydrate") { const exportName = path.parent.get("id").getValueProperty("name"); const innerName = path.parent .get("init", "arguments", 0) .getValueProperty("name"); if (withHydrateMap[chunk.name]) { withHydrateMap[chunk.name] = Object.assign( withHydrateMap[chunk.name], { [exportName]: innerName } ); } else { withHydrateMap[chunk.name] = { [exportName]: innerName }; } return false; } this.traverse(path); }, }); return null; } return null; }, generateBundle() { this.emitFile({ type: "asset", fileName: "hydrateMap.json", name: "hydrateMap.json", source: JSON.stringify(withHydrateMap), }); }, }; }; /** * Snowpack rewrites CSS to a `.css.proxy.js` file. * Great for dev, but we need to revert to the actual CSS file */ const rewriteSnowpackPreact = () => { return { name: "@microsite/rollup-rewrite-snowpack-preact", resolveId(source: string) { if (source.indexOf("pkg/preact") > -1) return source.slice(source.indexOf("preact"), -3); return null; }, }; }; /** * Snowpack rewrites CSS to a `.css.proxy.js` file. * Great for dev, but we need to revert to the actual CSS file */ const rewriteCssProxies = () => { return { name: "@microsite/rollup-rewrite-css-proxies", resolveId(source: string, importer: string) { if (!proxyImportTransformer.filter(source)) return null; return resolve( dirname(importer), proxyImportTransformer.transform(source) ); }, }; }; /** * Snowpack rewrites CSS to a `.css.proxy.js` file. * Great for dev, but we need to revert to the actual CSS file */ const rewritePreact = () => { return { name: "@microsite/rollup-rewrite-preact", resolveId(source: string) { if (!preactImportTransformer.filter(source)) return null; return preactImportTransformer.transform(source); }, }; }; async function ssr( manifest: ManifestEntry[], routeData: RouteDataEntry[], { basePath = "/", debug = false, hasGlobalScript = false } = {} ) { return Promise.all( routeData.map((entry) => renderPage( entry, manifest.find( (route) => route.name.replace(/^pages/, "") === entry.name ), { basePath, debug, hasGlobalScript } ) .then(({ name, contents }) => { return { name, contents }; }) .then(({ name, contents }) => emitFinalAsset(name, contents)) ) ); } async function cleanup() { const paths = [STAGING_DIR, SSR_DIR, CACHE_DIR]; await Promise.all(paths.map((p) => rmdir(p))); }
the_stack
import { emptyDb, sampleDb } from './TaskDb'; describe("db - DB queries and updates", () => { describe("Queries", () => { it("user by id with query/one", () => expect(sampleDb.users.find({ id: 'AS' }).one().name).toEqual("Arya Stark")); it("user by id with 'byId'", () => expect(sampleDb.users.byId('AS').name).toEqual("Arya Stark")); it("users by multiple id with 'in'", () => expect( sampleDb.users.find({ id: { in: ['AS', 'JS'] }}).orderBy('id').toArray().map(u => u.id)) .toEqual(['AS', 'JS']), ); it("user by name", () => expect(sampleDb.users.find({ name: "Arya Stark" }).one().id).toEqual('AS')); it("user by [null] name", () => expect(sampleDb.users.find({ name: null }).one()).toBeNull()); it("sort by name", () => expect( sampleDb.users .orderBy('name') .toArray() .map(e => e.name), ).toEqual(["Arya Stark", "Daenerys Targaryen", "John Snow"]), ); it("sort by name and sex", () => expect( sampleDb.users .orderBy('sex', 'desc') .thenBy('name') .map(e => e.name), ).toEqual(["John Snow", "Arya Stark", "Daenerys Targaryen"]), ); it("sort by name and sex via order", () => expect( sampleDb.users .order([{ field: 'sex' }, { field: 'name', direction: 'desc' }]) .map(e => e.name), ).toEqual(["Daenerys Targaryen", "Arya Stark", "John Snow"]), ); it("find tasks by multiple values with 'in'", () => expect( sampleDb.tasks.find({ createdBy: { in: ['AS', 'JS'] }}).orderBy('id').map(t => t.id), ).toEqual([6, 7]), ); it("find tasks by both indexed and non-indexed fields", () => expect( sampleDb.tasks.find({ createdBy: { in: ['DT'] }, assignedTo: 'JS', isDone: false }).orderBy('id').map(t => t.id), ).toEqual([4]), ); it("non-indexable filter criteria should work", () => expect( sampleDb.tasks.find({ id: { gte: 4 }, assignedTo: 'AS', isDone: false }).orderBy('id').map(t => t.id), ).toEqual([5, 7]), ); it("non-indexable and indexable criteria for the same field", () => expect( sampleDb.tasks.find({ createdBy: { in: ['AS', 'JS'], gt: 'B' }, isDone: false }).map(t => t.id), ).toEqual([6]), ); it("count should work with filter", () => expect(sampleDb.tasks.find({ assignedTo: 'AS' }).count()).toEqual(2)); it("range should work with filter", () => expect( sampleDb.tasks.find({ createdBy: 'DT', assignedTo: { isNull: false } }).orderBy('assignedTo').thenBy('id').range(1, 3).map(i => i.id), ).toEqual([1, 3, 4]), ); }); describe("Indexes and updates", () => { it("Should query correct after insert", () => { let db = sampleDb.with({ tasks: [{ id: 100, name: "Test", assignedTo: "QQ", createdBy: "WW", isDone: false, isDraft: false }]}); expect(db.tasks.find({ assignedTo: "QQ", createdBy: "WW" }).one().id).toBe(100); }); it("Should query correct after update", () => { let db = sampleDb.with({ tasks: [{ id: 1, name: "Test", createdBy: "QQ", isDone: false, isDraft: false }]}); expect(db.tasks.find({ createdBy: "QQ" }).one().id).toBe(1); expect(db.tasks.find({ createdBy: "DT" }).orderBy('id').map(u => u.id)).toEqual([2, 3, 4, 5]); }); it("user name update", () => { const newDb = sampleDb.with({ users: [{ id: 'AS', name: 'Ivan Ivanov' }]}); expect(newDb.users.byId('AS').name).toEqual("Ivan Ivanov"); // DB is immutable, so shallow copy should be created at all levels. expect(newDb.users).not.toBe(sampleDb.users); expect(newDb.tables.users).not.toBe(sampleDb.tables.users); expect(newDb.users.byId('AS')).not.toBe(sampleDb.users.byId('AS')); expect(sampleDb.users.byId('AS').name).toEqual("Arya Stark"); }); it("Should return updated record is index is not touched", () => { let db = sampleDb.with({ tasks: [{ id: 7, name: "Test", isDone: true, isDraft: false }]}); expect(db.tasks.find({ createdBy: "AS" }).one().id).toBe(7); expect(db.tasks.find({ createdBy: "AS" }).one().name).toBe("Test"); }); it("should handle null and undefined values", () => { const testDb = emptyDb.with({ tasks: [ { id: 1, assignedTo: null, isDone: null }, { id: 2 }, ], }); expect(testDb.tasks.find({ isDone: null }).toArray().map(i => i.id)).toEqual([1]); expect(testDb.tasks.find({ isDone: undefined }).toArray().map(i => i.id)).toEqual([2]); expect(testDb.tasks.find({ isDone: { isNull: true } }).toArray().map(i => i.id)).toEqual([1, 2]); expect(testDb.tasks.find({ assignedTo: null }).toArray().map(i => i.id)).toEqual([1]); expect(testDb.tasks.find({ assignedTo: undefined }).toArray().map(i => i.id)).toEqual([2]); expect(testDb.tasks.find({ assignedTo: { isNull: true } }).toArray().map(i => i.id)).toEqual([1, 2]); }); it("Should correctly handle changes from undefined to non-undefined and reverse (non-indexed)", () => { let db1 = sampleDb.with({ tasks: [{ id: 100 }]}); // initial - undefined expect(db1.tasks.find({ name: { isNull: true } }).one().id).toBe(100); expect(db1.tasks.find({ name: undefined }).one().id).toBe(100); expect(db1.tasks.find({ name: { in: [undefined]} }).one().id).toBe(100); let db2 = db1.with({ tasks: [{ id: 100, name: 'Test' }]}); // set value expect(db2.tasks.find({ name: 'Test' }).one().id).toBe(100); let db3 = db2.with({ tasks: [{ id: 100, isDone: true }]}); // keep value expect(db2.tasks.find({ name: 'Test' }).one().id).toBe(100); let db4 = db3.with({ tasks: [{ id: 100, name: undefined }]}); // set to undefined expect(db4.tasks.find({ name: { isNull: true } }).one().id).toBe(100); expect(db4.tasks.find({ name: undefined }).one().id).toBe(100); expect(db4.tasks.find({ name: { in: [undefined]} }).one().id).toBe(100); }); it("Should correctly handle changes from null to non-null and reverse (non-indexed)", () => { let db1 = sampleDb.with({ tasks: [{ id: 100, name: null }]}); // initial - null expect(db1.tasks.find({ name: { isNull: true } }).one().id).toBe(100); expect(db1.tasks.find({ name: null }).one().id).toBe(100); expect(db1.tasks.find({ name: { in: [null]} }).one().id).toBe(100); let db2 = db1.with({ tasks: [{ id: 100, name: 'Test' }]}); // set value expect(db2.tasks.find({ name: 'Test' }).one().id).toBe(100); let db3 = db2.with({ tasks: [{ id: 100, isDone: true }]}); // keep value expect(db2.tasks.find({ name: 'Test' }).one().id).toBe(100); let db4 = db3.with({ tasks: [{ id: 100, name: null }]}); // set to null expect(db4.tasks.find({ name: { isNull: true } }).one().id).toBe(100); expect(db4.tasks.find({ name: null }).one().id).toBe(100); expect(db4.tasks.find({ name: { in: [null]} }).one().id).toBe(100); }); it("Should correctly handle changes from null to non-null and reverse (indexed)", () => { let db1 = sampleDb.with({ tasks: [{ id: 100, name: "Test", createdBy: null }]}); // initial - null expect(db1.tasks.find({ createdBy: { isNull: true } }).one().id).toBe(100); expect(db1.tasks.find({ createdBy: null }).one().id).toBe(100); expect(db1.tasks.find({ createdBy: { in: [null]} }).one().id).toBe(100); let db2 = db1.with({ tasks: [{ id: 100, createdBy: 'QQ' }]}); // set value expect(db2.tasks.find({ createdBy: 'QQ' }).one().id).toBe(100); let db3 = db2.with({ tasks: [{ id: 100, isDone: true }]}); // keep value expect(db2.tasks.find({ createdBy: 'QQ' }).one().id).toBe(100); let db4 = db3.with({ tasks: [{ id: 100, createdBy: null }]}); // set to null expect(db4.tasks.find({ createdBy: { isNull: true } }).one().id).toBe(100); expect(db4.tasks.find({ createdBy: null }).one().id).toBe(100); expect(db4.tasks.find({ createdBy: { in: [null]} }).one().id).toBe(100); }); it("Should correctly handle changes from undefined to non-undefined and reverse (indexed)", () => { let db1 = sampleDb.with({ tasks: [{ id: 100, name: "Test" }]}); // initial - undefined expect(db1.tasks.find({ createdBy: { isNull: true } }).one().id).toBe(100); expect(db1.tasks.find({ createdBy: undefined }).one().id).toBe(100); expect(db1.tasks.find({ createdBy: { in: [undefined]} }).one().id).toBe(100); let db2 = db1.with({ tasks: [{ id: 100, createdBy: 'QQ' }]}); // set value expect(db2.tasks.find({ createdBy: 'QQ' }).one().id).toBe(100); let db3 = db2.with({ tasks: [{ id: 100, isDone: true }]}); // keep value expect(db2.tasks.find({ createdBy: 'QQ' }).one().id).toBe(100); let db4 = db3.with({ tasks: [{ id: 100, createdBy: undefined }]}); // set to undefined expect(db4.tasks.find({ createdBy: { isNull: true } }).one().id).toBe(100); expect(db4.tasks.find({ createdBy: undefined }).one().id).toBe(100); expect(db4.tasks.find({ createdBy: { in: [undefined]} }).one().id).toBe(100); }); it("Should work with update which doesn't touch indexed field", () => { let db = sampleDb.with({ tasks: [ // existing, index field exists, should update index { id: 6, name: "Test", isDone: true, isDraft: false, createdBy: 'XX' }, // existing, index field omitted, should skip index update { id: 7, name: "Test", isDone: true, isDraft: false }, // new, index field omitted, should be indexed as undefined { id: 123, name: "Test", isDone: true, isDraft: false }, ]}); expect(db.tasks.find({ createdBy: "XX" }).one().id).toBe(6); expect(db.tasks.find({ createdBy: "AS" }).one().id).toBe(7); expect(db.tasks.find({ createdBy: undefined }).one().id).toBe(123); let db2 = sampleDb.with({ tasks: [{ id: 123, createdBy: 'ZZ'}]}); expect(db2.tasks.find({ createdBy: 'ZZ' }).one().id).toBe(123); }); }); describe("Composite key updates", () => { it("Can merge new managers correctly", () => { expect(sampleDb.managers.count()).toEqual(0); const role1 = { subordinateId: 'JS', managerId: 'DT', role: 'RM' }; const role2 = { subordinateId: 'AS', managerId: 'DT', role: 'PM' }; // Add one role const db1 = sampleDb.with({ managers: [role1]}); expect(db1.managers.one()).toEqual(role1); expect(db1.managers).not.toBe(sampleDb.managers); // Add second role const db2 = db1.with({ managers: [role2] }); expect(db2.managers.find({ managerId: 'DT' }).count()).toEqual(2); expect(db2.managers.byId(['JS', 'DT'])).toEqual(role1); expect(db2.managers.find({ subordinateId: 'JS', managerId: 'DT' }).one()).toEqual(role1); expect(db2.managers.find({ subordinateId: 'AS' }).one()).toEqual(role2); // Update first role const role1New = { ...role1, role: 'DM' }; const db3 = db2.with({ managers: [role1New] }); expect(db3.managers.find({ subordinateId: 'JS', managerId: 'DT' }).one()).toEqual(role1New); }); }); });
the_stack
import classNames from 'classnames' import React from 'react' import { findDOMNode } from 'react-dom' import { ResizeSensor, IResizeEntry } from '@blueprintjs/core' import { PhotoId, Photo, PhotoSectionId, PhotoSectionById, isLoadedPhotoSection } from 'common/CommonTypes' import CancelablePromise from 'common/util/CancelablePromise' import { bindMany } from 'common/util/LangUtil' import { showError } from 'app/ErrorPresenter' import { GridSectionLayout, GridLayout, JustifiedLayoutBox } from 'app/UITypes' import { CommandGroupId, addCommandGroup, setCommandGroupEnabled, removeCommandGroup } from 'app/controller/HotkeyController' import { NailedGridPosition, GetGridLayoutFunction, PhotoGridPosition } from 'app/controller/LibraryController' import { LibrarySelectionController } from 'app/controller/LibrarySelectionController' import { isPhotoSelected } from 'app/state/selectors' import { PhotoLibraryPosition, PreselectionRange, SectionPreselection, SelectionState } from 'app/state/StateTypes' import { gridScrollBarWidth, toolbarHeight } from 'app/style/variables' import { getScrollbarSize } from 'app/util/DomUtil' import GridScrollBar from './GridScrollBar' import GridSection, { sectionHeadHeight } from './GridSection' import { showDetailsCombo, toggleSelectedCombo } from './Picture' import './Grid.less' const gridSpacerHeight = 1 const gridBottomPadding = toolbarHeight // Add padding at the bottom, so the bottom bars (import and slider) don't cover a photo interface Props { className?: any isActive: boolean sectionIds: PhotoSectionId[] sectionById: PhotoSectionById activePhoto: PhotoLibraryPosition | null selection: SelectionState | null preselectionRange: PreselectionRange | null gridRowHeight: number librarySelectionController: LibrarySelectionController getGridLayout: GetGridLayoutFunction getThumbnailSrc: (photo: Photo) => string createThumbnail: (sectionId: PhotoSectionId, photo: Photo) => CancelablePromise<string> setDetailPhotoById: (sectionId: PhotoSectionId, photoId: PhotoId) => void } interface State { scrollTop: number viewportWidth: number viewportHeight: number } export default class Grid extends React.Component<Props, State> { private commandGroupId: CommandGroupId private gridLayout: GridLayout | null = null private nailedGridPosition: NailedGridPosition | null = null private releaseNailTimer: NodeJS.Timer | null = null constructor(props: Props) { super(props) this.state = { scrollTop: 0, viewportWidth: 0, viewportHeight: 0 } bindMany(this, 'showPhotoDetails', 'onShowActiveInDetail', 'onToggleActiveSelected', 'onResize', 'onScroll', 'setScrollTop', 'moveActivePhotoLeft', 'moveActivePhotoRight', 'moveActivePhotoUp', 'moveActivePhotoDown') } componentDidMount() { this.commandGroupId = addCommandGroup([ { combo: 'left', onAction: this.moveActivePhotoLeft }, { combo: 'right', onAction: this.moveActivePhotoRight }, { combo: 'up', onAction: this.moveActivePhotoUp }, { combo: 'down', onAction: this.moveActivePhotoDown }, { combo: toggleSelectedCombo, onAction: this.onToggleActiveSelected }, { combo: showDetailsCombo, onAction: this.onShowActiveInDetail }, ]) } shouldComponentUpdate(nextProps: Props, nextState: State, nextContext: any): boolean { const prevProps = this.props const prevState = this.state const prevGridLayout = this.gridLayout if (nextProps.isActive !== prevProps.isActive) { setCommandGroupEnabled(this.commandGroupId, nextProps.isActive) } if (nextProps.gridRowHeight !== prevProps.gridRowHeight || nextState.viewportWidth !== prevState.viewportWidth || nextProps.sectionIds !== prevProps.sectionIds) { // Sizes have changed (e.g. window resize, open/close info, change of gridRowHeight) // or content has changed (e.g. during import) // -> Nail the grid position if (prevGridLayout && !this.nailedGridPosition) { this.nailedGridPosition = getNailedGridPosition(prevState.scrollTop, prevState.viewportHeight, prevGridLayout.sectionLayouts, prevProps.sectionIds, prevProps.sectionById) } if (this.releaseNailTimer) { clearTimeout(this.releaseNailTimer) } this.releaseNailTimer = setTimeout(() => { this.nailedGridPosition = null }, 1000) } this.gridLayout = this.getGridLayout(nextProps, nextState) return this.gridLayout !== prevGridLayout || nextProps.activePhoto !== prevProps.activePhoto || nextProps.selection !== prevProps.selection || nextProps.preselectionRange !== prevProps.preselectionRange || nextState.scrollTop !== prevState.scrollTop } componentDidUpdate(prevProps: Props, prevState: State) { const { props, state, gridLayout, nailedGridPosition } = this if (nailedGridPosition && gridLayout) { const nextScrollTop = getScrollTopForNailedGridPosition(nailedGridPosition, state.viewportHeight, gridLayout.sectionLayouts, props.sectionIds, props.sectionById) this.nailedGridPosition = null if (nextScrollTop !== null && nextScrollTop !== state.scrollTop) { // Scroll to new position, which will trigger rendering without nailing this.setScrollTop(nextScrollTop) } else { const nextGridLayout = this.getGridLayout(props, state) if (gridLayout !== nextGridLayout) { this.gridLayout = nextGridLayout // Render without nailing this.forceUpdate() } } } } componentWillUnmount() { removeCommandGroup(this.commandGroupId) } private getGridLayout(props: Props, state: State): GridLayout { return props.getGridLayout(props.sectionIds, props.sectionById, state.scrollTop, state.viewportWidth - gridScrollBarWidth, state.viewportHeight, props.gridRowHeight, this.nailedGridPosition) } private showPhotoDetails(sectionId: PhotoSectionId, photoId: PhotoId) { this.props.setDetailPhotoById(sectionId, photoId) } private onToggleActiveSelected() { const { props } = this if (props.activePhoto) { const { sectionId, photoId } = props.activePhoto const isSelected = isPhotoSelected(sectionId, photoId, props.selection) props.librarySelectionController.setPhotoSelected(sectionId, photoId, !isSelected) } } private onShowActiveInDetail() { const { props } = this if (props.activePhoto) { props.setDetailPhotoById(props.activePhoto.sectionId, props.activePhoto.photoId) } } private onResize(entries: IResizeEntry[]) { const contentRect = entries[0].contentRect this.setState({ viewportWidth: contentRect.width, viewportHeight: contentRect.height }) } private onScroll(event: any) { const scrollPaneElem = findDOMNode(this.refs.scrollPane) as HTMLElement this.setState({ scrollTop: scrollPaneElem.scrollTop }) } private setScrollTop(scrollTop: number) { scrollTop = Math.round(scrollTop) if (scrollTop !== this.state.scrollTop) { const scrollPaneElem = findDOMNode(this.refs.scrollPane) as HTMLElement scrollPaneElem.scrollTop = scrollTop } } private moveActivePhotoLeft() { this.props.librarySelectionController.moveActivePhoto('left') } private moveActivePhotoRight() { this.props.librarySelectionController.moveActivePhoto('right') } private moveActivePhotoUp() { this.props.librarySelectionController.moveActivePhoto('up') } private moveActivePhotoDown() { this.props.librarySelectionController.moveActivePhoto('down') } private renderVisibleSections() { const { props, state, gridLayout } = this if (!gridLayout) { return } const { activePhoto } = props let result: JSX.Element[] = [] for (let sectionIndex = gridLayout.fromSectionIndex; sectionIndex < gridLayout.toSectionIndex; sectionIndex++) { const sectionId = props.sectionIds[sectionIndex] const layout = gridLayout.sectionLayouts[sectionIndex] if (!layout) { // This should not happen, but in some rare cases it might happen (had it on 2018-09-02 after empty trash) showError(`Expected to have a layout for section #${sectionIndex} (${sectionId})`) continue } result.push( <GridSection key={sectionId} className="Grid-section" style={{ left: layout.left, top: layout.top, width: layout.width, height: layout.height }} inSelectionMode={!!props.selection} section={props.sectionById[sectionId]} layout={layout} activePhotoId={(activePhoto?.sectionId === sectionId) ? activePhoto.photoId : null} sectionSelection={props.selection?.sectionSelectionById[sectionId]} sectionPreselection={getSectionPreselection(sectionIndex, props.preselectionRange)} librarySelectionController={props.librarySelectionController} getThumbnailSrc={props.getThumbnailSrc} createThumbnail={props.createThumbnail} showPhotoDetails={this.showPhotoDetails} /> ) } return result } private calculateContentHeight(): number { const { props, gridLayout } = this const sectionCount = props.sectionIds.length if (!gridLayout || sectionCount === 0) { return 0 } else { const lastLayout = gridLayout.sectionLayouts[sectionCount - 1] return lastLayout.top + lastLayout.height + gridBottomPadding } } render() { const { props, state, gridLayout } = this if (!this.gridLayout) { // This is the first call of `render` this.gridLayout = this.getGridLayout(props, state) } const contentHeight = this.calculateContentHeight() const scrollbarWidth = getScrollbarSize().width return ( <ResizeSensor onResize={this.onResize}> <div className={classNames(props.className, 'Grid')}> <div ref='scrollPane' className='Grid-scrollPane' style={{ right: `-${scrollbarWidth}px` }} onScroll={this.onScroll}> {this.renderVisibleSections()} {!!contentHeight && <div className='Grid-spacer' style={{ top: contentHeight - gridSpacerHeight }} /> } </div> {gridLayout && props.sectionIds.length > 0 && <GridScrollBar className='Grid-scrollBar' gridLayout={gridLayout!} sectionIds={props.sectionIds} sectionById={props.sectionById} viewportHeight={state.viewportHeight} contentHeight={contentHeight} scrollTop={state.scrollTop} setScrollTop={this.setScrollTop} /> } </div> </ResizeSensor> ) } } function getNailedGridPosition(scrollTop: number, viewportHeight: number, sectionLayouts: GridSectionLayout[], sectionIds: PhotoSectionId[], sectionById: PhotoSectionById): NailedGridPosition | null { const positions: PhotoGridPosition[] = [] const scrollBottom = scrollTop + viewportHeight const scrollCenter = (scrollTop + scrollBottom) / 2 for (let sectionIndex = 0, sectionCount = sectionLayouts.length; sectionIndex < sectionCount; sectionIndex++) { const sectionLayout = sectionLayouts[sectionIndex] const section = sectionById[sectionIds[sectionIndex]] const sectionBodyTop = sectionLayout.top + sectionHeadHeight const sectionBottom = sectionLayout.top + sectionLayout.height if (sectionBottom >= scrollTop && sectionLayout.boxes && isLoadedPhotoSection(section)) { for (let photoIndex = 0, photoCount = sectionLayout.boxes.length; photoIndex < photoCount; photoIndex++) { const box = sectionLayout.boxes[photoIndex] const photoId = section.photoIds[photoIndex] const boxTopInGrid = sectionBodyTop + box.top const boxBottomInGrid = boxTopInGrid + box.height if (boxBottomInGrid >= scrollTop) { if (boxTopInGrid <= scrollBottom || !positions.length) { // This photo is in view positions.push(getPhotoGridPosition(scrollCenter, sectionBodyTop, box, section.id, photoId)) } else { // This photo is out of view -> We're done return { positions } } } } } } if (positions.length) { // Happens if the very last photo is in view return { positions } } else { return null } } function getSectionPreselection(sectionIndex: number, preselectionRange: PreselectionRange | null): SectionPreselection | undefined { if (!preselectionRange) { return undefined } const { selected, startSectionIndex, endSectionIndex } = preselectionRange if (sectionIndex < startSectionIndex || sectionIndex > endSectionIndex) { return undefined } else if (sectionIndex === startSectionIndex && sectionIndex === endSectionIndex) { return preselectionRange } else if (sectionIndex === startSectionIndex) { return { selected, startPhotoIndex: preselectionRange.startPhotoIndex, endPhotoIndex: Number.POSITIVE_INFINITY } } else if (sectionIndex === endSectionIndex) { return { selected, startPhotoIndex: 0, endPhotoIndex: preselectionRange.endPhotoIndex } } else { return selected ? 'all' : 'none' } } function getPhotoGridPosition(y: number, sectionBodyTop: number, box: JustifiedLayoutBox, sectionId: PhotoSectionId, photoId: PhotoId, positionToUpdate?: Partial<PhotoGridPosition> | null): PhotoGridPosition { if (!positionToUpdate) { positionToUpdate = {} } positionToUpdate.sectionId = sectionId positionToUpdate.photoId = photoId const yWithinBox = y - sectionBodyTop - box.top let relativeY = yWithinBox / box.height let offsetY = 0 if (relativeY < 0) { relativeY = 0 offsetY = yWithinBox } else if (relativeY > 1) { relativeY = 1 offsetY = yWithinBox - box.height } positionToUpdate.relativeY = relativeY positionToUpdate.offsetY = offsetY return positionToUpdate as PhotoGridPosition } function getScrollTopForNailedGridPosition(nailedGridPosition: NailedGridPosition, viewportHeight: number, sectionLayouts: GridSectionLayout[], sectionIds: PhotoSectionId[], sectionById: PhotoSectionById): number | null { let totalCenterY = 0 let centerYCount = 0 for (const position of nailedGridPosition.positions) { const centerY = getYForPhotoGridPosition(position, sectionLayouts, sectionIds, sectionById) if (centerY != null) { totalCenterY += centerY centerYCount++ } } if (centerYCount === 0) { return null } const avgCenterY = totalCenterY / centerYCount return Math.max(0, Math.round(avgCenterY - viewportHeight / 2)) } function getYForPhotoGridPosition(position: PhotoGridPosition, sectionLayouts: GridSectionLayout[], sectionIds: PhotoSectionId[], sectionById: PhotoSectionById): number | null { const sectionIndex = sectionIds.indexOf(position.sectionId) if (sectionIndex === -1) { return null } const section = sectionById[position.sectionId] const sectionLayout = sectionLayouts[sectionIndex] if (!isLoadedPhotoSection(section) || !sectionLayout.boxes) { return null } const photoIndex = section.photoIds.indexOf(position.photoId) if (photoIndex === -1) { return null } const box = sectionLayout.boxes[photoIndex] return sectionLayout.top + sectionHeadHeight + box.top + box.height * position.relativeY + position.offsetY }
the_stack
import { Smithchart, SmithchartLegend, ISmithchartLoadedEventArgs } from '../../../src/smithchart/index'; import { createElement, remove } from '@syncfusion/ej2-base'; import {profile , inMB, getMemoryProfile} from '../../common.spec'; Smithchart.Inject(SmithchartLegend); /** * Legend spec */ describe('Smithchart legend properties tesing', () => { beforeAll(() => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } }); describe('Legend testing', () => { let id: string = 'legend'; let smithchart: Smithchart; let ele: HTMLDivElement; let spec: Element; beforeAll(() => { ele = <HTMLDivElement>createElement('div', { id: id, styles: 'height: 512px; width: 512px;' }); document.body.appendChild(ele); smithchart = new Smithchart({ series: [{ points: [ { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.5, reactance: 0.2 }, { resistance: 1.0, reactance: 0.4 }, { resistance: 1.5, reactance: 0.5 }, { resistance: 2.0, reactance: 0.5 }, { resistance: 2.5, reactance: 0.4 }, { resistance: 3.5, reactance: 0.0 }, { resistance: 4.5, reactance: -0.5 }, { resistance: 5.0, reactance: -1.0 } ], fill: 'red', name: 'Transmission1' },{ points: [ { resistance: 0, reactance: 0.15 }, { resistance: 0.3, reactance: 0.2 }, { resistance: 0.5, reactance: 0.4 }, { resistance: 1.0, reactance: 0.8 }, { resistance: 1.5, reactance: 1.0 }, { resistance: 2.0, reactance: 1.2 }, { resistance: 2.5, reactance: 1.3 }, { resistance: 3.5, reactance: 1.6 }, { resistance: 4.5, reactance: 2.0 }, { resistance: 6.0, reactance: 4.5 }, { resistance: 8, reactance: 6 }, { resistance: 10, reactance: 25 } ], name: 'Transmission2', fill: 'blue' }], legendSettings: { visible: true, } }, '#' + id); }); afterAll(() => { remove(ele); smithchart.destroy(); }); it('Checking with legend with description', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.description = 'It represents to show and hide the legend series'; smithchart.refresh(); }); it('Legend position as top', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.position = 'Top'; smithchart.refresh(); }); it('Legend position as left', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.position = 'Left'; smithchart.refresh(); }); it('Legend position as right', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.position = 'Right'; smithchart.refresh(); }); it('Legend position as Bottom', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.position = 'Bottom'; smithchart.refresh(); }); it('Legend alignment as Near - bottom position', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.alignment = 'Near'; smithchart.refresh(); }); it('Legend alignment as Far - bottom position', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.alignment = 'Far'; smithchart.refresh(); }); it('Legend alignment as Far - Left position', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.position = 'Left'; smithchart.refresh(); }); it('Legend alignment as Near - left position', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.alignment = 'Near'; smithchart.refresh(); }); it('Checking with legend size - left position', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.height = 300; smithchart.legendSettings.width = 300; smithchart.legendSettings.position = 'Left'; smithchart.refresh(); }); it('Checking with legend size - top position', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.height = null; smithchart.legendSettings.width = null; smithchart.width = '300'; smithchart.height = '200'; smithchart.legendSettings.position = 'Top'; smithchart.refresh(); }); it('Checking with legend size - bottom position', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.height = null; smithchart.legendSettings.width = null; smithchart.width = '180'; smithchart.height = '200'; smithchart.legendSettings.position = 'Bottom'; smithchart.refresh(); }); it('Checking with legend size - right position', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.height = null; smithchart.legendSettings.width = null; smithchart.width = '500'; smithchart.height = '500'; smithchart.legendSettings.position = 'Right'; smithchart.refresh(); }); it('Checking with legend item padding', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.itemPadding = 0; smithchart.refresh(); }); it('Legend position as custom without location', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.position = 'Custom'; smithchart.refresh(); }); it('Legend position as custom', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.position = 'Custom'; smithchart.legendSettings.location.x = 100; smithchart.legendSettings.location.y = 200; smithchart.refresh(); }); it('Checking with legend title', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.title.text = 'legendgroup'; smithchart.refresh(); }); it('Checking with legend title with description', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.title.text = 'legendgroup'; smithchart.legendSettings.title.description = 'It represents the legend title'; smithchart.refresh(); }); it('Checking with rowCount with position as left ', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.rowCount = 2; smithchart.legendSettings.position = 'Left'; smithchart.refresh(); }); it('Checking with columnCount with position as top', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.columnCount = 2; smithchart.legendSettings.position = 'Top'; smithchart.refresh(); }); it('Checking with rowCount and columnCount', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.rowCount = 2; smithchart.legendSettings.columnCount = 2; smithchart.refresh(); }); it('Checking with rowCount and columnCount with position as top & legend title', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.rowCount = 1; smithchart.legendSettings.columnCount = 2; smithchart.legendSettings.title.text = 'legend'; smithchart.legendSettings.position = 'Top'; smithchart.refresh(); }); it('Checking with rowCount and columnCount with position as left & legend title', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.rowCount = 1; smithchart.legendSettings.columnCount = 2; smithchart.legendSettings.title.text = 'legend'; smithchart.legendSettings.position = 'Left'; smithchart.refresh(); }); it('Checking with rowCount greater than columnCount', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.rowCount = 2; smithchart.legendSettings.columnCount = 1; smithchart.refresh(); }); it('Checking with rowCount less than columnCount', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.rowCount = 1; smithchart.legendSettings.columnCount = 2; smithchart.refresh(); }); it('Legend shape as Rectangle ', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.shape = 'Rectangle'; smithchart.refresh(); }); it('Legend shape as Triangle ', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.shape = 'Triangle'; smithchart.refresh(); }); it('Legend shape as Pentagon ', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.shape = 'Pentagon'; smithchart.refresh(); }); it('Legend shape as Diamond ', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.shape = 'Diamond'; smithchart.refresh(); }); it('checking legend title with alignement far ', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.title.text = 'legendtitle'; smithchart.legendSettings.title.textAlignment = 'Far'; smithchart.refresh(); }); it('checking legend title with alignement Near ', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.title.text = 'legendtitle'; smithchart.legendSettings.title.textAlignment = 'Near'; smithchart.refresh(); }); it('checking legend title with alignement center ', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.legendSettings.title.text = 'smithchartlegendtitlegrouptextrendering'; smithchart.legendSettings.title.textAlignment = 'Center'; smithchart.refresh(); }); it('checking with legend without giving name to series', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.series[0].name = ''; smithchart.series[1].name = ''; smithchart.refresh(); }); it('checking with legend without giving color to series', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.series[0].fill = ''; smithchart.series[1].fill = ''; smithchart.refresh(); }); it('checking with series visibility as hidden', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_legend_group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.series[0].visibility = 'hidden'; smithchart.refresh(); }); it('checking with legend visibility as false', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_series0_points'); let color: string = element.getAttribute('stroke'); expect(color).toEqual('#00bdae'); }; smithchart.legendSettings.visible = false; smithchart.refresh(); }); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }); });
the_stack
import { spawn } from "node:child_process"; import * as path from "node:path"; import { watch } from "chokidar"; import clipboardy from "clipboardy"; import commandExists from "command-exists"; import { Box, Text, useApp, useInput, useStdin } from "ink"; import React, { useState, useEffect, useRef } from "react"; import { withErrorBoundary, useErrorHandler } from "react-error-boundary"; import onExit from "signal-exit"; import tmp from "tmp-promise"; import { fetch } from "undici"; import { runCustomBuild } from "../entry"; import { logger } from "../logger"; import openInBrowser from "../open-in-browser"; import { getAPIToken } from "../user"; import { Local } from "./local"; import { Remote } from "./remote"; import { useEsbuild } from "./use-esbuild"; import type { Config } from "../config"; import type { Entry } from "../entry"; import type { AssetPaths } from "../sites"; import type { CfWorkerInit } from "../worker"; import type { EsbuildBundle } from "./use-esbuild"; export type DevProps = { name?: string; entry: Entry; port: number; ip: string; inspectorPort: number; rules: Config["rules"]; accountId: string | undefined; initialMode: "local" | "remote"; jsxFactory: string | undefined; jsxFragment: string | undefined; tsconfig: string | undefined; upstreamProtocol: "https" | "http"; localProtocol: "https" | "http"; enableLocalPersistence: boolean; bindings: CfWorkerInit["bindings"]; crons: Config["triggers"]["crons"]; public: string | undefined; assetPaths: AssetPaths | undefined; compatibilityDate: string; compatibilityFlags: string[] | undefined; usageModel: "bundled" | "unbound" | undefined; minify: boolean | undefined; nodeCompat: boolean | undefined; build: { command?: string | undefined; cwd?: string | undefined; watch_dir?: string | undefined; }; env: string | undefined; legacyEnv: boolean; zone: | { id: string; host: string; } | undefined; }; export function DevImplementation(props: DevProps): JSX.Element { const apiToken = props.initialMode === "remote" ? getAPIToken() : undefined; const directory = useTmpDir(); useCustomBuild(props.entry, props.build); if (props.public && props.entry.format === "service-worker") { throw new Error( "You cannot use the service-worker format with a `public` directory." ); } if (props.bindings.wasm_modules && props.entry.format === "modules") { throw new Error( "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code" ); } if (props.bindings.text_blobs && props.entry.format === "modules") { throw new Error( "You cannot configure [text_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[rules]` in your wrangler.toml" ); } if (props.bindings.data_blobs && props.entry.format === "modules") { throw new Error( "You cannot configure [data_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[rules]` in your wrangler.toml" ); } const bundle = useEsbuild({ entry: props.entry, destination: directory, staticRoot: props.public, jsxFactory: props.jsxFactory, rules: props.rules, jsxFragment: props.jsxFragment, serveAssetsFromWorker: !!props.public, tsconfig: props.tsconfig, minify: props.minify, nodeCompat: props.nodeCompat, }); // only load the UI if we're running in a supported environment const { isRawModeSupported } = useStdin(); return isRawModeSupported ? ( <InteractiveDevSession {...props} bundle={bundle} apiToken={apiToken} /> ) : ( <DevSession {...props} bundle={bundle} apiToken={apiToken} local={props.initialMode === "local"} /> ); } type InteractiveDevSessionProps = DevProps & { apiToken: string | undefined; bundle: EsbuildBundle | undefined; }; function InteractiveDevSession(props: InteractiveDevSessionProps) { const toggles = useHotkeys( { local: props.initialMode === "local", tunnel: false, }, props.port, props.ip, props.inspectorPort, props.localProtocol ); useTunnel(toggles.tunnel); return ( <> <DevSession {...props} local={toggles.local} /> <Box borderStyle="round" paddingLeft={1} paddingRight={1}> <Text bold={true}>[b]</Text> <Text> open a browser, </Text> <Text bold={true}>[d]</Text> <Text> open Devtools, </Text> <Text bold={true}>[l]</Text> <Text> {toggles.local ? "turn off" : "turn on"} local mode, </Text> <Text bold={true}>[c]</Text> <Text> clear console, </Text> <Text bold={true}>[x]</Text> <Text> to exit</Text> </Box> </> ); } type DevSessionProps = InteractiveDevSessionProps & { local: boolean }; function DevSession(props: DevSessionProps) { return props.local ? ( <Local name={props.name} bundle={props.bundle} format={props.entry.format} compatibilityDate={props.compatibilityDate} compatibilityFlags={props.compatibilityFlags} bindings={props.bindings} assetPaths={props.assetPaths} public={props.public} port={props.port} ip={props.ip} rules={props.rules} inspectorPort={props.inspectorPort} enableLocalPersistence={props.enableLocalPersistence} crons={props.crons} /> ) : ( <Remote name={props.name} bundle={props.bundle} format={props.entry.format} accountId={props.accountId} apiToken={props.apiToken} bindings={props.bindings} assetPaths={props.assetPaths} public={props.public} port={props.port} ip={props.ip} localProtocol={props.localProtocol} inspectorPort={props.inspectorPort} compatibilityDate={props.compatibilityDate} compatibilityFlags={props.compatibilityFlags} usageModel={props.usageModel} env={props.env} legacyEnv={props.legacyEnv} zone={props.zone} /> ); } export interface DirectorySyncResult { name: string; removeCallback: () => void; } function useTmpDir(): string | undefined { const [directory, setDirectory] = useState<DirectorySyncResult>(); const handleError = useErrorHandler(); useEffect(() => { let dir: DirectorySyncResult | undefined; try { dir = tmp.dirSync({ unsafeCleanup: true }); setDirectory(dir); return; } catch (err) { logger.error( "Failed to create temporary directory to store built files." ); handleError(err); } return () => { dir?.removeCallback(); }; }, [handleError]); return directory?.name; } function useCustomBuild( expectedEntry: Entry, build: { command?: string | undefined; cwd?: string | undefined; watch_dir?: string | undefined; } ): void { useEffect(() => { if (!build.command) return; let watcher: ReturnType<typeof watch> | undefined; if (build.watch_dir) { watcher = watch(build.watch_dir, { persistent: true, ignoreInitial: true, }).on("all", (_event, filePath) => { const relativeFile = path.relative(expectedEntry.directory, expectedEntry.file) || "."; //TODO: we should buffer requests to the proxy until this completes logger.log(`The file ${filePath} changed, restarting build...`); runCustomBuild(expectedEntry.file, relativeFile, build).catch((err) => { logger.error("Custom build failed:", err); }); }); } return () => { watcher?.close(); }; }, [build, expectedEntry]); } function sleep(period: number) { return new Promise((resolve) => setTimeout(resolve, period)); } const SLEEP_DURATION = 2000; // really need a first class api for this const hostNameRegex = /userHostname="(.*)"/g; async function findTunnelHostname() { let hostName: string | undefined; while (!hostName) { try { const resp = await fetch("http://localhost:8789/metrics"); const data = await resp.text(); const matches = Array.from(data.matchAll(hostNameRegex)); hostName = matches[0][1]; } catch (err) { await sleep(SLEEP_DURATION); } } return hostName; } /** * Create a tunnel to the remote worker. * We've disabled this for now until we figure out a better user experience. */ function useTunnel(toggle: boolean) { const tunnel = useRef<ReturnType<typeof spawn>>(); const removeSignalExitListener = useRef<() => void>(); // TODO: test if cloudflared is available, if not // point them to a url where they can get docs to install it useEffect(() => { async function startTunnel() { if (toggle) { try { await commandExists("cloudflared"); } catch (e) { logger.warn( "To share your worker on the Internet, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation" ); return; } logger.log("⎔ Starting a tunnel..."); tunnel.current = spawn("cloudflared", [ "tunnel", "--url", "http://localhost:8787", "--metrics", "localhost:8789", ]); tunnel.current.on("close", (code) => { if (code) { logger.log(`Tunnel process exited with code ${code}`); } }); removeSignalExitListener.current = onExit((_code, _signal) => { logger.log("⎔ Shutting down local tunnel."); tunnel.current?.kill(); tunnel.current = undefined; }); const hostName = await findTunnelHostname(); await clipboardy.write(hostName); logger.log(`⬣ Sharing at ${hostName}, copied to clipboard.`); } } startTunnel().catch(async (err) => { logger.error("tunnel:", err); }); return () => { if (tunnel.current) { logger.log("⎔ Shutting down tunnel."); tunnel.current?.kill(); tunnel.current = undefined; removeSignalExitListener.current && removeSignalExitListener.current(); removeSignalExitListener.current = undefined; } }; }, [toggle]); } type useHotkeysInitialState = { local: boolean; tunnel: boolean; }; function useHotkeys( initial: useHotkeysInitialState, port: number, ip: string, inspectorPort: number, localProtocol: "http" | "https" ) { // UGH, we should put port in context instead const [toggles, setToggles] = useState(initial); const { exit } = useApp(); useInput( async ( input, // eslint-disable-next-line unused-imports/no-unused-vars key ) => { switch (input.toLowerCase()) { // clear console case "c": console.clear(); // This console.log causes Ink to re-render the `DevSession` component. // Couldn't find a better way to tell it to do so... console.log(); break; // open browser case "b": { await openInBrowser(`${localProtocol}://${ip}:${port}`); break; } // toggle inspector case "d": { await openInBrowser( `https://built-devtools.pages.dev/js_app?experiments=true&v8only=true&ws=localhost:${inspectorPort}/ws`, { forceChromium: true } ); break; } // toggle local case "l": setToggles((previousToggles) => ({ ...previousToggles, local: !previousToggles.local, })); break; // shut down case "q": case "x": exit(); break; default: // nothing? break; } } ); return toggles; } function ErrorFallback(props: { error: Error }) { const { exit } = useApp(); useEffect(() => exit(props.error)); return ( <> <Text>Something went wrong:</Text> <Text>{props.error.stack}</Text> </> ); } export default withErrorBoundary(DevImplementation, { FallbackComponent: ErrorFallback, });
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace Formmsdyn_iotalert_Information { interface Header extends DevKit.Controls.IHeader { /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface tab__B4D9BB28_1BD1_4896_AA83_A8CD2A781DDE_Sections { AlertDataSection: DevKit.Controls.Section; AssetSection: DevKit.Controls.Section; Connected_Device_Readings: DevKit.Controls.Section; Device_Summary_Visualization: DevKit.Controls.Section; HierarchySection: DevKit.Controls.Section; SuggestionsSection: DevKit.Controls.Section; } interface tab_AssetDetailsTab_Sections { AssetWorkOrdersSection: DevKit.Controls.Section; } interface tab_DeviceCommandsTab_Sections { DeviceCommandsSection: DevKit.Controls.Section; } interface tab_DeviceInsightsTab_Sections { DeviceInsightsSection: DevKit.Controls.Section; } interface tab__B4D9BB28_1BD1_4896_AA83_A8CD2A781DDE extends DevKit.Controls.ITab { Section: tab__B4D9BB28_1BD1_4896_AA83_A8CD2A781DDE_Sections; } interface tab_AssetDetailsTab extends DevKit.Controls.ITab { Section: tab_AssetDetailsTab_Sections; } interface tab_DeviceCommandsTab extends DevKit.Controls.ITab { Section: tab_DeviceCommandsTab_Sections; } interface tab_DeviceInsightsTab extends DevKit.Controls.ITab { Section: tab_DeviceInsightsTab_Sections; } interface Tabs { _B4D9BB28_1BD1_4896_AA83_A8CD2A781DDE: tab__B4D9BB28_1BD1_4896_AA83_A8CD2A781DDE; AssetDetailsTab: tab_AssetDetailsTab; DeviceCommandsTab: tab_DeviceCommandsTab; DeviceInsightsTab: tab_DeviceInsightsTab; } interface Body { Tab: Tabs; /** Data sent from the device about the alert. */ msdyn_AlertData: DevKit.Controls.String; /** Data sent from the device about the alert. */ msdyn_AlertData_1: DevKit.Controls.String; /** The suggested priority score for this alert. */ msdyn_alertpriorityscore: DevKit.Controls.Integer; /** The time the alert was issued. */ msdyn_AlertTime: DevKit.Controls.DateTime; /** The unique reference to the event id on the IoT provider. */ msdyn_AlertToken: DevKit.Controls.String; msdyn_alerttype: DevKit.Controls.OptionSet; /** External URL to view more information about the iot alert. */ msdyn_AlertURL: DevKit.Controls.String; /** The asset connected to the IoT device that raised the alert. */ msdyn_CustomerAsset: DevKit.Controls.Lookup; /** A description for the alert. */ msdyn_Description: DevKit.Controls.String; /** The IoT device for which this alert was raised. */ msdyn_Device: DevKit.Controls.Lookup; /** The IoT device for which this alert was raised. */ msdyn_Device_1: DevKit.Controls.Lookup; /** The IoT device for which this alert was raised. */ msdyn_Device_2: DevKit.Controls.Lookup; /** The ID of the IoT device that sent the alert. */ msdyn_DeviceID: DevKit.Controls.String; /** Reference to a primary alert. This field is inferred if Primary Alert Token is set. */ msdyn_ParentAlert: DevKit.Controls.Lookup; /** Reference to a previously created primary iot alert */ msdyn_ParentAlertToken: DevKit.Controls.String; /** The suggested incident type for this alert */ msdyn_suggestedincidenttype: DevKit.Controls.Lookup; /** The suggested priority for this alert. */ msdyn_suggestedpriority: DevKit.Controls.OptionSet; notescontrol: DevKit.Controls.Note; /** Reason for the status of the IoT Alert */ statuscode: DevKit.Controls.OptionSet; WebResource_PowerBIAlert: DevKit.Controls.WebResource; } interface quickForm_AssetWorkOrdersView_Body { } interface quickForm_AssetWorkOrdersView extends DevKit.Controls.IQuickView { Body: quickForm_AssetWorkOrdersView_Body; } interface QuickForm { AssetWorkOrdersView: quickForm_AssetWorkOrdersView; } interface ProcessIoT_Alert_to_Case_Process { /** The time the alert was issued. */ msdyn_AlertTime: DevKit.Controls.DateTime; /** The asset connected to the IoT device that raised the alert. */ msdyn_CustomerAsset: DevKit.Controls.Lookup; /** A description for the alert. */ msdyn_Description: DevKit.Controls.String; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface ProcessCFS_IoT_Alert_Process_Flow { /** The time the alert was issued. */ msdyn_AlertTime: DevKit.Controls.DateTime; /** A description for the alert. */ msdyn_Description: DevKit.Controls.String; /** The IoT device for which this alert was raised. */ msdyn_Device: DevKit.Controls.Lookup; } interface Process extends DevKit.Controls.IProcess { IoT_Alert_to_Case_Process: ProcessIoT_Alert_to_Case_Process; CFS_IoT_Alert_Process_Flow: ProcessCFS_IoT_Alert_Process_Flow; } interface Grid { DeviceCommandsGrid: DevKit.Controls.Grid; } } class Formmsdyn_iotalert_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form msdyn_iotalert_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form msdyn_iotalert_Information */ Body: DevKit.Formmsdyn_iotalert_Information.Body; /** The Header section of form msdyn_iotalert_Information */ Header: DevKit.Formmsdyn_iotalert_Information.Header; /** The QuickForm of form msdyn_iotalert_Information */ QuickForm: DevKit.Formmsdyn_iotalert_Information.QuickForm; /** The Process of form msdyn_iotalert_Information */ Process: DevKit.Formmsdyn_iotalert_Information.Process; /** The Grid of form msdyn_iotalert_Information */ Grid: DevKit.Formmsdyn_iotalert_Information.Grid; } class msdyn_iotalertApi { /** * DynamicsCrm.DevKit msdyn_iotalertApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the record. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Data sent from the device about the alert. */ msdyn_AlertData: DevKit.WebApi.StringValue; /** The suggested priority score for this alert. */ msdyn_alertpriorityscore: DevKit.WebApi.IntegerValue; /** The time the alert was issued. */ msdyn_AlertTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** The unique reference to the event id on the IoT provider. */ msdyn_AlertToken: DevKit.WebApi.StringValue; msdyn_alerttype: DevKit.WebApi.OptionSetValue; /** External URL to view more information about the iot alert. */ msdyn_AlertURL: DevKit.WebApi.StringValue; /** Case created for this iot alert. */ msdyn_case: DevKit.WebApi.LookupValue; /** The asset connected to the IoT device that raised the alert. */ msdyn_CustomerAsset: DevKit.WebApi.LookupValue; /** A description for the alert. */ msdyn_Description: DevKit.WebApi.StringValue; /** The IoT device for which this alert was raised. */ msdyn_Device: DevKit.WebApi.LookupValue; /** The ID of the IoT device that sent the alert. */ msdyn_DeviceID: DevKit.WebApi.StringValue; /** Unique identifier for entity instances */ msdyn_iotalertId: DevKit.WebApi.GuidValue; msdyn_LastCommandSent: DevKit.WebApi.LookupValue; msdyn_LastCommandSentTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Reference to a primary alert. This field is inferred if Primary Alert Token is set. */ msdyn_ParentAlert: DevKit.WebApi.LookupValue; /** Reference to a previously created primary iot alert */ msdyn_ParentAlertToken: DevKit.WebApi.StringValue; /** The suggested incident type for this alert */ msdyn_suggestedincidenttype: DevKit.WebApi.LookupValue; /** The suggested priority for this alert. */ msdyn_suggestedpriority: DevKit.WebApi.OptionSetValue; /** Work order created for this iot alert. */ msdyn_Workorder: DevKit.WebApi.LookupValue; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Contains the id of the process associated with the entity. */ processid: DevKit.WebApi.GuidValue; /** Contains the id of the stage where the entity is located. */ stageid: DevKit.WebApi.GuidValue; /** Status of the IoT Alert */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the IoT Alert */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** A comma separated list of string values representing the unique identifiers of stages in a Business Process Flow Instance in the order that they occur. */ traversedpath: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace msdyn_iotalert { enum msdyn_alerttype { /** 192350000 */ Anomaly, /** 192350001 */ Info, /** 192350002 */ Preventive_Maintenance, /** 192350003 */ Test } enum msdyn_suggestedpriority { /** 192350000 */ Calculating, /** 192350001 */ High, /** 192350002 */ Low, /** 192350003 */ No_Suggestions } enum statecode { /** 0 */ Active, /** 3 */ Closed, /** 1 */ Inactive, /** 2 */ InProgress } enum statuscode { /** 1 */ Active, /** 6 */ Closed, /** 3 */ In_Progress_Case_Created, /** 7 */ In_Progress_Command_Failed, /** 5 */ In_Progress_Command_Sent, /** 4 */ In_Progress_Work_Order_Created, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
const getSignedUrlResponse = jest.fn(); const mockS3 = { getSignedUrl: getSignedUrlResponse, }; const listJobsResponse = jest.fn(); const listJobsRequest = jest.fn().mockImplementation(() => { return { promise: listJobsResponse, }; }); const startDeploymentResponse = jest.fn(); const startDeploymentRequest = jest.fn().mockImplementation(() => { return { promise: startDeploymentResponse, }; }); const getJobResponse = jest.fn(); const getJobRequest = jest.fn().mockImplementation(() => { return { promise: getJobResponse, }; }); const mockAmplify = { listJobs: listJobsRequest, startDeployment: startDeploymentRequest, getJob: getJobRequest, }; jest.mock('aws-sdk', () => { return { S3: jest.fn(() => mockS3), Amplify: jest.fn(() => mockAmplify), config: { logger: '' }, }; }); import { onEvent, isComplete, } from '../../lib/asset-deployment-handler'; describe('handler', () => { let oldConsoleLog: any; beforeAll(() => { oldConsoleLog = global.console.log; global.console.log = jest.fn(); }); afterAll(() => { global.console.log = oldConsoleLog; }); afterEach(() => { jest.clearAllMocks(); }); it('onEvent CREATE success', async () => { // GIVEN listJobsResponse.mockImplementation(() => { return { jobSummaries: [], }; }); getSignedUrlResponse.mockImplementation(() => { return 'signedUrlValue'; }); startDeploymentResponse.mockImplementation(() => { return { jobSummary: { jobId: 'jobIdValue' }, }; }); // WHEN const response = await onEvent({ ServiceToken: 'serviceTokenValue', RequestType: 'Create', ResourceType: 'Custom::AmplifyAssetDeployment', ResourceProperties: { ServiceToken: 'serviceTokenValue', AppId: 'appIdValue', BranchName: 'branchNameValue', S3BucketName: 's3BucketNameValue', S3ObjectKey: 's3ObjectKeyValue', }, ResponseURL: 'responseUrlValue', StackId: 'stackIdValue', RequestId: 'requestIdValue', LogicalResourceId: 'logicalResourceIdValue', }); // THEN expect(response).toEqual({ AmplifyJobId: 'jobIdValue', }); expect(listJobsRequest).toHaveBeenCalledWith({ appId: 'appIdValue', branchName: 'branchNameValue', maxResults: 1, }); expect(listJobsResponse).toBeCalled(); expect(getSignedUrlResponse).toHaveBeenCalledWith('getObject', { Bucket: 's3BucketNameValue', Key: 's3ObjectKeyValue', }); expect(startDeploymentRequest).toHaveBeenCalledWith({ appId: 'appIdValue', branchName: 'branchNameValue', sourceUrl: 'signedUrlValue', }); expect(startDeploymentResponse).toBeCalled(); }); it('onEvent CREATE pending job', async () => { // GIVEN listJobsResponse.mockImplementation(() => { return { jobSummaries: [{ status: 'PENDING' }], }; }); // WHEN await expect(() => onEvent({ ServiceToken: 'serviceTokenValue', RequestType: 'Create', ResourceType: 'Custom::AmplifyAssetDeployment', ResourceProperties: { ServiceToken: 'serviceTokenValue', AppId: 'appIdValue', BranchName: 'branchNameValue', S3BucketName: 's3BucketNameValue', S3ObjectKey: 's3ObjectKeyValue', }, ResponseURL: 'responseUrlValue', StackId: 'stackIdValue', RequestId: 'requestIdValue', LogicalResourceId: 'logicalResourceIdValue', })).rejects.toMatch('Amplify job already running. Aborting deployment.'); expect(listJobsRequest).toHaveBeenCalledWith({ appId: 'appIdValue', branchName: 'branchNameValue', maxResults: 1, }); expect(listJobsResponse).toBeCalled(); expect(getSignedUrlResponse).not.toHaveBeenCalled(); expect(startDeploymentRequest).not.toHaveBeenCalled(); expect(startDeploymentResponse).not.toHaveBeenCalled(); }); it('isComplete CREATE success', async () => { // GIVEN getJobResponse.mockImplementation(() => { return { job: { summary: { status: 'SUCCEED' } }, }; }); // WHEN const response = await isComplete({ ServiceToken: 'serviceTokenValue', RequestType: 'Create', ResourceType: 'Custom::AmplifyAssetDeployment', ResourceProperties: { ServiceToken: 'serviceTokenValue', AppId: 'appIdValue', BranchName: 'branchNameValue', S3BucketName: 's3BucketNameValue', S3ObjectKey: 's3ObjectKeyValue', }, ResponseURL: 'responseUrlValue', StackId: 'stackIdValue', RequestId: 'requestIdValue', LogicalResourceId: 'logicalResourceIdValue', AmplifyJobId: 'amplifyJobIdValue', }); // THEN expect(response).toEqual({ Data: { JobId: 'amplifyJobIdValue', Status: 'SUCCEED', }, IsComplete: true, }); expect(getJobRequest).toHaveBeenCalledWith({ appId: 'appIdValue', branchName: 'branchNameValue', jobId: 'amplifyJobIdValue', }); expect(getJobResponse).toBeCalled(); }); it('isComplete CREATE pending', async () => { // GIVEN getJobResponse.mockImplementation(() => { return { job: { summary: { status: 'PENDING' } }, }; }); // WHEN const response = await isComplete({ ServiceToken: 'serviceTokenValue', RequestType: 'Create', ResourceType: 'Custom::AmplifyAssetDeployment', ResourceProperties: { ServiceToken: 'serviceTokenValue', AppId: 'appIdValue', BranchName: 'branchNameValue', S3BucketName: 's3BucketNameValue', S3ObjectKey: 's3ObjectKeyValue', }, ResponseURL: 'responseUrlValue', StackId: 'stackIdValue', RequestId: 'requestIdValue', LogicalResourceId: 'logicalResourceIdValue', AmplifyJobId: 'amplifyJobIdValue', }); // THEN expect(response).toEqual({ IsComplete: false, }); expect(getJobRequest).toHaveBeenCalledWith({ appId: 'appIdValue', branchName: 'branchNameValue', jobId: 'amplifyJobIdValue', }); expect(getJobResponse).toBeCalled(); }); it('isComplete CREATE failed', async () => { // GIVEN getJobResponse.mockImplementation(() => { return { job: { summary: { status: 'FAILED' } }, }; }); // WHEN await expect(() => isComplete({ ServiceToken: 'serviceTokenValue', RequestType: 'Create', ResourceType: 'Custom::AmplifyAssetDeployment', ResourceProperties: { ServiceToken: 'serviceTokenValue', AppId: 'appIdValue', BranchName: 'branchNameValue', S3BucketName: 's3BucketNameValue', S3ObjectKey: 's3ObjectKeyValue', }, ResponseURL: 'responseUrlValue', StackId: 'stackIdValue', RequestId: 'requestIdValue', LogicalResourceId: 'logicalResourceIdValue', AmplifyJobId: 'amplifyJobIdValue', })).rejects.toThrow('Amplify job failed with status: FAILED'); // THEN expect(getJobRequest).toHaveBeenCalledWith({ appId: 'appIdValue', branchName: 'branchNameValue', jobId: 'amplifyJobIdValue', }); expect(getJobResponse).toBeCalled(); }); it('isComplete CREATE cancelled', async () => { // GIVEN getJobResponse.mockImplementation(() => { return { job: { summary: { status: 'CANCELLED' } }, }; }); // WHEN await expect(() => isComplete({ ServiceToken: 'serviceTokenValue', RequestType: 'Create', ResourceType: 'Custom::AmplifyAssetDeployment', ResourceProperties: { ServiceToken: 'serviceTokenValue', AppId: 'appIdValue', BranchName: 'branchNameValue', S3BucketName: 's3BucketNameValue', S3ObjectKey: 's3ObjectKeyValue', }, ResponseURL: 'responseUrlValue', StackId: 'stackIdValue', RequestId: 'requestIdValue', LogicalResourceId: 'logicalResourceIdValue', AmplifyJobId: 'amplifyJobIdValue', })).rejects.toThrow('Amplify job failed with status: CANCELLED'); // THEN expect(getJobRequest).toHaveBeenCalledWith({ appId: 'appIdValue', branchName: 'branchNameValue', jobId: 'amplifyJobIdValue', }); expect(getJobResponse).toBeCalled(); }); it('isComplete CREATE no JobId', async () => { // GIVEN getJobResponse.mockImplementation(() => { return { job: { summary: { status: 'PENDING' } }, }; }); // WHEN await expect(() => isComplete({ ServiceToken: 'serviceTokenValue', RequestType: 'Create', ResourceType: 'Custom::AmplifyAssetDeployment', ResourceProperties: { ServiceToken: 'serviceTokenValue', AppId: 'appIdValue', BranchName: 'branchNameValue', S3BucketName: 's3BucketNameValue', S3ObjectKey: 's3ObjectKeyValue', }, ResponseURL: 'responseUrlValue', StackId: 'stackIdValue', RequestId: 'requestIdValue', LogicalResourceId: 'logicalResourceIdValue', })).rejects.toThrow('Unable to determine Amplify job status without job id'); // THEN expect(getJobRequest).not.toHaveBeenCalled(); expect(getJobResponse).not.toHaveBeenCalled(); }); it('onEvent UPDATE success', async () => { // GIVEN listJobsResponse.mockImplementation(() => { return { jobSummaries: [], }; }); getSignedUrlResponse.mockImplementation(() => { return 'signedUrlValue'; }); startDeploymentResponse.mockImplementation(() => { return { jobSummary: { jobId: 'jobIdValue' }, }; }); // WHEN const response = await onEvent({ ServiceToken: 'serviceTokenValue', RequestType: 'Update', ResourceType: 'Custom::AmplifyAssetDeployment', ResourceProperties: { ServiceToken: 'serviceTokenValue', AppId: 'appIdValue', BranchName: 'branchNameValue', S3BucketName: 's3BucketNameValue', S3ObjectKey: 's3ObjectKeyValue', }, OldResourceProperties: { ServiceToken: 'serviceTokenValue' }, ResponseURL: 'responseUrlValue', StackId: 'stackIdValue', RequestId: 'requestIdValue', LogicalResourceId: 'logicalResourceIdValue', PhysicalResourceId: 'physicalResourceIdValue', }); // THEN expect(response).toEqual({ AmplifyJobId: 'jobIdValue', }); expect(listJobsRequest).toHaveBeenCalledWith({ appId: 'appIdValue', branchName: 'branchNameValue', maxResults: 1, }); expect(listJobsResponse).toBeCalled(); expect(getSignedUrlResponse).toHaveBeenCalledWith('getObject', { Bucket: 's3BucketNameValue', Key: 's3ObjectKeyValue', }); expect(startDeploymentRequest).toHaveBeenCalledWith({ appId: 'appIdValue', branchName: 'branchNameValue', sourceUrl: 'signedUrlValue', }); expect(startDeploymentResponse).toBeCalled(); }); it('onEvent UPDATE pending job', async () => { // GIVEN listJobsResponse.mockImplementation(() => { return { jobSummaries: [{ status: 'PENDING' }], }; }); // WHEN await expect(() => onEvent({ ServiceToken: 'serviceTokenValue', RequestType: 'Update', ResourceType: 'Custom::AmplifyAssetDeployment', ResourceProperties: { ServiceToken: 'serviceTokenValue', AppId: 'appIdValue', BranchName: 'branchNameValue', S3BucketName: 's3BucketNameValue', S3ObjectKey: 's3ObjectKeyValue', }, OldResourceProperties: { ServiceToken: 'serviceTokenValue' }, ResponseURL: 'responseUrlValue', StackId: 'stackIdValue', RequestId: 'requestIdValue', LogicalResourceId: 'logicalResourceIdValue', PhysicalResourceId: 'physicalResourceIdValue', })).rejects.toMatch('Amplify job already running. Aborting deployment.'); // THEN expect(listJobsRequest).toHaveBeenCalledWith({ appId: 'appIdValue', branchName: 'branchNameValue', maxResults: 1, }); expect(listJobsResponse).toBeCalled(); expect(getSignedUrlResponse).not.toHaveBeenCalled(); expect(startDeploymentRequest).not.toHaveBeenCalled(); expect(startDeploymentResponse).not.toHaveBeenCalled(); }); it('isComplete UPDATE success', async () => { // GIVEN getJobResponse.mockImplementation(() => { return { job: { summary: { status: 'SUCCEED' } }, }; }); // WHEN const response = await isComplete({ ServiceToken: 'serviceTokenValue', RequestType: 'Update', ResourceType: 'Custom::AmplifyAssetDeployment', ResourceProperties: { ServiceToken: 'serviceTokenValue', AppId: 'appIdValue', BranchName: 'branchNameValue', S3BucketName: 's3BucketNameValue', S3ObjectKey: 's3ObjectKeyValue', }, OldResourceProperties: {}, ResponseURL: 'responseUrlValue', StackId: 'stackIdValue', RequestId: 'requestIdValue', LogicalResourceId: 'logicalResourceIdValue', AmplifyJobId: 'amplifyJobIdValue', PhysicalResourceId: 'physicalResourceIdValue', }); // THEN expect(response).toEqual({ Data: { JobId: 'amplifyJobIdValue', Status: 'SUCCEED', }, IsComplete: true, }); expect(getJobRequest).toHaveBeenCalledWith({ appId: 'appIdValue', branchName: 'branchNameValue', jobId: 'amplifyJobIdValue', }); expect(getJobResponse).toBeCalled(); }); it('isComplete UPDATE pending', async () => { // GIVEN getJobResponse.mockImplementation(() => { return { job: { summary: { status: 'PENDING' } }, }; }); // WHEN const response = await isComplete({ ServiceToken: 'serviceTokenValue', RequestType: 'Update', ResourceType: 'Custom::AmplifyAssetDeployment', ResourceProperties: { ServiceToken: 'serviceTokenValue', AppId: 'appIdValue', BranchName: 'branchNameValue', S3BucketName: 's3BucketNameValue', S3ObjectKey: 's3ObjectKeyValue', }, OldResourceProperties: {}, ResponseURL: 'responseUrlValue', StackId: 'stackIdValue', RequestId: 'requestIdValue', LogicalResourceId: 'logicalResourceIdValue', AmplifyJobId: 'amplifyJobIdValue', PhysicalResourceId: 'physicalResourceIdValue', }); // THEN expect(response).toEqual({ IsComplete: false, }); expect(getJobRequest).toHaveBeenCalledWith({ appId: 'appIdValue', branchName: 'branchNameValue', jobId: 'amplifyJobIdValue', }); expect(getJobResponse).toBeCalled(); }); it('isComplete UPDATE failed', async () => { // GIVEN getJobResponse.mockImplementation(() => { return { job: { summary: { status: 'FAILED' } }, }; }); // WHEN await expect(() => isComplete({ ServiceToken: 'serviceTokenValue', RequestType: 'Update', ResourceType: 'Custom::AmplifyAssetDeployment', ResourceProperties: { ServiceToken: 'serviceTokenValue', AppId: 'appIdValue', BranchName: 'branchNameValue', S3BucketName: 's3BucketNameValue', S3ObjectKey: 's3ObjectKeyValue', }, OldResourceProperties: {}, ResponseURL: 'responseUrlValue', StackId: 'stackIdValue', RequestId: 'requestIdValue', LogicalResourceId: 'logicalResourceIdValue', AmplifyJobId: 'amplifyJobIdValue', PhysicalResourceId: 'physicalResourceIdValue', })).rejects.toThrow('Amplify job failed with status: FAILED'); // THEN expect(getJobRequest).toHaveBeenCalledWith({ appId: 'appIdValue', branchName: 'branchNameValue', jobId: 'amplifyJobIdValue', }); expect(getJobResponse).toBeCalled(); }); it('isComplete UPDATE cancelled', async () => { // GIVEN getJobResponse.mockImplementation(() => { return { job: { summary: { status: 'CANCELLED' } }, }; }); // WHEN await expect(() => isComplete({ ServiceToken: 'serviceTokenValue', RequestType: 'Update', ResourceType: 'Custom::AmplifyAssetDeployment', ResourceProperties: { ServiceToken: 'serviceTokenValue', AppId: 'appIdValue', BranchName: 'branchNameValue', S3BucketName: 's3BucketNameValue', S3ObjectKey: 's3ObjectKeyValue', }, OldResourceProperties: {}, ResponseURL: 'responseUrlValue', StackId: 'stackIdValue', RequestId: 'requestIdValue', LogicalResourceId: 'logicalResourceIdValue', AmplifyJobId: 'amplifyJobIdValue', PhysicalResourceId: 'physicalResourceIdValue', })).rejects.toThrow('Amplify job failed with status: CANCELLED'); // THEN expect(getJobRequest).toHaveBeenCalledWith({ appId: 'appIdValue', branchName: 'branchNameValue', jobId: 'amplifyJobIdValue', }); expect(getJobResponse).toBeCalled(); }); it('isComplete UPDATE no JobId', async () => { // GIVEN getJobResponse.mockImplementation(() => { return { job: { summary: { status: 'PENDING' } }, }; }); // WHEN await expect(() => isComplete({ ServiceToken: 'serviceTokenValue', RequestType: 'Update', ResourceType: 'Custom::AmplifyAssetDeployment', ResourceProperties: { ServiceToken: 'serviceTokenValue', AppId: 'appIdValue', BranchName: 'branchNameValue', S3BucketName: 's3BucketNameValue', S3ObjectKey: 's3ObjectKeyValue', }, OldResourceProperties: {}, ResponseURL: 'responseUrlValue', StackId: 'stackIdValue', RequestId: 'requestIdValue', LogicalResourceId: 'logicalResourceIdValue', PhysicalResourceId: 'physicalResourceIdValue', })).rejects.toThrow('Unable to determine Amplify job status without job id'); // THEN expect(getJobRequest).not.toHaveBeenCalled(); expect(getJobResponse).not.toHaveBeenCalled(); }); it('onEvent DELETE success', async () => { // GIVEN // WHEN await expect(() => onEvent({ ServiceToken: 'serviceTokenValue', RequestType: 'Delete', ResourceType: 'Custom::AmplifyAssetDeployment', ResourceProperties: { ServiceToken: 'serviceTokenValue', AppId: 'appIdValue', BranchName: 'branchNameValue', S3BucketName: 's3BucketNameValue', S3ObjectKey: 's3ObjectKeyValue', }, ResponseURL: 'responseUrlValue', StackId: 'stackIdValue', RequestId: 'requestIdValue', LogicalResourceId: 'logicalResourceIdValue', PhysicalResourceId: 'physicalResourceIdValue', })).resolves; }); it('isComplete DELETE success', async () => { // GIVEN // WHEN const response = await isComplete({ ServiceToken: 'serviceTokenValue', RequestType: 'Delete', ResourceType: 'Custom::AmplifyAssetDeployment', ResourceProperties: { ServiceToken: 'serviceTokenValue', AppId: 'appIdValue', BranchName: 'branchNameValue', S3BucketName: 's3BucketNameValue', S3ObjectKey: 's3ObjectKeyValue', }, ResponseURL: 'responseUrlValue', StackId: 'stackIdValue', RequestId: 'requestIdValue', LogicalResourceId: 'logicalResourceIdValue', PhysicalResourceId: 'physicalResourceIdValue', }); // THEN expect(response).toEqual({ IsComplete: true, }); }); it('onEvent unsupported resource type', async () => { // GIVEN // WHEN await expect(() => onEvent({ ServiceToken: 'serviceTokenValue', RequestType: 'Update', ResourceType: 'Custom::BadResourceType', ResourceProperties: { ServiceToken: 'serviceTokenValue', AppId: 'appIdValue', BranchName: 'branchNameValue', S3BucketName: 's3BucketNameValue', S3ObjectKey: 's3ObjectKeyValue', }, OldResourceProperties: {}, ResponseURL: 'responseUrlValue', StackId: 'stackIdValue', RequestId: 'requestIdValue', LogicalResourceId: 'logicalResourceIdValue', PhysicalResourceId: 'physicalResourceIdValue', })).rejects.toThrow('Unsupported resource type "Custom::BadResourceType"'); // THEN expect(getJobRequest).not.toHaveBeenCalled(); expect(getJobResponse).not.toHaveBeenCalled(); }); it('isComplete unsupported resource type', async () => { // GIVEN // WHEN await expect(() => isComplete({ ServiceToken: 'serviceTokenValue', RequestType: 'Update', ResourceType: 'Custom::BadResourceType', ResourceProperties: { ServiceToken: 'serviceTokenValue', AppId: 'appIdValue', BranchName: 'branchNameValue', S3BucketName: 's3BucketNameValue', S3ObjectKey: 's3ObjectKeyValue', }, OldResourceProperties: {}, ResponseURL: 'responseUrlValue', StackId: 'stackIdValue', RequestId: 'requestIdValue', LogicalResourceId: 'logicalResourceIdValue', PhysicalResourceId: 'physicalResourceIdValue', })).rejects.toThrow('Unsupported resource type "Custom::BadResourceType"'); // THEN expect(getJobRequest).not.toHaveBeenCalled(); expect(getJobResponse).not.toHaveBeenCalled(); }); });
the_stack
import { SrcFileSet, Pos, NoPos } from './pos' import { Universe } from './universe' import { TypeCompat, basicTypeCompat } from './typecompat' import { ErrorCode, ErrorReporter, ErrorHandler } from './error' import { debuglog as dlog } from './util' import { token } from './token' import { Num } from './num' import { numEvalU32 } from './numeval' import { PathMap } from './pathmap' import * as ast from './ast' import { types, t_str, t_str0, t_stropt, t_nil, Type, UnresolvedType, PrimType, NumType, StrType, RestType, ListType, TupleType, FunType, OptionalType, UnionType, ReturnStmt, Expr, Ident, NumLit, LiteralExpr, SelectorExpr, TypeConvExpr, IndexExpr, SliceExpr, } from "./ast" function isResolvedType(t :Type|null) :t is Type { return t ? t.constructor !== UnresolvedType : false } // Type resolver is a reusable resource for resolving types from AST. // It is allocated on a per-package basis. // export class TypeResolver extends ErrorReporter { fset :SrcFileSet universe :Universe unresolved :Set<UnresolvedType> // genericInstanceCache = new PathMap<Type,GenericTypeInstance<GenericType>>() // // maintains a collection of generic type instances constructor(traceInDebugMode? :bool) { super('E_RESOLVE', null, traceInDebugMode) this.setupResolvers() } // getGenericInstance<T extends GenericType>(t :T, types :Type[]) :GenericTypeInstance<T> { // const r = this // assert(t.rest || types.length == t.vars.length) // let path = [t, ...types] // let ti = r.genericInstanceCache.get(path) // if (ti) { // return ti // } // // cache miss // ti = t.newInstance(types) // r.genericInstanceCache.set(path, ti) // return ti // } init(fset :SrcFileSet, universe :Universe, errh :ErrorHandler|null) { // note: normally initialized per package (not per file) const r = this r.errh = errh r.fset = fset r.universe = universe r.unresolved = new Set<UnresolvedType>() // r.genericInstanceCache.clear() } // error resports an error // error(msg :string, pos :Pos = NoPos, typ? :ErrorCode) { const r = this r.errorAt(msg, r.fset.position(pos), typ) } // syntaxError reports a syntax error. // Interface is compatible with that of Parser.syntaxError // syntaxError(msg :string, pos :Pos = NoPos) { this.error(msg, pos, 'E_SYNTAX') } getTupleType(tv :Type[]) :TupleType { return this.universe.internType(new TupleType(tv)) } getListType(t :Type) :ListType { return this.universe.internType(new ListType(t)) } getRestType(t :Type) :RestType { return this.universe.internType(new RestType(t)) } getOptionalUnionType2(l :OptionalType, r :OptionalType) :UnionType { return this.universe.internType( new UnionType(NoPos, new Set<Type>([ l.type.isStrType() && l.type.len != -1 ? t_stropt : l, r.type.isStrType() && r.type.len != -1 ? t_stropt : r, ])) ) } getUnionType2(l :Type, r :Type) :UnionType { return this.universe.internType( new UnionType(NoPos, new Set<Type>([ l.isStrType() && l.len != -1 ? t_str : l, r.isStrType() && r.len != -1 ? t_str : r, ])) ) } getFunType(args :Type[], result :Type) :FunType { return this.universe.internType(new FunType(NoPos, args, result)) } getOptionalType(t :Type) { return ( t.isOptionalType() ? this.universe.internType(t) : t.isStrType() ? t_stropt : this.universe.internType(new OptionalType(NoPos, t)) ) } getStrType(length :int) :StrType { return ( length < 0 ? t_str : length == 0 ? t_str0 : this.universe.internType(new StrType(NoPos, length)) ) } // getStructType(t :Type) :RestType { // return this.universe.internType(new RestType(t)) // } // resolve attempts to resolve or infer the type of n. // Returns UnresolvedType if the type refers to an undefined identifier. // // This function may mutate n.type, and may call ErrorHandler for undefined // fields. // resolve(n :Expr) :Type { if (n.type /*&& (n.type.constructor !== UnresolvedType)*/) { if (n.type.isUnresolvedType() && n !== n.type.def) { n.type.addRef(n) } return n.type } if (n.isIdent() && n.value.isEmpty) { throw new Error(`attempt to resolve type of "_"`) } const r = this let t = r.maybeResolve(n) if (!t) { t = r.markUnresolved(n) // error failing to resolve field of known type if (n.isSelectorExpr() && n.lhs.isIdent() && n.lhs.ent) { // Partially resolved selector, e.g. // "a.b undefined (type <typeof(a)> has no field or function b)" r.error(`${n} undefined`, n.pos) } n.type = t } return t } // maybeResolve attempts to resolve or infer the type of n. // Returns null if the type can't be resolved or inferred. // May mutate n.type and may call ErrorHandler. // maybeResolve(n :Expr|ReturnStmt) :Type|null { const r = this if (n.isType()) { return n } if (isResolvedType(n.type)) { // already resolved return n.type } // map node type to resolver function const resolver = r.resolvers.get(n.constructor) if (resolver) { return n.type = resolver(n) } dlog(`TODO handle ${n.constructor.name}`) return null // unknown type } resolvers = new Map<Function,(n:any)=>Type|null>() // setupResolvers defines all resolvers. // Called by constructor // setupResolvers() { const r = this // // nodes which has a TypeExpr "type" field // r.resolvers.set(ast.FieldDecl, r.maybeResolveNodeWithTypeExpr) // r.resolvers.set(ast.VarDecl, r.maybeResolveNodeWithTypeExpr) // r.resolvers.set(ast.TypeDecl, r.maybeResolveNodeWithTypeExpr) r.resolvers.set(ast.Ident, r.maybeResolveIdent) r.resolvers.set(ast.Block, r.maybeResolveBlock) r.resolvers.set(ast.FunExpr, r.maybeResolveFunExpr) r.resolvers.set(ast.TupleExpr, r.maybeResolveTupleExpr) // r.resolvers.set(ast.RestTypeExpr, r.maybeResolveRestTypeExpr) r.resolvers.set(ast.CallExpr, r.maybeResolveCallExpr) r.resolvers.set(ast.Assignment, r.maybeResolveAssignment) r.resolvers.set(ast.Operation, r.maybeResolveOperation) r.resolvers.set(ast.IndexExpr, r.maybeResolveIndexExpr) r.resolvers.set(ast.IfExpr, r.maybeResolveIfExpr) r.resolvers.set(ast.Bad, r.neverResolve) // r.resolvers.set(ast.ReturnStmt, r.maybeResolveReturnStmt) } // maybeResolveReturnStmt = (n :ast.ReturnStmt) => { // // return expressions always represents type of its results, if any // const r = this // return n.result ? r.resolve(n.result) : t_nil // } neverResolve = (_ :ast.Expr) => { return null } // maybeResolveNodeWithTypeExpr = (n :ast.FieldDecl|ast.VarDecl|ast.TypeDecl) => { // return n.type // } maybeResolveIdent = (n :ast.Ident) => { const r = this if (n.ent) { if (isResolvedType(n.ent.type)) { return n.ent.type } if (n.ent.value.isExpr()) { return r.maybeResolve(n.ent.value) } } return null } maybeResolveBlock = (n :ast.Block) => { const r = this // type of block is the type of the last statement, or in the case // of return, the type of the returned value. if (n.list.length == 0) { // empty block return t_nil } let s = n.list[n.list.length-1] if (s instanceof Expr) { return r.resolve(s) } // last statement is a declaration // dlog(`TODO handle Block with declaration at end`) return t_nil } maybeResolveFunExpr = (n :ast.FunExpr) => { const r = this const s = n.sig let restype :Type = t_nil if (s.result) { restype = r.resolve(s.result) } else { // automatic result type if (n.body) { restype = r.resolve(n.body) } // else: leave restype as t_nil } let argtypes = s.params.map(field => r.resolve(field.type)) let t = r.getFunType(argtypes, restype) if (t.result instanceof UnresolvedType) { t.result.addRef(t) } return t } maybeResolveTupleExpr = (n :ast.TupleExpr) => { return this.maybeResolveTupleType(n.entries) } maybeResolveTupleType(entries :Expr[]) { const r = this let types :Type[] = [] for (const x of entries) { // Note: We don't check for unresolved types // // TODO: when x is unresolved, register the tuple _type_ as a dependency // for that unresolved type, so that laste-bind can wire it up. // types.push(r.resolve(x)) } return r.getTupleType(types) } // maybeResolveRestTypeExpr = (n :ast.RestTypeExpr) => { // const r = this // let t = r.maybeResolve(n.expr) // return isResolvedType(t) ? r.getRestType(t) : t // } maybeResolveCallExpr = (n :ast.CallExpr) :Type|null => { const r = this const receiverType = r.resolve(n.receiver) if (n.receiver.isType()) { // call is a type call dlog(`TODO type call on ${n.receiver}`) return n.receiver } if (!isResolvedType(receiverType)) { // unresolved return receiverType } assert( receiverType.isFunType(), `unexpected funtype ${receiverType} (${receiverType.constructor.name})` ) let funtype = receiverType as FunType let wantArgs = funtype.args // resolve and verify arguments let argcount = n.args.length // wantArgs.length let wantLast = wantArgs[wantArgs.length - 1] let wantRest = wantLast.isRestType() ? wantLast.type : null let argdelta = argcount - wantArgs.length if (argdelta < 0 && (argdelta < -1 || !wantRest || n.hasRest)) { r.syntaxError( `not enough arguments in call to ${n.receiver}\n` + ` got (${n.args.map(a => a.type).join(", ")})\n` + ` want (${wantArgs.join(", ")})`, n.pos ) } else if (argdelta > 0 && (!wantRest || n.hasRest)) { r.syntaxError( `too many arguments in call to ${n.receiver}\n` + ` got (${n.args.map(a => a.type).join(", ")})\n` + ` want (${wantArgs.join(", ")})`, n.pos ) } // want (A, B, ...C) // // ok: // got (A, B, ...C) => (A, B, [*]C) // got (A, B, C, C) => (A, B, [2]C) // got (A, B, []C) => (A, B, [*]C) // got (A, B, C) => (A, B, [1]C) // got (A, B) => (A, B, [0]C) // // error: // got (A) Not enough arguments // got (A) Invalid type const convarg = (x :Expr, t :Type) :Expr => { if (x.type !== t) { let x2 = r.convert(t, x) if (x2) { return x2 } r.error( x.isIdent ? `passing ${x} (type ${x.type}) as argument where ${t} is expected` : `passing ${x.type} as argument where ${t} is expected`, x.pos ) } return x } let i = 0 // endPosArgs denotes the end of regular postional args let endPosArgs = wantRest ? wantArgs.length-2 : wantArgs.length-1 while (i <= endPosArgs) { let want = wantArgs[i] let x = n.args[i] let t = r.maybeResolve(x) if (!t) { return null // at least one argument is unresolved } // convert type of value if needed n.args[i] = convarg(x, want) i++ } // parse rest if (wantRest) { if (n.hasRest) { // rest forwarding or spread of array assert(argcount - i == 1, `more than one arg remaining (rest -> rest)`) let x = n.args[i] let t = r.maybeResolve(x) if (!t) { return null // unresolved } // TODO: check for collection type and convert to rest. // e.g. // a int[] = [3, 4, 5] // foo(a...) // if (!(x.type instanceof ListType) || x.type.type !== wantRest) { r.error( `passing ${x.type} as argument where ${wantRest} is expected`, x.pos ) } // ok. done } else { // synthetic rest let rest :Expr[] = [] for (; i < argcount; i++) { let x = n.args[i] let t = r.maybeResolve(x) if (!t) { return null // unresolved } // dlog(`rest arg #${i} want ${wantRest} got ${x} (${t})`) x = convarg(x, wantRest) rest.push(x) } // if (rest.length == 0) { // // nil denotes empty rest // n.args.push(ast.values.nil) // } } } return funtype.result } maybeResolveAssignment = (n :ast.Assignment) => { const r = this if (n.lhs.length == 1) { // single assignment (common case) // assert(n.rhs.length == 1) // return r.resolve(n.rhs[0]) let lhs = n.lhs[0] if (lhs.isIdent() && lhs.value.isEmpty) { assert(n.rhs.length == 1) return r.resolve(n.rhs[0]) } else { return r.resolve(lhs) } } // multi-assignment yields tuple // E.g. // a i32 // b f64 // t = a, b = 1, 2.3 // typeof(t) // => (i32, f64) // // variant of maybeResolveTupleType that considers LHS first and RHS second let types :Type[] = [] for (let i = 0; i < n.lhs.length; i++) { let x = n.lhs[i] if (x.isIdent() && x.value.isEmpty) { x = n.rhs[i] } // Note: _ = _ is invalid, so no need to check x for empty ident again. // // Note: We don't check for unresolved types. // // TODO: when x is unresolved, register the tuple _type_ as a dependency // for that unresolved type, so that laste-bind can wire it up. // types.push(r.resolve(x)) } return r.getTupleType(types) } maybeResolveOperation = (n :ast.Operation) => { const r = this const xt = r.resolve(n.x) if (!n.y) { // unary return xt } else { const yt = r.resolve(n.y) if (n.op > token.cmpop_beg && n.op < token.cmpop_end) { // Comparison operations always yield boolean values. if (n.op == token.ANDAND || n.op == token.OROR) { // Make sure operands are booleans -- convert as needed. if (xt !== types.bool) { n.x = new TypeConvExpr(n.x.pos, n.x._scope, n.x, types.bool) } if (yt !== types.bool) { n.y = new TypeConvExpr(n.y.pos, n.y._scope, n.y, types.bool) } } return types.bool } if (xt.isUnresolvedType() || yt.isUnresolvedType()) { // operation's effective type not yet know return null } if (xt === yt || xt.equals(yt)) { // both operands types are equivalent return xt } // operator that needs same-type operands if (n.op == token.ADD || n.op == token.SUB || n.op == token.MUL || n.op == token.QUO ) { if (xt.isFloatType() && !yt.isFloatType()) { let cx = r.convert(xt, n.y) if (cx) { n.y = cx return xt } } else if (!xt.isFloatType() && yt.isFloatType()) { let cx = r.convert(yt, n.x) if (cx) { n.x = cx return yt } } else { assert(xt.isPrimType()) assert(yt.isPrimType()) if ((xt as PrimType)._storageSize >= (yt as PrimType)._storageSize) { let cx = r.convert(xt, n.y) if (cx) { n.y = cx return xt } } else { let cx = r.convert(yt, n.x) if (cx) { n.x = cx return yt } } } } // try converting RHS operand to same type as LHS operand let x = r.convert(xt, n.y) if (x) { return x === n.y ? yt : r.resolve(x) } r.error(`invalid operation (mismatched types ${xt} and ${yt})`, n.pos) } return null } // resolveIndex attempts to resolve the type of an index expression. // maybeResolveIndexExpr = (n :ast.IndexExpr) => { const r = this // resolve operand type let opt = r.resolve(n.operand) if (opt.isUnresolvedType()) { // defer to bind stage dlog(`[index type] deferred to bind stage`) } else if (opt.isTupleType()) { r.maybeResolveTupleAccess(n, opt) } else { dlog(`[index type] operand is not a tuple; opt = ${opt}`) } return n.type } maybeResolveIfExpr = (n :ast.IfExpr) => { const r = this // resolve "then" branch type let thentyp = r.resolve(n.then) if (!n.els_) { // e.g. `if x A => A` // with only a single then branch, the result type is that branch. // if the branch is not taken, the result is a zero-initialized T. // special case: if thentyp is a string constant, we must resolve to // just "str" (length only known at runtime) since if the branch is // not taken, a zero-initialized string is returned, which is zero. if (thentyp.isStrType() && thentyp.len != 0) { return t_str } return thentyp } // resolve "else" branch type let eltyp = r.resolve(n.els_) if (eltyp.equals(thentyp)) { // e.g. `if x A else A => A` // e.g. `if x A? else A? => A?` return thentyp } if (eltyp === t_nil) { if (thentyp === t_nil) { // both branches are nil/void // e.g. `if x nil else nil => nil` return t_nil } // e.g. `if x A else nil => A?` if (thentyp.isPrimType()) { // e.g. `if x int else nil` r.error(`mixing ${thentyp} and optional type`, n.pos, 'E_CONV') } // makes the type optional return r.getOptionalType(thentyp) } if (thentyp === t_nil) { // e.g. `if x nil else A => A?` if (eltyp.isPrimType()) { // e.g. `if x nil else int` r.error(`mixing optional and ${eltyp} type`, n.pos, 'E_CONV') } return r.getOptionalType(eltyp) } if (eltyp.isOptionalType()) { if (thentyp.isOptionalType()) { // e.g. `if x A? else B? => A?|B?` // // Invariant: NOT eltyp.type.equals(thentyp.type) // since we checked that already above with eltyp.equals(thentyp) // if (eltyp.type.isStrType() && thentyp.type.isStrType()) { // e.g. `a str?; b str?; if x a else b => str` assert(eltyp.type.len != thentyp.type.len, "str type matches but StrType.equals failed") return t_stropt } return r.getOptionalUnionType2(thentyp, eltyp) } // e.g. `if x A else B? => A?|B?` // e.g. `if x A else A? => A?` // e.g. `if x A|B else A? => A?|B?` return r.joinOptional(n.pos, eltyp, thentyp) } if (thentyp.isOptionalType()) { // e.g. `if x A? else B => A?|B?` // e.g. `if x A? else B|C => A?|B?|C?` return r.joinOptional(n.pos, thentyp, eltyp) } if (eltyp.isStrType() && thentyp.isStrType()) { // e.g. `if x "foo" else "x" => str` return t_str } if (eltyp.isUnionType()) { if (thentyp.isOptionalType()) { // e.g. `if x A? else B|C => A?|B?|C?` return r.joinOptional(n.pos, thentyp, eltyp) } if (thentyp.isUnionType()) { // e.g. `if x A|B else A|C => A|B|C` // e.g. `if x A|B? else A|C => A?|B?|C?` return r.mergeUnions(thentyp, eltyp) } // else: e.g. `if x A else B|C => B|C|A` eltyp.add(thentyp) return eltyp } if (thentyp.isUnionType()) { // e.g. `if x A|B else C => A|B|C` thentyp.add(eltyp) return thentyp } // e.g. `if x A else B => A|B` return r.getUnionType2(thentyp, eltyp) } // joinOptional takes two types, one of them optional and the other not, // and considers them as two branches that are merging into one type, thus // this function returns an optional for t. The returned optional may be // incompatible with `opt`, or it might be t in the case of a union type. // joinOptional(pos :Pos, opt :OptionalType, t :Type) :Type { const r = this if (opt.type.equals(t)) { // return optional type since underlying type == t return opt } if (opt.type.isStrType() && t.isStrType()) { assert(opt.type.len != t.len, "str type matches but StrType.equals failed") // if the optional type is a string and the compile-time length // differs, return an optional string type with unknown length. return t_stropt } if (t.isUnionType()) { let ut = new UnionType(NoPos, new Set<Type>([opt])) for (let t1 of t.types) { if (!t1.isOptionalType()) { if (t1.isPrimType()) { this.error(`mixing optional and ${t1} type`, pos, 'E_CONV') } else { t1 = r.getOptionalType(t1) } } ut.add(t1) } return ut } if (t.isPrimType()) { this.error(`mixing optional and ${t} type`, pos, 'E_CONV') return t } // t is different than opt -- return optional of t return r.getOptionalType(t) } mergeOptionalUnions(a :UnionType, b :UnionType) :UnionType { const r = this let ut = new UnionType(NoPos, new Set<Type>()) for (let t of a.types) { if (!t.isOptionalType()) { t = r.getOptionalType(t) } ut.add(t) } for (let t of b.types) { if (!t.isOptionalType()) { t = r.getOptionalType(t) } ut.add(t) } return r.universe.internType(ut) } mergeUnions(a :UnionType, b :UnionType) :UnionType { const r = this let ut = new UnionType(NoPos, new Set<Type>()) for (let t of a.types) { if (t.isOptionalType()) { return r.mergeOptionalUnions(a, b) } ut.add(t) } for (let t of b.types) { if (t.isOptionalType()) { return r.mergeOptionalUnions(a, b) } ut.add(t) } return r.universe.internType(ut) } // resolveIndex attempts to resolve the type of an index expression. // returns x as a convenience. // resolveIndex(x :IndexExpr) :IndexExpr { const r = this // resolve operand type let opt = r.resolve(x.operand) if (opt.isUnresolvedType()) { // defer to bind stage dlog(`[index type] deferred to bind stage`) } else if (opt.isTupleType()) { r.maybeResolveTupleAccess(x, opt) } else { dlog(`TODO [index type] operand is not a tuple; opt = ${opt}`) } return x } tupleSlice(x :SliceExpr) :bool { const p = this let tupletype = x.operand.type as TupleType assert(tupletype, 'unresolved operand type') assert(tupletype instanceof TupleType) assert(tupletype.types.length > 0, 'empty tuple') let tuplelen = tupletype.types.length let starti = 0 let endi = tuplelen if (x.start) { starti = numEvalU32(x.start) if (starti < 0) { p.syntaxError(`invalid index into type ${tupletype}`, x.start.pos) return false } if (starti >= tuplelen) { p.outOfBoundsAccess(starti, tupletype, x.start.pos) return false } } if (x.end) { endi = numEvalU32(x.end) if (endi < 0) { p.syntaxError(`invalid index into type ${tupletype}`, x.end.pos) return false } if (endi >= tuplelen) { p.outOfBoundsAccess(endi, tupletype, x.end.pos) return false } } if (starti >= endi) { if (starti == endi) { p.syntaxError(`invalid empty slice: ${starti} == ${endi}`, x.pos) } else { p.syntaxError(`invalid slice index: ${starti} > ${endi}`, x.pos) } return false } let len = endi - starti if (len == 1) { p.syntaxError( `invalid single-element slice into type ${tupletype}`, x.pos, // `Instead of slicing a single element from a tuple, ` + // `access it directly with a subscript operation: ` + // `${x.operand}[${x.start || x.end}]`, ) return false } x.startnum = starti x.endnum = endi if (len == tuplelen) { // e.g. `(1,2,3)[:] => (1,2,3)` x.type = tupletype } else { x.type = p.getTupleType(tupletype.types.slice(starti, endi)) } return true } // maybeResolveTupleAccess attempts to evaluate a tuple access. // x.index must be constant. // Return true if resolution succeeded. // maybeResolveTupleAccess(x :IndexExpr, tupletype :TupleType) :bool { const p = this // let tupletype = x.operand.type!.canonicalType() as TupleType assert(tupletype, 'unresolved operand type') assert(tupletype.isTupleType()) assert(tupletype.types.length > 0, 'empty tuple') let i = numEvalU32(x.index) if (i < 0) { if (i == -1) { p.outOfBoundsAccess(i, tupletype, x.index.pos) } else { p.syntaxError(`invalid index into type ${tupletype}`, x.index.pos) } return false } let memberTypes = tupletype.types if (i as int >= memberTypes.length) { p.outOfBoundsAccess(i, tupletype, x.index.pos) return false } x.indexnum = i x.type = memberTypes[i as int] return true } // outOfBoundsAccess reports an error for out-of-bounds access // outOfBoundsAccess(i :Num, t :Type, pos :Pos) { this.syntaxError(`out-of-bounds index ${i} on type ${t}`, pos) } // registerUnresolved registers expr as having an unresolved type. // Does NOT set expr.type but instead returns an UnresolvedType object. // markUnresolved(expr :Expr) :UnresolvedType { if (expr.isIdent() && expr.toString() == "x") { throw new Error("XXX") } if (DEBUG) for (let t of this.unresolved) { if (t.def === expr) { throw new Error(`double-mark of ${expr} at ${this.fset.position(expr.pos)}`) } } const t = new UnresolvedType(expr.pos, expr) dlog(`expr ${expr} at ${this.fset.position(expr.pos)}`) this.unresolved.add(t) return t } // isConstant returns true if the expression is a compile-time constant // isConstant(x :Expr) :bool { return ( x instanceof LiteralExpr || (x instanceof Ident && x.ent != null && x.ent.isConstant()) ) // TODO: expand } // getLiteralExpr returns the literal expression for x, resolving // constant idenfifiers as needed. // Returns null if there's no literal expression at the end of x. // getLiteralExpr(x :Expr) :LiteralExpr|null { if (x instanceof LiteralExpr) { return x } let id :Expr|null = x while (id instanceof ast.Ident && id.ent && id.ent.isConstant()) { id = id.ent.value as Expr|null if (id instanceof LiteralExpr) { return id } } return null } // convertType attempts to convert expression x to type t. // If x is already of type t, x is returned unchanged. // If conversion is needed, a TypeConvExpr is returned, // encapsulating x. // If conversion is impossible, null is returned to indicate error. // convert(t :Type, x :Expr) :Expr|null { return this._convert(t, x, /*losslessOnly=*/false) } // convertLossless does the same thing as convert but returns null if the // conversion would be lossy. // convertLossless(t :Type, x :Expr) :Expr|null { return this._convert(t, x, /*losslessOnly=*/true) } _convert(t :Type, x :Expr, losslessOnly :bool) :Expr|null { const r = this const xt = r.resolve(x) if (xt === t || xt.equals(t)) { // no conversion needed; already same type return x } if (t.isPrimType() && xt.isPrimType()) { return r.convertBasic(t, x, losslessOnly) } dlog(`TODO conversion of ${x} into type ${t}`) // TODO: figure out a scalable type conversion system // TODO: conversion of other types return null } convertBasic(t :PrimType, x :Expr, losslessOnly :bool) :Expr|null { const r = this // literal let litx = r.getLiteralExpr(x) if (litx instanceof ast.NumLit) { let x2 = r.convertNumLit(t, litx, losslessOnly) if (x2) { return x2 } } assert(x.type instanceof PrimType) switch (basicTypeCompat(t, x.type as PrimType)) { // TypeCompat case TypeCompat.NO: { return null // Caller should report error } case TypeCompat.LOSSY: { if (losslessOnly) { return null // Caller should report error } r.error( x.isIdent ? `${x} (type ${x.type}) converted to ${t}` : `${x.type} converted to ${t}`, x.pos, 'E_CONV' ) // TODO: ^ use diag instead with DiagKind.ERROR as the default, so // that user code can override this error into a warning instead, as // it's still valid to perform a lossy conversion. return new TypeConvExpr(x.pos, x._scope, x, t) } case TypeCompat.LOSSLESS: { // complex conversion return new TypeConvExpr(x.pos, x._scope, x, t) } } } convertNumLit(t :NumType, x :NumLit, losslessOnly :bool) :NumLit|null { const r = this if (t.isFloatType()) { // attempt simple type rewrites for trivial conversions // e.g. 3.2 + 5 => (+ (f64 3.2) (i32 5)) => (+ (f64 3.2) (f64 5)) if (x.isFloatLit()) { // float -> float if (t === types.f32 && x.value > 0xffffff) { if (losslessOnly) { return null // Caller should report error } r.error(`constant ${x} truncated to ${t}`, x.pos, 'E_CONV') } x.type = t return x } else if (x.isIntLit()) { // int -> float // Note: IEEE-754 f32 has 24 significant bits, f64 has 53 bits. let f = typeof x.value == "number" ? x.value : x.value.toFloat64() if (f > (types.f32 ? 0xffffff : 0x1fffffffffffff)) { if (losslessOnly) { return null // Caller should report error } r.error(`constant ${x} truncated to ${t}`, x.pos, 'E_CONV') } return new ast.FloatLit(x.pos, f, t) } else if (x.isRuneLit()) { // rune -> float return new ast.FloatLit(x.pos, x.value, t) } } else { // t.isIntType() if (x.isIntLit() || x.isRuneLit()) { // int -> int x.type = t return x } } return null } }
the_stack
import * as assert from 'assert'; import * as path from 'path'; import { window, workspace, Uri, StatusBarAlignment, SymbolKind, Location, Range } from 'vscode'; import { SystemVerilogDocumentSymbolProvider } from '../providers/DocumentSymbolProvider'; import { SystemVerilogWorkspaceSymbolProvider } from '../providers/WorkspaceSymbolProvider'; import { SystemVerilogIndexer } from '../indexer'; import { SystemVerilogParser } from '../parser'; import { SystemVerilogSymbol } from '../symbol'; let docProvider: SystemVerilogDocumentSymbolProvider; let symProvider: SystemVerilogWorkspaceSymbolProvider; let indexer: SystemVerilogIndexer; let parser: SystemVerilogParser; let symbols: Map<string, Array<SystemVerilogSymbol>>; const testFolderLocation = '../../src/test'; const uri = Uri.file(path.join(__dirname, testFolderLocation, 'test-files', 'ModuleInstantiator.test.1.v')); const documentSymbols = ['adder', 'bar', 'akker', 'accer', 'anner', 'atter', 'apper', 'golden']; const nonSVUri = Uri.file(path.join(__dirname, testFolderLocation, 'test-files', 'foo.txt')); suite('indexer_map Tests', () => { test('test #1: addDocumentSymbols, removeDocumentSymbols', async () => { await setUp(); const sVDocument = await workspace.openTextDocument(uri); const nonSVDocument = await workspace.openTextDocument(nonSVUri); assert.strictEqual(symbols.size, 4); let count = await indexer.addDocumentSymbols(sVDocument, symbols); assert.strictEqual(count, 8); assert.strictEqual(symbols.size, 5); assert.strictEqual(symbols.get(uri.fsPath).length, 8); assert.strictEqual(getSymbolsCount(), 21); documentSymbols.forEach((symbolName) => { if (!symbolExists(symbolName)) { assert.fail(); } }); // Non-SV document count = await indexer.addDocumentSymbols(nonSVDocument, symbols); assert.strictEqual(count, 0); assert.strictEqual(symbols.size, 5); assert.strictEqual(symbols.get(nonSVUri.fsPath), undefined); assert.strictEqual(getSymbolsCount(), 21); // undefined/null document count = await indexer.addDocumentSymbols(undefined, symbols); assert.strictEqual(count, 0); assert.strictEqual(symbols.size, 5); assert.strictEqual(getSymbolsCount(), 21); count = await indexer.addDocumentSymbols(sVDocument, undefined); assert.strictEqual(count, 0); assert.strictEqual(symbols.size, 5); assert.strictEqual(getSymbolsCount(), 21); count = await indexer.addDocumentSymbols(undefined, undefined); assert.strictEqual(count, 0); assert.strictEqual(symbols.size, 5); assert.strictEqual(getSymbolsCount(), 21); count = await indexer.addDocumentSymbols(null, symbols); assert.strictEqual(count, 0); assert.strictEqual(symbols.size, 5); assert.strictEqual(getSymbolsCount(), 21); }); test('test #2: removeDocumentSymbols', async () => { await setUp(); const sVDocument = await workspace.openTextDocument(uri); const nonSVDocument = await workspace.openTextDocument(nonSVUri); assert.strictEqual(symbols.size, 4); let count = await indexer.addDocumentSymbols(sVDocument, symbols); assert.strictEqual(count, 8); assert.strictEqual(symbols.size, 5); assert.strictEqual(getSymbolsCount(), 21); count = indexer.removeDocumentSymbols(sVDocument.uri.fsPath, symbols); documentSymbols.forEach((symbolName) => { if (symbolExists(symbolName)) { assert.fail(); } }); assert.strictEqual(count, -8); assert.strictEqual(symbols.size, 4); assert.strictEqual(getSymbolsCount(), 13); // Non-SV document count = indexer.removeDocumentSymbols(nonSVDocument.uri.fsPath, symbols); assert.strictEqual(count, -0); assert.strictEqual(symbols.size, 4); assert.strictEqual(getSymbolsCount(), 13); // undefined/null document count = indexer.removeDocumentSymbols(undefined, symbols); assert.strictEqual(count, 0); assert.strictEqual(symbols.size, 4); assert.strictEqual(getSymbolsCount(), 13); count = indexer.removeDocumentSymbols(sVDocument.uri.fsPath, undefined); assert.strictEqual(count, 0); assert.strictEqual(symbols.size, 4); assert.strictEqual(getSymbolsCount(), 13); count = indexer.removeDocumentSymbols(undefined, undefined); assert.strictEqual(count, 0); assert.strictEqual(symbols.size, 4); assert.strictEqual(getSymbolsCount(), 13); count = indexer.removeDocumentSymbols(null, symbols); assert.strictEqual(count, 0); assert.strictEqual(symbols.size, 4); assert.strictEqual(getSymbolsCount(), 13); }); test('test #3: updateMostRecentModules', async () => { await setUp(); indexer.NUM_FILES = 5; indexer.symbols = symbols; indexer.updateMostRecentSymbols(undefined); assert.strictEqual(indexer.mostRecentSymbols.length, 5); const recentSymbols = new Array<SystemVerilogSymbol>(); const symbolInfo_1 = new SystemVerilogSymbol('symbolInfo_1', 'module', 'parent_module', undefined); const symbolInfo_2 = new SystemVerilogSymbol('symbolInfo_2', 'logic', 'parent_logic', undefined); const symbolInfo_3 = new SystemVerilogSymbol('symbolInfo_3', 'function', 'parent_function', undefined); const symbolInfo_4 = indexer.mostRecentSymbols[0]; const symbolInfo_5 = indexer.mostRecentSymbols[1]; recentSymbols.push(symbolInfo_1); recentSymbols.push(symbolInfo_2); recentSymbols.push(symbolInfo_3); indexer.updateMostRecentSymbols(recentSymbols); assert.strictEqual(indexer.mostRecentSymbols.length, 5); assert.strictEqual(indexer.mostRecentSymbols[0], symbolInfo_1); assert.strictEqual(indexer.mostRecentSymbols[1], symbolInfo_2); assert.strictEqual(indexer.mostRecentSymbols[2], symbolInfo_3); assert.strictEqual(indexer.mostRecentSymbols[3], symbolInfo_4); assert.strictEqual(indexer.mostRecentSymbols[4], symbolInfo_5); }); }); /** Sets up the `symbols` map for testing. */ async function setUp() { const document = await workspace.openTextDocument(uri); const settings = workspace.getConfiguration(); const statusBar = window.createStatusBarItem(StatusBarAlignment.Left, 0); parser = new SystemVerilogParser(); indexer = new SystemVerilogIndexer(statusBar, parser, window.createOutputChannel('SystemVerilog')); docProvider = new SystemVerilogDocumentSymbolProvider(parser); symProvider = new SystemVerilogWorkspaceSymbolProvider(indexer); symbols = new Map<string, Array<SystemVerilogSymbol>>(); const location = new Location( uri, new Range(document.positionAt(0), document.positionAt(document.getText().length)) ); // File_1 const file_1 = path.join(__dirname, testFolderLocation, 'test-files', 'file_1.v'); const list_1 = new Array<SystemVerilogSymbol>(); // Add SystemVerilogSymbol objects to list_1 const list_1_SymbolInfo_1 = new SystemVerilogSymbol('list_1_SymbolInfo_1', 'module', undefined, location); const list_1_SymbolInfo_2 = new SystemVerilogSymbol('list_1_SymbolInfo_2', 'logic', undefined, location); const list_1_SymbolInfo_3 = new SystemVerilogSymbol('list_1_SymbolInfo_3', 'function', undefined, location); const list_1_SymbolInfo_4 = new SystemVerilogSymbol('list_1_SymbolInfo_4', 'interface', undefined, location); list_1.push(list_1_SymbolInfo_1); list_1.push(list_1_SymbolInfo_2); list_1.push(list_1_SymbolInfo_3); list_1.push(list_1_SymbolInfo_4); // File_2 const file_2 = path.join(__dirname, testFolderLocation, 'test-files', 'file_2.v'); const list_2 = new Array<SystemVerilogSymbol>(); // Add SystemVerilogSymbol objects to list_1 const list_2_SymbolInfo_1 = new SystemVerilogSymbol('list_2_SymbolInfo_1', 'logic', undefined, location); const list_2_SymbolInfo_2 = new SystemVerilogSymbol('list_2_SymbolInfo_2', 'logic', undefined, location); const list_2_SymbolInfo_3 = new SystemVerilogSymbol('list_2_SymbolInfo_3', 'import', undefined, location); list_2.push(list_2_SymbolInfo_1); list_2.push(list_2_SymbolInfo_2); list_2.push(list_2_SymbolInfo_3); // File_3 const file_3 = path.join(__dirname, testFolderLocation, 'test-files', 'file_3.v'); const list_3 = new Array<SystemVerilogSymbol>(); // Add SystemVerilogSymbol objects to list_1 const list_3_SymbolInfo_1 = new SystemVerilogSymbol('list_3_SymbolInfo_1', 'logic', undefined, location); const list_3_SymbolInfo_2 = new SystemVerilogSymbol('list_3_SymbolInfo_2', 'logic', undefined, location); const list_3_SymbolInfo_3 = new SystemVerilogSymbol('list_3_SymbolInfo_3', 'module', undefined, location); const list_3_SymbolInfo_4 = new SystemVerilogSymbol('list_3_SymbolInfo_4', 'module', undefined, location); const list_3_SymbolInfo_5 = new SystemVerilogSymbol('list_3_SymbolInfo_5', 'module', undefined, location); const list_3_SymbolInfo_6 = new SystemVerilogSymbol('list_3_SymbolInfo_6', 'import', undefined, location); list_3.push(list_3_SymbolInfo_1); list_3.push(list_3_SymbolInfo_2); list_3.push(list_3_SymbolInfo_3); list_3.push(list_3_SymbolInfo_4); list_3.push(list_3_SymbolInfo_5); list_3.push(list_3_SymbolInfo_6); // File_4 const file_4 = path.join(__dirname, testFolderLocation, 'test-files', 'file_4.v'); const list_4 = new Array<SystemVerilogSymbol>(); // Map the lists to the files symbols.set(file_1, list_1); symbols.set(file_2, list_2); symbols.set(file_3, list_3); symbols.set(file_4, list_4); } /** Counts `SystemVerilogSymbol` objects in the `symbols` map. @return the symbols count */ function getSymbolsCount(): number { if (!symbols) { return 0; } let count = 0; symbols.forEach((list) => { count += list.length; }); return count; } /** Checks if a given `symbolName` exists in the `symbols` map. @param symbolName the symbol's name @return true if the symbol exists */ function symbolExists(symbolName: string): boolean { if (!symbols) { return false; } let exists = false; symbols.forEach((list) => { list.forEach((symbol: SystemVerilogSymbol) => { if (symbolName === symbol.name) { exists = true; } return false; }); if (exists) { return false; } }); return exists; }
the_stack
import React from 'react'; import { render, screen, fireEvent } from 'spec/helpers/testing-library'; import userEvent from '@testing-library/user-event'; import sinon from 'sinon'; import fetchMock from 'fetch-mock'; import * as actions from 'src/reports/actions/reports'; import * as featureFlags from 'src/featureFlags'; import mockState from 'spec/fixtures/mockStateWithoutUser'; import { HeaderProps } from './types'; import Header from '.'; const createProps = () => ({ addSuccessToast: jest.fn(), addDangerToast: jest.fn(), addWarningToast: jest.fn(), dashboardInfo: { id: 1, dash_edit_perm: false, dash_save_perm: false, dash_share_perm: false, userId: '1', metadata: {}, common: { conf: {}, }, }, user: { createdOn: '2021-04-27T18:12:38.952304', email: 'admin@test.com', firstName: 'admin', isActive: true, lastName: 'admin', permissions: {}, roles: { Admin: [['menu_access', 'Manage']] }, userId: 1, username: 'admin', }, reports: {}, dashboardTitle: 'Dashboard Title', charts: {}, layout: {}, expandedSlices: {}, css: '', customCss: '', isStarred: false, isLoading: false, lastModifiedTime: 0, refreshFrequency: 0, shouldPersistRefreshFrequency: false, onSave: jest.fn(), onChange: jest.fn(), fetchFaveStar: jest.fn(), fetchCharts: jest.fn(), onRefresh: jest.fn(), fetchUISpecificReport: jest.fn(), saveFaveStar: jest.fn(), savePublished: jest.fn(), isPublished: false, updateDashboardTitle: jest.fn(), editMode: false, setEditMode: jest.fn(), showBuilderPane: jest.fn(), updateCss: jest.fn(), setColorSchemeAndUnsavedChanges: jest.fn(), logEvent: jest.fn(), setRefreshFrequency: jest.fn(), hasUnsavedChanges: false, maxUndoHistoryExceeded: false, onUndo: jest.fn(), onRedo: jest.fn(), undoLength: 0, redoLength: 0, setMaxUndoHistoryExceeded: jest.fn(), maxUndoHistoryToast: jest.fn(), dashboardInfoChanged: jest.fn(), dashboardTitleChanged: jest.fn(), }); const props = createProps(); const editableProps = { ...props, editMode: true, dashboardInfo: { ...props.dashboardInfo, dash_edit_perm: true, dash_save_perm: true, }, }; const undoProps = { ...editableProps, undoLength: 1, }; const redoProps = { ...editableProps, redoLength: 1, }; const REPORT_ENDPOINT = 'glob:*/api/v1/report*'; fetchMock.get('glob:*/csstemplateasyncmodelview/api/read', {}); fetchMock.get(REPORT_ENDPOINT, {}); function setup(props: HeaderProps, initialState = {}) { return render( <div className="dashboard"> <Header {...props} /> </div>, { useRedux: true, initialState }, ); } async function openActionsDropdown() { const btn = screen.getByRole('img', { name: 'more-horiz' }); userEvent.click(btn); expect(await screen.findByRole('menu')).toBeInTheDocument(); } test('should render', () => { const mockedProps = createProps(); const { container } = setup(mockedProps); expect(container).toBeInTheDocument(); }); test('should render the title', () => { const mockedProps = createProps(); setup(mockedProps); expect(screen.getByText('Dashboard Title')).toBeInTheDocument(); }); test('should render the editable title', () => { setup(editableProps); expect(screen.getByDisplayValue('Dashboard Title')).toBeInTheDocument(); }); test('should edit the title', () => { setup(editableProps); const editableTitle = screen.getByDisplayValue('Dashboard Title'); expect(editableProps.onChange).not.toHaveBeenCalled(); userEvent.click(editableTitle); userEvent.clear(editableTitle); userEvent.type(editableTitle, 'New Title'); userEvent.click(document.body); expect(editableProps.onChange).toHaveBeenCalled(); expect(screen.getByDisplayValue('New Title')).toBeInTheDocument(); }); test('should render the "Draft" status', () => { const mockedProps = createProps(); setup(mockedProps); expect(screen.getByText('Draft')).toBeInTheDocument(); }); test('should publish', () => { setup(editableProps); const draft = screen.getByText('Draft'); expect(editableProps.savePublished).not.toHaveBeenCalled(); userEvent.click(draft); expect(editableProps.savePublished).toHaveBeenCalledTimes(1); }); test('should render the "Undo" action as disabled', () => { setup(editableProps); expect(screen.getByTitle('Undo').parentElement).toBeDisabled(); }); test('should undo', () => { setup(undoProps); const undo = screen.getByTitle('Undo'); expect(undoProps.onUndo).not.toHaveBeenCalled(); userEvent.click(undo); expect(undoProps.onUndo).toHaveBeenCalledTimes(1); }); test('should undo with key listener', () => { undoProps.onUndo.mockReset(); setup(undoProps); expect(undoProps.onUndo).not.toHaveBeenCalled(); fireEvent.keyDown(document.body, { key: 'z', code: 'KeyZ', ctrlKey: true }); expect(undoProps.onUndo).toHaveBeenCalledTimes(1); }); test('should render the "Redo" action as disabled', () => { setup(editableProps); expect(screen.getByTitle('Redo').parentElement).toBeDisabled(); }); test('should redo', () => { setup(redoProps); const redo = screen.getByTitle('Redo'); expect(redoProps.onRedo).not.toHaveBeenCalled(); userEvent.click(redo); expect(redoProps.onRedo).toHaveBeenCalledTimes(1); }); test('should redo with key listener', () => { redoProps.onRedo.mockReset(); setup(redoProps); expect(redoProps.onRedo).not.toHaveBeenCalled(); fireEvent.keyDown(document.body, { key: 'y', code: 'KeyY', ctrlKey: true }); expect(redoProps.onRedo).toHaveBeenCalledTimes(1); }); test('should render the "Discard changes" button', () => { setup(editableProps); expect(screen.getByText('Discard changes')).toBeInTheDocument(); }); test('should render the "Save" button as disabled', () => { setup(editableProps); expect(screen.getByText('Save').parentElement).toBeDisabled(); }); test('should save', () => { const unsavedProps = { ...editableProps, hasUnsavedChanges: true, }; setup(unsavedProps); const save = screen.getByText('Save'); expect(unsavedProps.onSave).not.toHaveBeenCalled(); userEvent.click(save); expect(unsavedProps.onSave).toHaveBeenCalledTimes(1); }); test('should NOT render the "Draft" status', () => { const mockedProps = createProps(); const publishedProps = { ...mockedProps, isPublished: true, }; setup(publishedProps); expect(screen.queryByText('Draft')).not.toBeInTheDocument(); }); test('should render the unselected fave icon', () => { const mockedProps = createProps(); setup(mockedProps); expect(mockedProps.fetchFaveStar).toHaveBeenCalled(); expect( screen.getByRole('img', { name: 'favorite-unselected' }), ).toBeInTheDocument(); }); test('should render the selected fave icon', () => { const mockedProps = createProps(); const favedProps = { ...mockedProps, isStarred: true, }; setup(favedProps); expect( screen.getByRole('img', { name: 'favorite-selected' }), ).toBeInTheDocument(); }); test('should NOT render the fave icon on anonymous user', () => { const mockedProps = createProps(); const anonymousUserProps = { ...mockedProps, user: undefined, }; setup(anonymousUserProps); expect(() => screen.getByRole('img', { name: 'favorite-unselected' }), ).toThrowError('Unable to find'); expect(() => screen.getByRole('img', { name: 'favorite-selected' }), ).toThrowError('Unable to find'); }); test('should fave', async () => { const mockedProps = createProps(); setup(mockedProps); const fave = screen.getByRole('img', { name: 'favorite-unselected' }); expect(mockedProps.saveFaveStar).not.toHaveBeenCalled(); userEvent.click(fave); expect(mockedProps.saveFaveStar).toHaveBeenCalledTimes(1); }); test('should toggle the edit mode', () => { const mockedProps = createProps(); const canEditProps = { ...mockedProps, dashboardInfo: { ...mockedProps.dashboardInfo, dash_edit_perm: true, }, }; setup(canEditProps); const editDashboard = screen.getByTitle('Edit dashboard'); expect(screen.queryByTitle('Edit dashboard')).toBeInTheDocument(); userEvent.click(editDashboard); expect(mockedProps.logEvent).toHaveBeenCalled(); }); test('should render the dropdown icon', () => { const mockedProps = createProps(); setup(mockedProps); expect(screen.getByRole('img', { name: 'more-horiz' })).toBeInTheDocument(); }); test('should refresh the charts', async () => { const mockedProps = createProps(); setup(mockedProps); await openActionsDropdown(); userEvent.click(screen.getByText('Refresh dashboard')); expect(mockedProps.onRefresh).toHaveBeenCalledTimes(1); }); describe('Email Report Modal', () => { let isFeatureEnabledMock: any; let dispatch: any; beforeEach(async () => { isFeatureEnabledMock = jest .spyOn(featureFlags, 'isFeatureEnabled') .mockImplementation(() => true); dispatch = sinon.spy(); }); afterAll(() => { isFeatureEnabledMock.mockRestore(); }); it('creates a new email report', async () => { // ---------- Render/value setup ---------- const mockedProps = createProps(); setup(mockedProps); const reportValues = { id: 1, result: { active: true, creation_method: 'dashboards', crontab: '0 12 * * 1', dashboard: mockedProps.dashboardInfo.id, name: 'Weekly Report', owners: [mockedProps.user.userId], recipients: [ { recipient_config_json: { target: mockedProps.user.email, }, type: 'Email', }, ], type: 'Report', }, }; // This is needed to structure the reportValues to match the fetchMock return const stringyReportValues = `{"id":1,"result":{"active":true,"creation_method":"dashboards","crontab":"0 12 * * 1","dashboard":${mockedProps.dashboardInfo.id},"name":"Weekly Report","owners":[${mockedProps.user.userId}],"recipients":[{"recipient_config_json":{"target":"${mockedProps.user.email}"},"type":"Email"}],"type":"Report"}}`; // Watch for report POST fetchMock.post(REPORT_ENDPOINT, reportValues); screen.logTestingPlaygroundURL(); // ---------- Begin tests ---------- // Click calendar icon to open email report modal const emailReportModalButton = screen.getByRole('button', { name: /schedule email report/i, }); userEvent.click(emailReportModalButton); // Click "Add" button to create a new email report const addButton = screen.getByRole('button', { name: /add/i }); userEvent.click(addButton); // Mock addReport from Redux const makeRequest = () => { const request = actions.addReport(reportValues); return request(dispatch); }; return makeRequest().then(() => { // 🐞 ----- There are 2 POST calls at this point ----- 🐞 // addReport's mocked POST return should match the mocked values expect(fetchMock.lastOptions()?.body).toEqual(stringyReportValues); // Dispatch should be called once for addReport expect(dispatch.callCount).toBe(2); const reportCalls = fetchMock.calls(REPORT_ENDPOINT); expect(reportCalls).toHaveLength(2); }); }); it('edits an existing email report', async () => { // TODO (lyndsiWilliams): This currently does not work, see TODOs below // The modal does appear with the edit title, but the PUT call is not registering // ---------- Render/value setup ---------- const mockedProps = createProps(); const editedReportValues = { active: true, creation_method: 'dashboards', crontab: '0 12 * * 1', dashboard: mockedProps.dashboardInfo.id, name: 'Weekly Report edit', owners: [mockedProps.user.userId], recipients: [ { recipient_config_json: { target: mockedProps.user.email, }, type: 'Email', }, ], type: 'Report', }; // getMockStore({ reports: reportValues }); setup(mockedProps, mockState); // TODO (lyndsiWilliams): currently fetchMock detects this PUT // address as 'glob:*/api/v1/report/undefined', is not detected // on fetchMock.calls() fetchMock.put(`glob:*/api/v1/report*`, editedReportValues); // Mock fetchUISpecificReport from Redux // const makeFetchRequest = () => { // const request = actions.fetchUISpecificReport( // mockedProps.user.userId, // 'dashboard_id', // 'dashboards', // mockedProps.dashboardInfo.id, // ); // return request(dispatch); // }; // makeFetchRequest(); dispatch(actions.setReport(editedReportValues)); // ---------- Begin tests ---------- // Click calendar icon to open email report modal const emailReportModalButton = screen.getByRole('button', { name: /schedule email report/i, }); userEvent.click(emailReportModalButton); const nameTextbox = screen.getByTestId('report-name-test'); userEvent.type(nameTextbox, ' edit'); const saveButton = screen.getByRole('button', { name: /save/i }); userEvent.click(saveButton); // TODO (lyndsiWilliams): There should be a report in state at this porint, // which would render the HeaderReportActionsDropDown under the calendar icon // BLOCKER: I cannot get report to populate, as its data is handled through redux expect.anything(); }); it('Should render report header', async () => { const mockedProps = createProps(); setup(mockedProps); expect( screen.getByRole('button', { name: 'Schedule email report' }), ).toBeInTheDocument(); }); it('Should not render report header even with menu access for anonymous user', async () => { const mockedProps = createProps(); const anonymousUserProps = { ...mockedProps, user: { roles: { Public: [['menu_access', 'Manage']], }, permissions: { datasource_access: ['[examples].[birth_names](id:2)'], }, }, }; setup(anonymousUserProps); expect( screen.queryByRole('button', { name: 'Schedule email report' }), ).not.toBeInTheDocument(); }); });
the_stack
import * as angular from 'angular'; import * as _ from "underscore"; import { FeedService } from '../../services/FeedService'; import { PolicyInputFormService } from '../policy-input-form/PolicyInputFormService'; import {moduleName} from "../../module-name";; export class FeedFieldPolicyRuleDialogController { static readonly $inject = ["$scope", "$mdDialog", "$mdToast", "$http", "StateService", "FeedService", "PolicyInputFormService", "FieldPolicyRuleOptionsFactory", "FeedFieldPolicyRuleService", "feed", "field"]; constructor(private $scope: IScope, private $mdDialog: angular.material.IDialogService, private $mdToast: angular.material.IToastService, private $http: angular.IHttpService, private StateService: any, private FeedService: FeedService , private PolicyInputFormService: PolicyInputFormService, private fieldPolicyRuleOptionsFactory: FieldPolicyRuleOptionsFactory, private feedFieldPolicyRuleService: FeedFieldPolicyRuleService, private feed: any, private field: any) { $scope.feed = feed; $scope.options = []; $scope.field = field; $scope.ruleMode = 'NEW' /** * The form for validation * @type {{}} */ $scope.policyForm = {}; /** * Flag if we are loading the available policies * @type {boolean} */ $scope.loadingPolicies = true; /** * The field policies associated with the field * @type {null} */ $scope.policyRules = null; /** * Renders Radio selection for different types * @type {[*]} */ $scope.optionTypes = [{ type: 'standardization', name: 'Standardization' }, { type: 'validation', name: 'Validation' }] /** * the selected Typed.. used with the optionTypes * @type {null} */ $scope.selectedOptionType = 'standardization'; /** * The list of either Standardizers or validators depending upon the selectedOptionType (radio button) * @type {Array} */ $scope.options = []; /** * The list of available validators * @type {Array} */ var validators: any = []; /** * The list of available standardizers * @type {Array} */ var standardizers: any = []; /** * Array of all standardizers and validators * @type {Array} */ var validatorsAndStandardizers: any = []; /** * flag to indicate the items have been re ordered/moved * @type {boolean} */ $scope.moved = false; this.fieldPolicyRuleOptionsFactory.getStandardizersAndValidators().then((response: any) => { var currentFeedValue = null; if ($scope.feed != null) { currentFeedValue = PolicyInputFormService.currentFeedValue($scope.feed); currentFeedValue = currentFeedValue.toLowerCase(); } var standardizationResults = []; var validationResults = []; if (response.standardization && response.standardization.data) { standardizationResults = _.sortBy(response.standardization.data, (r) => { return r.name; }); _.each(standardizationResults, (result) => { result.type = 'standardization'; }) } if (response.validation && response.validation.data) { validationResults = _.sortBy(response.validation.data, (r) => { return r.name; }); _.each(validationResults, (result) => { result.type = 'validation'; }) } standardizers = PolicyInputFormService.groupPolicyOptions(standardizationResults, currentFeedValue); validators = PolicyInputFormService.groupPolicyOptions(validationResults, currentFeedValue); validatorsAndStandardizers = _.union(validators, standardizers); //set the correct options in the drop down changedOptionType($scope.selectedOptionType); ruleTypesAvailable(); $scope.loadingPolicies = false; }); $scope.onChangedOptionType = changedOptionType; function changedOptionType(type: any) { $scope.options = type == 'standardization' ? standardizers : validators; $scope.selectedOptionType = type; } function setupPoliciesForFeed() { var arr = feedFieldPolicyRuleService.getAllPolicyRules(field); if (arr != null && arr != undefined) { $scope.policyRules = angular.copy(arr); } } setupPoliciesForFeed(); function findRuleType(ruleName: any, type: any) { return _.find(validatorsAndStandardizers, (opt: any) => { return opt.name == ruleName && opt.type == type; }); } function ruleTypesAvailable() { if ($scope.editRule != null) { $scope.ruleType = findRuleType($scope.editRule.name, $scope.editRule.type); if ($scope.ruleType && $scope.ruleType.type != $scope.selectedOptionType) { changedOptionType($scope.ruleType.type); } } } $scope.pendingEdits = false; $scope.editRule; $scope.ruleType = null; $scope.editIndex = null; $scope.editMode = 'NEW'; var modeText = "Add"; if ($scope.editMode == 'EDIT') { modeText = "Edit"; } /*if($scope.policyRules != null && $scope.policyRules.length && $scope.policyRules.length >0 ){ modeText = "Edit"; } */ $scope.title = modeText + " Field Policies"; $scope.titleText = 'Add a new policy'; $scope.addText = 'ADD RULE'; $scope.cancelText = 'CANCEL ADD'; function _cancelEdit() { $scope.editMode = 'NEW'; $scope.addText = 'ADD RULE'; $scope.cancelText = 'CANCEL ADD'; $scope.titleText = 'Add a new policy'; $scope.ruleType = null; $scope.editRule = null; } function resequence() { _.each($scope.policyRules, (rule: any, i: any) => { rule.sequence = i; }); } $scope.onMovedPolicyRule = ($index: any) => { $scope.policyRules.splice($index, 1); $scope.moved = true; $scope.pendingEdits = true; resequence(); } /** * when canceling a pending edit * @param $event */ $scope.cancelEdit = ($event: any) => { _cancelEdit(); } $scope.onRuleTypeChange = () => { if ($scope.ruleType != null) { var rule = angular.copy($scope.ruleType); rule.groups = PolicyInputFormService.groupProperties(rule); PolicyInputFormService.updatePropertyIndex(rule); //make all rules editable rule.editable = true; $scope.editRule = rule; } else { $scope.editRule = null; } } function validateForm() { var validForm = PolicyInputFormService.validateForm($scope.policyForm, $scope.editRule.properties, false); return validForm; } /* function buildDisplayString() { if ($scope.editRule != null) { var str = ''; _.each($scope.editRule.properties, function (prop, idx) { if (prop.type != 'currentFeed') { //chain it to the display string if (str != '') { str += ';'; } str += ' ' + prop.displayName; var val = prop.value; if ((val == null || val == undefined || val == '') && (prop.values != null && prop.values.length > 0)) { val = _.map(prop.values, function (labelValue) { return labelValue.value; }).join(","); } str += ": " + val; } }); $scope.editRule.propertyValuesDisplayString = str; } } */ $scope.deletePolicyByIndex = ($index: any) => { if ($scope.policyRules != null) { $scope.policyRules.splice($index, 1); } $scope.pendingEdits = true; _cancelEdit(); } $scope.deletePolicy = ($index: any) => { var index: any = $scope.editIndex; if ($scope.policyRules != null && index != null) { $scope.policyRules.splice($index, 1); } $scope.pendingEdits = true; _cancelEdit(); // $mdDialog.hide('done'); } $scope.editPolicy = ($event: any, index: any, rule: any) => { if ($scope.editMode == 'EDIT') { _cancelEdit(); } $scope.editMode = 'EDIT'; $scope.addText = 'SAVE EDIT'; $scope.titleText = 'Edit the policy'; $scope.editIndex = index; //get a copy of the saved rule var editRule = angular.copy($scope.policyRules[index]); //copy the rule from options with all the select options var startingRule = angular.copy(findRuleType(editRule.name, editRule.type)); //reset the values _.each(startingRule.properties, (ruleProperty: any) => { var editRuleProperty = _.find(editRule.properties, (editProperty: any) => { return editProperty.name == ruleProperty.name; }); if (editRuleProperty != null && editRuleProperty != undefined) { //assign the values ruleProperty.value = editRuleProperty.value; ruleProperty.values = editRuleProperty.values; } }); //reassign the editRule object to the one that has all the select values editRule = startingRule; editRule.groups = PolicyInputFormService.groupProperties(editRule); PolicyInputFormService.updatePropertyIndex(editRule); //make all rules editable editRule.editable = true; $scope.editRule = editRule; var match = findRuleType(rule.name, rule.type) $scope.ruleType = angular.copy(match); if ($scope.ruleType && $scope.ruleType.type != $scope.selectedOptionType) { changedOptionType($scope.ruleType.type); } $scope.selectedOptionType = editRule.type; } $scope.done = ($event: any) => { var validators: any = []; var standardizers: any = []; _.each($scope.policyRules, (rule: any, i: any) => { rule.sequence = i; if (rule.type == 'validation') { validators.push(rule); } else if (rule.type == 'standardization') { standardizers.push(rule); } }) field['validation'] = validators; field['standardization'] = standardizers; $mdDialog.hide('done'); } $scope.addPolicy = ($event: any) => { var validForm = validateForm(); if (validForm == true) { if ($scope.policyRules == null) { $scope.policyRules = []; } // buildDisplayString(); $scope.editRule.ruleType = $scope.ruleType; if ($scope.editMode == 'NEW') { $scope.policyRules.push($scope.editRule); } else if ($scope.editMode == 'EDIT') { $scope.policyRules[$scope.editIndex] = $scope.editRule; } $scope.pendingEdits = true; _cancelEdit(); } } $scope.hide = ($event: any) => { _cancelEdit(); $mdDialog.hide(); }; $scope.cancel = ($event: any) => { _cancelEdit(); $mdDialog.hide(); }; }; } angular.module(moduleName).controller('FeedFieldPolicyRuleDialogController', FeedFieldPolicyRuleDialogController); class FieldPolicyRuleOptionsFactory { standardizationOptions: any[] = []; validationOptions: any[] = []; static readonly $inject = ["$http", "$q", "RestUrlService"]; constructor(private $http: angular.IHttpService, private $q: angular.IQService, private RestUrlService: any) { } getStandardizationOptions() { return this.$http.get(this.RestUrlService.AVAILABLE_STANDARDIZATION_POLICIES, { cache: true }); } getValidationOptions() { return this.$http.get(this.RestUrlService.AVAILABLE_VALIDATION_POLICIES, { cache: true }); } getParserOptions() { return this.$http.get(this.RestUrlService.LIST_FILE_PARSERS, { cache: true }); } getSparkParserOptions() { return this.$http.get(this.RestUrlService.LIST_SPARK_FILE_PARSERS, {cache: true}); } getOptionsForType = (type: any) => { if (type == 'standardization-validation') { var defer = this.$q.defer(); var requests = { validation: this.getValidationOptions(), standardization: this.getStandardizationOptions() }; this.$q.all(requests).then((response: any) => { defer.resolve(response); }); return defer.promise; } if (type == 'standardization') { return this.getStandardizationOptions(); } else if (type == 'validation') { return this.getValidationOptions(); } else if (type == 'schemaParser') { return this.getParserOptions(); } else if (type == 'sparkSchemaParser') { return this.getSparkParserOptions(); } } getTitleForType = (type: any) => { if (type == 'standardization') { return "Standardization Policies"; } else if (type == 'validation') { return 'Validation Policies'; } else if (type == 'schemaParser') { return 'Supported Parsers' } else if (type == 'schemaParser') { return 'Supported Parsers' } } getStandardizersAndValidators = () => { return this.getOptionsForType('standardization-validation'); } } angular.module(moduleName).service('FieldPolicyRuleOptionsFactory', FieldPolicyRuleOptionsFactory); export class FeedFieldPolicyRuleService { constructor() { } getAllPolicyRules = (field: any) => { if (field === undefined) { return []; } var arr = []; var standardizers = field['standardization']; var validators = field['validation']; //add in the type so we know what we are dealing with if (standardizers) { _.each(standardizers, (item: any) => { item.type = 'standardization'; }); } if (validators) { _.each(validators, (item: any) => { item.type = 'validation'; }); } var tmpArr = _.union(standardizers, validators); var hasSequence = _.find(tmpArr, (item: any) => { return item.sequence != null && item.sequence != undefined; }) !== undefined; //if we dont have a sequence, add it in if (!hasSequence) { _.each(tmpArr, (item: any, idx: any) => { item.sequence = idx; }); } arr = _.sortBy(tmpArr, 'sequence'); return arr; } } angular.module(moduleName).service('FeedFieldPolicyRuleService', FeedFieldPolicyRuleService);
the_stack
import * as os from 'os'; const { EOL } = os; import * as fs from 'fs'; import * as path from 'path'; var stringify = require('json-stringify-safe'); import { pickBy, identity, isEmpty } from 'lodash'; import { logDebug, formatURL, NAME } from './common'; import * as vscode from 'vscode'; import { Method, RequestHeaderField } from './httpConstants'; import * as cache from './cache'; // full documentation available here: https://github.com/axios/axios#request-config // using default values for undefined export interface Request { url?: string | undefined, method: string, baseURL: string, headers?: any | undefined, params?: any | undefined, data?: string | any | undefined, timeout?: number | undefined, withCredentials?: boolean | false, auth?: any | undefined, responseType?: string | undefined, responseEncoding?: string | undefined, xsrfCookieName?: string | undefined, xsrfHeaderName?: string | undefined, maxContentLength?: number | undefined, maxBodyLength?: number | undefined, maxRedirects?: number | undefined, socketPath?: any | undefined, proxy?: any | undefined, decompress?: boolean | true } export class RequestParser { private originalText: string[]; private originalRequest: string[]; private requestOptions: Request | undefined; private baseUrl?: string; private variableName: string | undefined; private valuesReplacedBySecrets: string[] = []; constructor(query: string) { let linesOfText = query.split(EOL); if (linesOfText.filter(s => { return s; }).length === 0) { throw new Error('Please provide request information (at minimum a URL) before running the cell!'); } logDebug(linesOfText); this.originalText = linesOfText; this.originalRequest = this._parseOutVariableDeclarations(); if(this.originalRequest.length == 0) { return; } this.variableName = this._parseVariableName(); this.requestOptions = { method: this._parseMethod(), baseURL: this._parseBaseUrl(), timeout: 10000 }; this.requestOptions.params = this._parseQueryParams(); let defaultHeaders = {}; // eslint-disable-next-line @typescript-eslint/naming-convention if(process.env.NODE_ENV) { defaultHeaders = { "User-Agent": NAME }; } this.requestOptions.headers = this._parseHeaders() ?? defaultHeaders; this.requestOptions.data = this._parseBody(); } getRequest(): any | undefined { if(this.requestOptions === undefined) { return undefined; } return pickBy(this.requestOptions, identity); } getBaseUrl(): string | undefined { return this.baseUrl; } getVariableName(): string | undefined { return this.variableName; } wasReplacedBySecret(text: string): boolean { if(typeof text === 'string') { for(let replaced of this.valuesReplacedBySecrets) { if(text.includes(replaced)) { return true; } } } else if(typeof text === 'number') { for(let replaced of this.valuesReplacedBySecrets) { if(`${text}`.includes(replaced)) { return true; } } } return false; } private _parseOutVariableDeclarations(): string[] { const keyword = 'const '; let ret: string[] = []; let i = 0; while(i < this.originalText.length && this.originalText[i].trim().match(/const\s([A-Za-z0-9]+)(\s)?=/)) { let line = this.originalText[i]; let startIndex = (line.indexOf(keyword) + keyword.length); let nameLength = line.indexOf('=') - startIndex; let varName = line.substr(startIndex, nameLength).trim(); let varValueStr = line.substr(line.indexOf('=') + 1).trim(); try { let varValue = JSON.parse(varValueStr); cache.addToCache(varName, varValue); } catch (e) { cache.addToCache(varName, varValueStr); } i++; } while(i < this.originalText.length && (!this.originalText[i] || this.originalText[i].length === 0)) { i++; } for(i; i < this.originalText.length; i++) { ret.push(this.originalText[i]); } return ret; } private _parseVariableName(): string | undefined { let firstLine = this.originalRequest[0].trimLeft(); if(!firstLine.startsWith('let ')) { return undefined; } let endIndexOfVarName = firstLine.indexOf('=') + 1; let varDeclaration = firstLine.substring(0, endIndexOfVarName); let variableName = varDeclaration.replace('let ', ''); variableName = variableName.replace('=', ''); variableName = variableName.trim(); if (variableName.includes(' ')) { throw new Error('Invalid declaration of variable!'); } if(variableName === 'SECRETS') { throw new Error('"SECRETS" variable name reserved for Secrets storage!'); } return variableName; } private _stripVariableDeclaration(): string { let firstLine = this.originalRequest[0].trimLeft(); if(!firstLine.startsWith('let ')) { return firstLine; } let endIndexOfVarName = firstLine.indexOf('=') + 1; return firstLine.substring(endIndexOfVarName).trim(); } private _parseMethod(): Method { const tokens: string[] = this._stripVariableDeclaration().split(/[\s,]+/); if (tokens.length === 0) { throw new Error('Invalid request!'); } if (tokens.length === 1) { return Method.get; } if( !(tokens[0].toLowerCase() in Method) ) { throw new Error('Invalid method given!'); } return Method[<keyof typeof Method> tokens[0].toLowerCase()]; } private _parseBaseUrl(): string { const tokens: string[] = this._stripVariableDeclaration().split(/(?<=^\S+)\s/); if (tokens.length === 0) { throw new Error('Invalid request!'); } const findAndReplaceVarsInUrl = (url: string) => { let tokens = url.split('/'); for(let i = 0; i < tokens.length; i++) { if(!tokens[i].startsWith('$')) { continue; } tokens[i] = this._attemptToLoadVariable(tokens[i]); } return tokens.join('/'); }; if(tokens.length === 1) { let url = findAndReplaceVarsInUrl(tokens[0].split('?')[0]); this.baseUrl = url; return formatURL(url); } else if (tokens.length === 2) { let url = findAndReplaceVarsInUrl(tokens[1].split('?')[0]); this.baseUrl = url; return formatURL(url); } throw new Error('Invalid URL given!'); } private _parseQueryParams(): {[key: string] : string} | undefined { let queryInUrl = this._stripVariableDeclaration().split('?')[1]; let strParams: string[] = queryInUrl ? queryInUrl.split('&') : []; if (this.originalRequest.length >= 2) { let i = 1; while(i < this.originalRequest.length && (this.originalRequest[i].trim().startsWith('?') || this.originalRequest[i].trim().startsWith('&'))) { strParams.push(this.originalRequest[i].trim().substring(1)); i++; } } if(strParams.length === 0) { return undefined; } let params: {[key: string] : string} = {}; for(const p of strParams) { let parts = p.split('='); if (parts.length !== 2) { throw new Error(`Invalid query paramter for ${p}`); } params[parts[0]] = this._attemptToLoadVariable(parts[1].trim()); params[parts[0]] = params[parts[0]].replace(/%20/g, '+'); } return params; } private _parseHeaders(): {[key: string] : string} | undefined { if (this.originalRequest.length < 2) { return undefined; } let i = 1; while(i < this.originalRequest.length && (this.originalRequest[i].trim().startsWith('?') || this.originalRequest[i].trim().startsWith('&'))) { i++; } if(i >= this.originalRequest.length) { return undefined; } let headers: {[key: string] : string} = {}; while(i < this.originalRequest.length && this.originalRequest[i]) { let h = this.originalRequest[i]; let parts = h.split(/(:\s+)/).filter(s => { return !s.match(/(:\s+)/); }); if (parts.length !== 2) { throw new Error(`Invalid header ${h}`); } if(parts[0] === 'User-Agent' && !process.env.NODE_ENV) { continue; } headers[parts[0]] = this._attemptToLoadVariable(parts[1].trim()); i++; } return isEmpty(headers) ? undefined : headers; } private _parseBody(): {[key: string] : string} | string | undefined { if (this.originalRequest.length < 3) { return undefined; } let i = 0; while(i < this.originalRequest.length && this.originalRequest[i]) { i++; } i++; let bodyStr = this.originalRequest.slice(i).join('\n'); let fileContents = this._attemptToLoadFile(bodyStr); if( fileContents ) { return fileContents; } if(bodyStr.startsWith('$')) { let variableContents = cache.attemptToLoadVariable(bodyStr.substr(1)); if( variableContents ) { if(bodyStr.startsWith('$SECRETS')) { this.valuesReplacedBySecrets.push(variableContents); } return variableContents; } } try { let bodyObj = JSON.parse(bodyStr); // attemptToLoadVariableInObject(bodyObj); // TODO problems parsing body when given var name without quotes return bodyObj; } catch (e) { return bodyStr; } } private _attemptToLoadFile(possibleFilePath: string): string | undefined { try { const workSpaceDir = path.dirname(vscode.window.activeTextEditor?.document.uri.fsPath ?? ''); if (!workSpaceDir) { return; } const absolutePath = path.join(workSpaceDir, possibleFilePath); return fs.readFileSync(absolutePath).toString(); } catch (error) { // File doesn't exist } return; } private _attemptToLoadVariable(text: string): string { let indexOfDollarSign = text.indexOf('$'); if(indexOfDollarSign === -1) { return text; } let beforeVariable = text.substr(0, indexOfDollarSign); let indexOfEndOfPossibleVariable = this._getEndOfWordIndex(text, indexOfDollarSign); let possibleVariable = text.substr(indexOfDollarSign + 1, indexOfEndOfPossibleVariable); let loadedFromVariable = cache.attemptToLoadVariable(possibleVariable); if(loadedFromVariable) { if(typeof loadedFromVariable === 'string') { if(possibleVariable.startsWith('SECRETS')) { this.valuesReplacedBySecrets.push(loadedFromVariable); } return beforeVariable + loadedFromVariable; } else { return beforeVariable + stringify(loadedFromVariable); } } return text; } private _getEndOfWordIndex(text: string, startingIndex?: number): number { let indexOfSpace = text.indexOf(' ', startingIndex ?? 0); let indexOfComma = text.indexOf(',', startingIndex ?? 0); let indexOfSemicolon = text.indexOf(';', startingIndex ?? 0); let indexOfEnd = text.length - 1; let values: number[] = []; if(indexOfSpace !== -1) { values.push(indexOfSpace); } if(indexOfComma !== -1) { values.push(indexOfComma); } if(indexOfSemicolon !== -1) { values.push(indexOfSemicolon); } return Math.min(... values, indexOfEnd); } }
the_stack
import { strict as assert } from "assert"; import fs from "fs"; import { fork, call, race, delay, cancel } from "redux-saga/effects"; import { createStore, applyMiddleware } from "redux"; import createSagaMiddleware from "redux-saga"; import { KubeConfig } from "@kubernetes/client-node"; import { k8sListNamespacesOrError } from "@opstrace/kubernetes"; import { getGKEKubeconfig } from "@opstrace/gcp"; import { setAWSRegion, getEKSKubeconfig } from "@opstrace/aws"; import { log, SECOND, retryUponAnyError, checkIfDockerImageExistsOrErrorOut, die, Dict } from "@opstrace/utils"; import { rootReducer } from "./reducer"; import { ClusterUpgradeTimeoutError } from "./errors"; import { runInformers, blockUntilCacheHydrated } from "./informers"; import { upgradeProgressReporter, waitForControllerDeployment } from "./readiness"; import { cortexOperatorPreamble, opstraceInstanceRequiresUpgrade, upgradeControllerConfigMap, upgradeControllerDeployment, upgradeInfra } from "./upgrade"; import { getClusterConfig, LatestClusterConfigType } from "@opstrace/config"; import { ClusterCreateConfigInterface, setCreateConfig, waitUntilHTTPEndpointsAreReachable } from "@opstrace/installer"; import { workaroundRestartLokiDistributors } from "./workaround"; // Note: a largish number of attempts as long as micro retries are not yet // implemented carefully and thoughtfully. const UPGRADE_ATTEMPTS = 5; // timeout per cluster upgrade attempt const UPGRADE_INFRA_ATTEMPT_TIMEOUT_SECONDS = 60 * 20; // 20 min // A controller deployment upgrade can take longer, for example, if it needs to // rollout an update to the cortex ingesters. const UPGRADE_K8S_RESOURCES_ATTEMPT_TIMEOUT_SECONDS = 45 * 60; // 45 min interface UpgradeConfigInterface { cloudProvider: "gcp" | "aws"; clusterName: string; gcpProjectID: string | undefined; gcpRegion: string | undefined; awsRegion: string | undefined; } // think of this as singleton (set once, immutable, read from everywhere) let upgradeConfig: UpgradeConfigInterface; export function setUpgradeConfig(c: UpgradeConfigInterface): void { upgradeConfig = c; // Configure AWS client lib state with region information. Needs to be done // before using any AWS client lib (S3, EKS, ...). Could be done by the code // that also calls `setUpgradeConfig()` but on the other hand, this can // also be done in here, which is a little cleaner. if (c.awsRegion !== undefined) { log.debug( "setUpgradeConfig(): set AWS region for client libs: %s", c.awsRegion ); setAWSRegion(c.awsRegion); } } async function getKubecfgIfk8sClusterExists( upgradeConfig: UpgradeConfigInterface ): Promise<KubeConfig | undefined> { switch (upgradeConfig.cloudProvider) { case "gcp": return getGKEKubeconfig(upgradeConfig.clusterName); case "aws": return getEKSKubeconfig( upgradeConfig.awsRegion!, upgradeConfig.clusterName ); default: throw Error("must never be here"); } } // Uprade infrastructure. Infrastructure are all the components required to // create a Kubernetes cluster and any other components, ex. cloud storage // buckets, required to run Opstrace. Checks if Kubernetes cluster is available // before starting the upgrade. function* triggerInfraUpgrade() { // catch programmer's error (call setUpgradeConfig() first) assert(upgradeConfig); log.info("try to build kubeconfig for Opstrace instance"); const kubeConfig: KubeConfig | undefined = yield call( getKubecfgIfk8sClusterExists, upgradeConfig ); if (kubeConfig === undefined) { throw new Error("could not fetch cluster kubeconfig"); } const ucc: LatestClusterConfigType = getClusterConfig(); // Check the tenant API tokens are available and fail as early as possible // if they are not. const tenantApiTokens: Dict<string> = readTenantApiTokenFiles(ucc.tenants); const createConfig: ClusterCreateConfigInterface = { holdController: true, tenantApiTokens: tenantApiTokens, kubeconfigFilePath: "" }; // This is required by the waitUntil*AreReachable functions called by // triggerControllerDeploymentUpgrade to check the endpoints are available // when the upgrade finishes. setCreateConfig(createConfig); yield call(checkIfDockerImageExistsOrErrorOut, ucc.controller_image); // Explicitly test the availability of the k8s api and exit if interaction // fails. yield call(k8sListNamespacesOrError, kubeConfig); log.info("k8s cluster seems to exist, trigger infrastructure upgrade"); if (dryRun()) { log.debug("dry run: leave triggerInfraUpgrade() early"); return; } yield call(upgradeInfra, upgradeConfig.cloudProvider); log.info("infrastructure upgrade done"); } // Upgrade controller deployment and wait for it to finish updating Kubernetes // resources. function* triggerControllerDeploymentUpgrade(kubeConfig: KubeConfig) { if (!dryRun()) { yield call(upgradeControllerConfigMap, kubeConfig); // handle upgrades from clusters that are not running the cortex-operator yield call(cortexOperatorPreamble, kubeConfig); yield call(upgradeControllerDeployment, { opstraceClusterName: upgradeConfig.clusterName, kubeConfig: kubeConfig }); yield call(waitForControllerDeployment, { desiredReadyReplicas: 1 }); log.info('wait for upgrade to complete ("wait for deployments/..." phase)'); yield call(upgradeProgressReporter); // Workaround for https://github.com/opstrace/opstrace/issues/1066 yield call(workaroundRestartLokiDistributors); } // ensure the data endpoint, datadog api endpoints and ui are reachable const ucc: LatestClusterConfigType = getClusterConfig(); yield call(waitUntilHTTPEndpointsAreReachable, ucc); } function readTenantApiTokenFiles(tenantNames: string[]): Dict<string> { const tenantApiTokens: Dict<string> = {}; // also read system tenant api token const tnames = [...tenantNames]; tnames.push("system"); for (const tname of tnames) { const fpath = `tenant-api-token-${tname}`; log.info(`read tenant API token file: ${fpath}`); let bytes; try { bytes = fs.readFileSync(fpath); } catch (err: any) { die(`could not read api token file ${fpath}: ${err.message}`); } tenantApiTokens[tname] = bytes.toString(); } return tenantApiTokens; } /** * Timeout control around a single cluster infrastructure upgrade attempt. */ function* upgradeInfraAttemptWithTimeout() { log.debug("upgradeClusterInfraAttemptWithTimeout"); const { timeout } = yield race({ upgrade: call(triggerInfraUpgrade), timeout: delay(UPGRADE_INFRA_ATTEMPT_TIMEOUT_SECONDS * SECOND) }); if (timeout) { // Note that in this case redux-saga guarantees to have cancelled the // task(s) that lost the race, i.e. the `upgrade` task above. // see https://redux-saga.js.org/docs/advanced/TaskCancellation.html // however, this does not seem to reliable cancel all tasks spawned along // the hierarchy, maybe as of usage of promises as part of the stack? // also see opstrace-prelaunch/issues/1457 log.warning( "Opstrace instance infrastructure upgrade attempt timed out after %s seconds", UPGRADE_INFRA_ATTEMPT_TIMEOUT_SECONDS ); throw new ClusterUpgradeTimeoutError(); } } /** * Timeout control around a single cluster Kubernetes resources upgrade attempt. */ function* upgradeControllerDeploymentWithTimeout(kubeConfig: KubeConfig) { log.debug("upgradeControllerDeploymentWithTimeout"); const { timeout } = yield race({ upgrade: call(triggerControllerDeploymentUpgrade, kubeConfig), timeout: delay(UPGRADE_K8S_RESOURCES_ATTEMPT_TIMEOUT_SECONDS * SECOND) }); if (timeout) { // Note that in this case redux-saga guarantees to have cancelled the // task(s) that lost the race, i.e. the `upgrade` task above. // see https://redux-saga.js.org/docs/advanced/TaskCancellation.html // however, this does not seem to reliable cancel all tasks spawned along // the hierarchy, maybe as of usage of promises as part of the stack? // also see opstrace-prelaunch/issues/1457 log.warning( "cluster upgrade attempt timed out after %s seconds", UPGRADE_K8S_RESOURCES_ATTEMPT_TIMEOUT_SECONDS ); throw new ClusterUpgradeTimeoutError(); } } function* rootTaskUpgrade(): Generator<any, any, any> { if (upgradeConfig === undefined) { die("call setUpgradeConfig() first"); } const kubeConfig: KubeConfig | undefined = yield call( getKubecfgIfk8sClusterExists, upgradeConfig ); if (kubeConfig === undefined) { die("could not fetch cluster kubeconfig"); } const ucc: LatestClusterConfigType = getClusterConfig(); yield call(checkIfDockerImageExistsOrErrorOut, ucc.controller_image); // Explicitly test the availability of the k8s api and exit if interaction // fails. yield call(k8sListNamespacesOrError, kubeConfig); log.info("k8s cluster seems to exist, trigger Opstrace instance upgrade"); log.debug("starting kubernetes informers"); //@ts-ignore: TS7075 generator lacks return type (TS 4.3) const informers = yield fork(runInformers, kubeConfig); log.debug("blockUntilCacheHydrated()"); yield call(blockUntilCacheHydrated); const requiresUpgrade: boolean = yield call(opstraceInstanceRequiresUpgrade); if (!requiresUpgrade) { log.info( `Opstrace instance is already running the desired version, skipping upgrade` ); // Cancel the forked informers so we can exit yield cancel(informers); return; } // Note: a longish delay between attempts with the intention to give upgrade // attempts some time to take effect holistically (sometimes, that is our // impression, upgrade of an individual resource might be confirmed // synchronously, but after all still takes a while to be properly reflected // across all views). yield call(retryUponAnyError, { task: upgradeInfraAttemptWithTimeout, maxAttempts: UPGRADE_ATTEMPTS, doNotLogDetailForTheseErrors: [ClusterUpgradeTimeoutError], actionName: "Opstrace instance infrastructure upgrade", delaySeconds: 30 }); // Wait for controller to rollout the upgrade. yield call(upgradeControllerDeploymentWithTimeout, kubeConfig); // Cancel the forked informers so we can exit yield cancel(informers); log.info( "upgrade operation finished for %s (%s)", upgradeConfig.clusterName, upgradeConfig.cloudProvider ); log.info(`Log in here: https://${upgradeConfig.clusterName}.opstrace.io`); } /** * Entry point for cluster upgrade to be called by CLI. */ export async function upgradeCluster( smOnError: (e: Error, detail: unknown) => void ): Promise<void> { const sm = createSagaMiddleware({ onError: smOnError }); createStore(rootReducer, applyMiddleware(sm)); await sm.run(rootTaskUpgrade).toPromise(); // this is helpful when the runtime is supposed to crash but doesn't log.debug("end of upgradeCluster()"); } function dryRun(): boolean { return process.env.DRY_RUN_UPGRADES === "true"; }
the_stack
import * as React from 'react' import * as PropTypes from 'prop-types' import Icon from '../icon/Icon' import { parseDateString, classes } from '../utils' import Transition from '../transition/Transition' import DatePanel from './DatePanel' import MonthPanel from './MonthPanel' import YearPanel from './YearPanel' import DecadePanel from './DecadePanel' import './style' export interface DatePickerProps { value?: string defaultValue?: string defaultPickerValue?: string placeholder?: string footer?: string | React.ReactNode onChange?: (value: string, valueObject: DateValue | null) => any onOpenChange?: (visible: boolean) => any zIndex?: number className?: string style?: React.CSSProperties } export interface DateValue { year: number month: number date: number } export interface DatePickerState { derivedValue: DateValue | null pickerValue: DateValue calendarVisible: boolean mode: 'date' | 'month' | 'year' | 'decade' startYear: number startDecade: number } const componentName = 'DatePicker' class DatePicker extends React.Component<DatePickerProps, DatePickerState> { public static displayName = componentName public static defaultProps = { zIndex: 80 } public static propTypes = { value: PropTypes.string, defaultValue: PropTypes.string, defaultPickerValue: PropTypes.string, placeholder: PropTypes.string, footer: PropTypes.oneOfType([PropTypes.string, PropTypes.element]), onChange: PropTypes.func, onOpenChange: PropTypes.func, zIndex: PropTypes.number, className: PropTypes.string, style: PropTypes.object } public static getDerivedStateFromProps( nextProps: DatePickerProps, prevState: DatePickerState ) { if (nextProps.value && !isNaN(Date.parse(nextProps.value))) { return { derivedValue: parseDateString(nextProps.value), pickerValue: parseDateString(nextProps.value) } } return null } private datePickerRef: HTMLDivElement constructor(props: DatePickerProps) { super(props) const { defaultValue, defaultPickerValue } = props // 是否可被解析 const valueCanBeParsed = defaultValue && !isNaN(Date.parse(defaultValue)) const pickerValueCanBeParsed = defaultPickerValue && !isNaN(Date.parse(defaultPickerValue)) this.state = { derivedValue: valueCanBeParsed ? parseDateString(defaultValue) : null, pickerValue: pickerValueCanBeParsed ? parseDateString(defaultPickerValue) : parseDateString(), calendarVisible: false, mode: 'date', startYear: 0, startDecade: 0 } } public componentDidMount() { document.addEventListener('click', this.handleClickDocument, true) // 第三个参数为 true,让事件在捕获阶段触发,重要,否则被点击元素被移除的话会导致判断不准 } public componentDidUpdate( prevProps: DatePickerProps, prevState: DatePickerState ) { const { onOpenChange } = this.props const { calendarVisible } = this.state if (onOpenChange && prevState.calendarVisible !== calendarVisible) { onOpenChange(calendarVisible) } } public componentWillUnmount() { document.removeEventListener('click', this.handleClickDocument, true) } public handleClickDocument: EventListener = e => { const { calendarVisible } = this.state const target = e.target if (!this.datePickerRef.contains(target as Node) && calendarVisible) { this.setState({ calendarVisible: false }) } } public saveDatePickerRef = (node: HTMLDivElement) => { this.datePickerRef = node } // 监听点击 input 打开 calendar 面板 public handleClickInput = () => { this.setState({ calendarVisible: true, mode: 'date' }) } // 调用 onChange 回调 public handleOnChange = () => { const { onChange } = this.props const { derivedValue } = this.state if (onChange) { if (derivedValue) { const { year, month, date } = derivedValue onChange( year + '-' + this.fixNumberToString(month) + '-' + this.fixNumberToString(date), derivedValue ) } else { onChange('', null) } } } // 监听 date 面板点击 public handleClickDate = (value: DateValue) => { this.setState( { derivedValue: value, pickerValue: value, calendarVisible: false }, this.handleOnChange ) } // 监听点击 date 面板设置为今天 public handleClickToday = () => { this.setState( { derivedValue: parseDateString(), pickerValue: parseDateString(), calendarVisible: false }, this.handleOnChange ) } // 监听点击清除图标 public handleOnClear = () => { this.setState( { derivedValue: null, pickerValue: parseDateString() }, this.handleOnChange ) } // 监听 month 面板点击 public handleClickMonth = (month: number) => { const { pickerValue } = this.state this.setState({ pickerValue: Object.assign({}, pickerValue, { month }), mode: 'date' }) } // 监听 year 面板点击 public handleClickYear = ( year: number, type: 'first' | 'middle' | 'last' ) => { const { pickerValue } = this.state switch (type) { case 'first': this.setState({ pickerValue: Object.assign({}, pickerValue, { year: pickerValue.year - 10 }) }) break case 'middle': this.setState({ pickerValue: Object.assign({}, pickerValue, { year }), mode: 'date' }) break case 'last': this.setState({ pickerValue: Object.assign({}, pickerValue, { year: pickerValue.year + 10 }) }) break default: break } } // 监听 decade 面板点击 public handleClickDecade = ( decade: number, type: 'first' | 'middle' | 'last' ) => { const { pickerValue } = this.state switch (type) { case 'first': this.setState({ pickerValue: Object.assign({}, pickerValue, { year: pickerValue.year - 100 }) }) break case 'middle': this.setState({ pickerValue: Object.assign({}, pickerValue, { year: decade }), mode: 'year' }) break case 'last': this.setState({ pickerValue: Object.assign({}, pickerValue, { year: pickerValue.year + 100 }) }) break default: break } } // 渲染日历面板 public renderCalendarBody = () => { const { mode, pickerValue, derivedValue } = this.state switch (mode) { case 'date': return ( <DatePanel year={pickerValue.year} month={pickerValue.month} value={derivedValue} onClickDate={this.handleClickDate} /> ) case 'month': return ( <MonthPanel month={pickerValue.month} // 设为 pickerValue.month 可让面板上始终有选中的月份,下同 onClickMonth={this.handleClickMonth} /> ) case 'year': return ( <YearPanel startYear={Math.floor(pickerValue.year / 10) * 10} year={pickerValue.year} onClickYear={this.handleClickYear} /> ) case 'decade': return ( <DecadePanel startDecade={Math.floor(pickerValue.year / 100) * 100} decade={Math.floor(pickerValue.year / 10) * 10} onClickDecade={this.handleClickDecade} /> ) default: return null } } // 监听日期面板点击单箭头更改月份 public handleClickArrow = (position: string) => { const { pickerValue } = this.state // month-1 if (position === 'left') { pickerValue.month === 1 ? this.setState({ pickerValue: Object.assign({}, pickerValue, { year: pickerValue.year - 1, month: 12 }) }) : this.setState({ pickerValue: Object.assign({}, pickerValue, { month: pickerValue.month - 1 }) }) // month+1 } else { pickerValue.month === 12 ? this.setState({ pickerValue: Object.assign({}, pickerValue, { year: pickerValue.year + 1, month: 1 }) }) : this.setState({ pickerValue: Object.assign({}, pickerValue, { month: pickerValue.month + 1 }) }) } } // 监听 month year decade 面板点击双箭头 public handleClickDouble = (position: string) => { const { mode, pickerValue } = this.state // left - if (position === 'left') { switch (mode) { case 'month': this.setState({ pickerValue: Object.assign({}, pickerValue, { year: pickerValue.year - 1 }) }) break case 'year': this.setState({ pickerValue: Object.assign({}, pickerValue, { year: pickerValue.year - 10 }) }) break case 'decade': this.setState({ pickerValue: Object.assign({}, pickerValue, { year: pickerValue.year - 100 }) }) break default: break } // right + } else { switch (mode) { case 'month': this.setState({ pickerValue: Object.assign({}, pickerValue, { year: pickerValue.year + 1 }) }) break case 'year': this.setState({ pickerValue: Object.assign({}, pickerValue, { year: pickerValue.year + 10 }) }) break case 'decade': this.setState({ pickerValue: Object.assign({}, pickerValue, { year: pickerValue.year + 100 }) }) break default: break } } } // 监听点击动作条中间文字 public handleClickValue = () => { const { mode } = this.state switch (mode) { case 'month': this.setState({ mode: 'year' }) break case 'year': this.setState({ mode: 'decade' }) break default: break } } // 渲染动作条 public renderCalendarHandler = () => { const { mode, pickerValue } = this.state switch (mode) { case 'date': return ( <> <li className="left"> <span className="icon-wrapper" onClick={() => this.setState({ pickerValue: Object.assign({}, pickerValue, { year: pickerValue.year - 1 }) }) } > <Icon name="double" size={10} /> </span> <span className="icon-wrapper" onClick={() => this.handleClickArrow('left')} > <Icon name="right" size={11} /> </span> </li> <li className="middle"> <span className="value" onClick={() => this.setState({ mode: 'year' })} > {pickerValue.year}年&nbsp; </span> <span className="value" onClick={() => this.setState({ mode: 'month' })} > {this.fixNumberToString(pickerValue.month)}月 </span> </li> <li className="right"> <span className="icon-wrapper" onClick={() => this.handleClickArrow('right')} > <Icon name="right" size={11} /> </span> <span className="icon-wrapper" onClick={() => this.setState({ pickerValue: Object.assign({}, pickerValue, { year: pickerValue.year + 1 }) }) } > <Icon name="double" size={10} /> </span> </li> </> ) default: return ( <> <li className="left"> <span className="icon-wrapper" onClick={() => this.handleClickDouble('left')} > <Icon name="double" size={10} /> </span> </li> <li className="middle"> <span className={classes(componentName, ['value'], { decade: mode === 'decade' })} onClick={this.handleClickValue} > {this.getHandleBarText()} </span> </li> <li className="right"> <span className="icon-wrapper" onClick={() => this.handleClickDouble('right')} > <Icon name="double" size={10} /> </span> </li> </> ) } } // 动作条中间文字 public getHandleBarText = (): string => { const { mode, pickerValue } = this.state if (mode === 'year') { const year = Math.floor(pickerValue.year / 10) * 10 return year + '-' + (year + 9) } else if (mode === 'month') { return pickerValue.year + '' } else if (mode === 'decade') { const year = Math.floor(pickerValue.year / 100) * 100 return year + '-' + (year + 99) } return '' } // 获取 input 渲染文字 public getStringFromDerivedValue = (): string => { const { derivedValue } = this.state if (!derivedValue) { return '' } else { const { year, month, date } = derivedValue return ( year + '-' + this.fixNumberToString(month) + '-' + this.fixNumberToString(date) ) } } // 1 => '01' public fixNumberToString = (n: number): string => { if (n > 9) { return n + '' } else { return `0${n}` } } public render() { const cn = componentName const { placeholder, footer, className, style, zIndex } = this.props const { calendarVisible, mode } = this.state return ( <div className={classes(cn, '')} ref={this.saveDatePickerRef}> <span className={classes(cn, 'input-wrapper')}> {placeholder && !this.getStringFromDerivedValue() && ( <span className={classes(cn, 'placeholder')}>{placeholder}</span> )} <input type="text" value={this.getStringFromDerivedValue()} className={classes(cn, 'input', [className])} style={style} readOnly={true} onClick={this.handleClickInput} /> <span className={classes(cn, 'icon-wrapper')}> <Icon name="calendar" size={16} /> </span> {this.getStringFromDerivedValue() && ( <span className={classes(cn, 'icon-wrapper', ['close'])} onClick={this.handleOnClear} > <Icon name="close" size={12} /> </span> )} </span> <Transition visible={calendarVisible} beforeEnter={{ height: '260px', opacity: 0 }} afterEnter={{ height: '330px', opacity: 1 }} > <div className={classes(cn, 'calendar')} style={{ zIndex }}> {placeholder && !this.getStringFromDerivedValue() && ( <span className="calendar-placeholder">{placeholder}</span> )} <input type="text" value={this.getStringFromDerivedValue()} className="calendar-input" readOnly={true} /> <ul className="calendar-handlebar"> {this.renderCalendarHandler()} </ul> <div className="calendar-body">{this.renderCalendarBody()}</div> {mode === 'date' && ( <div className="calendar-footer"> {footer ? ( footer ) : ( <span className="footer-text" onClick={this.handleClickToday}> 今&nbsp;天 </span> )} </div> )} {/* 页脚,只在日期面板显示 */} </div> </Transition> </div> ) } } export default DatePicker
the_stack
export namespace DataLakeModels { /** * * @export * @class RequiredError * @extends {Error} */ export class RequiredError extends Error { name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } } /** * Access permission requested to be set for the path. Currently READ is allowed for all tenants and subtenants at root level. User can manage WRITE permissions for the paths * @export * @enum {string} */ export enum AccessPermission { WRITE = <any>"WRITE", } /** * Duration for which token will be valid this can be between 900 to 43200 (15 minutes to 12 hours). If value is not provided, the default value will be 3600 seconds(1 hour). * @export * @interface AccessTokenDurationSeconds */ export interface AccessTokenDurationSeconds {} /** * Access permission requested for the token. The permission could be READ or WRITE. Access Token with WRITE permission can be requested only on the paths for which WRITE access has been enabled. Default value will READ. * @export * @enum {string} */ export enum AccessTokenPermission { READ = <any>"READ", WRITE = <any>"WRITE", } /** * * @export * @interface AccessTokenPermissionRequest */ export interface AccessTokenPermissionRequest { /** * Optional, when tenants want to give access to one of their subtenant's path * @type {string} * @memberof AccessTokenPermissionRequest */ subtenantId?: string; /** * Path on which write permission is required * @type {string} * @memberof AccessTokenPermissionRequest */ path: string; /** * * @type {AccessPermission} * @memberof AccessTokenPermissionRequest */ permission: AccessPermission; } /** * * @export * @interface AccessTokenPermissionResource */ export interface AccessTokenPermissionResource { /** * Optional, subtenant Id, for which path write permission request was raised * @type {string} * @memberof AccessTokenPermissionResource */ subtenantId?: string; /** * Auto generated unique id for request * @type {string} * @memberof AccessTokenPermissionResource */ id: string; /** * Path on which write perission is given * @type {string} * @memberof AccessTokenPermissionResource */ path: string; /** * * @type {AccessPermission} * @memberof AccessTokenPermissionResource */ permission?: AccessPermission; /** * Time when write premission for the path was created * @type {string} * @memberof AccessTokenPermissionResource */ created?: string; } /** * * @export * @interface AccessTokenPermissionResources */ export interface AccessTokenPermissionResources { /** * * @type {Array<AccessTokenPermissionResource>} * @memberof AccessTokenPermissionResources */ accessTokenPermissions?: Array<AccessTokenPermissionResource>; /** * * @type {Page} * @memberof AccessTokenPermissionResources */ page?: Page; } /** * * @export * @interface AccessTokens */ export interface AccessTokens { /** * * @type {Credentials} * @memberof AccessTokens */ credentials: Credentials; /** * Name of the storage account, in case of AWS S3, it will be S3 bucket name * @type {string} * @memberof AccessTokens */ storageAccount: string; /** * Path on which the STS token based permissions are given (upto folder level). Path should be absolute path excluding storage endpoint URL. * @type {string} * @memberof AccessTokens */ storagePath: string; /** * Optional, subtenant Id, if STS token is generated for path belonging to subtenant * @type {string} * @memberof AccessTokens */ subtenantId?: string; /** * * @type {AccessTokenDurationSeconds} * @memberof AccessTokens */ durationSeconds?: AccessTokenDurationSeconds; /** * * @type {AccessTokenPermission} * @memberof AccessTokens */ permission?: AccessTokenPermission; } /** * AWS STS token * @export * @interface Credentials */ export interface Credentials { /** * SECRET_ACCESS_KEY * @type {string} * @memberof Credentials */ secretAccessKey: string; /** * ACCESS_KEY_ID * @type {string} * @memberof Credentials */ accessKeyId: string; /** * SESSION_TOKEN * @type {string} * @memberof Credentials */ sessionToken: string; } /** * * @export * @interface CrossAccount */ export interface CrossAccount { /** * Unique Id of the cross account resource * @type {string} * @memberof CrossAccount */ id: string; /** * name of the cross account * @type {string} * @memberof CrossAccount */ name: string; /** * account id of the accessor * @type {string} * @memberof CrossAccount */ accessorAccountId: string; /** * comment about why this cross account is required * @type {string} * @memberof CrossAccount */ description: string; /** * date time (as defined by RFC 3339, section 5.6) when the access was given or changed for other attributes * @type {Date} * @memberof CrossAccount */ timestamp: Date; /** * Contains a subtenant ID in case the cross account gives access to the subtenant's paths. Contains ** in case the cross account gives access to the tenant's paths and all of its subtenants' paths. Is omitted in case the cross account gives access to a tenant's paths only. * @type {string} * @memberof CrossAccount */ subtenantId?: string; /** * * @type {ETag} * @memberof CrossAccount */ eTag: ETag; } /** * * @export * @interface CrossAccountAccess */ export interface CrossAccountAccess { /** * Unique Id of the cross account access * @type {string} * @memberof CrossAccountAccess */ id: string; /** * comment about why the permissions are given to the path * @type {string} * @memberof CrossAccountAccess */ description: string; /** * Name of the storage account, in case of AWS S3, it will be S3 bucket name * @type {string} * @memberof CrossAccountAccess */ storageAccount: string; /** * Path on which the permissions are given (upto folder level). Path should be absolute path excluding storage endpoint URL. * @type {string} * @memberof CrossAccountAccess */ storagePath: string; /** * Path on which the permissions are given (upto folder level). * @type {string} * @memberof CrossAccountAccess */ path?: string; /** * * @type {Permission} * @memberof CrossAccountAccess */ permission: Permission; /** * Status of the cross account access. * @type {string} * @memberof CrossAccountAccess */ status?: CrossAccountAccess.StatusEnum; /** * Last changed timestamp for the access, according to ISO 8601 extended date/time format 'YYYY-MM-DDThh:mm:ss.sssZ' * @type {Date} * @memberof CrossAccountAccess */ timestamp: Date; /** * * @type {ETag} * @memberof CrossAccountAccess */ eTag: ETag; } /** * @export * @namespace CrossAccountAccess */ export namespace CrossAccountAccess { /** * @export * @enum {string} */ export enum StatusEnum { ENABLED = <any>"ENABLED", DISABLED = <any>"DISABLED", } } /** * * @export * @interface CrossAccountAccessListResource */ export interface CrossAccountAccessListResource { /** * * @type {Array<CrossAccountAccess>} * @memberof CrossAccountAccessListResource */ crossAccountAccesses?: Array<CrossAccountAccess>; /** * * @type {Page} * @memberof CrossAccountAccessListResource */ page?: Page; } /** * * @export * @interface CrossAccountAccessRequest */ export interface CrossAccountAccessRequest { /** * justification about why the permissions are given to the path * @type {string} * @memberof CrossAccountAccessRequest */ description?: string; /** * Path on which the permissions are required. The path should be given upto folder (not upto object). * @type {string} * @memberof CrossAccountAccessRequest */ path?: string; /** * * @type {Permission} * @memberof CrossAccountAccessRequest */ permission?: Permission; /** * Status of the cross account access. If the quota of ENABLED cross account accesses is exhausted, then cross account access can be created with status as \"DISABLED\". * @type {string} * @memberof CrossAccountAccessRequest */ status?: CrossAccountAccessRequest.StatusEnum; } /** * @export * @namespace CrossAccountAccessRequest */ export namespace CrossAccountAccessRequest { /** * @export * @enum {string} */ export enum StatusEnum { ENABLED = <any>"ENABLED", DISABLED = <any>"DISABLED", } } /** * * @export * @interface CrossAccountListResource */ export interface CrossAccountListResource { /** * * @type {Array<CrossAccount>} * @memberof CrossAccountListResource */ crossAccounts?: Array<CrossAccount>; /** * * @type {Page} * @memberof CrossAccountListResource */ page?: Page; } /** * * @export * @interface CrossAccountRequest */ export interface CrossAccountRequest { /** * name of the cross account * @type {string} * @memberof CrossAccountRequest */ name: string; /** * account id of the accessor * @type {string} * @memberof CrossAccountRequest */ accessorAccountId: string; /** * comment about why this cross account is required * @type {string} * @memberof CrossAccountRequest */ description: string; /** * Only to be used by tenants. In case a concrete subtenant ID is given, all accesses are to the subtenant's paths. In case ** is given, accesses are to the tenant's paths and all of its subtenants' paths. * @type {string} * @memberof CrossAccountRequest */ subtenantId?: string; } /** * * @export * @interface CrossAccountUpdateRequest */ export interface CrossAccountUpdateRequest { /** * name of the cross account * @type {string} * @memberof CrossAccountUpdateRequest */ name: string; /** * comment about why this cross account is required * @type {string} * @memberof CrossAccountUpdateRequest */ description: string; } /** * * @export * @interface DeleteObjectsJobErrorDetailsResponse */ export interface DeleteObjectsJobErrorDetailsResponse { /** * List of object paths to be deleted. * @type {Array<DeleteObjectsJobErrorDetailsResponseObjects>} * @memberof DeleteObjectsJobErrorDetailsResponse */ objects?: Array<DeleteObjectsJobErrorDetailsResponseObjects>; } /** * * @export * @interface DeleteObjectsJobErrorDetailsResponseObjects */ export interface DeleteObjectsJobErrorDetailsResponseObjects { /** * path of object including object name * @type {string} * @memberof DeleteObjectsJobErrorDetailsResponseObjects */ path?: string; /** * Status of the file to be deleted * @type {string} * @memberof DeleteObjectsJobErrorDetailsResponseObjects */ status?: DeleteObjectsJobErrorDetailsResponseObjects.StatusEnum; } /** * @export * @namespace DeleteObjectsJobErrorDetailsResponseObjects */ export namespace DeleteObjectsJobErrorDetailsResponseObjects { /** * @export * @enum {string} */ export enum StatusEnum { DELETED = <any>"DELETED", FAILED = <any>"FAILED", NOTFOUND = <any>"NOTFOUND", } } /** * * @export * @interface DeleteObjectsJobList */ export interface DeleteObjectsJobList { /** * * @type {Array<DeleteObjectsJobResponse>} * @memberof DeleteObjectsJobList */ deleteObjectsJobs?: Array<DeleteObjectsJobResponse>; /** * * @type {Page} * @memberof DeleteObjectsJobList */ page?: Page; } /** * * @export * @interface DeleteObjectsJobProgressDetails */ export interface DeleteObjectsJobProgressDetails { /** * Count of files submitted to the Delete Objects Job * @type {number} * @memberof DeleteObjectsJobProgressDetails */ totalObjects?: number; /** * Count of files which are being deleted by the Delete Objects Job * @type {number} * @memberof DeleteObjectsJobProgressDetails */ inProgressObjects?: number; /** * Count of files deleted successfully by the Delete Objects Job * @type {number} * @memberof DeleteObjectsJobProgressDetails */ deletedObjects?: number; /** * Count of files for which deletion failed by the Delete Objects Job * @type {number} * @memberof DeleteObjectsJobProgressDetails */ failedObjects?: number; } /** * * @export * @interface DeleteObjectsJobRequest */ export interface DeleteObjectsJobRequest { /** * Only to be used by a tenant, to import the time series data to a subtenant's path. If omitted, data is imported to the tenant's path. * @type {string} * @memberof DeleteObjectsJobRequest */ subtenantId?: string; /** * List of object paths to be deleted. * @type {Array<DeleteObjectsJobRequestObjects>} * @memberof DeleteObjectsJobRequest */ objects?: Array<DeleteObjectsJobRequestObjects>; } /** * * @export * @interface DeleteObjectsJobRequestObjects */ export interface DeleteObjectsJobRequestObjects { /** * path of object including object name * @type {string} * @memberof DeleteObjectsJobRequestObjects */ path?: string; } /** * * @export * @interface DeleteObjectsJobResponse */ export interface DeleteObjectsJobResponse { /** * Unique Id of the Delete Objects Job * @type {string} * @memberof DeleteObjectsJobResponse */ id?: string; /** * Only to be used by a tenant, to import the time series data to a subtenant's path. If omitted, data is imported to the tenant's path. * @type {string} * @memberof DeleteObjectsJobResponse */ subtenantId?: string; /** * * @type {DeleteObjectsJobProgressDetails} * @memberof DeleteObjectsJobResponse */ progressDetails?: DeleteObjectsJobProgressDetails; /** * * @type {DeleteObjectsJobStatus} * @memberof DeleteObjectsJobResponse */ status?: DeleteObjectsJobStatus; } /** * Status of the file to be deleted * @export * @enum {string} */ export enum DeleteObjectsJobStatus { COMPLETED = <any>"COMPLETED", INPROGRESS = <any>"IN_PROGRESS", COMPLETEDWITHERRORS = <any>"COMPLETED_WITH_ERRORS", } /** * * @export * @interface DownloadObjectUrls */ export interface DownloadObjectUrls extends Array<ObjectUrlsInner> {} /** * ETag of the resource * @export * @interface ETag */ export interface ETag {} /** * Error response body model. * @export * @interface Errors */ export interface Errors { /** * Concrete error codes and messages are defined at operation error response descriptions in this API specification. * @type {Array<ErrorsErrors>} * @memberof Errors */ errors?: Array<ErrorsErrors>; } /** * * @export * @interface ErrorsErrors */ export interface ErrorsErrors { /** * Unique error code. Every code is bound to one message. * @type {string} * @memberof ErrorsErrors */ code?: string; /** * Logging correlation ID for debugging purposes. * @type {string} * @memberof ErrorsErrors */ logref?: string; /** * Human readable error message in English. * @type {string} * @memberof ErrorsErrors */ message?: string; /** * In case an error message is parametrized, the parameter names and values are returned for, e.g., localization purposes. The parametrized error messages are defined at the operation error response descriptions in this API specification. Parameters are denoted by named placeholders '{\\<parameter name\\>}' in the message specifications. At runtime, returned message placeholders are substituted by actual parameter values. * @type {Array<ErrorsMessageParameters>} * @memberof ErrorsErrors */ messageParameters?: Array<ErrorsMessageParameters>; } /** * Message parameter * @export * @interface ErrorsMessageParameters */ export interface ErrorsMessageParameters { /** * Name of message parameter as specified in parametrized error message. * @type {string} * @memberof ErrorsMessageParameters */ name?: string; /** * Value of message parameter as substituted in returned error message. * @type {string} * @memberof ErrorsMessageParameters */ value?: string; } /** * * @export * @interface GenerateSTSPayload */ export interface GenerateSTSPayload { /** * Only to be used by tenants, to request access to the subtenant's paths. * @type {string} * @memberof GenerateSTSPayload */ subtenantId?: string; /** * object path location on which STS token is requested. This is optional for READ permission - If value for path is not provided then it will be considered on root level (\"/\"). * @type {string} * @memberof GenerateSTSPayload */ path?: string; /** * * @type {AccessTokenDurationSeconds} * @memberof GenerateSTSPayload */ durationSeconds?: AccessTokenDurationSeconds; /** * * @type {AccessTokenPermission} * @memberof GenerateSTSPayload */ permission?: AccessTokenPermission; } /** * * @export * @interface GenerateUrlPayload */ export interface GenerateUrlPayload { /** * * @type {Paths} * @memberof GenerateUrlPayload */ paths?: Paths; /** * * @type {SubtenantId} * @memberof GenerateUrlPayload */ subtenantId?: SubtenantId; } /** * * @export * @interface ImportJobDetails */ export interface ImportJobDetails extends ImportJobResponse { /** * List of aspect names. * @type {Array<string>} * @memberof ImportJobDetails */ aspectNames: Array<string>; /** * List of asset IDs. * @type {Array<string>} * @memberof ImportJobDetails */ assetIds: Array<string>; /** * Beginning of the time range to read * @type {string} * @memberof ImportJobDetails */ from: string; /** * End of the time range to read. * @type {string} * @memberof ImportJobDetails */ to: string; /** * Time series bulk import job progress. This is a number between 0.0 to 100.00 * @type {number} * @memberof ImportJobDetails */ progress: number; /** * Number of files imported * @type {number} * @memberof ImportJobDetails */ fileCount: number; /** * Response related to import job handling * @type {string} * @memberof ImportJobDetails */ responseMessage?: string; /** * Name of the storage account, in case of AWS S3, it will be S3 bucket name * @type {string} * @memberof ImportJobDetails */ storageAccount?: string; /** * Path on which the subscription is created (upto folder level). Path should be absolute path excluding storage endpoint URL. * @type {string} * @memberof ImportJobDetails */ storagePath?: string; } /** * @export * @namespace ImportJobDetails */ export namespace ImportJobDetails {} /** * * @export * @interface ImportJobListResource */ export interface ImportJobListResource { /** * * @type {Array<ImportJobResponse>} * @memberof ImportJobListResource */ timeSeriesImportJobs?: Array<ImportJobResponse>; /** * * @type {Page} * @memberof ImportJobListResource */ page?: Page; } /** * * @export * @interface ImportJobRequest */ export interface ImportJobRequest { /** * Name of the time series bulk import job * @type {string} * @memberof ImportJobRequest */ name: string; /** * User specified destination folder * @type {string} * @memberof ImportJobRequest */ destination?: string; /** * Only to be used by a tenant, to import the time series data to a subtenant's path. If omitted, data is imported to the tenant's path. * @type {string} * @memberof ImportJobRequest */ subtenantId?: string; /** * List of aspect names. * @type {Array<string>} * @memberof ImportJobRequest */ aspectNames: Array<string>; /** * List of asset IDs. * @type {Array<string>} * @memberof ImportJobRequest */ assetIds: Array<string>; /** * Beginning of the time range to read * @type {string} * @memberof ImportJobRequest */ from: string; /** * End of the time range to read. * @type {string} * @memberof ImportJobRequest */ to: string; } /** * * @export * @interface ImportJobResponse */ export interface ImportJobResponse { /** * Unique Id of the time series bulk import job * @type {string} * @memberof ImportJobResponse */ id: string; /** * Name of the time series bulk import job * @type {string} * @memberof ImportJobResponse */ name: string; /** * User specified destination folder * @type {string} * @memberof ImportJobResponse */ destinationPath: string; /** * Status of the time series bulk import job * @type {string} * @memberof ImportJobResponse */ status: ImportJobResponse.StatusEnum; /** * Contains a subtenant ID in case the target of the import is a subtenant's path. Is omitted otherwise. * @type {string} * @memberof ImportJobResponse */ subtenantId?: string; } /** * @export * @namespace ImportJobResponse */ export namespace ImportJobResponse { /** * @export * @enum {string} */ export enum StatusEnum { PENDING = <any>"PENDING", QUEUED = <any>"QUEUED", INPROGRESS = <any>"IN_PROGRESS", SUCCESS = <any>"SUCCESS", FAILED = <any>"FAILED", } } /** * * @export * @interface Metadata */ export interface Metadata { /** * Array of Metadata. * @type {Array<string>} * @memberof Metadata */ tags: Array<string>; } /** * * @export * @interface ObjectListResponse */ export interface ObjectListResponse { /** * * @type {TokenPagePage} * @memberof ObjectListResponse */ page: TokenPagePage; } /** * * @export * @interface ObjectMetaDataResponse */ export interface ObjectMetaDataResponse { /** * Object Name * @type {string} * @memberof ObjectMetaDataResponse */ name?: string; /** * Object path in Data Lake * @type {string} * @memberof ObjectMetaDataResponse */ path?: string; /** * Last Modified Time of the Object * @type {Date} * @memberof ObjectMetaDataResponse */ lastModified?: Date; /** * Size of the Object * @type {number} * @memberof ObjectMetaDataResponse */ size?: number; /** * Size of the Object * @type {Array<string>} * @memberof ObjectMetaDataResponse */ tags?: Array<string>; /** * Optional, subtenant Id, if the object metadata belongs to subtenant * @type {string} * @memberof ObjectMetaDataResponse */ subtenantId?: string; } /** * * @export * @interface ObjectMetadata */ export interface ObjectMetadata { /** * Object Name * @type {string} * @memberof ObjectMetadata */ name?: string; /** * Object Location in Data Lake * @type {string} * @memberof ObjectMetadata */ location?: string; /** * Last Modified Time of the Object * @type {Date} * @memberof ObjectMetadata */ lastModified?: Date; /** * Size of the Object * @type {number} * @memberof ObjectMetadata */ size?: number; /** * Size of the Object * @type {Array<string>} * @memberof ObjectMetadata */ tags?: Array<string>; /** * Name of the storage account, in case of AWS S3, it will be S3 bucket name * @type {string} * @memberof ObjectMetadata */ storageAccount?: string; /** * Path on which the subscription is created (upto folder level). Path should be absolute path excluding storage endpoint URL. * @type {string} * @memberof ObjectMetadata */ storagePath?: string; /** * Optional, subtenant Id, if the object metadata belongs to subtenant * @type {string} * @memberof ObjectMetadata */ subtenantId?: string; } /** * * @export * @interface ObjectUrls */ export interface ObjectUrls extends Array<ObjectUrlsInner> {} /** * * @export * @interface ObjectUrlsInner */ export interface ObjectUrlsInner { /** * The signed url of the object. * @type {string} * @memberof ObjectUrlsInner */ signedUrl?: string; /** * The path for the signed url. * @type {string} * @memberof ObjectUrlsInner */ path?: string; } /** * * @export * @interface Page */ export interface Page { /** * * @type {number} * @memberof Page */ size?: number; /** * * @type {number} * @memberof Page */ totalElements?: number; /** * * @type {number} * @memberof Page */ totalPages?: number; /** * * @type {number} * @memberof Page */ number?: number; } /** * * @export * @interface Path */ export interface Path { /** * The path where to upload object using the signed url. The path should denote folders and object name. e.g. basefolder/subfolder/objectname.objectext * @type {string} * @memberof Path */ path: string; } /** * * @export * @interface Paths */ export interface Paths extends Array<Path> {} /** * specific access * @export * @enum {string} */ export enum Permission { READ = <any>"READ", DELETE = <any>"DELETE", } /** * * @export * @interface SearchResponse */ export interface SearchResponse { /** * * @type {Array<ObjectMetadata>} * @memberof SearchResponse */ objectMetadata?: Array<ObjectMetadata>; /** * * @type {Page} * @memberof SearchResponse */ page?: Page; } /** * * @export * @interface SignedUrlResponse */ export interface SignedUrlResponse { /** * * @type {ObjectUrls} * @memberof SignedUrlResponse */ objectUrls?: ObjectUrls; /** * Optional, subtenant Id, if the generate Url request is for a subtenant * @type {string} * @memberof SignedUrlResponse */ subtenantId?: string; } /** * Sort Request defined as array. Defined using Sort criteria object. * @export * @interface Sort */ export interface Sort extends Array<SortCriteria> {} /** * * @export * @interface SortCriteria */ export interface SortCriteria { /** * Sort Criteria requested by User(name or location or lastModified or size). * @type {string} * @memberof SortCriteria */ field?: SortCriteria.FieldEnum; /** * Sort Order * @type {string} * @memberof SortCriteria */ order?: SortCriteria.OrderEnum; } /** * @export * @namespace SortCriteria */ export namespace SortCriteria { /** * @export * @enum {string} */ export enum FieldEnum { Name = <any>"name", Location = <any>"location", LastModified = <any>"lastModified", Size = <any>"size", } /** * @export * @enum {string} */ export enum OrderEnum { DESC = <any>"DESC", ASC = <any>"ASC", } } /** * * @export * @interface Subscription */ export interface Subscription { /** * path on which events result in notification * @type {string} * @memberof Subscription */ path: string; /** * endpoint where notification has to be published * @type {string} * @memberof Subscription */ destination: string; /** * Only to be used by tenants, to create a subscription to a subtenant's path. If not provided by a tenant, the subscription is for the tenant's path. * @type {string} * @memberof Subscription */ subtenantId?: string; } /** * * @export * @interface SubscriptionListResource */ export interface SubscriptionListResource { /** * * @type {Array<SubscriptionResponse>} * @memberof SubscriptionListResource */ subscriptions?: Array<SubscriptionResponse>; /** * * @type {Page} * @memberof SubscriptionListResource */ page?: Page; } /** * * @export * @interface SubscriptionResponse */ export interface SubscriptionResponse { /** * unique identifier of the subscription * @type {string} * @memberof SubscriptionResponse */ id: string; /** * Name of the storage account, in case of AWS S3, it will be S3 bucket name * @type {string} * @memberof SubscriptionResponse */ storageAccount: string; /** * Path on which the subscription is created (upto folder level). Path should be absolute path excluding storage endpoint URL. * @type {string} * @memberof SubscriptionResponse */ storagePath: string; /** * endpoint where notification has to be published * @type {string} * @memberof SubscriptionResponse */ destination: string; /** * * @type {ETag} * @memberof SubscriptionResponse */ eTag: ETag; /** * Contains a subtenant ID in case the subscription is for a subtenant's path. Is omitted otherwise. * @type {string} * @memberof SubscriptionResponse */ subtenantId?: string; /** * Status of the destination endpoint. By default, status will be active. But, if destination is not reachable then it will be changed to inactive. Patch API can be used to make it Active again. Possible values are \"ACTIVE\" or \"INACTIVE\" * @type {string} * @memberof SubscriptionResponse */ status: string; } /** * * @export * @interface SubscriptionUpdate */ export interface SubscriptionUpdate { /** * path on which events result in notification * @type {string} * @memberof SubscriptionUpdate */ path?: string; /** * endpoint where notification has to be published * @type {string} * @memberof SubscriptionUpdate */ destination?: string; /** * status for endpoint destination. \"ACTIVE\" is the only valid value * @type {string} * @memberof SubscriptionUpdate */ status?: string; } /** * Only to be used by tenants, to assign the resource to a subtenant. If not provided by a tenant, the resource is assigned to the tenant. * @export * @interface SubtenantId */ export interface SubtenantId {} /** * * @export * @interface TokenPage */ export interface TokenPage { /** * * @type {TokenPagePage} * @memberof TokenPage */ page: TokenPagePage; } /** * * @export * @interface TokenPagePage */ export interface TokenPagePage { /** * Opaque token to next page. Can be used in query paramter 'pageToken' to request next page. The property is only present in case there is a next page. * @type {string} * @memberof TokenPagePage */ nextToken?: string; } }
the_stack
import { ContractTransaction, Signer, BigNumber, BigNumberish, providers } from 'ethers'; import { ClientTypes, ExtensionTypes } from '@requestnetwork/types'; import { getBtcPaymentUrl } from './btc-address-based'; import { _getErc20PaymentUrl, getAnyErc20Balance } from './erc20'; import { payErc20Request } from './erc20'; import { _getEthPaymentUrl, payEthInputDataRequest } from './eth-input-data'; import { payEthFeeProxyRequest } from './eth-fee-proxy'; import { ITransactionOverrides } from './transaction-overrides'; import { getNetworkProvider, getProvider, getSigner } from './utils'; import { ISwapSettings } from './swap-erc20-fee-proxy'; import { RequestLogicTypes } from '@requestnetwork/types'; import { payAnyToErc20ProxyRequest } from './any-to-erc20-proxy'; import { payAnyToEthProxyRequest } from './any-to-eth-proxy'; import { WalletConnection } from 'near-api-js'; import { isNearNetwork, isNearAccountSolvent } from './utils-near'; import { ICurrencyManager } from '@requestnetwork/currency'; export const supportedNetworks = [ ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_PROXY_CONTRACT, ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_FEE_PROXY_CONTRACT, ExtensionTypes.ID.PAYMENT_NETWORK_ETH_INPUT_DATA, ]; export interface IConversionPaymentSettings { currency?: RequestLogicTypes.ICurrency; maxToSpend: BigNumberish; currencyManager?: ICurrencyManager; } const getPaymentNetwork = (request: ClientTypes.IRequestData): ExtensionTypes.ID | undefined => { // eslint-disable-next-line return Object.values(request.extensions).find((x) => x.type === 'payment-network')?.id; }; /** * Error thrown when the network is not supported. */ export class UnsupportedNetworkError extends Error { constructor(public networkName?: string) { super(`Payment network ${networkName} is not supported`); } } /** * Error thrown when the payment currency network is not supported. */ export class UnsupportedPaymentChain extends Error { constructor(public currencyNetworkName?: string) { super(`Payment currency network ${currencyNetworkName} is not supported`); } } /** * Processes a transaction to pay a Request. * Supported networks: * - ERC20_PROXY_CONTRACT * - ETH_INPUT_DATA * - ERC20_FEE_PROXY_CONTRACT * - ANY_TO_ERC20_PROXY * * @throws UnsupportedNetworkError if network isn't supported for swap or payment. * @throws UnsupportedPaymentChain if the currency network is not supported (eg Near) * @param request the request to pay. * @param signerOrProvider the Web3 provider, or signer. Defaults to window.ethereum. * @param amount optionally, the amount to pay. Defaults to remaining amount of the request. * @param overrides optionally, override default transaction values, like gas. */ export async function payRequest( request: ClientTypes.IRequestData, signerOrProvider: providers.Web3Provider | Signer = getProvider(), amount?: BigNumberish, overrides?: ITransactionOverrides, paymentSettings?: IConversionPaymentSettings, ): Promise<ContractTransaction> { throwIfNotWeb3(request); const signer = getSigner(signerOrProvider); const paymentNetwork = getPaymentNetwork(request); switch (paymentNetwork) { case ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_PROXY_CONTRACT: case ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_FEE_PROXY_CONTRACT: return payErc20Request(request, signer, amount, undefined, overrides); case ExtensionTypes.ID.PAYMENT_NETWORK_ANY_TO_ERC20_PROXY: { if (!paymentSettings) { throw new Error('Missing payment settings for a payment with conversion'); } return payAnyToErc20ProxyRequest( request, signer, paymentSettings, amount, undefined, overrides, ); } case ExtensionTypes.ID.PAYMENT_NETWORK_ANY_TO_ETH_PROXY: { if (!paymentSettings) { throw new Error('Missing payment settings for a payment with conversion'); } return payAnyToEthProxyRequest( request, signer, paymentSettings, amount, undefined, overrides, ); } case ExtensionTypes.ID.PAYMENT_NETWORK_ETH_INPUT_DATA: return payEthInputDataRequest(request, signer, amount, overrides); case ExtensionTypes.ID.PAYMENT_NETWORK_ETH_FEE_PROXY_CONTRACT: return payEthFeeProxyRequest(request, signer, amount, undefined, overrides); default: throw new UnsupportedNetworkError(paymentNetwork); } } /** * Processes a transaction to pay a Request with a swap * Supported payment networks: ERC20_PROXY_CONTRACT, ETH_INPUT_DATA, ERC20_FEE_PROXY_CONTRACT * * @throws UnsupportedNetworkError if network isn't supported for swap or payment. * @throws UnsupportedPaymentChain if the currency network is not supported (eg Near) * @param request the request to pay. * @param swapSettings the information of how to swap from another payment token. * @param signerOrProvider the Web3 provider, or signer. Defaults to window.ethereum. * @param amount optionally, the amount to pay in request currency. Defaults to remaining amount of the request. * @param overrides optionally, override default transaction values, like gas. */ export async function swapToPayRequest( request: ClientTypes.IRequestData, swapSettings: ISwapSettings, signerOrProvider: providers.Web3Provider | Signer = getProvider(), amount?: BigNumberish, overrides?: ITransactionOverrides, ): Promise<ContractTransaction> { throwIfNotWeb3(request); const signer = getSigner(signerOrProvider); const paymentNetwork = getPaymentNetwork(request); if (!canSwapToPay(request)) { throw new UnsupportedNetworkError(paymentNetwork); } return payErc20Request(request, signer, amount, undefined, overrides, swapSettings); } /** * Verifies the address has enough funds to pay the request in its currency. * Supported networks: ERC20_PROXY_CONTRACT, ETH_INPUT_DATA * * @throws UnsupportedNetworkError if network isn't supported * @param request the request to verify. * @param address the address holding the funds * @param providerOptions.provider the Web3 provider. Defaults to getDefaultProvider. * @param providerOptions.nearWalletConnection the Near WalletConnection */ export async function hasSufficientFunds( request: ClientTypes.IRequestData, address: string, providerOptions?: { provider?: providers.Provider; nearWalletConnection?: WalletConnection; }, ): Promise<boolean> { const paymentNetwork = getPaymentNetwork(request); if (!paymentNetwork || !supportedNetworks.includes(paymentNetwork)) { throw new UnsupportedNetworkError(paymentNetwork); } if (!providerOptions?.nearWalletConnection && !providerOptions?.provider) { providerOptions = { provider: getNetworkProvider(request) }; } let feeAmount = 0; if (paymentNetwork === ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_FEE_PROXY_CONTRACT) { feeAmount = request.extensions[paymentNetwork].values.feeAmount || 0; } return isSolvent( address, request.currencyInfo, BigNumber.from(request.expectedAmount).add(feeAmount), providerOptions, ); } /** * Verifies the address has enough funds to pay an amount in a given currency. * * @param fromAddress the address willing to pay * @param amount * @param currency * @param providerOptions.provider the Web3 provider. Defaults to getDefaultProvider. * @param providerOptions.nearWalletConnection the Near WalletConnection * @throws UnsupportedNetworkError if network isn't supported */ export async function isSolvent( fromAddress: string, currency: RequestLogicTypes.ICurrency, amount: BigNumberish, providerOptions?: { provider?: providers.Provider; nearWalletConnection?: WalletConnection; }, ): Promise<boolean> { // Near case if (isNearNetwork(currency.network) && providerOptions?.nearWalletConnection) { return isNearAccountSolvent(amount, providerOptions.nearWalletConnection); } // Main case (web3) if (!providerOptions?.provider) { throw new Error('provider missing'); } const provider = providerOptions.provider; const ethBalance = await provider.getBalance(fromAddress); const needsGas = !(provider as any)?.provider?.safe?.safeAddress && !['Safe Multisig WalletConnect', 'Gnosis Safe Multisig'].includes( (provider as any)?.provider?.wc?._peerMeta?.name, ); if (currency.type === 'ETH') { return ethBalance.gt(amount); } else { const balance = await getCurrencyBalance(fromAddress, currency, provider); return (ethBalance.gt(0) || !needsGas) && BigNumber.from(balance).gte(amount); } } /** * Returns the balance of a given address in a given currency. * @param address the address holding the funds * @param paymentCurrency if different from the requested currency * @param provider the Web3 provider. Defaults to Etherscan. * @throws UnsupportedNetworkError if the currency is not implemented. */ async function getCurrencyBalance( address: string, paymentCurrency: RequestLogicTypes.ICurrency, provider: providers.Provider, ): Promise<BigNumberish> { switch (paymentCurrency.type) { case 'ETH': { return provider.getBalance(address); } case 'ERC20': { return getAnyErc20Balance(paymentCurrency.value, address, provider); } default: throw new UnsupportedNetworkError(paymentCurrency.network); } } /** * Given a request, the function gives whether swap is supported for its payment network. * @param request the request that accepts or not swap to payment */ export function canSwapToPay(request: ClientTypes.IRequestData): boolean { const paymentNetwork = getPaymentNetwork(request); return ( paymentNetwork !== undefined && paymentNetwork === ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_FEE_PROXY_CONTRACT ); } /** * Get a payment URL, if applicable to the payment network, for a request. * BTC: BIP21. * ERC20: EIP-681. (Warning, not widely used. Some wallets may not be able to pay.) * ETH: EIP-681. (Warning, not widely used. Some wallets may not be able to pay.) * @throws UnsupportedNetworkError if the network is not supported. * @param request the request to pay * @param amount optionally, the amount to pay. Defaults to remaining amount of the request. */ export function _getPaymentUrl(request: ClientTypes.IRequestData, amount?: BigNumberish): string { const paymentNetwork = getPaymentNetwork(request); switch (paymentNetwork) { case ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_PROXY_CONTRACT: case ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_FEE_PROXY_CONTRACT: return _getErc20PaymentUrl(request, amount); case ExtensionTypes.ID.PAYMENT_NETWORK_ETH_INPUT_DATA: return _getEthPaymentUrl(request, amount); case ExtensionTypes.ID.PAYMENT_NETWORK_BITCOIN_ADDRESS_BASED: case ExtensionTypes.ID.PAYMENT_NETWORK_TESTNET_BITCOIN_ADDRESS_BASED: return getBtcPaymentUrl(request, amount); default: throw new UnsupportedNetworkError(paymentNetwork); } } // FIXME: should also compare the signer.chainId with the request.currencyInfo.network... const throwIfNotWeb3 = (request: ClientTypes.IRequestData) => { // FIXME: there is a near web3Provider equivalent: https://github.com/aurora-is-near/near-web3-provider if (request.currencyInfo?.network && isNearNetwork(request.currencyInfo.network)) { throw new UnsupportedPaymentChain(request.currencyInfo.network); } };
the_stack
import 'reflect-metadata' // Must be imported exactly once for Inversify /* eslint-disable @typescript-eslint/no-var-requires */ import * as assert from 'assert' import * as fs from 'fs' import * as path from 'path' import * as process from 'process' import * as request from 'request' import { HttpStatusCode } from '../../src/common/errors' import { LiveValidator, RequestResponsePair } from 'oav/dist/lib/liveValidation/liveValidator' import { config } from '../../src/common/index' import { createLiveRequestForCreateApiManagementService, createLiveRequestForCreateRG } from '../tools' import { exec } from 'child_process' const specDir = path.join(__dirname, '../../test/testData/swaggers') const optionsForTest = { directory: specDir } const requestOptions: Record<string, any> = { json: true } async function startVirtualServer() { const cmd = `node dist/src/main.js` return await new Promise<void>((resolve) => { const serverProcesss = exec(cmd, { cwd: path.join(__dirname, '..', '..') }) serverProcesss.stderr.on('data', (data) => { console.error(data) }) serverProcesss.stdout.on('data', (data) => { if (Buffer.isBuffer(data)) data = data.toString() if (typeof data === 'string' && data.indexOf('validator initialized') >= 0) { return resolve() } }) }) } function createTestUrl(path: string, port = config.httpPortStateless): string { return `http://localhost:${port}${path}` } function createTestUrlWithHttps(path: string, port = config.httpsPortStateless): string { return `https://localhost:${port}${path}` } describe('Start virtual server and send requests', () => { const validator = new LiveValidator(optionsForTest) beforeAll(async () => { await startVirtualServer() requestOptions.ca = fs.readFileSync( path.join(__dirname, '..', '..', '.ssh', 'localhost-ca.crt') ) await validator.initialize() process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '1' }) afterAll(async () => { request.post(createTestUrl('/mock-service-host/shutdown'), requestOptions) }) it('stateless request', (done) => { const fileName = path.join(__dirname, '..', 'testData', 'payloads', 'valid_input.json') const pair: RequestResponsePair = require(fileName) request.get( createTestUrlWithHttps(pair.liveRequest.url), requestOptions, async (err, res, body) => { pair.liveResponse.body = body const response = validator.validateLiveResponse(pair.liveResponse, { url: pair.liveRequest.url, method: pair.liveRequest.method }) assert.doesNotReject(response) const responseValidationResult = await response assert.strictEqual(res.statusCode, HttpStatusCode.OK) assert.strictEqual(responseValidationResult.isSuccessful, true) done() } ) }) it('stateless HTTP request', (done) => { const fileName = path.join(__dirname, '..', 'testData', 'payloads', 'valid_input.json') const pair: RequestResponsePair = require(fileName) request.get(createTestUrl(pair.liveRequest.url), requestOptions, async (err, res, body) => { pair.liveResponse.body = body const response = validator.validateLiveResponse(pair.liveResponse, { url: pair.liveRequest.url, method: pair.liveRequest.method }) assert.doesNotReject(response) const responseValidationResult = await response assert.strictEqual(res.statusCode, HttpStatusCode.OK) assert.strictEqual(responseValidationResult.isSuccessful, true) done() }) }) it('alwaysError request', (done) => { const fileName = path.join(__dirname, '..', 'testData', 'payloads', 'valid_input.json') const pair: RequestResponsePair = require(fileName) request.get( createTestUrlWithHttps(pair.liveRequest.url, config.internalErrorPort), requestOptions, async (err, res, body) => { pair.liveResponse.body = body const responseValidationResult = await validator.validateLiveResponse( pair.liveResponse, { url: pair.liveRequest.url, method: pair.liveRequest.method } ) assert.strictEqual(res.statusCode, HttpStatusCode.INTERNAL_SERVER) assert.strictEqual(responseValidationResult.isSuccessful, false) done() } ) }) it('stateful get before put', (done) => { const fileName = path.join(__dirname, '..', 'testData', 'payloads', 'valid_input.json') const pair: RequestResponsePair = require(fileName) request.get( createTestUrlWithHttps(pair.liveRequest.url, config.httpsPortStateful), requestOptions, (err, res, body) => { assert.strictEqual(res.statusCode, HttpStatusCode.RESOURCE_NOT_FOUND) done() } ) }) it('stateful delete before put', (done) => { const fileName = path.join( __dirname, '..', 'testData', 'payloads', 'valid_input_delete.json' ) const pair: RequestResponsePair = require(fileName) request.delete( createTestUrlWithHttps(pair.liveRequest.url, config.httpsPortStateful), { ...requestOptions, body: pair.liveRequest.body, headers: pair.liveRequest.headers }, (err, res, body) => { assert.strictEqual(res.statusCode, HttpStatusCode.RESOURCE_NOT_FOUND) done() } ) }) it('stateful put->get->delete', (done) => { const createRGRequest = createLiveRequestForCreateRG() request.put( createTestUrlWithHttps(createRGRequest.url, config.httpsPortStateful), { ...requestOptions, json: createRGRequest.body }, (err, res, body) => { const createServiceRequest = createLiveRequestForCreateApiManagementService() request.put( createTestUrlWithHttps(createServiceRequest.url, config.httpsPortStateful), { ...requestOptions, json: createServiceRequest.body, qs: createServiceRequest.query }, (err, res, body) => { let fileName = path.join( __dirname, '..', 'testData', 'payloads', 'valid_input_create.json' ) let pair: RequestResponsePair = require(fileName) request.put( createTestUrlWithHttps(pair.liveRequest.url, config.httpsPortStateful), requestOptions, (err, res, body) => { assert.strictEqual(res.statusCode, HttpStatusCode.OK) fileName = path.join( __dirname, '..', 'testData', 'payloads', 'valid_input.json' ) pair = require(fileName) request.get( createTestUrlWithHttps( pair.liveRequest.url, config.httpsPortStateful ), requestOptions, (err, res, body) => { assert.strictEqual(res.statusCode, HttpStatusCode.OK) fileName = path.join( __dirname, '..', 'testData', 'payloads', 'valid_input_delete.json' ) pair = require(fileName) request.delete( createTestUrlWithHttps( pair.liveRequest.url, config.httpsPortStateful ), { ...requestOptions, body: pair.liveRequest.body, headers: pair.liveRequest.headers }, (err, res, body) => { assert.strictEqual( res.statusCode, HttpStatusCode.OK ) done() } ) } ) } ) } ) } ) }) it('special endpoints use json response', async () => { const endpoints = [ '/common/.well-known/openid-configuration', '/metadata/endpoints', '/mock/oauth2/token', '/mock/oauth2/v2.0/token', '/mock/servicePrincipals', '/subscriptions', '/subscriptions/xxx', '/subscriptions/0000/locations', '/subscriptions/mock/providers', '/tenants' ] // on stateful endpoint for (const endpoint of endpoints) { request.get( createTestUrlWithHttps(endpoint, config.httpsPortStateful), requestOptions, (err, res, body) => { assert.strictEqual(res.statusCode, HttpStatusCode.OK) assert.strictEqual(typeof body, 'object') } ) } // on stateless endpoint for (const endpoint of endpoints) { request.get( createTestUrlWithHttps(endpoint, config.httpsPortStateless), requestOptions, (err, res, body) => { assert.strictEqual(res.statusCode, HttpStatusCode.OK) assert.strictEqual(typeof body, 'object') } ) } }) })
the_stack
import { Injectable } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { NgxsDataPluginModule } from '@angular-ru/ngxs'; import { DataAction, Payload, StateRepository } from '@angular-ru/ngxs/decorators'; import { getRepository } from '@angular-ru/ngxs/internals'; import { NgxsImmutableDataRepository } from '@angular-ru/ngxs/repositories'; import { NGXS_DATA_EXCEPTIONS } from '@angular-ru/ngxs/tokens'; import { NgxsModule, State } from '@ngxs/store'; describe('[TEST]: Action decorator', () => { afterEach(() => TestBed.resetTestingModule()); it(`don't should be working without @StateRepository decorator`, () => { let message: string | null = null; try { @State({ name: 'custom', defaults: 'hello world' }) @Injectable() class InvalidState extends NgxsImmutableDataRepository<string> { @DataAction() public setup(val: string): void { this.ctx.setState(val); } } TestBed.configureTestingModule({ imports: [NgxsModule.forRoot([InvalidState]), NgxsDataPluginModule.forRoot()] }); const state: InvalidState = TestBed.inject(InvalidState); state.setState('new value'); } catch (e: unknown) { message = (e as Error).message; } expect(message).toEqual(NGXS_DATA_EXCEPTIONS.NGXS_DATA_STATE_DECORATOR); }); it(`don't should be working without @StateRepository and @State decorator`, () => { let message: string | null = null; try { @Injectable() class InvalidState extends NgxsImmutableDataRepository<string> { @DataAction() public setup(@Payload('val') val: string): void { this.ctx.setState(val); } } TestBed.configureTestingModule({ imports: [NgxsModule.forRoot([InvalidState]), NgxsDataPluginModule.forRoot()] }); const state: InvalidState = TestBed.inject(InvalidState); state.setState('new value'); } catch (e: unknown) { message = (e as Error).message; } expect(message).toBe('States must be decorated with @State() decorator'); }); it(`don't should be working without provided meta information`, () => { let message: string | null = null; try { @State({ name: 'custom', defaults: 'hello world' }) @Injectable() class InvalidState { @DataAction() public setup(): void { // ... } } TestBed.configureTestingModule({ imports: [NgxsModule.forRoot([InvalidState]), NgxsDataPluginModule.forRoot()] }); const state: InvalidState = TestBed.inject(InvalidState); state.setup(); } catch (e: unknown) { message = (e as Error).message; } expect(message).toEqual(NGXS_DATA_EXCEPTIONS.NGXS_DATA_STATE_DECORATOR); }); it(`don't should be working when register as service`, () => { let message: string | null = null; try { @State({ name: 'custom', defaults: 'hello world' }) @Injectable() class InvalidState { @DataAction() public setup(): void { // ... } } TestBed.configureTestingModule({ imports: [NgxsModule.forRoot([]), NgxsDataPluginModule.forRoot()], providers: [InvalidState] }); const state: InvalidState = TestBed.inject(InvalidState); state.setup(); } catch (e: unknown) { message = (e as Error).message; } expect(message).toEqual(NGXS_DATA_EXCEPTIONS.NGXS_DATA_STATE_DECORATOR); }); it('should be correct mutate metadata', () => { @StateRepository() @State({ name: 'a', defaults: 'a' }) @Injectable() class A extends NgxsImmutableDataRepository<string> { @DataAction() public setup(): string { return this.getState(); } } TestBed.configureTestingModule({ imports: [NgxsModule.forRoot([A]), NgxsDataPluginModule.forRoot()] }); const stateA: A = TestBed.inject(A); expect(getRepository(A)).toEqual({ stateMeta: { name: 'a', actions: {}, defaults: 'a', path: 'a', makeRootSelector: expect.any(Function), children: undefined }, stateClass: A, operations: {} }); expect(stateA.setup()).toBe('a'); expect(getRepository(A)).toEqual({ stateMeta: { name: 'a', actions: { '@a.setup()': [ { type: '@a.setup()', options: { cancelUncompleted: true }, fn: '@a.setup()' } ] }, makeRootSelector: expect.any(Function), defaults: 'a', path: 'a' }, stateClass: A, operations: { setup: { type: '@a.setup()', options: { cancelUncompleted: true } } } }); }); describe('complex inheritance', () => { @StateRepository() @State({ name: 'a', defaults: 'a' }) @Injectable() class A extends NgxsImmutableDataRepository<string> { // noinspection JSUnusedGlobalSymbols protected word: string = 'hello'; @DataAction() public a(): string { return this.getState(); } @DataAction() public withValueSetStateAsAction(@Payload('name') name: string): string { this.setState(`new value - ${this.word} - ${this.name} - ${name}`); return this.getState(); } // noinspection JSUnusedGlobalSymbols public withValueSetStateAsMethod(name: string): string { this.setState(`new value as method - ${this.word} - ${this.name} - ${name}`); return this.getState(); } } @StateRepository() @State({ name: 'b', defaults: 'b' }) @Injectable() class B extends A { @DataAction() public b(): string { return this.getState(); } // noinspection JSUnusedGlobalSymbols public superA(): string { return super.a() + super.word; } // noinspection JSUnusedGlobalSymbols public thisB(): string { return this.a() + this.word; } } @StateRepository() @State({ name: 'c', defaults: 'c' }) @Injectable() class C extends B { @DataAction() public b(): string { return this.getState(); } public superA(): string { return super.superA(); } // noinspection JSUnusedGlobalSymbols public thisA(): string { return this.thisB(); } } let stateA: A; let stateB: B; let stateC: C; beforeAll(() => { TestBed.configureTestingModule({ imports: [NgxsModule.forRoot([A, B, C]), NgxsDataPluginModule.forRoot()] }); stateA = TestBed.inject(A); stateB = TestBed.inject(B); stateC = TestBed.inject(C); }); it('should be correct metadata before invoked actions', () => { expect(getRepository(A)).toEqual({ stateMeta: { name: 'a', actions: {}, defaults: 'a', makeRootSelector: expect.any(Function), path: 'a' }, operations: {}, stateClass: A }); expect(getRepository(B)).toEqual({ stateMeta: { name: 'b', actions: {}, defaults: 'b', makeRootSelector: expect.any(Function), path: 'b' }, operations: {}, stateClass: B }); expect(getRepository(C)).toEqual({ stateMeta: { name: 'c', actions: {}, defaults: 'c', makeRootSelector: expect.any(Function), path: 'c' }, operations: {}, stateClass: C }); }); it('should be prepare metadata after invoke first action', () => { expect(stateA.a()).toBe('a'); expect(stateB.a()).toBe('b'); expect(stateC.a()).toBe('c'); expect(getRepository(A)).toEqual({ stateMeta: { name: 'a', actions: { '@a.a()': [ { type: '@a.a()', options: { cancelUncompleted: true }, fn: '@a.a()' } ] }, makeRootSelector: expect.any(Function), defaults: 'a', path: 'a' }, stateClass: A, operations: { a: { type: '@a.a()', options: { cancelUncompleted: true } } } }); expect(getRepository(B)).toEqual({ stateMeta: { name: 'b', actions: { '@b.a()': [ { type: '@b.a()', options: { cancelUncompleted: true }, fn: '@b.a()' } ] }, makeRootSelector: expect.any(Function), defaults: 'b', path: 'b' }, stateClass: B, operations: { a: { type: '@b.a()', options: { cancelUncompleted: true } } } }); expect(getRepository(C)).toEqual({ stateMeta: { name: 'c', actions: { '@c.a()': [ { type: '@c.a()', options: { cancelUncompleted: true }, fn: '@c.a()' } ] }, makeRootSelector: expect.any(Function), defaults: 'c', path: 'c' }, stateClass: C, operations: { a: { type: '@c.a()', options: { cancelUncompleted: true } } } }); }); it('super !== this', () => { // noinspection SpellCheckingInspection expect(stateB.superA()).toBe('bundefined'); // noinspection SpellCheckingInspection expect(stateC.superA()).toBe('cundefined'); // noinspection SpellCheckingInspection expect(stateB.thisB()).toBe('bhello'); // noinspection SpellCheckingInspection expect(stateC.thisA()).toBe('chello'); }); it('detect problem with invoke action into action', () => { // A expect(stateA.withValueSetStateAsAction('LEONARD')).toBe('a'); expect(stateA.getState()).toBe('new value - hello - a - LEONARD'); stateA.reset(); expect(stateA.getState()).toBe('a'); expect(stateA.withValueSetStateAsMethod('LEONARD')).toBe('new value as method - hello - a - LEONARD'); expect(stateA.getState()).toBe('new value as method - hello - a - LEONARD'); // B expect(stateB.withValueSetStateAsAction('SHELDON')).toBe('b'); expect(stateB.getState()).toBe('new value - hello - b - SHELDON'); stateB.reset(); expect(stateB.getState()).toBe('b'); expect(stateB.withValueSetStateAsMethod('SHELDON')).toBe('new value as method - hello - b - SHELDON'); expect(stateB.getState()).toBe('new value as method - hello - b - SHELDON'); // C expect(stateC.withValueSetStateAsAction('HOWARD')).toBe('c'); expect(stateC.getState()).toBe('new value - hello - c - HOWARD'); stateC.reset(); expect(stateC.getState()).toBe('c'); expect(stateC.withValueSetStateAsMethod('HOWARD')).toBe('new value as method - hello - c - HOWARD'); expect(stateC.getState()).toBe('new value as method - hello - c - HOWARD'); expect(getRepository(A)).toEqual({ stateMeta: { name: 'a', actions: { '@a.withValueSetStateAsAction(name)': [ { type: '@a.withValueSetStateAsAction(name)', options: { cancelUncompleted: true }, fn: '@a.withValueSetStateAsAction(name)' } ], '@a.a()': [ { type: '@a.a()', options: { cancelUncompleted: true }, fn: '@a.a()' } ], '@a.setState(stateValue)': [ { type: '@a.setState(stateValue)', options: { cancelUncompleted: true }, fn: '@a.setState(stateValue)' } ], '@a.reset()': [ { type: '@a.reset()', options: { cancelUncompleted: true }, fn: '@a.reset()' } ] }, makeRootSelector: expect.any(Function), defaults: 'a', path: 'a' }, stateClass: A, operations: { withValueSetStateAsAction: { type: '@a.withValueSetStateAsAction(name)', options: { cancelUncompleted: true } }, setState: { type: '@a.setState(stateValue)', options: { cancelUncompleted: true } }, a: { type: '@a.a()', options: { cancelUncompleted: true } }, reset: { type: '@a.reset()', options: { cancelUncompleted: true } } } }); expect(getRepository(B)).toEqual({ stateMeta: { name: 'b', actions: { '@b.withValueSetStateAsAction(name)': [ { type: '@b.withValueSetStateAsAction(name)', options: { cancelUncompleted: true }, fn: '@b.withValueSetStateAsAction(name)' } ], '@b.setState(stateValue)': [ { type: '@b.setState(stateValue)', options: { cancelUncompleted: true }, fn: '@b.setState(stateValue)' } ], '@b.a()': [ { type: '@b.a()', options: { cancelUncompleted: true }, fn: '@b.a()' } ], '@b.reset()': [ { type: '@b.reset()', options: { cancelUncompleted: true }, fn: '@b.reset()' } ] }, makeRootSelector: expect.any(Function), defaults: 'b', path: 'b' }, stateClass: B, operations: { withValueSetStateAsAction: { type: '@b.withValueSetStateAsAction(name)', options: { cancelUncompleted: true } }, setState: { type: '@b.setState(stateValue)', options: { cancelUncompleted: true } }, a: { type: '@b.a()', options: { cancelUncompleted: true } }, reset: { type: '@b.reset()', options: { cancelUncompleted: true } } } }); expect(getRepository(C)).toEqual({ stateMeta: { name: 'c', actions: { '@c.withValueSetStateAsAction(name)': [ { type: '@c.withValueSetStateAsAction(name)', options: { cancelUncompleted: true }, fn: '@c.withValueSetStateAsAction(name)' } ], '@c.setState(stateValue)': [ { type: '@c.setState(stateValue)', options: { cancelUncompleted: true }, fn: '@c.setState(stateValue)' } ], '@c.a()': [ { type: '@c.a()', options: { cancelUncompleted: true }, fn: '@c.a()' } ], '@c.reset()': [ { type: '@c.reset()', options: { cancelUncompleted: true }, fn: '@c.reset()' } ] }, makeRootSelector: expect.any(Function), defaults: 'c', path: 'c' }, stateClass: C, operations: { withValueSetStateAsAction: { type: '@c.withValueSetStateAsAction(name)', options: { cancelUncompleted: true } }, setState: { type: '@c.setState(stateValue)', options: { cancelUncompleted: true } }, a: { type: '@c.a()', options: { cancelUncompleted: true } }, reset: { type: '@c.reset()', options: { cancelUncompleted: true } } } }); }); }); });
the_stack
import { AfterViewInit, ChangeDetectorRef, Component, ElementRef, EventEmitter, forwardRef, Inject, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, ViewChild } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { MatAutocomplete, MatAutocompleteSelectedEvent, MatAutocompleteTrigger } from '@angular/material/autocomplete'; import { MatFormFieldAppearance } from '@angular/material/form-field'; import { BehaviorSubject, combineLatest, fromEvent, Subject } from 'rxjs'; import { debounceTime, startWith, takeUntil } from 'rxjs/operators'; import { MatSelectCountryLangToken } from './tokens'; import { MatInput } from '@angular/material/input'; /** * Country interface ISO 3166 */ export interface Country { name: string; alpha2Code: string; alpha3Code: string; numericCode: string; callingCode: string; } type Optional<T, K extends keyof T> = Omit<T, K> & Partial<T>; type CountryOptionalMandatoryAlpha2Code = Optional<Country, 'alpha3Code' | 'name' | 'callingCode' | 'numericCode'>; /** * @author Anthony Nahas * @since 11.19 * @version 2.1.0 */ @Component({ selector: 'mat-select-country', templateUrl: 'mat-select-country.component.html', styleUrls: ['mat-select-country.component.scss'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MatSelectCountryComponent), multi: true, }, ], }) export class MatSelectCountryComponent implements OnInit, OnChanges, OnDestroy, ControlValueAccessor { @Input() appearance: MatFormFieldAppearance; @Input() countries: Country[] = []; @Input() label: string; @Input() placeHolder = 'Select country'; @Input() required: boolean; @Input() disabled: boolean; @Input() nullable: boolean; @Input() readonly: boolean; @Input() tabIndex: number | string; @Input() class: string; @Input() itemsLoadSize: number; @Input() loading: boolean; @Input() showCallingCode = false; @Input() excludedCountries: CountryOptionalMandatoryAlpha2Code[] = []; @Input() autocomplete: string; @Input() language: string; @Input() name: string = 'country'; @ViewChild('countryAutocomplete') statesAutocompleteRef: MatAutocomplete; @ViewChild(MatAutocompleteTrigger) autocompleteTrigger: MatAutocompleteTrigger; @ViewChild(MatInput) inputElement: MatInput; // tslint:disable-next-line: no-output-on-prefix @Output() onCountrySelected: EventEmitter<Country> = new EventEmitter<Country>(); filteredOptions: Country[]; db: Country[]; loadingDB: boolean; debounceTime = 300; filterString = ''; private modelChanged: Subject<string> = new Subject<string>(); private countries$ = new BehaviorSubject<Country[]>([]); private excludedCountries$ = new BehaviorSubject<Country[]>([]); private value$ = new BehaviorSubject<Country>(null); private unsubscribe$ = new Subject<void>(); // tslint:disable-next-line: variable-name private _value: Country; constructor( @Inject(forwardRef(() => MatSelectCountryLangToken)) public i18n: string, private cdRef: ChangeDetectorRef ) {} get value(): Country { return this._value; } @Input() set value(value: Country) { // setting a value on a reactive form (formControlName) doesn't trigger ngOnChanges but it does call this setter this.value$.next(value); } propagateChange = (_: any) => {}; ngOnInit() { combineLatest([ this.countries$, this.value$, this.excludedCountries$ ]) .pipe( // fixing the glitch on combineLatest https://blog.strongbrew.io/combine-latest-glitch/ debounceTime(0), takeUntil(this.unsubscribe$) ) .subscribe(( [countries, value, excludedCountries] ) => { this._populateCountries(countries, excludedCountries); if (value) { this._setValue( value ); } }); if (!this.countries.length) { this._loadCountriesFromDb(); } this.modelChanged .pipe( startWith(''), debounceTime(this.debounceTime), takeUntil(this.unsubscribe$) ) .subscribe((value) => { this.filterString = value; this._filter(value); }); } ngOnChanges(changes: SimpleChanges) { if (changes.countries?.currentValue) { this.countries$.next(changes.countries.currentValue); } if (changes.excludedCountries?.currentValue) { this.excludedCountries$.next(changes.excludedCountries.currentValue); } if(changes.language?.currentValue) { let lastValue = this._value; this.filterString = ""; this.inputChanged(""); this._setValue(null); this.onCountrySelected.emit(null); this._loadCountriesFromDb(lastValue?.alpha2Code); } } onBlur() { if (!this.inputElement.value && this.nullable && this.statesAutocompleteRef.panel) { this._setValue(null); this.onCountrySelected.emit(null); } } onOptionsSelected($event: MatAutocompleteSelectedEvent) { const value = this.countries.find( (country) => country.name === $event.option.value ); this._setValue(value); this.onCountrySelected.emit(value); } writeValue(obj: any): void { if (obj) { this.value = obj; } } registerOnChange(fn: any): void { this.propagateChange = fn; } registerOnTouched(fn: any): void { // throw new Error('Method not implemented.'); } setDisabledState?(isDisabled: boolean): void { this.disabled = isDisabled; } autocompleteScroll() { if (this.itemsLoadSize) { setTimeout(() => { if ( this.statesAutocompleteRef && this.autocompleteTrigger && this.statesAutocompleteRef.panel ) { fromEvent(this.statesAutocompleteRef.panel.nativeElement, 'scroll') .pipe(takeUntil(this.autocompleteTrigger.panelClosingActions)) .subscribe(() => { const scrollTop = this.statesAutocompleteRef.panel.nativeElement .scrollTop; const scrollHeight = this.statesAutocompleteRef.panel .nativeElement.scrollHeight; const elementHeight = this.statesAutocompleteRef.panel .nativeElement.clientHeight; const atBottom = scrollHeight === scrollTop + elementHeight; if (atBottom) { // fetch more data if not filtered if (this.filterString === '') { const fromIndex = this.filteredOptions.length; const toIndex: number = +this.filteredOptions.length + +this.itemsLoadSize; this.filteredOptions = [ ...this.filteredOptions, ...this.countries.slice(fromIndex, toIndex), ]; } } }); } }); } } inputChanged(value: string): void { this.modelChanged.next(value); } ngOnDestroy(): void { this.unsubscribe$.next(); this.unsubscribe$.complete(); } private _loadCountriesFromDb(alpha2Code?: string): void { this.loadingDB = true; this._importLang() .then((res) => { this.countries$.next(res); this._setValue(res.find(el => el.alpha2Code == alpha2Code)); }) .catch((err) => console.error('Error: ' + err)) .finally(() => this.loadingDB = false); } private _populateCountries(countries: Country[], excludedCountries: CountryOptionalMandatoryAlpha2Code[]): void { const excludeCountries = excludedCountries.map(c => c.alpha2Code); this.countries = countries.filter(c => !excludeCountries.includes(c.alpha2Code)); } private _setValue(value: Country | null): void { if (value && (!value.name || value.name === 'Unknown')) { // lookup name based on alpha2 values could be extended to lookup on other values too const matchingCountry = this.countries.find( (c) => c.alpha2Code === value.alpha2Code ); if (!!matchingCountry) { value = matchingCountry; } } this._value = value?.name ? value : null; this.propagateChange(this._value); } private _importLang(): Promise<any> { const lang = this.language || this.i18n; switch (lang) { case 'br': return import('./i18n/br').then(result => result.COUNTRIES_DB_BR).then(y => y); case 'by': return import('./i18n/by').then(result => result.COUNTRIES_DB_BY).then(y => y); case 'de': return import('./i18n/de').then(result => result.COUNTRIES_DB_DE).then(y => y); case 'es': return import('./i18n/es').then(result => result.COUNTRIES_DB_ES).then(y => y); case 'fr': return import('./i18n/fr').then(result => result.COUNTRIES_DB_FR).then(y => y); case 'hr': return import('./i18n/hr').then(result => result.COUNTRIES_DB_HR).then(y => y); case 'it': return import('./i18n/it').then(result => result.COUNTRIES_DB_IT).then(y => y); case 'nl': return import('./i18n/nl').then(result => result.COUNTRIES_DB_NL).then(y => y); case 'pt': return import('./i18n/pt').then(result => result.COUNTRIES_DB_PT).then(y => y); case 'ru': return import('./i18n/ru').then(result => result.COUNTRIES_DB_RU).then(y => y); case 'ua': return import('./i18n/ua').then(result => result.COUNTRIES_DB_UA).then(y => y); case 'gl': return import('./i18n/gl').then(result => result.COUNTRIES_DB_GL).then(y => y); case 'eu': return import('./i18n/eu').then(result => result.COUNTRIES_DB_EU).then(y => y); case 'ca': return import('./i18n/ca').then(result => result.COUNTRIES_DB_CA).then(y => y); default: return import('./i18n/en').then(result => result.COUNTRIES_DB).then(y => y); } } private _filter(value: string) { const filterValue = value.toLowerCase(); // if not filtered, fetch reduced array if (this.itemsLoadSize && filterValue === '') { this.filteredOptions = this.countries.slice(0, this.itemsLoadSize); } else { this.filteredOptions = this.countries.filter( (option: Country) => option.name.toLowerCase().includes(filterValue) || option.alpha2Code.toLowerCase().includes(filterValue) || option.alpha3Code.toLowerCase().includes(filterValue) ); } // options in the UI are not updated when this component is used within a host component that uses OnPush this.cdRef.markForCheck(); } }
the_stack
import { IChatJoinProperties, IUserInfo, IConversationEvent, IChatJoined, IAccountMinimal, IStoreRemoteUser } from "../bifrost/Events"; import { XmppJsInstance, XMPP_PROTOCOL } from "./XJSInstance"; import { IBifrostAccount, IChatJoinOptions } from "../bifrost/Account"; import { IBifrostInstance } from "../bifrost/Instance"; import { BifrostProtocol } from "../bifrost/Protocol"; import { Element, x } from "@xmpp/xml"; import { jid, JID } from "@xmpp/jid"; import { IBasicProtocolMessage } from "../MessageFormatter"; import { Metrics } from "../Metrics"; import { Logging } from "matrix-appservice-bridge"; import { v4 as uuid } from "uuid"; import { XHTMLIM } from "./XHTMLIM"; import { StzaMessage, StzaIqPing, StzaPresenceJoin, StzaPresencePart, StzaIqVcardRequest } from "./Stanzas"; const IDPREFIX = "pbridge"; const CONFLICT_SUFFIX = "[m]"; const LASTSTANZA_CHECK_MS = 2 * 60000; const LASTSTANZA_MAXDURATION = 10 * 60000; const log = Logging.get("XmppJsAccount"); export class XmppJsAccount implements IBifrostAccount { get waitingJoinRoomProps(): undefined { return undefined; } get name(): string { return this.remoteId; } get protocol(): BifrostProtocol { return XMPP_PROTOCOL; } public readonly waitingToJoin: Set<string>; public readonly isEnabled = true; public readonly connected = true; public readonly roomHandles: Map<string, string>; private readonly pmSessions: Set<string>; private lastStanzaTs: Map<string, number>; private checkInterval: NodeJS.Timeout; constructor( public readonly remoteId: string, public readonly resource: string, private xmpp: XmppJsInstance, public readonly mxId: string, ) { this.roomHandles = new Map(); this.waitingToJoin = new Set(); this.pmSessions = new Set(); this.lastStanzaTs = new Map(); this.checkInterval = setInterval(() => { this.lastStanzaTs.forEach((ts, roomName) => { if (Date.now() - ts > LASTSTANZA_MAXDURATION) { this.selfPing(roomName).then((isInRoom) => { if (isInRoom) { this.lastStanzaTs.set(roomName, Date.now()); return; } this.joinChat({ fullRoomName: roomName, handle: this.roomHandles.get(roomName)!, }); }); } }); }, LASTSTANZA_CHECK_MS); } public stop() { clearInterval(this.checkInterval); } public xmppBumpLastStanzaTs(roomName: string) { this.lastStanzaTs.set(roomName, Date.now()); } public createNew(password?: string) { throw Error("Xmpp.js doesn't support registering accounts"); } public setEnabled(enable: boolean) { throw Error("Xmpp.js doesn't allow you to enable or disable accounts"); } public sendIM(recipient: string, msg: IBasicProtocolMessage) { msg.id = msg.id || IDPREFIX + Date.now().toString(); // Check if the recipient is a gateway user, because if so we need to do some fancy masking. const res = this.xmpp.gateway ? this.xmpp.gateway.maskPMSenderRecipient(this.mxId, recipient) : null; let sender = `${this.remoteId}/${this.resource}`; if (res) { recipient = res.recipient; sender = res.sender; } log.debug(`IM ${sender} -> ${recipient}`); const message = new StzaMessage( sender, recipient, msg, "chat", ); if (!this.pmSessions.has(recipient)) { this.pmSessions.add(recipient); } this.xmpp.xmppAddSentMessage(msg.id); this.xmpp.xmppSend(message); Metrics.remoteCall("xmpp.message.chat"); } public sendChat(chatName: string, msg: IBasicProtocolMessage) { const id = msg.id || IDPREFIX + Date.now().toString(); if (msg.formatted && msg.formatted.length) { msg.formatted.forEach( (f) => { if (f.type === "html") { f.body = XHTMLIM.HTMLToXHTML(f.body); } }, ); } const xMsg = new StzaMessage(`${this.remoteId}/${this.resource}`, chatName, msg, "groupchat"); if (msg.id) { // Send RR for message if we have the matrixId. this.xmpp.emitReadReciepts(msg.id, chatName, true); } this.xmpp.xmppAddSentMessage(id); this.xmpp.xmppSend(xMsg); Metrics.remoteCall("xmpp.message.groupchat"); } public getBuddy(user: string): any|undefined { // TODO: Not implemented return; } public getJoinPropertyForRoom(roomName: string, key: string): string|undefined { // TODO: Not implemented return; } public setJoinPropertiesForRoom(roomName: string, props: IChatJoinProperties) { // TODO: Not implemented } public isInRoom(roomName: string): boolean { const handle = this.roomHandles.get(roomName); if (!handle) { return false; } const res = this.xmpp.presenceCache.getStatus(roomName + "/" + handle); log.debug("isInRoom: Got presence for user:", res, this.remoteId); if (!res) { return false; } return res.online; } public async selfPing(to: string): Promise<boolean> { const id = uuid(); log.debug(`Self-pinging ${to}`); const pingStanza = new StzaIqPing( `${this.remoteId}/${this.resource}`, to, id, "get", ); Metrics.remoteCall("xmpp.iq.ping"); try { await this.xmpp.sendIq(pingStanza); return true; } catch (ex) { return false; } } public reconnectToRooms() { log.info("Recovering rooms for", this.remoteId); this.roomHandles.forEach(async (handle, fullRoomName) => { try { log.debug("Rejoining", fullRoomName); await this.joinChat({ handle, fullRoomName, }); } catch (ex) { log.warn(`Failed to rejoin ${fullRoomName}`, ex); } }); } public async rejoinChat(fullRoomName: string) { log.info(`Rejoining ${fullRoomName} for ${this.remoteId}`); try { const handle = this.roomHandles.get(fullRoomName); if (!handle) { throw new Error("User has no assigned handle for this room, we cannot rejoin!"); } await this.joinChat({ handle, fullRoomName, }); } catch (ex) { log.warn(`Failed to rejoin ${fullRoomName}`, ex); } } public async joinChat( components: IChatJoinProperties, instance?: IBifrostInstance, timeout: number = 5000, setWaiting: boolean = true) : Promise<IConversationEvent|void> { if (!components.fullRoomName && (!components.room || !components.server)) { throw Error("Missing fullRoomName OR room|server"); } if (!components.handle) { throw Error("Missing handle"); } const roomName = components.fullRoomName || `${components.room}@${components.server}`; const to = `${roomName}/${components.handle}`; log.debug(`joinChat:`, this.remoteId, components); if (this.isInRoom(roomName)) { log.debug("Didn't join, already joined"); return { eventName: "already-joined", account: { username: this.remoteId, protocol_id: XMPP_PROTOCOL.id, } as IAccountMinimal, conv: { name: roomName, }, }; } if (await this.selfPing(to)) { log.debug("Didn't join, self ping says we are joined"); this.roomHandles.set(roomName, components.handle); return { eventName: "already-joined", account: { username: this.remoteId, protocol_id: XMPP_PROTOCOL.id, } as IAccountMinimal, conv: { name: roomName, }, }; } const from = `${this.remoteId}/${this.resource}`; log.info(`Joining to=${to} from=${from}`); const message = new StzaPresenceJoin( from, to, ); this.roomHandles.set(roomName, components.handle); if (setWaiting) { this.waitingToJoin.add(roomName); } let p: Promise<IChatJoined>|undefined; if (instance) { p = new Promise((resolve, reject) => { const timer = setTimeout(reject, timeout); const cb = (data: IChatJoined) => { if (data.conv.name === roomName) { this.waitingToJoin.delete(roomName); log.info(`Got ack for join ${roomName}`); clearTimeout(timer); this.xmpp.removeListener("chat-joined", cb); resolve(data); } }; this.xmpp.on("chat-joined", cb); }); } // To catch out races, we will emit this first. this.xmpp.emit("store-remote-user", { mxId: this.mxId, remoteId: to, protocol_id: XMPP_PROTOCOL.id, } as IStoreRemoteUser); await this.xmpp.xmppSend(message); Metrics.remoteCall("xmpp.presence.join"); return p; } public async xmppRetryJoin(from: JID) { log.info("Retrying join for ", from.toString()); if (from.resource.endsWith(CONFLICT_SUFFIX)) { // Kick from the room. throw new Error(`A user with the prefix '${CONFLICT_SUFFIX}' already exists, cannot join to room.`); } return this.joinChat({ room: from.local, server: from.domain, handle: `${from.resource}${CONFLICT_SUFFIX}`, }); } public async rejectChat(components: IChatJoinProperties) { /** This also handles leaving */ const room = `${components.room}@${components.server}`; components.handle = this.roomHandles.get(room)!; log.info(`${this.remoteId} (${components.handle}) is leaving ${room}`); await this.xmpp.xmppSend(new StzaPresencePart( `${this.remoteId}/${this.resource}`, `${components.room}@${components.server}/${components.handle}`, )); this.roomHandles.delete(room); Metrics.remoteCall("xmpp.presence.left"); } public getConversation(name: string): any { throw Error("getConversation not implemented"); } public getChatParamsForProtocol(): IChatJoinOptions[] { return [ { identifier: "server", label: "server", required: true, }, { identifier: "room", label: "room", required: true, }, { identifier: "handle", label: "handle", required: false, }, ]; } public async getUserInfo(who: string): Promise<IUserInfo> { const j = jid(who); const status = this.xmpp.presenceCache.getStatus(who); const ui: IUserInfo = { Nickname: j.resource || j.local, eventName: "meh", who, account: { protocol_id: this.protocol.id, username: this.remoteId, }, }; if (status && status.photoId) { ui.Avatar = status.photoId; } return ui; } public async getAvatarBuffer(iconPath: string, senderId: string): Promise<{type: string, data: Buffer}> { log.info(`Fetching avatar for ${senderId} (hash: ${iconPath})`); const vCard = await this.xmpp.getVCard(senderId); const photo = vCard.getChild("PHOTO"); if (!photo) { throw Error("No PHOTO in vCard given"); } return { data: Buffer.from( photo.getChildText("BINVAL")!, "base64", ), type: photo!.getChildText("TYPE") || "image/jpeg", }; } public setStatus() { // No-op return; } public sendIMTyping() { // No-op return; } }
the_stack
import * as fs from 'fs'; import * as path from 'path'; import sade from 'sade'; import colors from 'kleur'; import { elapsed, repeat, left_pad, format_milliseconds } from './utils'; import { InvalidEvent, ErrorEvent, FatalEvent, BuildEvent, ReadyEvent } from './interfaces'; const debug = require('debug')('ssg:cli'); type TODO_ANY = any; const prog = sade('ssg').version(0.01); if (process.argv[2] === 'start') { // remove this in a future version console.error(colors.bold().red(`'sapper start' has been removed`)); console.error(`Use 'node [build_dir]' instead`); process.exit(1); } const start = Date.now(); prog .command('eject') .describe('Copy out fallback files') .action(async () => { const { ejectCommand } = await import('./eject'); await ejectCommand(); }); prog .command('dev') .describe('Start a development server') .option('-p, --port', 'Specify a port') .option('-o, --open', 'Open a browser window') .option('--dev-port', 'Specify a port for development server') .option('--hot', 'Use hot module replacement (requires webpack)', true) .option('--live', 'Reload on changes if not using --hot', true) .option('--bundler', 'Specify a bundler (rollup or webpack)') .option('--cwd', 'Current working directory', '.') .option('--src', 'Source directory', 'src') .option('--routes', 'Routes directory', 'src/routes') .option('--static', 'Static files directory', 'static') .option( '--output', 'Sapper intermediate file output directory', 'node_modules/@sapper' ) .option('--build-dir', 'Development build directory', '__sapper__/dev') .option('--ext', 'Custom Route Extension', '.svelte .svexy .html') .option('--ssgConfig', 'SSG config file', 'ssg.config.js') .action( async (opts: { port: number; open: boolean; 'dev-port': number; live: boolean; hot: boolean; bundler?: 'rollup' | 'webpack'; cwd: string; src: string; routes: string; static: string; output: string; 'build-dir': string; ext: string; ssgConfig: string; }) => { // @ts-ignore const { dev } = await import('@ssgjs/sapper/api'); try { const watcher = dev({ cwd: opts.cwd, src: opts.src, routes: opts.routes, static: opts.static, output: opts.output, dest: opts['build-dir'], port: opts.port, 'dev-port': opts['dev-port'], live: opts.live, hot: opts.hot, bundler: opts.bundler, ext: opts.ext }); let first = true; /** * * SSG SECTION * * verify ssg config exists * */ const { getSSGDataOnce, watchSSGFiles, readSSGConfig } = await import( './cli-ssg' ); let ssgConfigPath = opts.ssgConfig || 'ssg.config.js'; // warning: opts.ssgConfig doesnt work for the readConfig seciton yet // TODO! debug('reading ssg config'); const ssgConfig = readSSGConfig(ssgConfigPath); debug('getting SSG data Index'); await getSSGDataOnce(ssgConfig, path.resolve(opts['build-dir'], '../')); debug('getting watching SSG data files...'); // actually do stuff with it watchSSGFiles(watcher, ssgConfig); /** * * END SSG SECTION * * */ watcher.on('stdout', (data: TODO_ANY) => { process.stdout.write(data); }); watcher.on('stderr', (data: TODO_ANY) => { process.stderr.write(data); }); watcher.on('ready', async (event: ReadyEvent) => { if (first) { console.log( colors .bold() .cyan(`> Listening on http://localhost:${event.port}`) ); if (opts.open) { const { exec } = await import('child_process'); exec(`open http://localhost:${event.port}`); } first = false; } }); watcher.on('invalid', (event: InvalidEvent) => { event.changed = event.changed.filter(Boolean); if (event.changed.length < 1) { // console.log('SSGDEBUG invalidevent', event) return; } const changed = event.changed .map((filename: string) => path.relative(process.cwd(), filename)) .join(', '); console.log( `\n${colors.bold().cyan(changed)} changed. rebuilding...` ); }); watcher.on('error', (event: ErrorEvent) => { const { type, error } = event; console.log(colors.bold().red(`✗ ${type}`)); if (error.loc && error.loc.file) { console.log( colors.bold( `${path.relative(process.cwd(), error.loc.file)} (${ error.loc.line }:${error.loc.column})` ) ); } console.log(colors.red(event.error.message)); if (error.frame) console.log(error.frame); }); watcher.on('fatal', (event: FatalEvent) => { console.log(colors.bold().red(`> ${event.message}`)); if (event.log) console.log(event.log); }); watcher.on('build', (event: BuildEvent) => { if (event.errors.length) { console.log(colors.bold().red(`✗ ${event.type}`)); event.errors .filter((e: TODO_ANY) => !e.duplicate) .forEach((error: TODO_ANY) => { if (error.file) console.log(colors.bold(error.file)); console.log(error.message); }); const hidden = event.errors.filter((e: TODO_ANY) => e.duplicate) .length; if (hidden > 0) { console.log( `${hidden} duplicate ${ hidden === 1 ? 'error' : 'errors' } hidden\n` ); } } else if (event.warnings.length) { console.log(colors.bold().yellow(`• ${event.type}`)); event.warnings .filter((e) => !e.duplicate) .forEach((warning: TODO_ANY) => { if (warning.file) console.log(colors.bold(warning.file)); console.log(warning.message); }); const hidden = event.warnings.filter((e: TODO_ANY) => e.duplicate) .length; if (hidden > 0) { console.log( `${hidden} duplicate ${ hidden === 1 ? 'warning' : 'warnings' } hidden\n` ); } } else { console.log( `${colors.bold().green(`✔ ${event.type}`)} ${colors.gray( `(${format_milliseconds(event.duration)})` )}` ); } }); } catch (err) { console.log(colors.bold().red(`> ${err.message}`)); console.log(colors.gray(err.stack)); process.exit(1); } } ); prog .command('build [dest]') .describe('Create a production-ready version of your app') .option('-p, --port', 'Default of process.env.PORT', '3000') .option('--bundler', 'Specify a bundler (rollup or webpack, blank for auto)') .option('--legacy', 'Create separate legacy build') .option('--cwd', 'Current working directory', '.') .option('--src', 'Source directory', 'src') .option('--routes', 'Routes directory', 'src/routes') .option( '--output', 'Sapper intermediate file output directory', 'node_modules/@sapper' ) .option( '--ext', 'Custom page route extensions (space separated)', '.svelte .svexy .html' ) .example(`build custom-dir -p 4567`) .action( async ( dest: string = '__sapper__/build', opts: { port: string; legacy: boolean; bundler?: 'rollup' | 'webpack'; cwd: string; src: string; routes: string; output: string; ext: string; } ) => { console.log(`> Building...`); try { await _build( opts.bundler, opts.legacy, opts.cwd, opts.src, opts.routes, opts.output, dest, opts.ext ); const launcher = path.resolve(dest, 'index.js'); fs.writeFileSync( launcher, ` // generated by sapper build at ${new Date().toISOString()} process.env.NODE_ENV = process.env.NODE_ENV || 'production'; process.env.PORT = process.env.PORT || ${opts.port || 3000}; console.log('Starting server on port ' + process.env.PORT); require('./server/server.js'); ` .replace(/^\t+/gm, '') .trim() ); console.error( `\n> Finished in ${elapsed(start)}. Type ${colors .bold() .cyan(`node ${dest}`)} to run the app.` ); } catch (err) { console.log(`${colors.bold().red(`> ${err.message}`)}`); console.log(colors.gray(err.stack)); process.exit(1); } } ); prog .command('export [dest]') .describe('Export your app as static files (if possible)') .option('--build', '(Re)build app before exporting', true) .option('--basepath', 'Specify a base path') .option('--host', 'Host header to use when crawling site') .option('--concurrent', 'Concurrent requests', 8) .option( '--timeout', 'Milliseconds to wait for a page (--no-timeout to disable)', 5000 ) .option('--legacy', 'Create separate legacy build') .option('--bundler', 'Specify a bundler (rollup or webpack, blank for auto)') .option('--cwd', 'Current working directory', '.') .option('--src', 'Source directory', 'src') .option('--routes', 'Routes directory', 'src/routes') .option('--static', 'Static files directory', 'static') .option( '--output', 'Sapper intermediate file output directory', 'node_modules/@sapper' ) .option('--build-dir', 'Intermediate build directory', '__sapper__/build') .option( '--ext', 'Custom page route extensions (space separated)', '.svelte .svexy .html' ) .option('--entry', 'Custom entry points (space separated)', '/') .option('--ssgConfig', 'path to your SSG config file', 'ssg.config.js') .action( async ( dest: string = '__sapper__/export', opts: { build: boolean; legacy: boolean; bundler?: 'rollup' | 'webpack'; basepath?: string; host?: string; concurrent: number; timeout: number | false; cwd: string; src: string; routes: string; static: string; output: string; 'build-dir': string; ext: string; entry: string; ssgConfig: string; // swyx } ) => { try { if (opts.build) { console.log(`> Building...`); await _build( opts.bundler, opts.legacy, opts.cwd, opts.src, opts.routes, opts.output, opts['build-dir'], opts.ext ); console.error(`\n> Built in ${elapsed(start)}`); } // @ts-ignore const { export: _export } = await import('@ssgjs/sapper/api'); const { default: pb } = await import('pretty-bytes'); /** * * SSG SECTION * * verify ssg config exists * */ debug('reading ssg config'); const { getSSGDataOnce, readSSGConfig } = await import('./cli-ssg'); let ssgConfigPath = opts.ssgConfig || 'ssg.config.js'; // warning: opts.ssgConfig doesnt work for the readConfig seciton yet // TODO! const ssgConfig = readSSGConfig(ssgConfigPath); let mainIndex; debug('getting SSG data Index'); mainIndex = await getSSGDataOnce( ssgConfig, path.resolve(opts['build-dir'], '../') ); // if (ssgConfig) { // // actually do stuff with it // } /** * * END SSG SECTION * * */ await _export({ cwd: opts.cwd, static: opts.static, build_dir: opts['build-dir'], export_dir: dest, basepath: opts.basepath, host_header: opts.host, timeout: opts.timeout, concurrent: opts.concurrent, entry: opts.entry, oninfo: (event: TODO_ANY) => { console.log(colors.bold().cyan(`> ${event.message}`)); }, onfile: (event: TODO_ANY) => { const size_color = event.size > 150000 ? colors.bold().red : event.size > 50000 ? colors.bold().yellow : colors.bold().gray; const size_label = size_color(left_pad(pb(event.size), 10)); const file_label = event.status === 200 ? event.file : colors .bold() [event.status >= 400 ? 'red' : 'yellow']( `(${event.status}) ${event.file}` ); console.log(`${size_label} ${file_label}`); } }); /** * * SSG SECTION * * verify ssg config exists * */ if (ssgConfig && ssgConfig.postExport && mainIndex) { debug('running ssg postExport'); await ssgConfig.postExport(mainIndex); } /** * * END SSG SECTION * * */ console.error( `\n> Finished in ${elapsed(start)}. Type ${colors .bold() .cyan(`npx serve ${dest}`)} to run the app.` ); } catch (err) { console.error(colors.bold().red(`> ${err.message}`)); process.exit(1); } } ); prog.parse(process.argv, { unknown: (arg: string) => `Unknown option: ${arg}` }); async function _build( bundler: 'rollup' | 'webpack' | undefined, legacy: boolean, cwd: string, src: string, routes: string, output: string, dest: string, ext: string ) { // @ts-ignore const { build } = await import('@ssgjs/sapper/api'); await build({ bundler, legacy, cwd, src, routes, dest, ext, output, oncompile: (event: TODO_ANY) => { let banner = `built ${event.type}`; let c = (txt: string) => colors.cyan(txt); const { warnings } = event.result; if (warnings.length > 0) { banner += ` with ${warnings.length} ${ warnings.length === 1 ? 'warning' : 'warnings' }`; c = (txt: string) => colors.cyan(txt); } console.log(); console.log(c(`┌─${repeat('─', banner.length)}─┐`)); console.log(c(`│ ${colors.bold(banner)} │`)); console.log(c(`└─${repeat('─', banner.length)}─┘`)); console.log(event.result.print()); } }); }
the_stack
import meiosis, { ActionConstructor, App, FunctionPatch, ImmerPatch, LocalPatch, Local, MergerinoApp, MergerinoMeiosisOne, MergerinoPatch, Stream } from "../../source/dist"; import flyd from "flyd"; import merge from "mergerino"; import produce from "immer"; import { html, render as litHtmlRender, TemplateResult } from "lit-html"; import m from "mithril"; import MStream from "mithril/stream"; import { h, render as preactRender, VNode } from "preact"; import { useState } from "preact/hooks"; import React from "react"; import ReactDOM from "react-dom"; const { stream, scan } = meiosis.simpleStream; // simple-stream (() => { const s1 = stream<number>(0); const s2 = scan<number, number>((x, y) => x + y, 0, s1); s2.map(x => x); })(); // common code type Sky = "SUNNY" | "CLOUDY" | "MIX"; interface Conditions { precipitations: boolean; sky: Sky; } interface ConditionsActions<P1, P2> { togglePrecipitations: (local: LocalPatch<P1, P2>, value: boolean) => void; changeSky: (local: LocalPatch<P1, P2>, value: Sky) => void; } interface ConditionsComponent<P1, P2> { initial: Conditions; Actions: ActionConstructor<Conditions, P1, ConditionsActions<P1, P2>>; } type TemperatureUnits = "C" | "F"; interface Temperature { label: string; value: number; units: TemperatureUnits; } interface TemperatureActions<P1, P2> { increment: (local: LocalPatch<P1, P2>, amount: number) => void; changeUnits: (local: LocalPatch<P1, P2>) => void; } interface TemperatureComponent<P1, P2> { Initial: (label: string) => Temperature; Actions: ActionConstructor<Temperature, P1, TemperatureActions<P1, P2>>; } interface State { conditions: Conditions; temperature: { air: Temperature; water: Temperature; }; } const initialConditions: Conditions = { precipitations: false, sky: "SUNNY" }; const convert = (value: number, to: TemperatureUnits): number => { return Math.round(to === "C" ? ((value - 32) / 9) * 5 : (value * 9) / 5 + 32); }; const InitialTemperature = (label: string): Temperature => ({ label, value: 22, units: "C" }); // lit-html + functionPatches + simple-stream (() => { type Patch = FunctionPatch<State>; type ConditionsPatch = FunctionPatch<Conditions>; type TemperaturePatch = FunctionPatch<Temperature>; type Update = Stream<Patch>; type ConditionsLocal = Local<State, Patch, Conditions, ConditionsPatch>; type TemperatureLocal = Local<State, Patch, Temperature, TemperaturePatch>; interface Actions { conditions: ConditionsActions<Patch, ConditionsPatch>; temperature: TemperatureActions<Patch, TemperaturePatch>; } interface Attrs { state: State; actions: Actions; } interface SkyOptionAttrs extends Attrs { local: ConditionsLocal; value: string; label: string; } interface ConditionsAttrs extends Attrs { local: ConditionsLocal; } interface TemperatureAttrs extends Attrs { local: TemperatureLocal; } const nest = meiosis.functionPatches.nest; const conditions: ConditionsComponent<Patch, ConditionsPatch> = { initial: initialConditions, Actions: (update: Update) => ({ togglePrecipitations: (local, value) => { update(local.patch(state => ({ ...state, precipitations: value }))); }, changeSky: (local, value) => { update(local.patch(state => ({ ...state, sky: value }))); } }) }; const skyOption: (attrs: SkyOptionAttrs) => TemplateResult = ({ state, local, actions, value, label }) => html` <label> <input type="radio" value=${value} .checked=${local.get(state).sky === value} @change=${evt => actions.conditions.changeSky(local, evt.target.value)} /> ${label} </label> `; const Conditions: (attrs: ConditionsAttrs) => TemplateResult = ({ state, local, actions }) => html` <div> <label> <input type="checkbox" .checked=${local.get(state).precipitations} @change=${evt => actions.conditions.togglePrecipitations(local, evt.target.checked)} /> Precipitations </label> <div> ${skyOption({ state, local, actions, value: "SUNNY", label: "Sunny" })} ${skyOption({ state, local, actions, value: "CLOUDY", label: "Cloudy" })} ${skyOption({ state, local, actions, value: "MIX", label: "Mix of sun/clouds" })} </div> </div> `; const temperature: TemperatureComponent<Patch, TemperaturePatch> = { Initial: InitialTemperature, Actions: update => ({ increment: (local, amount) => { update(local.patch(state => ({ ...state, value: state.value + amount }))); }, changeUnits: local => { update( local.patch(state => { const value = state.value; const newUnits = state.units === "C" ? "F" : "C"; const newValue = convert(value, newUnits); return { ...state, value: newValue, units: newUnits }; }) ); } }) }; const Temperature: (attrs: TemperatureAttrs) => TemplateResult = ({ state, local, actions }) => html` <div> ${local.get(state).label} Temperature: ${local.get(state).value}&deg;${local.get(state).units} <div> <button @click=${() => actions.temperature.increment(local, 1)}>Increment</button> <button @click=${() => actions.temperature.increment(local, -1)}>Decrement</button> </div> <div> <button @click=${() => actions.temperature.changeUnits(local)}>Change Units</button> </div> </div> `; const app: App<State, Patch, Actions> = { initial: { conditions: conditions.initial, temperature: { air: temperature.Initial("Air"), water: temperature.Initial("Water") } }, Actions: update => ({ conditions: conditions.Actions(update), temperature: temperature.Actions(update) }) }; const App: (attrs: Attrs) => TemplateResult = ({ state, actions }) => html` <div style="display: grid; grid-template-columns: 1fr 1fr"> <div> ${Conditions({ state, local: nest("conditions"), actions })} ${Temperature({ state, local: nest(["temperature", "air"]), actions })} ${Temperature({ state, local: nest(["temperature", "water"]), actions })} </div> <pre style="margin: 0">${JSON.stringify(state, null, 4)}</pre> </div> `; const { states, actions } = meiosis.functionPatches.setup<State, Actions>({ stream: meiosis.simpleStream, app }); const element = document.getElementById("litHtmlApp") as HTMLElement; states.map(state => litHtmlRender(App({ state, actions }), element)); })(); // mithril + mergerino + mithril-stream (() => { type Patch = MergerinoPatch<State>; type ConditionsPatch = MergerinoPatch<Conditions>; type TemperaturePatch = MergerinoPatch<Temperature>; type Update = Stream<Patch>; type ConditionsLocal = Local<State, Patch, Conditions, ConditionsPatch>; type TemperatureLocal = Local<State, Patch, Temperature, TemperaturePatch>; interface Actions { conditions: ConditionsActions<Patch, ConditionsPatch>; temperature: TemperatureActions<Patch, TemperaturePatch>; } interface Attrs { state: State; actions: Actions; } interface SkyOptionAttrs extends Attrs { local: ConditionsLocal; value: string; label: string; } interface ConditionsAttrs extends Attrs { local: ConditionsLocal; } interface TemperatureAttrs extends Attrs { local: TemperatureLocal; } const nest = meiosis.mergerino.nest; const conditions: ConditionsComponent<Patch, ConditionsPatch> = { initial: initialConditions, Actions: (update: Update) => ({ togglePrecipitations: (local, value) => { update(local.patch({ precipitations: value })); }, changeSky: (local, value) => { update(local.patch({ sky: value })); } }) }; const SkyOption: m.Component<SkyOptionAttrs> = { view: ({ attrs: { state, local, actions, value, label } }) => m( "label", m("input", { type: "radio", value, checked: local.get(state).sky === value, // FIXME: evt type onchange: evt => actions.conditions.changeSky(local, evt.target.value) }), label ) }; const Conditions: m.Component<ConditionsAttrs> = { view: ({ attrs: { state, local, actions } }) => m( "div", m( "label", m("input", { type: "checkbox", checked: local.get(state).precipitations, onchange: evt => actions.conditions.togglePrecipitations(local, evt.target.checked) }), "Precipitations" ), m( "div", m(SkyOption, { state, local, actions, value: "SUNNY", label: "Sunny" }), m(SkyOption, { state, local, actions, value: "CLOUDY", label: "Cloudy" }), m(SkyOption, { state, local, actions, value: "MIX", label: "Mix of sun/clouds" }) ) ) }; const temperature: TemperatureComponent<Patch, TemperaturePatch> = { Initial: InitialTemperature, Actions: update => ({ increment: (local, amount) => { update(local.patch({ value: x => x + amount })); }, changeUnits: local => { update( local.patch(state => { const value = state.value; const newUnits = state.units === "C" ? "F" : "C"; const newValue = convert(value, newUnits); return { ...state, value: newValue, units: newUnits }; }) ); } }) }; const Temperature: m.Component<TemperatureAttrs> = { view: ({ attrs: { state, local, actions } }) => m( "div", local.get(state).label, " Temperature: ", local.get(state).value, m.trust("&deg;"), local.get(state).units, m( "div", m("button", { onclick: () => actions.temperature.increment(local, 1) }, "Increment"), m("button", { onclick: () => actions.temperature.increment(local, -1) }, "Decrement") ), m( "div", m("button", { onclick: () => actions.temperature.changeUnits(local) }, "Change Units") ) ) }; const app: MergerinoApp<State, Actions> = { initial: { conditions: conditions.initial, temperature: { air: temperature.Initial("Air"), water: temperature.Initial("Water") } }, Actions: update => ({ conditions: conditions.Actions(update), temperature: temperature.Actions(update) }) }; const App: m.Component<Attrs> = { view: ({ attrs: { state, actions } }) => m( "div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr" } }, m( "div", m(Conditions, { state, local: nest("conditions") as ConditionsLocal, actions }), m(Temperature, { state, local: nest(["temperature", "air"]) as TemperatureLocal, actions }), m(Temperature, { state, local: nest(["temperature", "water"]) as TemperatureLocal, actions }) ), m("pre", { style: { margin: "0" } }, JSON.stringify(state, null, 4)) ) }; const stream = { stream: (value?: any) => MStream(value), scan: (acc: any, init: any, stream: any) => MStream.scan(acc, init, stream) }; const { states, actions } = meiosis.mergerino.setup<State, Actions>({ stream, merge, app }); m.mount(document.getElementById("mithrilApp") as HTMLElement, { view: () => m(App, { state: states(), actions }) }); states.map(() => m.redraw()); })(); // preact + mergerino + simple-stream (() => { type Patch = MergerinoPatch<State>; type ConditionsPatch = MergerinoPatch<Conditions>; type TemperaturePatch = MergerinoPatch<Temperature>; type Update = Stream<Patch>; type ConditionsLocal = Local<State, Patch, Conditions, ConditionsPatch>; type TemperatureLocal = Local<State, Patch, Temperature, TemperaturePatch>; interface Actions { conditions: ConditionsActions<Patch, ConditionsPatch>; temperature: TemperatureActions<Patch, TemperaturePatch>; } interface Attrs { state: State; actions: Actions; } interface SkyOptionAttrs extends Attrs { local: ConditionsLocal; value: string; label: string; } interface ConditionsAttrs extends Attrs { local: ConditionsLocal; } interface TemperatureAttrs extends Attrs { local: TemperatureLocal; } const nest = meiosis.mergerino.nest; const conditions: ConditionsComponent<Patch, ConditionsPatch> = { initial: initialConditions, Actions: (update: Update) => ({ togglePrecipitations: (local, value) => { update(local.patch({ precipitations: value })); }, changeSky: (local, value) => { update(local.patch({ sky: value })); } }) }; // Normally we could use JSX with the Preact.h pragma, but since we already have React in this // file, we'll use h here. const SkyOption: (attrs: SkyOptionAttrs) => VNode = ({ state, local, actions, value, label }) => h( "label", {}, h("input", { type: "radio", value, checked: local.get(state).sky === value, onchange: evt => actions.conditions.changeSky(local, evt.target.value) }), label ); const Conditions: (attrs: ConditionsAttrs) => VNode = ({ state, local, actions }) => h( "div", {}, h( "label", {}, h("input", { type: "checkbox", checked: local.get(state).precipitations, onchange: evt => actions.conditions.togglePrecipitations(local, evt.target.checked) }), "Precipitations" ), h( "div", {}, h(SkyOption, { state, local, actions, value: "SUNNY", label: "Sunny" }), h(SkyOption, { state, local, actions, value: "CLOUDY", label: "Cloudy" }), h(SkyOption, { state, local, actions, value: "MIX", label: "Mix of sun/clouds" }) ) ); const temperature: TemperatureComponent<Patch, TemperaturePatch> = { Initial: InitialTemperature, Actions: update => ({ increment: (local, amount) => { update(local.patch({ value: x => x + amount })); }, changeUnits: local => { update( local.patch(state => { const value = state.value; const newUnits = state.units === "C" ? "F" : "C"; const newValue = convert(value, newUnits); return { ...state, value: newValue, units: newUnits }; }) ); } }) }; const Temperature: (attrs: TemperatureAttrs) => VNode = ({ state, local, actions }) => h( "div", {}, local.get(state).label, " Temperature: ", local.get(state).value, h("span", { dangerouslySetInnerHTML: { __html: "&deg;" } }), local.get(state).units, h( "div", {}, h("button", { onclick: () => actions.temperature.increment(local, 1) }, "Increment"), h("button", { onclick: () => actions.temperature.increment(local, -1) }, "Decrement") ), h( "div", {}, h("button", { onclick: () => actions.temperature.changeUnits(local) }, "Change Units") ) ); const app: MergerinoApp<State, Actions> = { initial: { conditions: conditions.initial, temperature: { air: temperature.Initial("Air"), water: temperature.Initial("Water") } }, Actions: update => ({ conditions: conditions.Actions(update), temperature: temperature.Actions(update) }) }; const Root: (attrs: Attrs) => VNode = ({ state, actions }) => h( "div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr" } }, h( "div", {}, h(Conditions, { state, local: nest("conditions") as ConditionsLocal, actions }), h(Temperature, { state, local: nest(["temperature", "air"]) as TemperatureLocal, actions }), h(Temperature, { state, local: nest(["temperature", "water"]) as TemperatureLocal, actions }) ), h("pre", { style: { margin: "0" } }, JSON.stringify(state, null, 4)) ); const App = meiosis.preact.setup<State, Attrs, VNode>({ h, useState, Root }); const { states, update, actions } = meiosis.mergerino.setup<State, Actions>({ stream: meiosis.simpleStream, merge, app }); // Just testing TypeScript support here. const _test = meiosis.simpleStream.stream<number>(); const _init = _test(); _test(5); update({ temperature: { air: { value: 21 } } }); update({ temperature: { air: { value: x => x + 1 } } }); update({ temperature: { air: { value: () => 21 } } }); const element = document.getElementById("preactApp") as HTMLElement; preactRender(h(App, { states, actions }), element); })(); // react + immer + flyd (() => { type Patch = ImmerPatch<State>; type ConditionsPatch = ImmerPatch<Conditions>; type TemperaturePatch = ImmerPatch<Temperature>; type Update = Stream<Patch>; type ConditionsLocal = Local<State, Patch, Conditions, ConditionsPatch>; type TemperatureLocal = Local<State, Patch, Temperature, TemperaturePatch>; interface Actions { conditions: ConditionsActions<Patch, ConditionsPatch>; temperature: TemperatureActions<Patch, TemperaturePatch>; } interface Attrs { state: State; actions: Actions; } interface SkyOptionAttrs extends Attrs { local: ConditionsLocal; value: string; label: string; } interface ConditionsAttrs extends Attrs { local: ConditionsLocal; } interface TemperatureAttrs extends Attrs { local: TemperatureLocal; } const nest = meiosis.immer.nest(produce); const conditions: ConditionsComponent<Patch, ConditionsPatch> = { initial: initialConditions, Actions: (update: Update) => ({ togglePrecipitations: (local, value) => { update( local.patch(state => { state.precipitations = value; }) ); }, changeSky: (local, value) => { update( local.patch(state => { state.sky = value; }) ); } }) }; const SkyOption: (attrs: SkyOptionAttrs) => JSX.Element = ({ state, local, actions, value, label }) => ( <label> <input type="radio" value={value} checked={local.get(state).sky === value} onChange={evt => actions.conditions.changeSky(local, evt.target.value)} /> {label} </label> ); const Conditions: (attrs: ConditionsAttrs) => JSX.Element = ({ state, local, actions }) => ( <div> <label> <input type="checkbox" checked={local.get(state).precipitations} onChange={evt => actions.conditions.togglePrecipitations(local, evt.target.checked)} /> Precipitations </label> <div> <SkyOption state={state} local={local} actions={actions} value="SUNNY" label="Sunny" /> <SkyOption state={state} local={local} actions={actions} value="CLOUDY" label="Cloudy" /> <SkyOption state={state} local={local} actions={actions} value="MIX" label="Mix of sun/clouds" /> </div> </div> ); const temperature: TemperatureComponent<Patch, TemperaturePatch> = { Initial: InitialTemperature, Actions: update => ({ increment: (local, amount) => { update( local.patch(state => { state.value += amount; }) ); }, changeUnits: local => { update( local.patch(state => { const value = state.value; const newUnits = state.units === "C" ? "F" : "C"; const newValue = convert(value, newUnits); state.value = newValue; state.units = newUnits; }) ); } }) }; const Temperature: (attrs: TemperatureAttrs) => JSX.Element = ({ state, local, actions }) => ( <div> {local.get(state).label} Temperature: {local.get(state).value}&deg;{local.get(state).units} <div> <button onClick={() => actions.temperature.increment(local, 1)}>Increment</button> <button onClick={() => actions.temperature.increment(local, -1)}>Decrement</button> </div> <div> <button onClick={() => actions.temperature.changeUnits(local)}>Change Units</button> </div> </div> ); const app: App<State, Patch, Actions> = { initial: { conditions: conditions.initial, temperature: { air: temperature.Initial("Air"), water: temperature.Initial("Water") } }, Actions: update => ({ conditions: conditions.Actions(update), temperature: temperature.Actions(update) }) }; const Root: (attrs: Attrs) => JSX.Element = ({ state, actions }) => ( <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr" }}> <div> <Conditions state={state} local={nest("conditions") as ConditionsLocal} actions={actions} /> <Temperature state={state} local={nest(["temperature", "air"]) as TemperatureLocal} actions={actions} /> <Temperature state={state} local={nest(["temperature", "water"]) as TemperatureLocal} actions={actions} /> </div> <pre style={{ margin: "0" }}>{JSON.stringify(state, null, 4)}</pre> </div> ); const stream = { stream: (value?: any) => flyd.stream(value), scan: (acc: any, init: any, stream: any) => flyd.scan(acc, init, stream) }; const { states, actions } = meiosis.immer.setup<State, Actions>({ stream, produce: (s, p) => produce(s, p), app }); const App = meiosis.react.setup<State, Attrs, JSX.Element>({ React, Root }); const element = document.getElementById("reactApp"); ReactDOM.render(React.createElement(App, { states, actions }), element); })(); // MeiosisOne + mergerino + mithril + mithril-stream (() => { type Patch = MergerinoPatch<State>; type ConditionsPatch = MergerinoPatch<Conditions>; type TemperaturePatch = MergerinoPatch<Temperature>; type Update = Stream<Patch>; interface Actions { conditions: ConditionsActions<Patch, ConditionsPatch>; temperature: TemperatureActions<Patch, TemperaturePatch>; } interface Attrs { context: MergerinoMeiosisOne<State, Actions>; } interface SkyOptionAttrs { context: MergerinoMeiosisOne<Conditions, Actions>; value: string; label: string; } interface ConditionsAttrs { context: MergerinoMeiosisOne<Conditions, Actions>; } interface TemperatureAttrs { context: MergerinoMeiosisOne<Temperature, Actions>; } const conditions: ConditionsComponent<Patch, ConditionsPatch> = { initial: initialConditions, Actions: (update: Update) => ({ togglePrecipitations: (local, value) => { update(local.patch({ precipitations: value })); }, changeSky: (local, value) => { update(local.patch({ sky: value })); } }) }; const SkyOption: m.Component<SkyOptionAttrs> = { view: ({ attrs: { context, value, label } }) => m( "label", m("input", { type: "radio", value, checked: context.getState().sky === value, onchange: evt => context.actions.conditions.changeSky(evt.target.value) }), label ) }; const Conditions: m.Component<ConditionsAttrs> = { view: ({ attrs: { context } }) => m( "div", m( "label", m("input", { type: "checkbox", checked: context.getState().precipitations, onchange: evt => context.actions.conditions.togglePrecipitations(evt.target.checked) }), "Precipitations" ), m( "div", m(SkyOption, { context, value: "SUNNY", label: "Sunny" }), m(SkyOption, { context, value: "CLOUDY", label: "Cloudy" }), m(SkyOption, { context, value: "MIX", label: "Mix of sun/clouds" }) ) ) }; const temperature: TemperatureComponent<Patch, TemperaturePatch> = { Initial: InitialTemperature, Actions: update => ({ increment: (local, amount) => { update(local.patch({ value: x => x + amount })); }, changeUnits: local => { update( local.patch(state => { const value = state.value; const newUnits = state.units === "C" ? "F" : "C"; const newValue = convert(value, newUnits); return { ...state, value: newValue, units: newUnits }; }) ); } }) }; const Temperature: m.Component<TemperatureAttrs> = { view: ({ attrs: { context } }) => m( "div", context.getState().label, " Temperature: ", context.getState().value, m.trust("&deg;"), context.getState().units, m( "div", m("button", { onclick: () => context.actions.temperature.increment(1) }, "Increment"), m("button", { onclick: () => context.actions.temperature.increment(-1) }, "Decrement") ), m( "div", m("button", { onclick: () => context.actions.temperature.changeUnits() }, "Change Units") ) ) }; const app: App<State, Patch, Actions> = { initial: { conditions: conditions.initial, temperature: { air: temperature.Initial("Air"), water: temperature.Initial("Water") } }, Actions: update => ({ conditions: conditions.Actions(update), temperature: temperature.Actions(update) }) }; const App: m.Component<Attrs> = { view: ({ attrs: { context } }) => m( "div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr" } }, m( "div", m(Conditions, { context: context.nest("conditions") }), m(Temperature, { context: context.nest("temperature").nest("air") }), m(Temperature, { context: context.nest("temperature").nest("water") }) ), m("pre", { style: { margin: "0" } }, JSON.stringify(context.getState(), null, 4)) ) }; const stream = { stream: (value?: any) => MStream(value), scan: (acc: any, init: any, stream: any) => MStream.scan(acc, init, stream) }; const context = meiosis.mergerino.meiosisOne<State, Actions>({ stream, merge, app }); m.mount(document.getElementById("mergerinoMeiosisOneApp") as HTMLElement, { view: () => m(App, { context }) }); context.states.map(() => m.redraw()); })();
the_stack
import { BunyanProvider, Logger, LogLevel } from './BunyanProvider' import { DuplicateHandlerVersionError, MismatchedBlockHashError, MissingHandlerVersionError, } from './errors' import { Action, ActionHandler, ActionHandlerOptions, BlockInfo, CurriedEffectRun, DeferredEffects, Effect, EffectRunMode, EffectsInfo, HandlerInfo, HandlerVersion, IndexState, NextBlock, VersionedAction, } from './interfaces' import { QueryablePromise, makeQuerablePromise } from './makeQueryablePromise' /** * Takes `block`s output from implementations of `AbstractActionReader` and processes their actions through the * `Updater`s and `Effect`s of the current `HandlerVersion`. Pass an object exposing a persistence API as `state` to the * `handleWithState` method. Persist and retrieve information about the last block processed with `updateIndexState` and * `loadIndexState`. Implement `rollbackTo` to handle when a fork is encountered. * */ export abstract class AbstractActionHandler implements ActionHandler { protected lastProcessedBlockNumber: number = 0 protected lastProcessedBlockHash: string = '' protected lastIrreversibleBlockNumber: number = 0 protected handlerVersionName: string = 'v1' protected isReplay: boolean = false protected log: Logger protected effectRunMode: EffectRunMode protected initialized: boolean = false private deferredEffects: DeferredEffects = {} private handlerVersionMap: { [versionName: string]: HandlerVersion } = {} private runningEffects: Array<QueryablePromise<void>> = [] private effectErrors: string[] = [] private maxEffectErrors: number private validateBlocks: boolean /** * @param handlerVersions An array of `HandlerVersion`s that are to be used when processing blocks. The default * version name is `"v1"`. * * @param options */ constructor( handlerVersions: HandlerVersion[], options?: ActionHandlerOptions, ) { const optionsWithDefaults = { effectRunMode: EffectRunMode.All, logSource: 'AbstractActionHandler', logLevel: 'info' as LogLevel, maxEffectErrors: 100, validateBlocks: true, ...options, } this.initHandlerVersions(handlerVersions) this.effectRunMode = optionsWithDefaults.effectRunMode this.maxEffectErrors = optionsWithDefaults.maxEffectErrors this.log = BunyanProvider.getLogger(optionsWithDefaults) this.validateBlocks = optionsWithDefaults.validateBlocks } /** * Receive block, validate, and handle actions with updaters and effects */ public async handleBlock( nextBlock: NextBlock, isReplay: boolean, ): Promise<number | null> { const { block, blockMeta } = nextBlock const { blockInfo } = block const { isRollback, isEarliestBlock } = blockMeta if (!this.initialized) { this.log.info('Action Handler was not initialized before started, so it is being initialized now') await this.initialize() } await this.handleRollback(isRollback, blockInfo.blockNumber, isReplay, isEarliestBlock) await this.refreshIndexState() const nextBlockNeeded = this.lastProcessedBlockNumber + 1 // Just processed this block; skip if (blockInfo.blockNumber === this.lastProcessedBlockNumber && blockInfo.blockHash === this.lastProcessedBlockHash) { this.log.debug(`Block ${blockInfo.blockNumber} was just handled; skipping`) return null } // If it's the first block but we've already processed blocks, seek to next block if (isEarliestBlock && this.lastProcessedBlockHash) { return nextBlockNeeded } // Only check if this is the block we need if it's not the first block if (!isEarliestBlock && this.validateBlocks) { if (blockInfo.blockNumber !== nextBlockNeeded) { this.log.debug( `Got block ${blockInfo.blockNumber} but block ${nextBlockNeeded} is needed; ` + `requesting block ${nextBlockNeeded}` ) return nextBlockNeeded } // Block sequence consistency should be handled by the ActionReader instance if (blockInfo.previousBlockHash !== this.lastProcessedBlockHash) { throw new MismatchedBlockHashError( blockInfo.blockNumber, this.lastProcessedBlockHash, blockInfo.previousBlockHash ) } } const handleWithArgs: (state: any, context?: any) => Promise<void> = async (state: any, context: any = {}) => { await this.handleActions(state, context, nextBlock, isReplay) } await this.handleWithState(handleWithArgs) return null } /** * Information about the current state of the Action Handler */ public get info(): HandlerInfo { const effectInfo = this.checkRunningEffects() return { lastProcessedBlockNumber: this.lastProcessedBlockNumber, lastProcessedBlockHash: this.lastProcessedBlockHash, lastIrreversibleBlockNumber: this.lastIrreversibleBlockNumber, handlerVersionName: this.handlerVersionName, isReplay: this.isReplay, effectRunMode: this.effectRunMode, numberOfRunningEffects: effectInfo.numberOfRunningEffects, effectErrors: effectInfo.effectErrors, } } /** * Performs all required initialization for the handler. */ public async initialize(): Promise<void> { this.log.debug('Initializing Action Handler...') const setupStart = Date.now() await this.setup() const betweenSetupAndIndexState = Date.now() await this.refreshIndexState() this.initialized = true const setupTime = betweenSetupAndIndexState - setupStart const indexStateTime = Date.now() - betweenSetupAndIndexState const initializeTime = setupTime + indexStateTime this.log.debug( `Initialized Action Handler (${setupTime}ms setup + ${indexStateTime}ms index state = ${initializeTime}ms)` ) } /** * Updates the `lastProcessedBlockNumber` and `lastProcessedBlockHash` meta state, coinciding with the block * that has just been processed. These are the same values read by `updateIndexState()`. */ protected abstract async updateIndexState( state: any, nextBlock: NextBlock, isReplay: boolean, handlerVersionName: string, context?: any, ): Promise<void> /** * Returns a promise for the `lastProcessedBlockNumber` and `lastProcessedBlockHash` meta state, * coinciding with the block that has just been processed. * These are the same values written by `updateIndexState()`. * @returns A promise that resolves to an `IndexState` */ protected abstract async loadIndexState(): Promise<IndexState> /** * Must call the passed-in `handle` function within this method, passing in a state object that will be passed in to * the `state` parameter to all calls of `Updater.apply`. Optionally, pass in a `context` object as a second * parameter, which can be utilized to share state across `Updater.apply` and `Effect.run` calls on a per-block basis. */ protected abstract async handleWithState(handle: (state: any, context?: any) => void): Promise<void> /** * Idempotently performs any required setup. */ protected abstract async setup(): Promise<void> /** * This method is used when matching the types of incoming actions against the types the `Updater`s and `Effect`s are * subscribed to. When this returns true, their corresponding functions will run. * * By default, this method tests for direct equivalence between the incoming candidate type and the type that is * subscribed. Override this method to extend this functionality (e.g. wildcards). * * @param candidateType The incoming action's type * @param subscribedType The type the Updater of Effect is subscribed to * @param _payload The payload of the incoming Action. */ protected matchActionType(candidateType: string, subscribedType: string, _payload?: any): boolean { // tslint:disable-line return candidateType === subscribedType } /** * Process actions against deterministically accumulating `Updater` functions. Returns a promise of versioned actions * for consumption by `runEffects`, to make sure the correct effects are run on blocks that include a `HandlerVersion` * change. To change a `HandlerVersion`, have an `Updater` function return the `versionName` of the corresponding * `HandlerVersion` you want to change to. */ protected async applyUpdaters( state: any, nextBlock: NextBlock, context: any, isReplay: boolean, ): Promise<VersionedAction[]> { const versionedActions = [] as VersionedAction[] const { block: { actions, blockInfo } } = nextBlock for (const action of actions) { let updaterIndex = -1 for (const updater of this.handlerVersionMap[this.handlerVersionName].updaters) { updaterIndex += 1 if (this.matchActionType(action.type, updater.actionType, action.payload)) { const { payload } = action this.log.debug(`Applying updater for action type '${action.type}'...`) const updaterStart = Date.now() const newVersion = await updater.apply(state, payload, blockInfo, context) const updaterTime = Date.now() - updaterStart this.log.debug(`Applied updater for action type '${action.type}' (${updaterTime}ms)`) if (newVersion && !this.handlerVersionMap.hasOwnProperty(newVersion)) { this.warnHandlerVersionNonexistent(newVersion) } else if (newVersion) { this.log.info(`Updated Handler Version to '${newVersion}' (block ${blockInfo.blockNumber})`) this.warnSkippingUpdaters(updaterIndex, action.type) await this.loggedUpdateIndexState(state, nextBlock, isReplay, newVersion, context) this.handlerVersionName = newVersion break } } } versionedActions.push({ action, handlerVersionName: this.handlerVersionName, }) } return versionedActions } /** * Process versioned actions against asynchronous side effects. */ protected async runEffects( versionedActions: VersionedAction[], context: any, nextBlock: NextBlock, ) { await this.runDeferredEffects(nextBlock.lastIrreversibleBlockNumber) for (const { action, handlerVersionName } of versionedActions) { for (const effect of this.handlerVersionMap[handlerVersionName].effects) { if (this.shouldRunOrDeferEffect(effect, action)) { await this.runOrDeferEffect(effect, action.payload, nextBlock, context) } } } } /** * Will run when a rollback block number is passed to handleActions. Implement this method to * handle reversing actions full blocks at a time, until the last applied block is the block * number passed to this method. */ protected abstract async rollbackTo(blockNumber: number): Promise<void> /** * Calls `applyUpdaters` and `runEffects` on the given actions */ protected async handleActions( state: any, context: any, nextBlock: NextBlock, isReplay: boolean, ): Promise<void> { const { block } = nextBlock const { blockInfo } = block const versionedActions = await this.applyUpdaters(state, nextBlock, context, isReplay) if (!isReplay) { await this.runEffects(versionedActions, context, nextBlock) } await this.loggedUpdateIndexState(state, nextBlock, isReplay, this.handlerVersionName, context) this.lastProcessedBlockNumber = blockInfo.blockNumber this.lastProcessedBlockHash = blockInfo.blockHash this.checkRunningEffects() } private async handleRollback(isRollback: boolean, blockNumber: number, isReplay: boolean, isEarliestBlock: boolean) { if (isRollback || (isReplay && isEarliestBlock)) { const rollbackBlockNumber = blockNumber - 1 const rollbackCount = this.lastProcessedBlockNumber - rollbackBlockNumber this.log.debug(`Rolling back ${rollbackCount} blocks to block ${rollbackBlockNumber}...`) const rollbackStart = Date.now() await this.rollbackTo(rollbackBlockNumber) this.rollbackDeferredEffects(blockNumber) const rollbackTime = Date.now() - rollbackStart this.log.info(`Rolled back ${rollbackCount} blocks to block ${rollbackBlockNumber} (${rollbackTime}ms)`) } } private range(start: number, end: number) { return Array(end - start).fill(0).map((_, i: number) => i + start) } protected async runOrDeferEffect( effect: Effect, payload: any, nextBlock: NextBlock, context: any, ) { const { block, lastIrreversibleBlockNumber } = nextBlock const { blockInfo } = block const queueTime = Date.now() const curriedEffectRun = this.curryEffectRun(effect, payload, blockInfo, context, queueTime) const shouldRunImmediately = ( !effect.deferUntilIrreversible || blockInfo.blockNumber <= lastIrreversibleBlockNumber ) if (shouldRunImmediately) { this.runningEffects.push( makeQuerablePromise(curriedEffectRun(blockInfo.blockNumber, true), false), ) } else { if (!this.deferredEffects[blockInfo.blockNumber]) { this.deferredEffects[blockInfo.blockNumber] = [] } this.log.debug( `Deferring effect for '${effect.actionType}' until block ${blockInfo.blockNumber} becomes irreversible` ) this.deferredEffects[blockInfo.blockNumber].push(curriedEffectRun) } } protected shouldRunOrDeferEffect(effect: Effect, action: Action) { if (!this.matchActionType(action.type, effect.actionType, action.payload)) { return false } else if (this.effectRunMode === EffectRunMode.None) { return false } else if (this.effectRunMode === EffectRunMode.OnlyImmediate && effect.deferUntilIrreversible) { return false } else if (this.effectRunMode === EffectRunMode.OnlyDeferred && !effect.deferUntilIrreversible) { return false } return true } private curryEffectRun( effect: Effect, payload: any, blockInfo: BlockInfo, context: any, queueTime: number, ): CurriedEffectRun { return async (currentBlockNumber: number, immediate: boolean = false) => { const effectStart = Date.now() const waitedBlocks = currentBlockNumber - blockInfo.blockNumber const waitedTime = effectStart - queueTime this.log.debug( `Running ${immediate ? '' : 'deferred '}effect for '${effect.actionType}'...` + (immediate ? '' : ` (waited ${waitedBlocks} blocks; ${waitedTime}ms)`) ) await effect.run(payload, blockInfo, context) const effectTime = Date.now() - effectStart this.log.debug(`Ran ${immediate ? '' : 'deferred '}effect for '${effect.actionType}' (${effectTime}ms)`) } } private async runDeferredEffects(lastIrreversibleBlockNumber: number) { const nextDeferredBlockNumber = this.getNextDeferredBlockNumber() if (!nextDeferredBlockNumber) { return } for (const blockNumber of this.range(nextDeferredBlockNumber, lastIrreversibleBlockNumber + 1)) { if (this.deferredEffects[blockNumber]) { const effects = this.deferredEffects[blockNumber] this.log.debug(`Block ${blockNumber} is now irreversible, running ${effects.length} deferred effects`) for (const deferredEffectRun of effects) { this.runningEffects.push( makeQuerablePromise(deferredEffectRun(blockNumber), false) ) } delete this.deferredEffects[blockNumber] } } } private getNextDeferredBlockNumber() { const blockNumbers = Object.keys(this.deferredEffects).map((num) => parseInt(num, 10)) if (blockNumbers.length === 0) { return 0 } return Math.min(...blockNumbers) } private checkRunningEffects(): EffectsInfo { const newEffectErrors = this.runningEffects .filter((effectPromise) => { return effectPromise.isRejected() }) .map((rejectedPromise): string => { const error = rejectedPromise.error() if (error && error.stack) { return error.stack } return '(stack trace not captured)' }) this.effectErrors.push(...newEffectErrors) this.effectErrors.splice(0, this.effectErrors.length - this.maxEffectErrors) this.runningEffects = this.runningEffects.filter((effectPromise) => effectPromise.isPending()) return { numberOfRunningEffects: this.runningEffects.length, effectErrors: this.effectErrors, } } private rollbackDeferredEffects(rollbackTo: number) { const blockNumbers = Object.keys(this.deferredEffects).map((num) => parseInt(num, 10)) const toRollBack = blockNumbers.filter((bn) => bn >= rollbackTo) for (const blockNumber of toRollBack) { this.log.debug( `Removing ${this.deferredEffects[blockNumber].length} deferred effects for rolled back block ${blockNumber}` ) delete this.deferredEffects[blockNumber] } } private initHandlerVersions(handlerVersions: HandlerVersion[]) { if (handlerVersions.length === 0) { throw new MissingHandlerVersionError() } for (const handlerVersion of handlerVersions) { if (this.handlerVersionMap.hasOwnProperty(handlerVersion.versionName)) { throw new DuplicateHandlerVersionError(handlerVersion.versionName) } this.handlerVersionMap[handlerVersion.versionName] = handlerVersion } if (!this.handlerVersionMap.hasOwnProperty(this.handlerVersionName)) { this.handlerVersionName = handlerVersions[0].versionName this.warnMissingHandlerVersion(handlerVersions[0].versionName) } else if (handlerVersions[0].versionName !== 'v1') { this.warnIncorrectFirstHandler(handlerVersions[0].versionName) } } private async loggedUpdateIndexState( state: any, nextBlock: NextBlock, isReplay: boolean, handlerVersionName: string, context?: any, ): Promise<void> { this.log.debug('Updating Index State...') const updateStart = Date.now() await this.updateIndexState(state, nextBlock, isReplay, handlerVersionName, context) const updateTime = Date.now() - updateStart this.log.debug(`Updated Index State (${updateTime}ms)`) } private async refreshIndexState() { this.log.debug('Loading Index State...') const refreshStart = Date.now() const indexState = await this.loadIndexState() this.lastProcessedBlockNumber = indexState.blockNumber this.lastProcessedBlockHash = indexState.blockHash this.lastIrreversibleBlockNumber = indexState.lastIrreversibleBlockNumber this.handlerVersionName = indexState.handlerVersionName this.isReplay = indexState.isReplay const refreshTime = Date.now() - refreshStart this.log.debug(`Loaded Index State (${refreshTime}ms)`) } private warnMissingHandlerVersion(actualVersion: string) { this.log.warn(`No Handler Version found with name '${this.handlerVersionName}': starting with ` + `'${actualVersion}' instead.`) } private warnIncorrectFirstHandler(actualVersion: string) { this.log.warn(`First Handler Version '${actualVersion}' is not '${this.handlerVersionName}', ` + `and there is also '${this.handlerVersionName}' present. Handler Version ` + `'${this.handlerVersionName}' will be used, even though it is not first.`) } private warnHandlerVersionNonexistent(newVersion: string) { this.log.warn(`Attempted to switch to handler version '${newVersion}', however this version ` + `does not exist. Handler will continue as version '${this.handlerVersionName}'`) } private warnSkippingUpdaters(updaterIndex: number, actionType: string) { const remainingUpdaters = this.handlerVersionMap[this.handlerVersionName].updaters.length - updaterIndex - 1 if (remainingUpdaters) { this.log.warn(`Handler Version was updated to version '${this.handlerVersionName}' while there ` + `were still ${remainingUpdaters} updaters left! These updaters will be skipped for the ` + `current action '${actionType}'.`) } } }
the_stack
import {Mutable, Cursor} from "@swim/util"; import type {FastenerOwner} from "@swim/component"; import {AnyValue, Value, Form} from "@swim/structure"; import {Uri} from "@swim/uri"; import type {MapDownlinkObserver, MapDownlink} from "../downlink/MapDownlink"; import type {WarpRef} from "../ref/WarpRef"; import {DownlinkFastenerInit, DownlinkFastenerClass, DownlinkFastener} from "./DownlinkFastener"; /** @internal */ export type MapDownlinkFastenerKeyType<F extends MapDownlinkFastener<any, any, any>> = F extends MapDownlinkFastener<any, infer K, any, any, any> ? K : never; /** @internal */ export type MapDownlinkFastenerKeyInitType<F extends MapDownlinkFastener<any, any, any>> = F extends MapDownlinkFastener<any, infer K, infer KU, any, any> ? K | KU : never; /** @internal */ export type MapDownlinkFastenerValueType<F extends MapDownlinkFastener<any, any, any>> = F extends MapDownlinkFastener<any, any, any, infer V, any> ? V : never; /** @internal */ export type MapDownlinkFastenerValueInitType<F extends MapDownlinkFastener<any, any, any>> = F extends MapDownlinkFastener<any, any, any, infer V, infer VU> ? V | VU : never; /** @beta */ export interface MapDownlinkFastenerInit<K = unknown, V = unknown, KU = K, VU = V> extends DownlinkFastenerInit, MapDownlinkObserver<K, V, KU, VU> { extends?: {prototype: MapDownlinkFastener<any, any, any>} | string | boolean | null; keyForm?: Form<K, KU>; valueForm?: Form<V, VU>; initDownlink?(downlink: MapDownlink<K, V, KU, VU>): MapDownlink<K, V, KU, VU>; } /** @beta */ export type MapDownlinkFastenerDescriptor<O = unknown, K = unknown, V = unknown, KU = K, VU = V, I = {}> = ThisType<MapDownlinkFastener<O, K, V, KU, VU> & I> & MapDownlinkFastenerInit<K, V, KU, VU> & Partial<I>; /** @beta */ export interface MapDownlinkFastenerClass<F extends MapDownlinkFastener<any, any, any> = MapDownlinkFastener<any, any, any>> extends DownlinkFastenerClass<F> { } /** @beta */ export interface MapDownlinkFastenerFactory<F extends MapDownlinkFastener<any, any, any> = MapDownlinkFastener<any, any, any>> extends MapDownlinkFastenerClass<F> { extend<I = {}>(className: string, classMembers?: Partial<I> | null): MapDownlinkFastenerFactory<F> & I; define<O, K extends Value = Value, V extends Value = Value, KU extends AnyValue = AnyValue, VU extends AnyValue = AnyValue>(className: string, descriptor: MapDownlinkFastenerDescriptor<O, K, V, KU, VU>): MapDownlinkFastenerFactory<MapDownlinkFastener<any, K, V, KU, VU>>; define<O, K = unknown, V extends Value = Value, KU = K, VU extends AnyValue = AnyValue>(className: string, descriptor: {keyForm: Form<K, KU>} & MapDownlinkFastenerDescriptor<O, K, V, KU, VU>): MapDownlinkFastenerFactory<MapDownlinkFastener<any, K, V, KU, VU>>; define<O, K extends Value = Value, V = unknown, KU extends AnyValue = AnyValue, VU = V>(className: string, descriptor: {valueForm: Form<V, VU>} & MapDownlinkFastenerDescriptor<O, K, V, KU, VU>): MapDownlinkFastenerFactory<MapDownlinkFastener<any, K, V, KU, VU>>; define<O, K, V, KU = K, VU = V>(className: string, escriptor: {keyForm: Form<K, KU>, valueForm: Form<V, VU>} & MapDownlinkFastenerDescriptor<O, K, V, KU, VU>): MapDownlinkFastenerFactory<MapDownlinkFastener<any, K, V, KU, VU>>; define<O, K extends Value = Value, V extends Value = Value, KU extends AnyValue = AnyValue, VU extends AnyValue = AnyValue, I = {}>(className: string, descriptor: {implements: unknown} & MapDownlinkFastenerDescriptor<O, V, VU, I>): MapDownlinkFastenerFactory<MapDownlinkFastener<any, K, V, KU, VU> & I>; define<O, K = unknown, V extends Value = Value, KU = K, VU extends AnyValue = AnyValue, I = {}>(className: string, descriptor: {implements: unknown; keyForm: Form<K, KU>} & MapDownlinkFastenerDescriptor<O, K, V, KU, VU, I>): MapDownlinkFastenerFactory<MapDownlinkFastener<any, K, V, KU, VU> & I>; define<O, K extends Value = Value, V = unknown, KU extends AnyValue = AnyValue, VU = V, I = {}>(className: string, descriptor: {implements: unknown; valueForm: Form<V, VU>} & MapDownlinkFastenerDescriptor<O, K, V, KU, VU, I>): MapDownlinkFastenerFactory<MapDownlinkFastener<any, K, V, KU, VU> & I>; define<O, K, V, KU = K, VU = V, I = {}>(className: string, descriptor: {implements: unknown; keyForm: Form<K, KU>, valueForm: Form<V, VU>} & MapDownlinkFastenerDescriptor<O, K, V, KU, VU, I>): MapDownlinkFastenerFactory<MapDownlinkFastener<any, K, V, KU, VU> & I>; <O, K extends Value = Value, V extends Value = Value, KU extends AnyValue = AnyValue, VU extends AnyValue = AnyValue>(descriptor: MapDownlinkFastenerDescriptor<O, K, V, KU, VU>): PropertyDecorator; <O, K = unknown, V extends Value = Value, KU = K, VU extends AnyValue = AnyValue>(descriptor: {keyForm: Form<K, KU>} & MapDownlinkFastenerDescriptor<O, K, V, KU, VU>): PropertyDecorator; <O, K extends Value = Value, V = unknown, KU extends AnyValue = AnyValue, VU = V>(descriptor: {valueForm: Form<V, VU>} & MapDownlinkFastenerDescriptor<O, K, V, KU, VU>): PropertyDecorator; <O, K, V, KU = K, VU = V>(descriptor: {keyForm: Form<K, KU>, valueForm: Form<V, VU>} & MapDownlinkFastenerDescriptor<O, K, V, KU, VU>): PropertyDecorator; <O, K extends Value = Value, V extends Value = Value, KU extends AnyValue = AnyValue, VU extends AnyValue = AnyValue, I = {}>(descriptor: {implements: unknown} & MapDownlinkFastenerDescriptor<O, K, V, KU, VU, I>): PropertyDecorator; <O, K = unknown, V extends Value = Value, KU = K, VU extends AnyValue = AnyValue, I = {}>(descriptor: {implements: unknown; keyForm: Form<K, KU>} & MapDownlinkFastenerDescriptor<O, K, V, KU, VU, I>): PropertyDecorator; <O, K extends Value = Value, V = unknown, KU extends AnyValue = AnyValue, VU = V, I = {}>(descriptor: {implements: unknown; valueForm: Form<V, VU>} & MapDownlinkFastenerDescriptor<O, K, V, KU, VU, I>): PropertyDecorator; <O, K, V, KU = K, VU = V, I = {}>(descriptor: {implements: unknown; keyForm: Form<K, KU>, valueForm: Form<V, VU>} & MapDownlinkFastenerDescriptor<O, K, V, KU, VU, I>): PropertyDecorator; } /** @beta */ export interface MapDownlinkFastener<O = unknown, K = unknown, V = unknown, KU = K, VU = V> extends DownlinkFastener<O> { (key: K | KU): V | undefined; (key: K | KU, value: V | VU): O; /** @internal */ ownKeyForm: Form<K, KU> | null; keyForm(): Form<K, KU> | null; keyForm(keyForm: Form<K, KU> | null): this; /** @internal */ readonly ownValueForm: Form<V, VU> | null; valueForm(): Form<V, VU> | null; valueForm(valueForm: Form<V, VU> | null): this; get size(): number; isEmpty(): boolean; has(key: K | KU): boolean; get(key: K | KU): V | undefined; getEntry(index: number): [K, V] | undefined; firstKey(): K | undefined; firstValue(): V | undefined; firstEntry(): [K, V] | undefined; lastKey(): K | undefined; lastValue(): V | undefined; lastEntry(): [K, V] | undefined; nextKey(keyObject: K): K | undefined; nextValue(keyObject: K): V | undefined; nextEntry(keyObject: K): [K, V] | undefined; previousKey(keyObject: K): K | undefined; previousValue(keyObject: K): V | undefined; previousEntry(keyObject: K): [K, V] | undefined; set(key: K | KU, newValue: V | VU): this; delete(key: K | KU): boolean; drop(lower: number): this; take(upper: number): this; clear(): void; forEach<T>(callback: (key: K, value: V) => T | void): T | undefined; forEach<T, S>(callback: (this: S, key: K, value: V) => T | void, thisArg: S): T | undefined; keys(): Cursor<K>; values(): Cursor<V>; entries(): Cursor<[K, V]>; /** @override */ readonly downlink: MapDownlink<K, V, KU, VU> | null; /** @internal @override */ createDownlink(warp: WarpRef): MapDownlink<K, V, KU, VU>; /** @internal @override */ bindDownlink(downlink: MapDownlink<K, V, KU, VU>): MapDownlink<K, V, KU, VU>; /** @internal */ initDownlink?(downlink: MapDownlink<K, V, KU, VU>): MapDownlink<K, V, KU, VU>; } /** @beta */ export const MapDownlinkFastener = (function (_super: typeof DownlinkFastener) { const MapDownlinkFastener: MapDownlinkFastenerFactory = _super.extend("MapDownlinkFastener"); MapDownlinkFastener.prototype.keyForm = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>, keyForm?: Form<K, KU> | null): Form<K, KU> | null | typeof this { if (keyForm === void 0) { return this.ownKeyForm; } else { if (this.ownKeyForm !== keyForm) { (this as Mutable<typeof this>).ownKeyForm = keyForm; this.relink(); } return this; } } as typeof MapDownlinkFastener.prototype.keyForm; MapDownlinkFastener.prototype.valueForm = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>, valueForm?: Form<V, VU> | null): Form<V, VU> | null | typeof this { if (valueForm === void 0) { return this.ownValueForm; } else { if (this.ownValueForm !== valueForm) { (this as Mutable<typeof this>).ownValueForm = valueForm; this.relink(); } return this; } } as typeof MapDownlinkFastener.prototype.valueForm; Object.defineProperty(MapDownlinkFastener.prototype, "size", { get: function (this: MapDownlinkFastener<unknown>): number { const downlink = this.downlink; return downlink !== null ? downlink.size : 0; }, configurable: true, }); MapDownlinkFastener.prototype.isEmpty = function (this: MapDownlinkFastener<unknown>): boolean { const downlink = this.downlink; return downlink !== null ? downlink.isEmpty() : true; }; MapDownlinkFastener.prototype.has = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>, key: K | KU): boolean { const downlink = this.downlink; return downlink !== null ? downlink.has(key) : false; }; MapDownlinkFastener.prototype.get = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>, key: K | KU): V | undefined { const downlink = this.downlink; let value: V | undefined; if (downlink !== null) { value = downlink.get(key); } if (value === void 0 && this.ownValueForm !== null) { value = this.ownValueForm.unit; } return value; }; MapDownlinkFastener.prototype.getEntry = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>, index: number): [K, V] | undefined { const downlink = this.downlink; return downlink !== null ? downlink.getEntry(index) : void 0; }; MapDownlinkFastener.prototype.firstKey = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>): K | undefined { const downlink = this.downlink; return downlink !== null ? downlink.firstKey() : void 0; }; MapDownlinkFastener.prototype.firstValue = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>): V | undefined { const downlink = this.downlink; return downlink !== null ? downlink.firstValue() : void 0; }; MapDownlinkFastener.prototype.firstEntry = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>): [K, V] | undefined { const downlink = this.downlink; return downlink !== null ? downlink.firstEntry() : void 0; }; MapDownlinkFastener.prototype.lastKey = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>): K | undefined { const downlink = this.downlink; return downlink !== null ? downlink.lastKey() : void 0; }; MapDownlinkFastener.prototype.lastValue = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>): V | undefined { const downlink = this.downlink; return downlink !== null ? downlink.lastValue() : void 0; }; MapDownlinkFastener.prototype.lastEntry = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>): [K, V] | undefined { const downlink = this.downlink; return downlink !== null ? downlink.lastEntry() : void 0; }; MapDownlinkFastener.prototype.nextKey = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>, keyObject: K): K | undefined { const downlink = this.downlink; return downlink !== null ? downlink.nextKey(keyObject) : void 0; }; MapDownlinkFastener.prototype.nextValue = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>, keyObject: K): V | undefined { const downlink = this.downlink; return downlink !== null ? downlink.nextValue(keyObject) : void 0; }; MapDownlinkFastener.prototype.nextEntry = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>, keyObject: K): [K, V] | undefined { const downlink = this.downlink; return downlink !== null ? downlink.nextEntry(keyObject) : void 0; }; MapDownlinkFastener.prototype.previousKey = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>, keyObject: K): K | undefined { const downlink = this.downlink; return downlink !== null ? downlink.previousKey(keyObject) : void 0; }; MapDownlinkFastener.prototype.previousValue = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>, keyObject: K): V | undefined { const downlink = this.downlink; return downlink !== null ? downlink.previousValue(keyObject) : void 0; }; MapDownlinkFastener.prototype.previousEntry = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>, keyObject: K): [K, V] | undefined { const downlink = this.downlink; return downlink !== null ? downlink.previousEntry(keyObject) : void 0; }; MapDownlinkFastener.prototype.set = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>, key: K | KU, newValue: V | VU): typeof this { const downlink = this.downlink; if (downlink !== null) { downlink.set(key, newValue); } return this; }; MapDownlinkFastener.prototype.delete = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>, key: K | KU): boolean { const downlink = this.downlink; return downlink !== null ? downlink.delete(key) : false; }; MapDownlinkFastener.prototype.drop = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>, lower: number): typeof this { const downlink = this.downlink; if (downlink !== null) { downlink.drop(lower); } return this; }; MapDownlinkFastener.prototype.take = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>, upper: number): typeof this { const downlink = this.downlink; if (downlink !== null) { downlink.take(upper); } return this; }; MapDownlinkFastener.prototype.clear = function (this: MapDownlinkFastener<unknown>): void { const downlink = this.downlink; if (downlink !== null) { downlink.clear(); } }; MapDownlinkFastener.prototype.forEach = function <K, V, KU, VU, T, S>(this: MapDownlinkFastener<unknown, K, V, KU, VU>, callback: (this: S | undefined, key: K, value: V) => T | void, thisArg?: S): T | undefined { const downlink = this.downlink; return downlink !== null ? downlink.forEach(callback, thisArg) : void 0; }; MapDownlinkFastener.prototype.keys = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>): Cursor<K> { const downlink = this.downlink; return downlink !== null ? downlink.keys() : Cursor.empty(); }; MapDownlinkFastener.prototype.values = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>): Cursor<V> { const downlink = this.downlink; return downlink !== null ? downlink.values() : Cursor.empty(); }; MapDownlinkFastener.prototype.entries = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>): Cursor<[K, V]> { const downlink = this.downlink; return downlink !== null ? downlink.entries() : Cursor.empty(); }; MapDownlinkFastener.prototype.createDownlink = function <K, V, KU, VU>(this: MapDownlinkFastener<unknown, K, V, KU, VU>, warp: WarpRef): MapDownlink<K, V, KU, VU> { let downlink = warp.downlinkMap() as unknown as MapDownlink<K, V, KU, VU>; if (this.ownKeyForm !== null) { downlink = downlink.keyForm(this.ownKeyForm); } if (this.ownValueForm !== null) { downlink = downlink.valueForm(this.ownValueForm); } return downlink; }; MapDownlinkFastener.construct = function <F extends MapDownlinkFastener<any, any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F { if (fastener === null) { fastener = function (key: MapDownlinkFastenerKeyType<F> | MapDownlinkFastenerKeyInitType<F>, value?: MapDownlinkFastenerValueType<F> | MapDownlinkFastenerValueInitType<F>): MapDownlinkFastenerValueType<F> | undefined | FastenerOwner<F> { if (arguments.length === 1) { return fastener!.get(key); } else { fastener!.set(key, value!); return fastener!.owner; } } as F; delete (fastener as Partial<Mutable<F>>).name; // don't clobber prototype name Object.setPrototypeOf(fastener, fastenerClass.prototype); } fastener = _super.construct(fastenerClass, fastener, owner) as F; (fastener as Mutable<typeof fastener>).ownKeyForm = null; (fastener as Mutable<typeof fastener>).ownValueForm = null; return fastener; }; MapDownlinkFastener.define = function <O, K, V, KU, VU>(className: string, descriptor: MapDownlinkFastenerDescriptor<O, K, V, KU, VU>): MapDownlinkFastenerFactory<MapDownlinkFastener<any, K, V, KU, VU>> { let superClass = descriptor.extends as MapDownlinkFastenerFactory | null | undefined; const affinity = descriptor.affinity; const inherits = descriptor.inherits; const keyForm = descriptor.keyForm; const valueForm = descriptor.valueForm; let hostUri = descriptor.hostUri; let nodeUri = descriptor.nodeUri; let laneUri = descriptor.laneUri; let prio = descriptor.prio; let rate = descriptor.rate; let body = descriptor.body; delete descriptor.extends; delete descriptor.implements; delete descriptor.affinity; delete descriptor.inherits; delete descriptor.keyForm; delete descriptor.valueForm; delete descriptor.hostUri; delete descriptor.nodeUri; delete descriptor.laneUri; delete descriptor.prio; delete descriptor.rate; delete descriptor.body; if (superClass === void 0 || superClass === null) { superClass = this; } const fastenerClass = superClass.extend(className, descriptor); fastenerClass.construct = function (fastenerClass: {prototype: MapDownlinkFastener<any, any, any>}, fastener: MapDownlinkFastener<O, K, V, KU, VU> | null, owner: O): MapDownlinkFastener<O, K, V, KU, VU> { fastener = superClass!.construct(fastenerClass, fastener, owner); if (affinity !== void 0) { fastener.initAffinity(affinity); } if (inherits !== void 0) { fastener.initInherits(inherits); } if (hostUri !== void 0) { (fastener as Mutable<typeof fastener>).ownHostUri = hostUri as Uri; } if (nodeUri !== void 0) { (fastener as Mutable<typeof fastener>).ownNodeUri = nodeUri as Uri; } if (laneUri !== void 0) { (fastener as Mutable<typeof fastener>).ownLaneUri = laneUri as Uri; } if (prio !== void 0) { (fastener as Mutable<typeof fastener>).ownPrio = prio as number; } if (rate !== void 0) { (fastener as Mutable<typeof fastener>).ownRate = rate as number; } if (body !== void 0) { (fastener as Mutable<typeof fastener>).ownBody = body as Value; } if (keyForm !== void 0) { (fastener as Mutable<typeof fastener>).ownKeyForm = keyForm; } if (valueForm !== void 0) { (fastener as Mutable<typeof fastener>).ownValueForm = valueForm; } return fastener; }; if (typeof hostUri === "function") { fastenerClass.prototype.initHostUri = hostUri; hostUri = void 0; } else if (hostUri !== void 0) { hostUri = Uri.fromAny(hostUri); } if (typeof nodeUri === "function") { fastenerClass.prototype.initNodeUri = nodeUri; nodeUri = void 0; } else if (nodeUri !== void 0) { nodeUri = Uri.fromAny(nodeUri); } if (typeof laneUri === "function") { fastenerClass.prototype.initLaneUri = laneUri; laneUri = void 0; } else if (laneUri !== void 0) { laneUri = Uri.fromAny(laneUri); } if (typeof prio === "function") { fastenerClass.prototype.initPrio = prio; prio = void 0; } if (typeof rate === "function") { fastenerClass.prototype.initRate = rate; rate = void 0; } if (typeof body === "function") { fastenerClass.prototype.initBody = body; body = void 0; } else if (body !== void 0) { body = Value.fromAny(body); } return fastenerClass; }; return MapDownlinkFastener; })(DownlinkFastener);
the_stack
import { createServer, Server } from 'http'; import { CloudFrontRequest } from 'aws-lambda'; import getPort from 'get-port'; import { ProxyConfig } from '../src/types'; import { generateCloudFrontRequestEvent } from './test-utils'; /* ----------------------------------------------------------------------------- * Proxy config server mock * ---------------------------------------------------------------------------*/ class ConfigServer { public proxyConfig?: ProxyConfig; public staticFiles: string[] = []; private server?: Server; async start() { const port = await getPort(); this.server = createServer((req, res) => { if (req.url && req.url.startsWith('/filesystem')) { const splittedUrl = req.url.split('/'); const filePath = decodeURIComponent( splittedUrl[splittedUrl.length - 1] ); if (this.staticFiles.includes(filePath)) { res.statusCode = 200; } else { res.statusCode = 404; } return res.end(JSON.stringify({})); } // Respond with config res.end(JSON.stringify(this.proxyConfig)); }); await new Promise<void>((resolve) => this.server!.listen(port, resolve)); return `http://localhost:${port}`; } stop() { if (!this.server) { return Promise.resolve(); } return new Promise<void>((resolve, reject) => { this.server!.close((err) => { if (err) { return reject(err); } resolve(); }); }); } } /* ----------------------------------------------------------------------------- * Tests * ---------------------------------------------------------------------------*/ describe('[proxy] Handler', () => { let handler: any; let configServer: ConfigServer; let configEndpoint: string; beforeEach(async () => { // Since the handler has it's own state we need to isolate it between test runs to prevent // using a cached proxyConfig jest.isolateModules(() => { handler = require('../src/handler').handler; }); configServer = new ConfigServer(); configEndpoint = await configServer.start(); }); afterEach(async () => { await configServer.stop(); }); test('External redirect [HTTP]', async () => { const proxyConfig: ProxyConfig = { etag: '123', deploymentId: 'abc', lambdaRoutes: {}, prerenders: {}, routes: [ { src: '^\\/docs(?:\\/([^\\/]+?))$', dest: 'http://example.com/docs/$1', check: true, }, ], }; const requestPath = '/docs/hello-world'; // Prepare configServer configServer.proxyConfig = proxyConfig; const cloudFrontEvent = generateCloudFrontRequestEvent({ configEndpoint, uri: requestPath, }); const result = (await handler(cloudFrontEvent)) as CloudFrontRequest; expect(result.origin?.custom).toEqual( expect.objectContaining({ domainName: 'example.com', path: '', port: 80, protocol: 'http', }) ); expect(result.uri).toBe('/docs/hello-world'); expect(result.headers.host).toEqual( expect.arrayContaining([ { key: 'host', value: 'example.com', }, ]) ); }); test('External redirect [HTTPS]', async () => { const proxyConfig: ProxyConfig = { etag: '123', deploymentId: 'abc', lambdaRoutes: {}, prerenders: {}, routes: [ { src: '^\\/docs(?:\\/([^\\/]+?))$', dest: 'https://example.com/docs/$1', check: true, }, ], }; const requestPath = '/docs/hello-world'; // Prepare configServer configServer.proxyConfig = proxyConfig; const cloudFrontEvent = generateCloudFrontRequestEvent({ configEndpoint, uri: requestPath, }); const result = (await handler(cloudFrontEvent)) as CloudFrontRequest; expect(result.origin?.custom).toEqual( expect.objectContaining({ domainName: 'example.com', path: '', port: 443, protocol: 'https', }) ); expect(result.uri).toBe('/docs/hello-world'); expect(result.headers.host).toEqual( expect.arrayContaining([ { key: 'host', value: 'example.com', }, ]) ); }); test('External redirect [Custom Port]', async () => { const proxyConfig: ProxyConfig = { etag: '123', deploymentId: 'abc', lambdaRoutes: {}, prerenders: {}, routes: [ { src: '^\\/docs(?:\\/([^\\/]+?))$', dest: 'https://example.com:666/docs/$1', check: true, }, ], }; const requestPath = '/docs/hello-world'; // Prepare configServer configServer.proxyConfig = proxyConfig; const cloudFrontEvent = generateCloudFrontRequestEvent({ configEndpoint, uri: requestPath, }); const result = (await handler(cloudFrontEvent)) as CloudFrontRequest; expect(result.origin?.custom).toEqual( expect.objectContaining({ domainName: 'example.com', path: '', port: 666, protocol: 'https', }) ); expect(result.uri).toBe('/docs/hello-world'); expect(result.headers.host).toEqual( expect.arrayContaining([ { key: 'host', value: 'example.com', }, ]) ); }); test('External redirect [Subdomain]', async () => { const proxyConfig: ProxyConfig = { etag: '123', deploymentId: 'abc', lambdaRoutes: {}, prerenders: {}, routes: [ { src: '^\\/docs(?:\\/([^\\/]+?))$', dest: 'https://sub.example.com/docs/$1', check: true, }, ], }; const requestPath = '/docs/hello-world'; // Prepare configServer configServer.proxyConfig = proxyConfig; const cloudFrontEvent = generateCloudFrontRequestEvent({ configEndpoint, uri: requestPath, }); const result = (await handler(cloudFrontEvent)) as CloudFrontRequest; expect(result.origin?.custom).toEqual( expect.objectContaining({ domainName: 'sub.example.com', path: '', port: 443, protocol: 'https', }) ); expect(result.uri).toBe('/docs/hello-world'); expect(result.headers.host).toEqual( expect.arrayContaining([ { key: 'host', value: 'sub.example.com', }, ]) ); }); test('i18n default locale rewrite', async () => { const proxyConfig: ProxyConfig = { etag: '123', deploymentId: 'abc', lambdaRoutes: {}, prerenders: {}, routes: [ { src: '^/(?!(?:_next/.*|en|fr\\-FR|nl)(?:/.*|$))(.*)$', dest: '$wildcard/$1', continue: true, }, { src: '/', locale: { redirect: { en: '/', 'fr-FR': '/fr-FR', nl: '/nl', }, cookie: 'NEXT_LOCALE', }, continue: true, }, { src: '^/$', dest: '/en', continue: true, }, ], }; const requestPath = '/'; // Prepare configServer configServer.proxyConfig = proxyConfig; const cloudFrontEvent = generateCloudFrontRequestEvent({ configEndpoint, uri: requestPath, }); const result = (await handler(cloudFrontEvent)) as CloudFrontRequest; expect(result.origin?.s3).toEqual( expect.objectContaining({ domainName: 's3.localhost', path: '', }) ); // deploymentId + path expect(result.uri).toBe('/abc/static/en'); }); test('Correctly request /index object from S3 when requesting /', async () => { const proxyConfig: ProxyConfig = { etag: '123', deploymentId: 'abc', lambdaRoutes: {}, routes: [ { src: '^(?:\\/((?:[^\\/]+?)(?:\\/(?:[^\\/]+?))*))\\/$', headers: { Location: '/$1', }, status: 308, continue: true, }, { src: '/404', status: 404, continue: true, }, { handle: 'filesystem', }, { handle: 'resource', }, { src: '/.*', status: 404, }, { handle: 'miss', }, { handle: 'rewrite', }, { handle: 'hit', }, { handle: 'error', }, { src: '/.*', dest: '/404', status: 404, }, ], prerenders: {}, }; const requestPath = '/'; // Prepare configServer configServer.staticFiles = ['404', '500', 'index']; configServer.proxyConfig = proxyConfig; const cloudFrontEvent = generateCloudFrontRequestEvent({ configEndpoint, uri: requestPath, }); const result = (await handler(cloudFrontEvent)) as CloudFrontRequest; expect(result.origin?.s3).toEqual( expect.objectContaining({ domainName: 's3.localhost', path: '', }) ); expect(result.uri).toBe('/abc/static/index'); }); test('Add x-forwarded-host header to API-Gateway requests', async () => { const hostHeader = 'example.org'; const proxyConfig: ProxyConfig = { etag: '123', deploymentId: 'abc', lambdaRoutes: { '/__NEXT_API_LAMBDA_0': 'https://lambda-endpoint.localhost/__NEXT_API_LAMBDA_0', }, prerenders: {}, routes: [ { src: '^(?:\\/((?:[^\\/]+?)(?:\\/(?:[^\\/]+?))*))\\/$', headers: { Location: '/$1', }, status: 308, continue: true, }, { src: '/404', status: 404, continue: true, }, { handle: 'filesystem', }, { src: '^/api/test/?$', dest: '/__NEXT_API_LAMBDA_0', headers: { 'x-nextjs-page': '/api/test', }, check: true, }, { handle: 'resource', }, { src: '/.*', status: 404, }, { handle: 'miss', }, { handle: 'rewrite', }, { src: '^/api/test/?$', dest: '/__NEXT_API_LAMBDA_0', headers: { 'x-nextjs-page': '/api/test', }, check: true, }, { handle: 'hit', }, { handle: 'error', }, { src: '/.*', dest: '/404', status: 404, }, ], }; const requestPath = '/api/test'; // Prepare configServer configServer.proxyConfig = proxyConfig; const cloudFrontEvent = generateCloudFrontRequestEvent({ configEndpoint, uri: requestPath, }); const result = (await handler(cloudFrontEvent)) as CloudFrontRequest; expect(result.origin?.custom).toEqual( expect.objectContaining({ domainName: 'lambda-endpoint.localhost', path: '/__NEXT_API_LAMBDA_0', }) ); expect(result.headers).toEqual( expect.objectContaining({ 'x-nextjs-page': [ { key: 'x-nextjs-page', value: '/api/test', }, ], 'x-forwarded-host': [ { key: 'X-Forwarded-Host', value: hostHeader, }, ], }) ); }); // Related to issue: https://github.com/milliHQ/terraform-aws-next-js/issues/218 test('Dynamic routes with dynamic part in directory', async () => { const proxyConfig: ProxyConfig = { etag: '123', deploymentId: 'abc', lambdaRoutes: { '/__NEXT_API_LAMBDA_0': 'https://lambda-endpoint.localhost/__NEXT_API_LAMBDA_0', '/__NEXT_PAGE_LAMBDA_0': 'https://lambda-endpoint.localhost/__NEXT_PAGE_LAMBDA_0', }, prerenders: {}, routes: [ { src: '^(?:\\/((?:[^\\/]+?)(?:\\/(?:[^\\/]+?))*))\\/$', headers: { Location: '/$1', }, status: 308, continue: true, }, { src: '^\\/blog(?:\\/((?:[^\\/]+?)(?:\\/(?:[^\\/]+?))*))?$', headers: { Location: '/test/$1', }, status: 308, }, { src: '/404', status: 404, continue: true, }, { handle: 'filesystem', }, { src: '^/api/robots/?$', dest: '/__NEXT_API_LAMBDA_0', headers: { 'x-nextjs-page': '/api/robots', }, check: true, }, { src: '^(/|/index|)/?$', dest: '/__NEXT_PAGE_LAMBDA_0', headers: { 'x-nextjs-page': '/index', }, check: true, }, { src: '^\\/robots\\.txt$', dest: '/api/robots', check: true, }, { handle: 'resource', }, { src: '/.*', status: 404, }, { handle: 'miss', }, { handle: 'rewrite', }, { src: '^/_next/data/oniBm2oZ9GXevuUEdEG44/index.json$', dest: '/', check: true, }, { src: '^/_next/data/oniBm2oZ9GXevuUEdEG44/test/(?<slug>.+?)\\.json$', dest: '/test/[...slug]?slug=$slug', check: true, }, { src: '^/test/\\[\\.\\.\\.slug\\]/?$', dest: '/__NEXT_PAGE_LAMBDA_0', headers: { 'x-nextjs-page': '/test/[...slug]', }, check: true, }, { src: '^/api/robots/?$', dest: '/__NEXT_API_LAMBDA_0', headers: { 'x-nextjs-page': '/api/robots', }, check: true, }, { src: '^(/|/index|)/?$', dest: '/__NEXT_PAGE_LAMBDA_0', headers: { 'x-nextjs-page': '/index', }, check: true, }, { src: '^/test/(?<slug>.+?)(?:/)?$', dest: '/test/[...slug]?slug=$slug', check: true, }, { src: '^/test/\\[\\.\\.\\.slug\\]/?$', dest: '/__NEXT_PAGE_LAMBDA_0', headers: { 'x-nextjs-page': '/test/[...slug]', }, check: true, }, { src: '^/users/(?<user_id>[^/]+?)(?:/)?$', dest: '/users/[user_id]?user_id=$user_id', check: true, }, { handle: 'hit', }, { handle: 'error', }, { src: '/.*', dest: '/404', status: 404, }, ], }; const requestPath = '/users/432'; // Prepare configServer configServer.proxyConfig = proxyConfig; configServer.staticFiles = [ '404', '500', 'favicon.ico', 'about', 'users/[user_id]', ]; const cloudFrontEvent = generateCloudFrontRequestEvent({ configEndpoint, uri: requestPath, }); const result = (await handler(cloudFrontEvent)) as CloudFrontRequest; expect(result.origin?.s3).toEqual( expect.objectContaining({ domainName: 's3.localhost', path: '', }) ); expect(result.uri).toBe('/abc/static/users/[user_id]'); }); test('Redirects with querystring', async () => { const proxyConfig: ProxyConfig = { etag: '123', deploymentId: 'abc', lambdaRoutes: {}, prerenders: {}, routes: [ { src: '^(?:\\/((?:[^\\/]+?)(?:\\/(?:[^\\/]+?))*))\\/$', headers: { Location: '/$1', }, status: 308, continue: true, }, { src: '^\\/one$', headers: { Location: '/newplace', }, status: 308, }, { src: '^\\/two(?:\\/((?:[^\\/]+?)(?:\\/(?:[^\\/]+?))*))?$', headers: { Location: '/newplacetwo/$1', }, status: 308, }, { src: '^\\/three$', headers: { Location: '/newplace?foo=bar', }, status: 308, }, { src: '^\\/four$', headers: { Location: 'https://example.com', }, status: 308, }, ], }; configServer.proxyConfig = proxyConfig; { // Remove trailing slash // /test/?foo=bar -> /test?foo=bar const cloudFrontEvent = generateCloudFrontRequestEvent({ configEndpoint, uri: '/test/', querystring: 'foo=bar', }); const result = (await handler(cloudFrontEvent)) as CloudFrontRequest; expect(result.headers).toEqual( expect.objectContaining({ location: [ { key: 'Location', value: '/test?foo=bar', }, ], }) ); } { // Relative route replace // /one?foo=bar -> /newplace?foo=bar const cloudFrontEvent = generateCloudFrontRequestEvent({ configEndpoint, uri: '/one', querystring: 'foo=bar', }); const result = (await handler(cloudFrontEvent)) as CloudFrontRequest; expect(result.headers).toEqual( expect.objectContaining({ location: [ { key: 'Location', value: '/newplace?foo=bar', }, ], }) ); } { // Relative route partial replace // /two/some/path?foo=bar -> /newplace/some/path?foo=bar const cloudFrontEvent = generateCloudFrontRequestEvent({ configEndpoint, uri: '/two/some/path', querystring: 'foo=bar', }); const result = (await handler(cloudFrontEvent)) as CloudFrontRequest; expect(result.headers).toEqual( expect.objectContaining({ location: [ { key: 'Location', value: '/newplacetwo/some/path?foo=bar', }, ], }) ); } { // Try to override predefined param // /three?foo=badValue -> /newplace?foo=bar const cloudFrontEvent = generateCloudFrontRequestEvent({ configEndpoint, uri: '/three', querystring: 'foo=badValue', }); const result = (await handler(cloudFrontEvent)) as CloudFrontRequest; expect(result.headers).toEqual( expect.objectContaining({ location: [ { key: 'Location', value: '/newplace?foo=bar', }, ], }) ); } { // Redirect to external URL // /four?foo=bar -> https://example.com?foo=bar const cloudFrontEvent = generateCloudFrontRequestEvent({ configEndpoint, uri: '/four', querystring: 'foo=bar', }); const result = (await handler(cloudFrontEvent)) as CloudFrontRequest; expect(result.headers).toEqual( expect.objectContaining({ location: [ { key: 'Location', value: 'https://example.com/?foo=bar', }, ], }) ); } }); });
the_stack
const FILE_POSTFIXES = ['', '.js', '.json', '/package.json', '/index.js', '/index.json']; const FOLDER_POSTFIXES = ['/package.json', '/index.js', '/index.json']; const MODULE_PREFIX = '(function (module, exports, require, __filename, __dirname) { '; const MODULE_POSTFIX = '\n});'; export type ModuleLoader = ( module: Module, exports: any, require: Module['require'], filename: string, dirname: string ) => any; export type AddPathOptions = { baseUrl?: string, paths: {[pattern: string]: string[]} }; export default class Module { public static root: Module; public readonly id: string; public readonly parent: Module | null; public exports: any = {}; protected readonly _cache: { [id: string]: Module | false } = {}; protected readonly _paths: { [pattern: string]: string[] } = {}; constructor(id?: string, parent?: Module | null, content?: ModuleLoader | object) { this.id = id || ''; this.parent = parent || null; let exports = {}; let resolved = false; const require = this.require.bind(this); Object.defineProperty(this, '_cache', { enumerable: false, writable: false, value: this.parent ? this.parent._cache : this._cache }); Object.defineProperty(this, '_paths', { enumerable: false, writable: false, value: this.parent ? this.parent._paths : this._paths }); if (id) { this._cache[id] = this; } Object.defineProperty(this, 'exports', { set(value) { exports = value; }, get() { if (!resolved) { resolved = true; if (typeof content === 'function' && id) { content(this, exports, require, id.slice(1), dirname(id).slice(1)); } else if (content instanceof Object) { exports = content; } } return exports; } }); checkBrowserField(this); } public require(request: string) { if (request.slice(0, 1) !== '.') { const cached = this._cache[request]; if (cached) { return cached.exports; } const mapped = findMappedModule.call(this, request); if (mapped) { return mapped.exports; } this._cache[request] = false; return findNodeModule.call(this, request).exports; } return findFileModule.call(this, request).exports; } static createLoader(url: string): ModuleLoader | null { let result; try { result = tabris._client.loadAndExecute(url, MODULE_PREFIX, MODULE_POSTFIX); } catch (ex) { throw new Error('Could not parse ' + url + ':' + ex); } if (result.loadError) { return null; } return result.executeResult; } static execute(code: string, url: string) { return tabris._client.execute(code, url).executeResult; } static readJSON(url: string) { const src = this.load(url); if (src) { try { return JSON.parse(src); } catch (ex) { throw new Error('Could not parse ' + url + ': ' + ex.message); } } } static getSourceMap() { return null; } static load(url: string) { return tabris._client.load(url); } static createRequire(path: string) { if ((typeof path !== 'string') || path[0] !== '/') { throw new Error(`The argument 'path' must be an absolute path string. Received ${path}`); } return function(request: string) { return Module.root.require(normalizePath(dirname('.' + path) + '/' + request)); }; } static define(path: string, exports: any) { if (arguments.length !== 2) { throw new Error(`Expected exactly 2 arguments, got ${arguments.length}`); } if (typeof path !== 'string') { throw new Error('Expected argument 1 to be of type string'); } if (path.charAt(0) !== '/') { throw new Error('Path needs to start with a "/"'); } const id = '.' + path; if (Module.root._cache[id]) { throw new Error(`Module "${path}" is already defined'`); } if (Module.root._cache[id] === false) { throw new Error(`Module "${path}" was accessed before it was defined'`); } if (exports instanceof Module) { throw new Error('Expected argument 2 to be module exports, got a module instance'); } new Module('.' + path, this.root, module => module.exports = exports); } static addPath(pattern: string, alias: string[]): void; static addPath(options: AddPathOptions): void; static addPath(arg1: string | AddPathOptions, arg2?: string[]) { if (arg1 instanceof Object) { checkAddPathOptions(arg1); for (const pattern in arg1.paths) { const paths = arg1.paths[pattern]; if (!Array.isArray(paths) || paths.some(path => typeof path !== 'string')) { throw new Error(`Expected paths for pattern "${pattern}" to be array of strings`); } this.addPath( pattern, paths.map(path => arg1.baseUrl ? ('./' + normalizePath(arg1.baseUrl + '/' + path)) : path) ); } } else { if (arguments.length <= 1) { throw new Error('Expected argument 1 to be of type object'); } checkAddPathArgs(arg1, arg2); if (this.root._paths[arg1]) { throw new Error(`Pattern "${arg1}" is already registered`); } const prefix = arg1.split('*')[0]; if (Object.keys(this.root._cache).some(request => request.startsWith(prefix))) { throw new Error(`Can not add pattern "${arg1}" since a matching module was already imported'`); } this.root._paths[arg1] = arg2; } } } Module.root = new Module(); function findFileModule(this: Module, request: string) { const path = normalizePath(dirname(this.id) + '/' + request); const result = findModule.call(this, path, getPostfixes(request)); if (!result) { throw new Error('Cannot find module \'' + request + '\''); } return result; } function findNodeModule(this: Module, request: string) { let currentDir = dirname(this.id); const postfixes = getPostfixes(request); const modulesPath = '/node_modules'; const filePath = modulesPath + '/' + request; let result; do { result = findModule.call(this, normalizePath(currentDir + filePath), postfixes); currentDir = normalizePath(currentDir + '/..'); if (currentDir && currentDir.slice(-1 * modulesPath.length) === modulesPath) { currentDir = normalizePath(currentDir + '/..'); } } while (!result && currentDir); if (!result) { throw new Error('Cannot find module \'' + request + '\''); } return result; } function findMappedModule(this: Module, request: string): Module | null { if (this.id.indexOf('/node_modules') !== -1) { return null; } // Based on https://github.com/Microsoft/TypeScript/issues/5039#pathMappings let matchedPattern: string | undefined; let matchedWildcard: string | undefined; let longestMatchedPrefixLength = 0; for (const pattern in this._paths) { const indexOfWildcard = pattern.indexOf('*'); if (indexOfWildcard !== -1) { const prefix = pattern.substr(0, indexOfWildcard); const suffix = pattern.substr(indexOfWildcard + 1); if (request.length >= prefix.length + suffix.length && request.startsWith(prefix) && request.endsWith(suffix) && longestMatchedPrefixLength < prefix.length ) { longestMatchedPrefixLength = prefix.length; matchedPattern = pattern; matchedWildcard = request.substr(prefix.length, request.length - suffix.length); } } else if (pattern === request) { matchedPattern = pattern; matchedWildcard = undefined; break; } } if (!matchedPattern) { return null; } const attempts: string[] = []; for (const subst of this._paths[matchedPattern]) { const path = matchedWildcard ? subst.replace('*', matchedWildcard) : subst; attempts.push(path); const module = findModule.call(this, path, getPostfixes(request)); if (module) { return module; } } throw new Error(`Cannot find module "${request}" at "${attempts.join('" or "')}"`); } function findModule(this: Module, path: string, postfixes: string[]): Module | null { if (path) { for (const postfix of postfixes) { let module = getModule.call(this, path + postfix); if (postfix === '/package.json') { if (getMain(module)) { const normalizedPath = normalizePath(path + '/' + getMain(module)); module = findModule.call(this, normalizedPath, FILE_POSTFIXES); } else { module = null; } } if (module) { return module; } } } return null; } function checkBrowserField(module: Module | null) { if (module?.id.endsWith('package.json') && module.exports && 'browser' in module.exports) { const msg = module.id + ' has a "browser" field.\nThis module may function better with a file bundler'; if (console.print) { console.print('warn', msg); } else { (console as any).warn(msg); } } } function getMain(module: Module | null): string | null { return module && module.exports && module.exports.main; } function getModule(this: Module, url: string): Module | null { if (url in this._cache) { return this._cache[url] || null; } if (url.slice(-5) === '.json') { const data = Module.readJSON(url); if (data) { return new Module(url, this, data); } } else { const loader = Module.createLoader(url); if (loader) { return new Module(url, this, loader); } } this._cache[url] = false; return null; } function getPostfixes(request: string) { return request.slice(-1) === '/' ? FOLDER_POSTFIXES : FILE_POSTFIXES; } function dirname(id: string) { if (!id || id.slice(0, 1) !== '.') { return './'; } return id.slice(0, id.lastIndexOf('/')); } function normalizePath(path: string) { const segments = []; const pathSegments = path.split('/'); for (const segment of pathSegments) { if (segment === '..') { const removed = segments.pop(); if (!removed || removed === '.') { return ''; } } else if (segment === '.' ? segments.length === 0 : segment !== '') { segments.push(segment); } } return segments.join('/'); } function checkAddPathOptions(arg1: AddPathOptions) { if (!('paths' in arg1)) { throw new Error('Missing option "paths"'); } if (!(arg1.paths instanceof Object)) { throw new Error('Expected option "paths" to be an object'); } if (('baseUrl' in arg1) && typeof arg1.baseUrl !== 'string') { throw new Error('Expected option "baseUrl" to be a string'); } if (arg1.baseUrl && !arg1.baseUrl.startsWith('/')) { throw new Error('Expected baseUrl to start with "/"'); } } function checkAddPathArgs(arg1: string, arg2: string[] | undefined): asserts arg2 is string[] { if (typeof arg1 !== 'string') { throw new Error('Expected argument 1 to be of type string'); } if (!Array.isArray(arg2)) { throw new Error(`Expected paths for pattern "${arg1}" to be array of strings`); } if (arg2.some(path => typeof path !== 'string')) { throw new Error(`Expected paths for pattern "${arg1}" to be array of strings`); } if (arg1 === '') { throw new Error('Pattern not be empty string'); } if (/^[./]./.test(arg1)) { throw new Error(`Pattern may not start with "${arg1.charAt(0)}"`); } if (arg1.split('*').length > 2) { throw new Error('Pattern may contain only one "*"'); } if (arg1.includes(' ')) { throw new Error('Pattern may not contain spaces'); } if (arg2.length === 0) { throw new Error(`Paths array for pattern "${arg1}" is empty`); } const wildcard = arg1.includes('*'); arg2.forEach(path => { if (!path.startsWith('./')) { throw new Error(`Expected path "${path}" for pattern "${arg1}" to start with "./"`); } const pathWildcards = path.split('*').length - 1; if (wildcard) { if (pathWildcards !== 1) { throw new Error(`Expected path "${path}" for pattern "${arg1}" to contain exactly one "*"`); } } else if (pathWildcards !== 0) { throw new Error(`Expected path "${path}" for pattern "${arg1}" to not contain "*"`); } }); }
the_stack
declare module FoundationSites { // https://get.foundation/sites/docs/abide.html#javascript-reference interface Abide { enableValidation(): void; disableValidation(): void; requiredCheck(element: JQuery): boolean; findFormError(element: JQuery, failedValidators?: string[]): JQuery; findLabel(element: JQuery): boolean; findRadioLabels(elements: JQuery): boolean; findCheckboxLabels(elements: JQuery): boolean; addErrorClasses(element: JQuery, failedValidators?: string[]): void; addA11yAttributes(element: JQuery): void; addGlobalErrorA11yAttributes(element: JQuery): void; removeRadioErrorClasses(groupName: string): void; removeCheckboxErrorClasses(groupName: string): void; removeErrorClasses(element: JQuery): void; validateInput(element: JQuery): boolean; validateForm(): boolean; initialized: boolean; validateText(element: JQuery, pattern: string): boolean; validateRadio(groupName: string): boolean; validateCheckbox(groupName: string): boolean; matchValidation(element: JQuery, validators: string, required: boolean): boolean; resetForm(): void; } interface AbideDefaults { validateOn: string | null; labelErrorClass: string; inputErrorClass: string; formErrorSelector: string; formErrorClass: string; a11yAttributes: boolean; a11yErrorLevel: string; liveValidate: boolean; validateOnBlur: boolean; patterns: IAbidePatterns; validators: any; // TODO, maybe there is a better solution to describe how this object may look like } interface IAbidePatterns { alpha?: RegExp; alpha_numeric?: RegExp; integer?: RegExp; number?: RegExp; card?: RegExp; cvv?: RegExp; email ?: RegExp; url?: RegExp; domain?: RegExp; datetime?: RegExp; date?: RegExp; time?: RegExp; dateISO?: RegExp; month_day_year?: RegExp; day_month_year?: RegExp; color?: RegExp; website?: any; } interface IAbideOptions { validateOn?: string | null; labelErrorClass?: string; inputErrorClass?: string; formErrorSelector?: string; formErrorClass?: string; a11yAttributes?: boolean; a11yErrorLevel?: string; liveValidate?: boolean; validateOnBlur?: boolean; patterns?: IAbidePatterns; validators?: any; } // https://get.foundation/sites/docs/accordion.html#javascript-reference interface Accordion { toggle(target: JQuery): void; down(target: JQuery, firstTime: boolean): void; up(target: JQuery): void; } interface IAccordionOptions { slideSpeed?: number; multiExpand?: boolean; allowAllClosed?: boolean; deepLink?: boolean; deepLinkSmudge?: boolean; deepLinkSmudgeDelay?: number; deepLinkSmudgeOffset?: number; updateHistory?: boolean; } // https://get.foundation/sites/docs/accordion-menu.html#javascript-reference interface AccordionMenu { hideAll(): void; showAll(): void; toggle(target: JQuery): void; down(target: JQuery, firstTime: boolean): void; up(target: JQuery): void; } interface IAccordionMenuOptions { parentLink?: boolean; slideSpeed?: number; submenuToggle?: boolean; submenuToggleText?: string; multiOpen?: boolean; } // https://get.foundation/sites/docs/drilldown-menu.html#javascript-reference interface Drilldown { // no public methods } interface IDrilldownOptions { autoApplyClass?: boolean; backButton?: string; backButtonPosition?: string; wrapper?: string; parentLink?: boolean; closeOnClick?: boolean; autoHeight?: boolean; animateHeight?: boolean; scrollTop?: boolean; scrollTopElement?: string; scrollTopOffset?: number; animationDuration?: number; animationEasing?: string; } // https://get.foundation/sites/docs/dropdown.html#javascript-reference interface Dropdown { open(): void; close(): void; toggle(): void; } interface IDropdownOptions { parentClass?: string | null; hoverDelay?: number; hover?: boolean; hoverPane?: boolean; vOffset?: number; hOffset?: number; position?: string; alignment?: string; allowOverlap?: boolean; allowBottomOverlap?: boolean; trapFocus?: boolean; autoFocus?: boolean; closeOnClick?: boolean; forceFollow?: boolean; } // https://get.foundation/sites/docs/dropdown-menu.html#javascript-reference interface DropdownMenu { // No public methods } interface IDropdownMenuOptions { disableHover?: boolean; disableHoverOnTouch?: boolean; autoclose?: boolean; hoverDelay?: number; clickOpen?: boolean; closingTime?: number; alignment?: string; closeOnClick?: boolean; closeOnClickInside?: boolean; verticalClass?: string; rightClass?: string; forceFollow?: boolean; } // https://get.foundation/sites/docs/equalizer.html#javascript-reference interface Equalizer { getHeights(cb: Function): any[]; getHeightsByRow(cb: Function): any[]; applyHeight(heights: any[]): void; applyHeightByRow(groups: any[]): void; } interface IEqualizerOptions { equalizeOnStack?: boolean; equalizeByRow?: boolean; equalizeOn?: string; } // https://get.foundation/sites/docs/interchange.html#javascript-reference interface Interchange { replace(path: string): void; } interface IInterchangeOptions { rules?: any[]; type?: string; } // https://get.foundation/sites/docs/magellan.html#javascript-reference interface Magellan { calcPoints(): void; scrollToLoc(location: string): void; reflow(): void; } interface IMagellanOptions { animationDuration?: number; animationEasing?: string; threshold?: number; activeClass?: string; deepLinking?: boolean; updateHistory?: boolean; offset?: number; } // https://get.foundation/sites/docs/offcanvas.html#javascript-reference interface OffCanvas { reveal(isRevealed: boolean): void; open(event: Event, trigger: JQuery): void; close(cb?: Function): void; toggle(event: Event, trigger: JQuery): void; } interface IOffCanvasOptions { closeOnClick?: boolean; contentOverlay?: boolean; contentId?: string | null; nested?: boolean; contentScroll?: boolean; transitionTime?: string; transition?: string; forceTo?: string | null; isRevealed?: boolean; revealOn?: string | null; inCanvasOn?: string | null; autoFocus?: boolean; revealClass?: string; trapFocus?: boolean; } // https://get.foundation/sites/docs/orbit.html#javascript-reference interface Orbit { geoSync(): void; changeSlide(isLTR: boolean, chosenSlide?: JQuery, idx?: number): void; } interface IOrbitOptions { bullets?: boolean; navButtons?: boolean; animInFromRight?: string; animOutToRight?: string; animInFromLeft?: string; animOutToLeft?: string; autoPlay?: boolean; timerDelay?: number; infiniteWrap?: boolean; swipe?: boolean; pauseOnHover?: boolean; accessible?: boolean; containerClass?: string; slideClass?: string; boxOfBullets?: string; nextClass?: string; prevClass?: string; useMUI?: boolean; } interface Positionable { // No public methods } interface IPositionableOptions { position?: string; alignment?: string; allowOverlap?: boolean; allowBottomOverlap?: boolean; vOffset?: number; hOffset?: number; } interface ResponsiveAccordionTabs { storezfData: any; open(_target: any, ...args: any[]): any; close(_target: any, ...args: any[]): any; toggle(_target: any, ...args: any[]): any; } interface IResponsiveAccordionTabsOptions { // No Options } interface ResponsiveMenu { // No public methods } interface IResponsiveMenuOptions { // No Options } interface ResponsiveToggle { toggleMenu(): void; } interface IResponsiveToggleOptions { hideFor?: string; animate?: boolean; } // https://get.foundation/sites/docs/reveal.html#javascript-reference interface Reveal { open(): void; toggle(): void; close(): void; } interface IRevealOptions { animationIn?: string; animationOut?: string; showDelay?: number; hideDelay?: number; closeOnClick?: boolean; closeOnEsc?: boolean; multipleOpened?: boolean; vOffset?: number | string; hOffset?: number | string; fullScreen?: boolean; overlay?: boolean; resetOnClose?: boolean; deepLink?: boolean; updateHistory?: boolean; appendTo?: string; additionalOverlayClasses?: string; } // https://get.foundation/sites/docs/slider.html#javascript-reference interface Slider { // No public methods } interface ISliderOptions { start?: number; end?: number; step?: number; initialStart?: number; initialEnd?: number; binding?: boolean; clickSelect?: boolean; vertical?: boolean; draggable?: boolean; disabled?: boolean; doubleSided?: boolean; decimal?: number; moveTime?: number; disabledClass?: string; invertVertical?: boolean; changedDelay?: number; nonLinearBase?: number; positionValueFunction?: string; } interface SmoothScroll { scrollToLoc(loc: string, options: any, callback: Function): boolean; constructor(element: any, options: any); } interface ISmoothScrollOptions { animationDuration?: number; animationEasing?: string; threshold?: number; offset?: number; } // https://get.foundation/sites/docs/sticky.html#javascript-reference interface Sticky { // No public methods } interface IStickyOptions { container?: string; stickTo?: string; anchor?: string; topAnchor?: string; btmAnchor?: string; marginTop?: number; marginBottom?: number; stickyOn?: string; stickyClass?: string; containerClass?: string; dynamicHeight?: boolean; checkEvery?: number; } // https://get.foundation/sites/docs/tabs.html#javascript-reference interface Tabs { selectTab(element: JQuery | string): void; } interface ITabsOptions { deepLink?: boolean; deepLinkSmudge?: boolean; deepLinkSmudgeDelay?: number; deepLinkSmudgeOffset?: number; updateHistory?: boolean; autoFocus?: boolean; wrapOnKeys?: boolean; matchHeight?: boolean; activeCollapse?: boolean; linkClass?: string; linkActiveClass?: string; panelClass?: string; panelActiveClass?: string; } // https://get.foundation/sites/docs/toggler.html#javascript-reference interface Toggler { toggle(): void; } interface ITogglerOptions { toggler?: string; animate?: boolean; } // https://get.foundation/sites/docs/tooltip.html#javascript-reference interface Tooltip { show(): void; hide(): void; toggle(): void; } interface ITooltipOptions { hoverDelay?: number; fadeInDuration?: number; fadeOutDuration?: number; disableHover?: boolean; disableForTouch?: any; templateClasses?: string; tooltipClass?: string; triggerClass?: string; showOn?: string; template?: string; tipText?: string; touchCloseText?: string; clickOpen?: boolean; position?: string; alignment?: string; allowOverlap?: boolean; allowBottomOverlap?: boolean; vOffset?: number; hOffset?: number; tooltipHeight?: number; tooltipWidth?: number; allowHtml?: boolean; } // Utilities // --------- interface Box { ImNotTouchingYou(element: Object, parent?: Object, lrOnly?: boolean, tbOnly?: boolean): boolean; OverlapArea(element: Object, parent?: Object, lrOnly?: boolean, tbOnly?: boolean, ignoreBottom?: boolean): number; GetDimensions(element: Object): Object; GetExplicitOffsets(element: any, anchor: any, position: string, alignment: any, vOffset: number, hOffset: number, isOverflow: boolean): Object } interface Keyboard { parseKey(event: any): string; handleKey(event: any, component: any, functions: any): void; findFocusable(element: JQuery): Object; register(componentName: any, cmds: any): void; trapFocus(element: JQuery): void; releaseFocus(element: JQuery): void; } interface MediaQuery { queries: any[]; current: string; atLeast(size: string): boolean; only(size: string): boolean; upTo(size: string): boolean; is(size: string): boolean; get(size: string): string | null; next(size: string): string | null; } interface Motion { animateIn(element: Object, animation: any, cb: Function): void; animateOut(element: Object, animation: any, cb: Function): void; } interface Move { // TODO } interface Nest { Feather(menu: any, type: any): void; Burn(menu: any, type: any): void; } interface Timer { start(): void; restart(): void; pause(): void; } interface Touch { setupSpotSwipe(event: Object): void; setupTouchHandler(event: Object): void; init(event: Object): void; } interface Triggers { // TODO :extension on jQuery } interface FoundationSitesStatic { version: string; rtl(): boolean; plugin(plugin: Object, name: string): void; registerPlugin(plugin: Object): void; unregisterPlugin(plugin: Object): void; reInit(plugins: Array<any>): void; GetYoDigits(length: number, namespace?: string): string; reflow(elem: Object, plugins?: Array<string>|string): void; getFnName(fn: string): string; RegExpEscape(str: string): string; transitionend(element: JQuery): any; onLoad(elem: any, handler: any): string; util: { throttle(func: (...args: any[]) => any, delay: number): (...args: any[]) => any; }; Abide: { new(element: JQuery, options?: IAbideOptions): Abide; defaults: AbideDefaults; } Accordion: { new(element: JQuery, options?: IAccordionOptions): Accordion; } AccordionMenu: { new(element: JQuery, options?: IAccordionMenuOptions): AccordionMenu; } Drilldown: { new(element: JQuery, options?: IDrilldownOptions): Drilldown; } Dropdown: { new(element: JQuery, options?: IDropdownOptions): Dropdown; } DropdownMenu: { new(element: JQuery, options?: IDropdownMenuOptions): DropdownMenu; } Equalizer: { new(element: JQuery, options?: IEqualizerOptions): Equalizer; } Interchange: { new(element: JQuery, options?: IInterchangeOptions): Interchange; } Magellan: { new(element: JQuery, options?: IMagellanOptions): Magellan; } OffCanvas: { new(element: JQuery, options?: IOffCanvasOptions): OffCanvas; } Orbit: { new(element: JQuery, options?: IOrbitOptions): Orbit; } Positionable: { new(element: JQuery, options?: IPositionableOptions): Positionable; } ResponsiveAccordionTabs: { new(element: JQuery, options?: IResponsiveAccordionTabsOptions): ResponsiveAccordionTabs; }; ResponsiveMenu: { new(element: JQuery, options?: IResponsiveMenuOptions): ResponsiveMenu; }; ResponsiveToggle: { new(element: JQuery, options?: IResponsiveToggleOptions): ResponsiveToggle; }; Reveal: { new(element: JQuery, options?: IRevealOptions): Reveal; }; Slider: { new(element: JQuery, options?: ISliderOptions): Slider; } SmoothScroll: { new(element: JQuery, options?: ISmoothScrollOptions): SmoothScroll; } Sticky: { new(element: JQuery, options?: IStickyOptions): Sticky; } Tabs: { new(element: JQuery, options?: ITabsOptions): Tabs; } Toggler: { new(element: JQuery, options?: ITogglerOptions): Toggler; } Tooltip: { new(element: JQuery, options?: ITooltipOptions): Tooltip; } // utils Box: Box; Keyboard: Keyboard; MediaQuery: MediaQuery; Motion: Motion; Move: Move; Nest: Nest; Timer: Timer; Touch: Touch; Triggers: Triggers; } } interface JQuery { foundation(method?: string | Array<any>, ...args: any[]): JQuery; } declare var Foundation: FoundationSites.FoundationSitesStatic; declare module "Foundation" { export = Foundation; } declare module "foundation-sites" { export = Foundation; }
the_stack
import * as console from "../shared/Logger"; // import {getCurrentFiberStackInDev} from 'react-reconciler/src/ReactCurrentFiber'; function getCurrentFiberStackInDev(): string { // Stub. return ""; } // : AncestorInfo let validateDOMNesting: ( childTag: string | undefined | void | null, childText: string | undefined | void | null, ancestorInfo: AncestorInfo | undefined | void | null ) => AncestorInfo | void = ( childTag: string | undefined | void | null, childText: string | undefined | void | null, ancestorInfo: AncestorInfo | undefined | void | null ) => {}; let updatedAncestorInfo: (oldInfo: AncestorInfo | undefined | void | null, tag: string) => void = ( oldInfo: AncestorInfo | undefined | void | null, tag: string ) => {}; type AncestorInfoTagObj = { tag: string }; interface AncestorInfo { current: null | AncestorInfoTagObj; formTag: null | AncestorInfoTagObj; aTagInScope: null | AncestorInfoTagObj; buttonTagInScope: null | AncestorInfoTagObj; nobrTagInScope: null | AncestorInfoTagObj; pTagInButtonScope: null | AncestorInfoTagObj; listItemTagAutoclosing: null | AncestorInfoTagObj; dlItemTagAutoclosing: null | AncestorInfoTagObj; } if ((global as any).__DEV__) { // This validation code was written based on the HTML5 parsing spec: // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope // // Note: this does not catch all invalid nesting, nor does it try to (as it's // not clear what practical benefit doing so provides); instead, we warn only // for cases where the parser will give a parse tree differing from what React // intended. For example, <b><div></div></b> is invalid but we don't warn // because it still parses correctly; we do warn for other cases like nested // <p> tags where the beginning of the second element implicitly closes the // first, causing a confusing mess. // https://html.spec.whatwg.org/multipage/syntax.html#special const specialTags = [ "address", "applet", "area", "article", "aside", "base", "basefont", "bgsound", "blockquote", "body", "br", "button", "caption", "center", "col", "colgroup", "dd", "details", "dir", "div", "dl", "dt", "embed", "fieldset", "figcaption", "figure", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "iframe", "img", "input", "isindex", "li", "link", "listing", "main", "marquee", "menu", "menuitem", "meta", "nav", "noembed", "noframes", "noscript", "object", "ol", "p", "param", "plaintext", "pre", "script", "section", "select", "source", "style", "summary", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "title", "tr", "track", "ul", "wbr", "xmp", ]; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope const inScopeTags = [ "applet", "caption", "html", "table", "td", "th", "marquee", "object", "template", // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point // TODO: Distinguish by namespace here -- for <title>, including it here // errs on the side of fewer warnings "foreignObject", "desc", "title", ]; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope const buttonScopeTags = inScopeTags.concat(["button"]); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags const impliedEndTags = ["dd", "dt", "li", "option", "optgroup", "p", "rp", "rt"]; const emptyAncestorInfo: AncestorInfo = { current: null, formTag: null, aTagInScope: null, buttonTagInScope: null, nobrTagInScope: null, pTagInButtonScope: null, listItemTagAutoclosing: null, dlItemTagAutoclosing: null, }; updatedAncestorInfo = function(oldInfo: AncestorInfo | undefined | null, tag: string): AncestorInfo { let ancestorInfo: AncestorInfo = { ...(oldInfo || emptyAncestorInfo) }; let info: AncestorInfoTagObj = { tag }; if (inScopeTags.indexOf(tag) !== -1) { ancestorInfo.aTagInScope = null; ancestorInfo.buttonTagInScope = null; ancestorInfo.nobrTagInScope = null; } if (buttonScopeTags.indexOf(tag) !== -1) { ancestorInfo.pTagInButtonScope = null; } // See rules for 'li', 'dd', 'dt' start tags in // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody if (specialTags.indexOf(tag) !== -1 && tag !== "address" && tag !== "div" && tag !== "p") { ancestorInfo.listItemTagAutoclosing = null; ancestorInfo.dlItemTagAutoclosing = null; } ancestorInfo.current = info; if (tag === "form") { ancestorInfo.formTag = info; } if (tag === "a") { ancestorInfo.aTagInScope = info; } if (tag === "button") { ancestorInfo.buttonTagInScope = info; } if (tag === "nobr") { ancestorInfo.nobrTagInScope = info; } if (tag === "p") { ancestorInfo.pTagInButtonScope = info; } if (tag === "li") { ancestorInfo.listItemTagAutoclosing = info; } if (tag === "dd" || tag === "dt") { ancestorInfo.dlItemTagAutoclosing = info; } return ancestorInfo; }; /** * Returns whether */ const isTagValidWithParent = function(tag: string | undefined | null, parentTag: string | undefined | null) { // First, let's check if we're in an unusual parsing mode... switch (parentTag) { // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect case "select": return tag === "option" || tag === "optgroup" || tag === "#text"; case "optgroup": return tag === "option" || tag === "#text"; // Strictly speaking, seeing an <option> doesn't mean we're in a <select> // but case "option": return tag === "#text"; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption // No special behavior since these rules fall back to "in body" mode for // all except special table nodes which cause bad parsing behavior anyway. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr case "tr": return tag === "th" || tag === "td" || tag === "style" || tag === "script" || tag === "template"; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody case "tbody": case "thead": case "tfoot": return tag === "tr" || tag === "style" || tag === "script" || tag === "template"; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup case "colgroup": return tag === "col" || tag === "template"; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable case "table": return ( tag === "caption" || tag === "colgroup" || tag === "tbody" || tag === "tfoot" || tag === "thead" || tag === "style" || tag === "script" || tag === "template" ); // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead case "head": return ( tag === "base" || tag === "basefont" || tag === "bgsound" || tag === "link" || tag === "meta" || tag === "title" || tag === "noscript" || tag === "noframes" || tag === "style" || tag === "script" || tag === "template" ); // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element case "html": return tag === "head" || tag === "body" || tag === "frameset"; case "frameset": return tag === "frame"; case "#document": return tag === "html"; } // Probably in the "in body" parsing mode, so we outlaw only tag combos // where the parsing rules cause implicit opens or closes to be added. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody switch (tag) { case "h1": case "h2": case "h3": case "h4": case "h5": case "h6": return ( parentTag !== "h1" && parentTag !== "h2" && parentTag !== "h3" && parentTag !== "h4" && parentTag !== "h5" && parentTag !== "h6" ); case "rp": case "rt": return impliedEndTags.indexOf(parentTag) === -1; case "body": case "caption": case "col": case "colgroup": case "frameset": case "frame": case "head": case "html": case "tbody": case "td": case "tfoot": case "th": case "thead": case "tr": // These tags are only valid with a few parents that have special child // parsing rules -- if we're down here, then none of those matched and // so we allow it only if we don't know what the parent is, as all other // cases are invalid. return parentTag == null; } return true; }; /** * Returns whether */ const findInvalidAncestorForTag = function(tag: string, ancestorInfo: AncestorInfo) { switch (tag) { case "address": case "article": case "aside": case "blockquote": case "center": case "details": case "dialog": case "dir": case "div": case "dl": case "fieldset": case "figcaption": case "figure": case "footer": case "header": case "hgroup": case "main": case "menu": case "nav": case "ol": case "p": case "section": case "summary": case "ul": case "pre": case "listing": case "table": case "hr": case "xmp": case "h1": case "h2": case "h3": case "h4": case "h5": case "h6": return ancestorInfo.pTagInButtonScope; case "form": return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; case "li": return ancestorInfo.listItemTagAutoclosing; case "dd": case "dt": return ancestorInfo.dlItemTagAutoclosing; case "button": return ancestorInfo.buttonTagInScope; case "a": // Spec says something about storing a list of markers, but it sounds // equivalent to this check. return ancestorInfo.aTagInScope; case "nobr": return ancestorInfo.nobrTagInScope; } return null; }; const didWarn = {}; validateDOMNesting = function( childTag: string | undefined | null, childText: string | undefined | null, ancestorInfo: AncestorInfo | undefined | null ) { ancestorInfo = ancestorInfo || emptyAncestorInfo; const parentInfo: AncestorInfoTagObj = ancestorInfo.current; const parentTag = parentInfo && parentInfo.tag; if (childText != null) { if (childTag != null) { console.warn("validateDOMNesting: when childText is passed, childTag should be null"); } childTag = "#text"; } const invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo; const invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); const invalidParentOrAncestor = invalidParent || invalidAncestor; if (!invalidParentOrAncestor) { return; } const ancestorTag = invalidParentOrAncestor.tag; const addendum = getCurrentFiberStackInDev(); const warnKey = !!invalidParent + "|" + childTag + "|" + ancestorTag + "|" + addendum; if (didWarn[warnKey]) { return; } didWarn[warnKey] = true; let tagDisplayName = childTag; let whitespaceInfo = ""; if (childTag === "#text") { if (/\S/.test(childText)) { tagDisplayName = "Text nodes"; } else { tagDisplayName = "Whitespace text nodes"; whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + "each line of your source code."; } } else { tagDisplayName = "<" + childTag + ">"; } if (invalidParent) { let info = ""; if (ancestorTag === "table" && childTag === "tr") { info += " Add a <tbody> to your code to match the DOM tree generated by " + "the browser."; } console.warn( "validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s%s", tagDisplayName, ancestorTag, whitespaceInfo, info, addendum ); } else { console.warn( "validateDOMNesting(...): %s cannot appear as a descendant of " + "<%s>.%s", tagDisplayName, ancestorTag, addendum ); } }; } export { updatedAncestorInfo, validateDOMNesting };
the_stack
import React, {useMemo, useState} from "react"; import {Card, Input, Row, Select, Button, Form, InputNumber, Spin} from "antd"; import {useApplication} from "../../context/ApplicationProvider"; import {TaskStateClosable} from "../tags/TaskState"; import {badgedOption} from "../tags/BadgedOption"; import {MetricsService} from "../../api/metrics"; import {handleAPIError, handleAPIResponse} from "../../utils/errors"; const {Option} = Select; const FormItem = Form.Item; interface TasksFilterContextData { onFilter(value: {}); filters: any } const loadingIndicator = <Row justify="center" align="middle" style={{width: "100%"}}><Spin size="small"/></Row>; const TaskAttributesFilter: React.FC<TasksFilterContextData> = (props: TasksFilterContextData) => { const {currentEnv, currentApp} = useApplication(); const metricsService = new MetricsService(); const [form] = Form.useForm(); const [seenTasks, setSeenTasks] = useState([]); const [seenRoutingKeys, setSeenRoutingKeys] = useState([]); const [seenQueues, setSeenQueues] = useState([]); const [seenWorkers, setSeenWorkers] = useState([]); // Fetch progress const [seenTasksFetching, setSeenTasksFetching] = useState<boolean>(); const [seenRoutingKeysFetching, setSeenRoutingKeysFetching] = useState<boolean>(); const [seenQueuesFetching, setSeenQueuesFetching] = useState<boolean>(); const [seenWorkersFetching, setSeenWorkersFetching] = useState<boolean>(); // UI Callbacks function handleReset() { form.resetFields(); form.submit() } function onSubmit(filters) { props.onFilter(filters) } function getSeenTasks(open) { if (!currentApp || !open) return; setSeenTasksFetching(true); metricsService.getSeenTasks(currentApp, currentEnv, props.filters) .then(handleAPIResponse) .then((result: any) => { setSeenTasks(result.aggregations.seen_tasks.buckets); }, handleAPIError) .catch(handleAPIError) .finally(() => setSeenTasksFetching(false)); } function getSeenRoutingKeys(open) { if (!currentApp || !open) return; setSeenRoutingKeysFetching(true); metricsService.getSeenRoutingKeys(currentApp, currentEnv, props.filters) .then(handleAPIResponse) .then((result: any) => { setSeenRoutingKeys(result.aggregations.seen_routing_keys.buckets); }, handleAPIError) .catch(handleAPIError) .finally(() => setSeenRoutingKeysFetching(false)); } function getSeenQueues(open) { if (!currentApp || !open) return; setSeenQueuesFetching(true); metricsService.getSeenQueues(currentApp, currentEnv, props.filters) .then(handleAPIResponse) .then((result: any) => { setSeenQueues(result.aggregations.seen_queues.buckets); }, handleAPIError) .catch(handleAPIError) .finally(() => setSeenQueuesFetching(false)); } function getSeenWorkers(open) { if (!currentApp || !open) return; setSeenWorkersFetching(true); metricsService.getSeenWorkers(currentApp, currentEnv, props.filters) .then(handleAPIResponse) .then((result: any) => { setSeenWorkers(result.aggregations.seen_workers.buckets); }, handleAPIError) .catch(handleAPIError) .finally(() => setSeenWorkersFetching(false)); } const memoizedTaskNameOptions = useMemo(() => { // memoize this because it's common to have many different task names, which causes the dropdown to be very laggy. // This is a known problem in Ant Design return seenTasks.map((task, key) => badgedOption(task)) }, [seenTasks]) return ( <Card title={ <Button size="small" type="primary" onClick={form.submit}> Filter </Button> } size={"small"} extra={<Button onClick={handleReset} size="small">Reset</Button>} style={{width: "100%"}} > <Form style={{width: "100%"}} form={form} onFinish={onSubmit} initialValues={{runtime_op: "gte", retries_op: "gte"}}> <Row> <FormItem name="uuid" style={{width: "100%"}}> <Input placeholder="uuid" allowClear/> </FormItem> </Row> <Row> <FormItem name="name" style={{width: "100%"}}> <Select placeholder="Name" mode="multiple" style={{width: "100%"}} allowClear showSearch dropdownMatchSelectWidth={false} onDropdownVisibleChange={getSeenTasks} notFoundContent={seenTasksFetching ? loadingIndicator : null} > {memoizedTaskNameOptions} </Select> </FormItem> </Row> <Row> <FormItem name="state" style={{width: "100%"}}> <Select placeholder="State" mode="multiple" tagRender={TaskStateClosable} style={{width: "100%"}} allowClear> <Option key="QUEUED" value="QUEUED">QUEUED</Option> <Option key="RECEIVED" value="RECEIVED">RECEIVED</Option> <Option key="STARTED" value="STARTED">STARTED</Option> <Option key="SUCCEEDED" value="SUCCEEDED">SUCCEEDED</Option> <Option key="RECOVERED" value="RECOVERED">RECOVERED</Option> <Option key="RETRY" value="RETRY">RETRY</Option> <Option key="FAILED" value="FAILED">FAILED</Option> <Option key="CRITICAL" value="CRITICAL">CRITICAL</Option> <Option key="REJECTED" value="REJECTED">REJECTED</Option> <Option key="REVOKED" value="REVOKED">REVOKED</Option> </Select> </FormItem> </Row> <Row> <FormItem name="routing_key" style={{width: "100%"}}> <Select placeholder="Routing key" mode="multiple" style={{width: "100%"}} notFoundContent={seenRoutingKeysFetching ? loadingIndicator : null} onDropdownVisibleChange={getSeenRoutingKeys} allowClear> { seenRoutingKeys.map((rq, key) => badgedOption(rq)) } </Select> </FormItem> </Row> <Row> <FormItem name="queue" style={{width: "100%"}}> <Select placeholder="Queue" mode="multiple" style={{width: "100%"}} notFoundContent={seenQueuesFetching ? loadingIndicator : null} onDropdownVisibleChange={getSeenQueues} allowClear> { seenQueues.map((queue, key) => badgedOption(queue)) } </Select> </FormItem> </Row> <Row> <FormItem name="worker" style={{width: "100%"}}> <Select placeholder="Worker" mode="multiple" style={{width: "100%"}} notFoundContent={seenWorkersFetching ? loadingIndicator : null} onDropdownVisibleChange={getSeenWorkers} allowClear> { seenWorkers.map((worker, key) => badgedOption(worker)) } </Select> </FormItem> </Row> <Row> <Input.Group compact> <FormItem name="runtime_op" style={{width: "30%"}}> <Select style={{width: '100%'}}> <Option value="gte">{"gte"}</Option> <Option value="lte">{"lte"}</Option> </Select> </FormItem> <FormItem name="runtime" style={{width: "70%"}}> <InputNumber style={{width: '100%'}} min={0} max={10000} step={0.0001} placeholder="Runtime" /> </FormItem> </Input.Group> </Row> <Row> <Input.Group compact> <FormItem name="retries_op" style={{width: "30%"}}> <Select style={{width: '100%'}}> <Option value="gte">{"gte"}</Option> <Option value="lte">{"lte"}</Option> </Select> </FormItem> <FormItem name="retries" style={{width: "70%"}}> <InputNumber style={{width: '100%'}} min={0} max={10000} step={1} placeholder="Retries" /> </FormItem> </Input.Group> </Row> <Row> <FormItem name="exception" style={{width: "100%"}}> <Input placeholder="Exception" allowClear/> </FormItem> </Row> <Row> <FormItem name="traceback" style={{width: "100%"}}> <Input placeholder="Traceback (wildcard, ex: *cel*y*)" allowClear/> </FormItem> </Row> <Row> <FormItem name="args" style={{width: "100%"}}> <Input placeholder="args (wildcard)" allowClear/> </FormItem> </Row> <Row> <FormItem name="kwargs" style={{width: "100%"}}> <Input placeholder="kwargs (wildcard)" allowClear/> </FormItem> </Row> <Row> <FormItem name="result" style={{width: "100%"}}> <Input placeholder="Result (wildcard)" allowClear/> </FormItem> </Row> <Row> <FormItem name="revocation_reason" style={{width: "100%"}}> <Select placeholder="Revocation reason" allowClear> <Option value="expired">{"Expired"}</Option> <Option value="terminated">{"Terminated"}</Option> </Select> </FormItem> </Row> <Row> <FormItem name="rejection_outcome" style={{width: "100%"}}> <Select placeholder="Rejection outcome" allowClear> <Option value="requeued">{"Requeued"}</Option> <Option value="ignored">{"Ignored"}</Option> </Select> </FormItem> </Row> <Row> <FormItem name="root_id" style={{width: "100%"}}> <Input placeholder="Root id" allowClear/> </FormItem> </Row> <Row> <FormItem name="parent_id" style={{width: "100%"}}> <Input placeholder="Parent id" allowClear/> </FormItem> </Row> <Row> <FormItem name="root_name" style={{width: "100%"}}> <Select placeholder="Root name (soon)" disabled={true}> </Select> </FormItem> </Row> <Row> <FormItem name="parent_name" style={{width: "100%"}}> <Select placeholder="Parent name (soon)" disabled={true}> </Select> </FormItem> </Row> </Form> </Card> ); }; export default TaskAttributesFilter
the_stack
import {Debugger} from '../common/debugger'; import {Engine} from '../common/engine'; import {locales} from '../l10n/l10n'; import {Axis, DynamicCstr} from './dynamic_cstr'; export interface MappingsJson { default: {[key: string]: string}; [domainName: string]: {[key: string]: string}; } export interface UnicodeJson { key: string; category: string; names?: string[]; si?: boolean; mappings: MappingsJson; // TODO (TS): It would be nice to handle these in CtrlJson type. But that // leads to a lot of casting at the moment. Maybe have a special ctrl // entry in the overall file Json and handle it there. modality?: string; locale?: string; domain?: string; } export interface SiJson { [key: string]: string; } export interface SimpleRule { cstr: DynamicCstr; action: string; } /** * A base store for simple Math objects. */ export class MathSimpleStore { /** * The category of the character/function/unit. */ public category: string = ''; /** * Maps locales to lists of simple rules. */ public rules: Map<string, SimpleRule[]> = new Map(); /** * Parses a string with a hex representation of a unicode code point into the * corresponding unicode character. * @param num The code point to be parsed. * @return The unicode character. */ public static parseUnicode(num: string): string { let keyValue = parseInt(num, 16); return String.fromCodePoint(keyValue); } /** * Tests whether a speech rule satisfies a set of dynamic constraints. Unless * the engine is in strict mode, the dynamic constraints can be "relaxed", * that is, a default value can also be choosen. * @param dynamic Dynamic constraints. * @param rule The rule. * @return True if the preconditions apply to the node. */ private static testDynamicConstraints_( dynamic: DynamicCstr, rule: SimpleRule): boolean { if (Engine.getInstance().strict) { return rule.cstr.equal(dynamic); } return Engine.getInstance().comparator.match(rule.cstr); } /** * Turns a domain mapping from its JSON representation containing simple * strings only into a list of speech rules. * @param name Name for the rules. * @param str String for precondition and constraints. * @param mapping Simple string * mapping. */ public defineRulesFromMappings( name: string, locale: string, modality: string, str: string, mapping: MappingsJson) { for (let domain in mapping) { for (let style in mapping[domain]) { let content = mapping[domain][style]; this.defineRuleFromStrings( name, locale, modality, domain, style, str, content); } } } /** * Retrieves a store for a given locale string. * @param key The locale key. */ public getRules(key: string) { let store = this.rules.get(key); if (!store) { store = []; this.rules.set(key, store); } return store; } /** * Creates a single rule from strings. * @param name Name of the rule. * @param domain The domain axis. * @param style The style axis. * @param str String for precondition and constraints. * @param content The content for the postcondition. */ public defineRuleFromStrings( _name: string, locale: string, modality: string, domain: string, style: string, _str: string, content: string) { let store = this.getRules(locale); let parser = Engine.getInstance().parsers[domain] || Engine.getInstance().defaultParser; let comp = Engine.getInstance().comparators[domain]; let cstr = `${locale}.${modality}.${domain}.${style}`; let dynamic = parser.parse(cstr); // TODO: Simplify here. No need for comparator? let comparator = comp ? comp() : Engine.getInstance().comparator; let oldCstr = comparator.getReference(); comparator.setReference(dynamic); let rule = {cstr: dynamic, action: content}; store = store.filter(r => !dynamic.equal(r.cstr)); store.push(rule); this.rules.set(locale, store); comparator.setReference(oldCstr); } /** * @override */ public lookupRule(_node: Node, dynamic: DynamicCstr) { let rules = this.getRules(dynamic.getValue(Axis.LOCALE)); rules = rules.filter(function(rule) { return MathSimpleStore.testDynamicConstraints_(dynamic, rule); }); if (rules.length === 1) { return rules[0]; } return rules.length ? rules.sort( (r1, r2) => Engine.getInstance().comparator.compare(r1.cstr, r2.cstr))[0] : null; } } /** * A compound store for simple Math objects. */ export namespace MathCompoundStore { /** * The locale for the store. */ export let locale: string = DynamicCstr.DEFAULT_VALUES[Axis.LOCALE]; /** * The modality of the store. */ export let modality: string = DynamicCstr.DEFAULT_VALUES[Axis.MODALITY]; /** * An association list of SI prefixes. */ export let siPrefixes: SiJson = {}; /** * A set of efficient substores. */ const subStores_: {[key: string]: MathSimpleStore} = {}; /** * Function creates a rule store in the compound store for a particular * string, and populates it with a set of rules. * @param name Name of the rule. * @param str String used as key to refer to the rule store * precondition and constr * @param cat The category if it exists. * @param mappings JSON representation of mappings from styles and * domains to strings, from which the speech rules will be computed. */ export function defineRules(name: string, str: string, cat: string, mappings: MappingsJson) { let store = getSubStore_(str); setupStore_(store, cat); store.defineRulesFromMappings(name, locale, modality, str, mappings); } /** * Creates a single rule from strings. * @param name Name of the rule. * @param domain The domain axis. * @param style The style axis. * @param cat The category if it exists. * @param str String for precondition and constraints. * @param content The content for the postcondition. */ export function defineRule( name: string, domain: string, style: string, cat: string, str: string, content: string) { let store = getSubStore_(str); setupStore_(store, cat); store.defineRuleFromStrings(name, locale, modality, domain, style, str, content); } /** * Makes a speech rule for Unicode characters from its JSON representation. * @param json JSON object of the speech rules. */ export function addSymbolRules(json: UnicodeJson) { if (changeLocale_(json)) { return; } let key = MathSimpleStore.parseUnicode(json['key']); defineRules(json['key'], key, json['category'], json['mappings']); } /** * Makes a speech rule for Function names from its JSON representation. * @param json JSON object of the speech rules. */ export function addFunctionRules(json: UnicodeJson) { if (changeLocale_(json)) { return; } let names = json['names']; let mappings = json['mappings']; let category = json['category']; for (let j = 0, name; name = names[j]; j++) { defineRules(name, name, category, mappings); } } /** * Makes speech rules for Unit descriptors from its JSON representation. * @param json JSON object of the speech rules. */ export function addUnitRules(json: UnicodeJson) { if (changeLocale_(json)) { return; } if (json['si']) { addSiUnitRules(json); return; } addUnitRules_(json); } /** * Makes speech rules for SI units from the JSON representation of the base * unit. * @param json JSON object of the base speech rules. */ export function addSiUnitRules(json: UnicodeJson) { for (let key of Object.keys(siPrefixes)) { let newJson = Object.assign({}, json); newJson.mappings = {} as MappingsJson; let prefix = siPrefixes[key]; newJson['key'] = key + newJson['key']; newJson['names'] = newJson['names'].map(function(name) { return key + name; }); for (let domain of Object.keys(json['mappings'])) { newJson.mappings[domain] = {}; for (let style of Object.keys(json['mappings'][domain])) { // TODO: This should not really call the locale method. newJson['mappings'][domain][style] = locales[locale]().FUNCTIONS.si( prefix, json['mappings'][domain][style]); } } addUnitRules_(newJson); } addUnitRules_(json); } /** * Retrieves a rule for the given node if one exists. * @param node A node. * @param dynamic Additional dynamic * constraints. These are matched against properties of a rule. * @return The speech rule if it exists. */ export function lookupRule(node: string, dynamic: DynamicCstr): SimpleRule { let store = subStores_[node]; return store ? store.lookupRule(null, dynamic) : null; } /** * Retrieves the category of a character or string if it has one. * @param character The character or string. * @return The category if it exists. */ export function lookupCategory(character: string): string { let store = subStores_[character]; return store ? store.category : ''; } /** * Looks up a rule for a given string and executes its actions. * @param text The text to be translated. * @param dynamic Additional dynamic * constraints. These are matched against properties of a rule. * @return The string resulting from the action of speech rule. */ export function lookupString(text: string, dynamic: DynamicCstr): string { let rule = lookupRule(text, dynamic); if (!rule) { return null; } return rule.action; } /** * Collates information on dynamic constraint values of the currently active * trie of the engine. * @param opt_info Initial dynamic constraint information. * @return The collated information. */ export function enumerate(info: Object = {}): Object { for (let store of Object.values(subStores_)) { for (let [_locale, rules] of store.rules.entries()) { for (let {cstr: dynamic} of rules) { info = enumerate_(dynamic.getValues(), info); } } } return info; } function enumerate_(dynamic: string[], info: {[key: string]: any}): {[key: string]: any} { info = info || {}; if (!dynamic.length) { return info; } info[dynamic[0]] = enumerate_(dynamic.slice(1), info[dynamic[0]]); return info; } /** * Adds a single speech rule for Unit descriptors from its JSON * representation. * @param json JSON object of the speech rules. */ function addUnitRules_(json: UnicodeJson) { let names = json['names']; if (names) { json['names'] = names.map(function(name) { return name + ':' + 'unit'; }); } addFunctionRules(json); } /** * Changes the internal locale for the rule definitions if the given JSON * element is a locale instruction. * @param json JSON object of a speech rules. * @return True if the locale was changed. */ function changeLocale_(json: UnicodeJson): boolean { if (!json['locale'] && !json['modality']) { return false; } locale = json['locale'] || locale; modality = json['modality'] || modality; return true; } /** * Retrieves a substore for a key. Creates a new one if it does not exist. * @param key The key for the store. * @return The rule store. */ function getSubStore_(key: string): MathSimpleStore { let store = subStores_[key]; if (store) { Debugger.getInstance().output('Store exists! ' + key); return store; } store = new MathSimpleStore(); subStores_[key] = store; return store; } /** * Transfers parameters of the compound store to a substore. * @param opt_cat The category if it exists. */ function setupStore_(store: MathSimpleStore, opt_cat?: string) { if (opt_cat) { store.category = opt_cat; } } }
the_stack
import { RequestParameters } from "@azure-rest/core-client"; import { Product, Sku, SubProduct } from "./models"; export interface LROsPut200SucceededBodyParam { /** Product to put */ body?: Product; } export interface LROsPut200SucceededMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPut200SucceededParameters = LROsPut200SucceededMediaTypesParam & LROsPut200SucceededBodyParam & RequestParameters; export interface LROsPatch200SucceededIgnoreHeadersBodyParam { /** Product to patch */ body?: Product; } export interface LROsPatch200SucceededIgnoreHeadersMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPatch200SucceededIgnoreHeadersParameters = LROsPatch200SucceededIgnoreHeadersMediaTypesParam & LROsPatch200SucceededIgnoreHeadersBodyParam & RequestParameters; export interface LROsPut201SucceededBodyParam { /** Product to put */ body?: Product; } export interface LROsPut201SucceededMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPut201SucceededParameters = LROsPut201SucceededMediaTypesParam & LROsPut201SucceededBodyParam & RequestParameters; export type LROsPost202ListParameters = RequestParameters; export interface LROsPut200SucceededNoStateBodyParam { /** Product to put */ body?: Product; } export interface LROsPut200SucceededNoStateMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPut200SucceededNoStateParameters = LROsPut200SucceededNoStateMediaTypesParam & LROsPut200SucceededNoStateBodyParam & RequestParameters; export interface LROsPut202Retry200BodyParam { /** Product to put */ body?: Product; } export interface LROsPut202Retry200MediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPut202Retry200Parameters = LROsPut202Retry200MediaTypesParam & LROsPut202Retry200BodyParam & RequestParameters; export interface LROsPut201CreatingSucceeded200BodyParam { /** Product to put */ body?: Product; } export interface LROsPut201CreatingSucceeded200MediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPut201CreatingSucceeded200Parameters = LROsPut201CreatingSucceeded200MediaTypesParam & LROsPut201CreatingSucceeded200BodyParam & RequestParameters; export interface LROsPut200UpdatingSucceeded204BodyParam { /** Product to put */ body?: Product; } export interface LROsPut200UpdatingSucceeded204MediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPut200UpdatingSucceeded204Parameters = LROsPut200UpdatingSucceeded204MediaTypesParam & LROsPut200UpdatingSucceeded204BodyParam & RequestParameters; export interface LROsPut201CreatingFailed200BodyParam { /** Product to put */ body?: Product; } export interface LROsPut201CreatingFailed200MediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPut201CreatingFailed200Parameters = LROsPut201CreatingFailed200MediaTypesParam & LROsPut201CreatingFailed200BodyParam & RequestParameters; export interface LROsPut200Acceptedcanceled200BodyParam { /** Product to put */ body?: Product; } export interface LROsPut200Acceptedcanceled200MediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPut200Acceptedcanceled200Parameters = LROsPut200Acceptedcanceled200MediaTypesParam & LROsPut200Acceptedcanceled200BodyParam & RequestParameters; export interface LROsPutNoHeaderInRetryBodyParam { /** Product to put */ body?: Product; } export interface LROsPutNoHeaderInRetryMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPutNoHeaderInRetryParameters = LROsPutNoHeaderInRetryMediaTypesParam & LROsPutNoHeaderInRetryBodyParam & RequestParameters; export interface LROsPutAsyncRetrySucceededBodyParam { /** Product to put */ body?: Product; } export interface LROsPutAsyncRetrySucceededMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPutAsyncRetrySucceededParameters = LROsPutAsyncRetrySucceededMediaTypesParam & LROsPutAsyncRetrySucceededBodyParam & RequestParameters; export interface LROsPutAsyncNoRetrySucceededBodyParam { /** Product to put */ body?: Product; } export interface LROsPutAsyncNoRetrySucceededMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPutAsyncNoRetrySucceededParameters = LROsPutAsyncNoRetrySucceededMediaTypesParam & LROsPutAsyncNoRetrySucceededBodyParam & RequestParameters; export interface LROsPutAsyncRetryFailedBodyParam { /** Product to put */ body?: Product; } export interface LROsPutAsyncRetryFailedMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPutAsyncRetryFailedParameters = LROsPutAsyncRetryFailedMediaTypesParam & LROsPutAsyncRetryFailedBodyParam & RequestParameters; export interface LROsPutAsyncNoRetrycanceledBodyParam { /** Product to put */ body?: Product; } export interface LROsPutAsyncNoRetrycanceledMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPutAsyncNoRetrycanceledParameters = LROsPutAsyncNoRetrycanceledMediaTypesParam & LROsPutAsyncNoRetrycanceledBodyParam & RequestParameters; export interface LROsPutAsyncNoHeaderInRetryBodyParam { /** Product to put */ body?: Product; } export interface LROsPutAsyncNoHeaderInRetryMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPutAsyncNoHeaderInRetryParameters = LROsPutAsyncNoHeaderInRetryMediaTypesParam & LROsPutAsyncNoHeaderInRetryBodyParam & RequestParameters; export interface LROsPutNonResourceBodyParam { /** sku to put */ body?: Sku; } export interface LROsPutNonResourceMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPutNonResourceParameters = LROsPutNonResourceMediaTypesParam & LROsPutNonResourceBodyParam & RequestParameters; export interface LROsPutAsyncNonResourceBodyParam { /** Sku to put */ body?: Sku; } export interface LROsPutAsyncNonResourceMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPutAsyncNonResourceParameters = LROsPutAsyncNonResourceMediaTypesParam & LROsPutAsyncNonResourceBodyParam & RequestParameters; export interface LROsPutSubResourceBodyParam { /** Sub Product to put */ body?: SubProduct; } export interface LROsPutSubResourceMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPutSubResourceParameters = LROsPutSubResourceMediaTypesParam & LROsPutSubResourceBodyParam & RequestParameters; export interface LROsPutAsyncSubResourceBodyParam { /** Sub Product to put */ body?: SubProduct; } export interface LROsPutAsyncSubResourceMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPutAsyncSubResourceParameters = LROsPutAsyncSubResourceMediaTypesParam & LROsPutAsyncSubResourceBodyParam & RequestParameters; export type LROsDeleteProvisioning202Accepted200SucceededParameters = RequestParameters; export type LROsDeleteProvisioning202DeletingFailed200Parameters = RequestParameters; export type LROsDeleteProvisioning202Deletingcanceled200Parameters = RequestParameters; export type LROsDelete204SucceededParameters = RequestParameters; export type LROsDelete202Retry200Parameters = RequestParameters; export type LROsDelete202NoRetry204Parameters = RequestParameters; export type LROsDeleteNoHeaderInRetryParameters = RequestParameters; export type LROsDeleteAsyncNoHeaderInRetryParameters = RequestParameters; export type LROsDeleteAsyncRetrySucceededParameters = RequestParameters; export type LROsDeleteAsyncNoRetrySucceededParameters = RequestParameters; export type LROsDeleteAsyncRetryFailedParameters = RequestParameters; export type LROsDeleteAsyncRetrycanceledParameters = RequestParameters; export type LROsPost200WithPayloadParameters = RequestParameters; export interface LROsPost202Retry200BodyParam { /** Product to put */ body?: Product; } export interface LROsPost202Retry200MediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPost202Retry200Parameters = LROsPost202Retry200MediaTypesParam & LROsPost202Retry200BodyParam & RequestParameters; export interface LROsPost202NoRetry204BodyParam { /** Product to put */ body?: Product; } export interface LROsPost202NoRetry204MediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPost202NoRetry204Parameters = LROsPost202NoRetry204MediaTypesParam & LROsPost202NoRetry204BodyParam & RequestParameters; export type LROsPostDoubleHeadersFinalLocationGetParameters = RequestParameters; export type LROsPostDoubleHeadersFinalAzureHeaderGetParameters = RequestParameters; export type LROsPostDoubleHeadersFinalAzureHeaderGetDefaultParameters = RequestParameters; export interface LROsPostAsyncRetrySucceededBodyParam { /** Product to put */ body?: Product; } export interface LROsPostAsyncRetrySucceededMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPostAsyncRetrySucceededParameters = LROsPostAsyncRetrySucceededMediaTypesParam & LROsPostAsyncRetrySucceededBodyParam & RequestParameters; export interface LROsPostAsyncNoRetrySucceededBodyParam { /** Product to put */ body?: Product; } export interface LROsPostAsyncNoRetrySucceededMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPostAsyncNoRetrySucceededParameters = LROsPostAsyncNoRetrySucceededMediaTypesParam & LROsPostAsyncNoRetrySucceededBodyParam & RequestParameters; export interface LROsPostAsyncRetryFailedBodyParam { /** Product to put */ body?: Product; } export interface LROsPostAsyncRetryFailedMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPostAsyncRetryFailedParameters = LROsPostAsyncRetryFailedMediaTypesParam & LROsPostAsyncRetryFailedBodyParam & RequestParameters; export interface LROsPostAsyncRetrycanceledBodyParam { /** Product to put */ body?: Product; } export interface LROsPostAsyncRetrycanceledMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsPostAsyncRetrycanceledParameters = LROsPostAsyncRetrycanceledMediaTypesParam & LROsPostAsyncRetrycanceledBodyParam & RequestParameters; export interface LRORetrysPut201CreatingSucceeded200BodyParam { /** Product to put */ body?: Product; } export interface LRORetrysPut201CreatingSucceeded200MediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LRORetrysPut201CreatingSucceeded200Parameters = LRORetrysPut201CreatingSucceeded200MediaTypesParam & LRORetrysPut201CreatingSucceeded200BodyParam & RequestParameters; export interface LRORetrysPutAsyncRelativeRetrySucceededBodyParam { /** Product to put */ body?: Product; } export interface LRORetrysPutAsyncRelativeRetrySucceededMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LRORetrysPutAsyncRelativeRetrySucceededParameters = LRORetrysPutAsyncRelativeRetrySucceededMediaTypesParam & LRORetrysPutAsyncRelativeRetrySucceededBodyParam & RequestParameters; export type LRORetrysDeleteProvisioning202Accepted200SucceededParameters = RequestParameters; export type LRORetrysDelete202Retry200Parameters = RequestParameters; export type LRORetrysDeleteAsyncRelativeRetrySucceededParameters = RequestParameters; export interface LRORetrysPost202Retry200BodyParam { /** Product to put */ body?: Product; } export interface LRORetrysPost202Retry200MediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LRORetrysPost202Retry200Parameters = LRORetrysPost202Retry200MediaTypesParam & LRORetrysPost202Retry200BodyParam & RequestParameters; export interface LRORetrysPostAsyncRelativeRetrySucceededBodyParam { /** Product to put */ body?: Product; } export interface LRORetrysPostAsyncRelativeRetrySucceededMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LRORetrysPostAsyncRelativeRetrySucceededParameters = LRORetrysPostAsyncRelativeRetrySucceededMediaTypesParam & LRORetrysPostAsyncRelativeRetrySucceededBodyParam & RequestParameters; export interface LrosaDsPutNonRetry400BodyParam { /** Product to put */ body?: Product; } export interface LrosaDsPutNonRetry400MediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LrosaDsPutNonRetry400Parameters = LrosaDsPutNonRetry400MediaTypesParam & LrosaDsPutNonRetry400BodyParam & RequestParameters; export interface LrosaDsPutNonRetry201Creating400BodyParam { /** Product to put */ body?: Product; } export interface LrosaDsPutNonRetry201Creating400MediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LrosaDsPutNonRetry201Creating400Parameters = LrosaDsPutNonRetry201Creating400MediaTypesParam & LrosaDsPutNonRetry201Creating400BodyParam & RequestParameters; export interface LrosaDsPutNonRetry201Creating400InvalidJsonBodyParam { /** Product to put */ body?: Product; } export interface LrosaDsPutNonRetry201Creating400InvalidJsonMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LrosaDsPutNonRetry201Creating400InvalidJsonParameters = LrosaDsPutNonRetry201Creating400InvalidJsonMediaTypesParam & LrosaDsPutNonRetry201Creating400InvalidJsonBodyParam & RequestParameters; export interface LrosaDsPutAsyncRelativeRetry400BodyParam { /** Product to put */ body?: Product; } export interface LrosaDsPutAsyncRelativeRetry400MediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LrosaDsPutAsyncRelativeRetry400Parameters = LrosaDsPutAsyncRelativeRetry400MediaTypesParam & LrosaDsPutAsyncRelativeRetry400BodyParam & RequestParameters; export type LrosaDsDeleteNonRetry400Parameters = RequestParameters; export type LrosaDsDelete202NonRetry400Parameters = RequestParameters; export type LrosaDsDeleteAsyncRelativeRetry400Parameters = RequestParameters; export interface LrosaDsPostNonRetry400BodyParam { /** Product to put */ body?: Product; } export interface LrosaDsPostNonRetry400MediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LrosaDsPostNonRetry400Parameters = LrosaDsPostNonRetry400MediaTypesParam & LrosaDsPostNonRetry400BodyParam & RequestParameters; export interface LrosaDsPost202NonRetry400BodyParam { /** Product to put */ body?: Product; } export interface LrosaDsPost202NonRetry400MediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LrosaDsPost202NonRetry400Parameters = LrosaDsPost202NonRetry400MediaTypesParam & LrosaDsPost202NonRetry400BodyParam & RequestParameters; export interface LrosaDsPostAsyncRelativeRetry400BodyParam { /** Product to put */ body?: Product; } export interface LrosaDsPostAsyncRelativeRetry400MediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LrosaDsPostAsyncRelativeRetry400Parameters = LrosaDsPostAsyncRelativeRetry400MediaTypesParam & LrosaDsPostAsyncRelativeRetry400BodyParam & RequestParameters; export interface LrosaDsPutError201NoProvisioningStatePayloadBodyParam { /** Product to put */ body?: Product; } export interface LrosaDsPutError201NoProvisioningStatePayloadMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LrosaDsPutError201NoProvisioningStatePayloadParameters = LrosaDsPutError201NoProvisioningStatePayloadMediaTypesParam & LrosaDsPutError201NoProvisioningStatePayloadBodyParam & RequestParameters; export interface LrosaDsPutAsyncRelativeRetryNoStatusBodyParam { /** Product to put */ body?: Product; } export interface LrosaDsPutAsyncRelativeRetryNoStatusMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LrosaDsPutAsyncRelativeRetryNoStatusParameters = LrosaDsPutAsyncRelativeRetryNoStatusMediaTypesParam & LrosaDsPutAsyncRelativeRetryNoStatusBodyParam & RequestParameters; export interface LrosaDsPutAsyncRelativeRetryNoStatusPayloadBodyParam { /** Product to put */ body?: Product; } export interface LrosaDsPutAsyncRelativeRetryNoStatusPayloadMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LrosaDsPutAsyncRelativeRetryNoStatusPayloadParameters = LrosaDsPutAsyncRelativeRetryNoStatusPayloadMediaTypesParam & LrosaDsPutAsyncRelativeRetryNoStatusPayloadBodyParam & RequestParameters; export type LrosaDsDelete204SucceededParameters = RequestParameters; export type LrosaDsDeleteAsyncRelativeRetryNoStatusParameters = RequestParameters; export interface LrosaDsPost202NoLocationBodyParam { /** Product to put */ body?: Product; } export interface LrosaDsPost202NoLocationMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LrosaDsPost202NoLocationParameters = LrosaDsPost202NoLocationMediaTypesParam & LrosaDsPost202NoLocationBodyParam & RequestParameters; export interface LrosaDsPostAsyncRelativeRetryNoPayloadBodyParam { /** Product to put */ body?: Product; } export interface LrosaDsPostAsyncRelativeRetryNoPayloadMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LrosaDsPostAsyncRelativeRetryNoPayloadParameters = LrosaDsPostAsyncRelativeRetryNoPayloadMediaTypesParam & LrosaDsPostAsyncRelativeRetryNoPayloadBodyParam & RequestParameters; export interface LrosaDsPut200InvalidJsonBodyParam { /** Product to put */ body?: Product; } export interface LrosaDsPut200InvalidJsonMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LrosaDsPut200InvalidJsonParameters = LrosaDsPut200InvalidJsonMediaTypesParam & LrosaDsPut200InvalidJsonBodyParam & RequestParameters; export interface LrosaDsPutAsyncRelativeRetryInvalidHeaderBodyParam { /** Product to put */ body?: Product; } export interface LrosaDsPutAsyncRelativeRetryInvalidHeaderMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LrosaDsPutAsyncRelativeRetryInvalidHeaderParameters = LrosaDsPutAsyncRelativeRetryInvalidHeaderMediaTypesParam & LrosaDsPutAsyncRelativeRetryInvalidHeaderBodyParam & RequestParameters; export interface LrosaDsPutAsyncRelativeRetryInvalidJsonPollingBodyParam { /** Product to put */ body?: Product; } export interface LrosaDsPutAsyncRelativeRetryInvalidJsonPollingMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LrosaDsPutAsyncRelativeRetryInvalidJsonPollingParameters = LrosaDsPutAsyncRelativeRetryInvalidJsonPollingMediaTypesParam & LrosaDsPutAsyncRelativeRetryInvalidJsonPollingBodyParam & RequestParameters; export type LrosaDsDelete202RetryInvalidHeaderParameters = RequestParameters; export type LrosaDsDeleteAsyncRelativeRetryInvalidHeaderParameters = RequestParameters; export type LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingParameters = RequestParameters; export interface LrosaDsPost202RetryInvalidHeaderBodyParam { /** Product to put */ body?: Product; } export interface LrosaDsPost202RetryInvalidHeaderMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LrosaDsPost202RetryInvalidHeaderParameters = LrosaDsPost202RetryInvalidHeaderMediaTypesParam & LrosaDsPost202RetryInvalidHeaderBodyParam & RequestParameters; export interface LrosaDsPostAsyncRelativeRetryInvalidHeaderBodyParam { /** Product to put */ body?: Product; } export interface LrosaDsPostAsyncRelativeRetryInvalidHeaderMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LrosaDsPostAsyncRelativeRetryInvalidHeaderParameters = LrosaDsPostAsyncRelativeRetryInvalidHeaderMediaTypesParam & LrosaDsPostAsyncRelativeRetryInvalidHeaderBodyParam & RequestParameters; export interface LrosaDsPostAsyncRelativeRetryInvalidJsonPollingBodyParam { /** Product to put */ body?: Product; } export interface LrosaDsPostAsyncRelativeRetryInvalidJsonPollingMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LrosaDsPostAsyncRelativeRetryInvalidJsonPollingParameters = LrosaDsPostAsyncRelativeRetryInvalidJsonPollingMediaTypesParam & LrosaDsPostAsyncRelativeRetryInvalidJsonPollingBodyParam & RequestParameters; export interface LROsCustomHeaderPutAsyncRetrySucceededBodyParam { /** Product to put */ body?: Product; } export interface LROsCustomHeaderPutAsyncRetrySucceededMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsCustomHeaderPutAsyncRetrySucceededParameters = LROsCustomHeaderPutAsyncRetrySucceededMediaTypesParam & LROsCustomHeaderPutAsyncRetrySucceededBodyParam & RequestParameters; export interface LROsCustomHeaderPut201CreatingSucceeded200BodyParam { /** Product to put */ body?: Product; } export interface LROsCustomHeaderPut201CreatingSucceeded200MediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsCustomHeaderPut201CreatingSucceeded200Parameters = LROsCustomHeaderPut201CreatingSucceeded200MediaTypesParam & LROsCustomHeaderPut201CreatingSucceeded200BodyParam & RequestParameters; export interface LROsCustomHeaderPost202Retry200BodyParam { /** Product to put */ body?: Product; } export interface LROsCustomHeaderPost202Retry200MediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsCustomHeaderPost202Retry200Parameters = LROsCustomHeaderPost202Retry200MediaTypesParam & LROsCustomHeaderPost202Retry200BodyParam & RequestParameters; export interface LROsCustomHeaderPostAsyncRetrySucceededBodyParam { /** Product to put */ body?: Product; } export interface LROsCustomHeaderPostAsyncRetrySucceededMediaTypesParam { /** Request content type */ contentType?: "application/json"; } export type LROsCustomHeaderPostAsyncRetrySucceededParameters = LROsCustomHeaderPostAsyncRetrySucceededMediaTypesParam & LROsCustomHeaderPostAsyncRetrySucceededBodyParam & RequestParameters;
the_stack
import {InfectionExposureRepository, InstallationRepository, PatientRepository} from '../../../repositories'; import {testdb} from '../../fixtures/datasources/testdb.datasource'; import {InfectionExposure, Patient} from "../../../models"; import {PushNotificationService} from "../../../services/pushnotification.service"; import {PatientService} from "../../../services/patient.service"; import {UserValidatorMockService} from "../../../services/impl/user-validator-mock.service"; import {EcdcExposureRiskDecisor} from "../../../services/impl/ecdc-exposure-risk-decisor"; import {expect} from "@loopback/testlab"; import {PatientStatus} from "../../../common/utils/enums"; import {InfectionExposureController} from "../../../controllers"; describe('ExposureRiskDecisor (integration)', () => { let patientRepository: PatientRepository; let infectionExposureRepository: InfectionExposureRepository; let patientService: PatientService; let infectionExposureController: InfectionExposureController; beforeEach(prepareRepositoriesAndServices); function prepareRepositoriesAndServices() { //set the exposure risk level to HIGHT process.env.EXPOSURE_RISK_LEVEL_TO_QUARANTINE = 'HIGH'; patientRepository = new PatientRepository(testdb); infectionExposureRepository = new InfectionExposureRepository(testdb); patientService = new PatientService(patientRepository, new UserValidatorMockService(), new PushNotificationService(new InstallationRepository(testdb)), new EcdcExposureRiskDecisor(patientRepository) ); infectionExposureController = new InfectionExposureController( patientService, infectionExposureRepository ); } describe('decideRisk(infectionExposures)', () => { it('decide risk based on ONE single infection exposure entries', async () => { let patient: Patient = new Patient(); patient.firstName = 'Antuan'; patient.lastName = 'Parrax'; patient.documentNumber = '443512342N'; patient.birthday = new Date(); let result: Patient| null= await patientService.signUpPatient(patient); expect(result).to.not.null(); expect(result).to.containEql({status: PatientStatus.UNKNOWN}); if(result != null) { let infectionExposure = new InfectionExposure(); infectionExposure.patientId = result.id; infectionExposure.timestampFrom = new Date().getTime() - 3600000; infectionExposure.timestampTo = new Date().getTime() - 1400000; infectionExposure.rssi = -30; infectionExposure.anonymizedInfectedUuid = '55555'; let infectionExposures = new Array(); infectionExposures.push(infectionExposure); await infectionExposureController.createAll(infectionExposures); let patientFromDb = await patientRepository.findById(result.id); expect(patientFromDb).to.not.null(); expect(patientFromDb).to.containEql({status: PatientStatus.INFECTION_SUSPECTED}); } }); it('HIGH risk based on 2 single infection exposure entries', async () => { let patient: Patient = new Patient(); patient.firstName = 'Antuan'; patient.lastName = 'Parrax'; patient.documentNumber = '447546712N'; patient.birthday = new Date(); let result: Patient| null= await patientService.signUpPatient(patient); expect(result).to.not.null(); expect(result).to.containEql({status: PatientStatus.UNKNOWN}); if(result != null) { let infectionExposures = new Array(); let infectionExposure = new InfectionExposure(); infectionExposure.patientId = result.id; infectionExposure.timestampFrom = new Date().getTime() - 4200000; infectionExposure.timestampTo = new Date().getTime() - 4100000; infectionExposure.rssi = -60; infectionExposure.anonymizedInfectedUuid = '44444'; infectionExposures.push(infectionExposure); infectionExposure = new InfectionExposure(); infectionExposure.patientId = result.id; infectionExposure.timestampFrom = new Date().getTime() - 2450000; infectionExposure.timestampTo = new Date().getTime() - 2430000; infectionExposure.rssi = -40; infectionExposure.anonymizedInfectedUuid = '44444'; infectionExposures.push(infectionExposure); //the algo is expected to join both exposures so: average rssi: -50, average distance: 0.11220184543019636, total time exposed: 1650000 (4100000 - 2450000) await infectionExposureController.createAll(infectionExposures); let patientFromDb = await patientRepository.findById(result.id); expect(patientFromDb).to.not.null(); expect(patientFromDb).to.containEql({status: PatientStatus.INFECTION_SUSPECTED}); } }); it('LOW risk based on 2 single infection exposure entries', async () => { let patient: Patient = new Patient(); patient.firstName = 'Antuan'; patient.lastName = 'Parrax'; patient.documentNumber = '423446712R'; patient.birthday = new Date(); let result: Patient| null= await patientService.signUpPatient(patient); expect(result).to.not.null(); expect(result).to.containEql({status: PatientStatus.UNKNOWN}); if(result != null) { result.status = PatientStatus.UNINFECTED; result.firstName = 'Anthony'; await patientRepository.save(result); let patientFromDb = await patientRepository.findById(result.id); expect(patientFromDb).to.not.null(); expect(patientFromDb).to.containEql({status: PatientStatus.UNINFECTED}); let infectionExposures = new Array(); let infectionExposure = new InfectionExposure(); infectionExposure.patientId = result.id; infectionExposure.timestampFrom = new Date().getTime() - 14200000; infectionExposure.timestampTo = new Date().getTime() - 14100000; infectionExposure.rssi = -60; infectionExposure.anonymizedInfectedUuid = '44444'; infectionExposures.push(infectionExposure); infectionExposure = new InfectionExposure(); infectionExposure.patientId = result.id; infectionExposure.timestampFrom = new Date().getTime() - 2450000; infectionExposure.timestampTo = new Date().getTime() - 2430000; infectionExposure.rssi = -40; infectionExposure.anonymizedInfectedUuid = '44444'; infectionExposures.push(infectionExposure); //the algo is expected to join both exposures so: average rssi: -50, average distance: 0.11220184543019636, total time exposed: 120000 ((14200000 - 14100000) + (2450000 - 2430000)) //because the separation of timestamps between both infection exposures is greater than 30 minutes //take into account that the algo just unify infection exposures that are so closed in time (at least less than 30 minutes) await infectionExposureController.createAll(infectionExposures); patientFromDb = await patientRepository.findById(result.id); expect(patientFromDb).to.not.null(); expect(patientFromDb).to.containEql({status: PatientStatus.UNKNOWN}); // ------------------------------------------------------------------------ //Now check that LOW priority or even HIGH priority does not change if the patient //is already infected patientFromDb.status = PatientStatus.INFECTED; await patientRepository.save(patientFromDb); patientFromDb = await patientRepository.findById(result.id); expect(patientFromDb).to.not.null(); expect(patientFromDb).to.containEql({status: PatientStatus.INFECTED}); infectionExposure = new InfectionExposure(); infectionExposure.patientId = result.id; infectionExposure.timestampFrom = new Date().getTime() - 14200000; infectionExposure.timestampTo = new Date().getTime() - 14100000; infectionExposure.rssi = -60; infectionExposure.anonymizedInfectedUuid = '77777'; infectionExposures.push(infectionExposure); infectionExposure = new InfectionExposure(); infectionExposure.patientId = result.id; infectionExposure.timestampFrom = new Date().getTime() - 2450000; infectionExposure.timestampTo = new Date().getTime() - 2430000; infectionExposure.rssi = -40; infectionExposure.anonymizedInfectedUuid = '77777'; infectionExposures.push(infectionExposure); await infectionExposureController.createAll(infectionExposures); patientFromDb = await patientRepository.findById(result.id); expect(patientFromDb).to.not.null(); expect(patientFromDb).to.containEql({status: PatientStatus.INFECTED}); // ------------------------------------------------------------------------ //Now check that LOW priority does not change if the patient //is already infection suspected patientFromDb.status = PatientStatus.INFECTION_SUSPECTED; await patientRepository.save(patientFromDb); patientFromDb = await patientRepository.findById(result.id); expect(patientFromDb).to.not.null(); expect(patientFromDb).to.containEql({status: PatientStatus.INFECTION_SUSPECTED}); infectionExposure = new InfectionExposure(); infectionExposure.patientId = result.id; infectionExposure.timestampFrom = new Date().getTime() - 14200000; infectionExposure.timestampTo = new Date().getTime() - 14100000; infectionExposure.rssi = -60; infectionExposure.anonymizedInfectedUuid = '123098'; infectionExposures.push(infectionExposure); infectionExposure = new InfectionExposure(); infectionExposure.patientId = result.id; infectionExposure.timestampFrom = new Date().getTime() - 2450000; infectionExposure.timestampTo = new Date().getTime() - 2430000; infectionExposure.rssi = -40; infectionExposure.anonymizedInfectedUuid = '123098'; infectionExposures.push(infectionExposure); await infectionExposureController.createAll(infectionExposures); patientFromDb = await patientRepository.findById(result.id); expect(patientFromDb).to.not.null(); expect(patientFromDb).to.containEql({status: PatientStatus.INFECTION_SUSPECTED}); } }); it('HIGH risk based on 4 single infection exposure entries', async () => { let patient: Patient = new Patient(); patient.firstName = 'Antuan'; patient.lastName = 'Parrax'; patient.documentNumber = '447523712H'; patient.birthday = new Date(); let result: Patient| null= await patientService.signUpPatient(patient); expect(result).to.not.null(); expect(result).to.containEql({status: PatientStatus.UNKNOWN}); if(result != null) { let infectionExposures = new Array(); let infectionExposure = new InfectionExposure(); infectionExposure.patientId = result.id; infectionExposure.timestampFrom = new Date().getTime() - 14200000; infectionExposure.timestampTo = new Date().getTime() - 14100000; infectionExposure.rssi = -60; infectionExposure.anonymizedInfectedUuid = '123456'; infectionExposures.push(infectionExposure); infectionExposure = new InfectionExposure(); infectionExposure.patientId = result.id; infectionExposure.timestampFrom = new Date().getTime() - 22450000; infectionExposure.timestampTo = new Date().getTime() - 21830000; infectionExposure.rssi = -40; infectionExposure.anonymizedInfectedUuid = '123456'; infectionExposures.push(infectionExposure); infectionExposure = new InfectionExposure(); infectionExposure.patientId = result.id; infectionExposure.timestampFrom = new Date().getTime() - 450000; infectionExposure.timestampTo = new Date().getTime() - 130000; infectionExposure.rssi = -40; infectionExposure.anonymizedInfectedUuid = '123456'; infectionExposures.push(infectionExposure); //the algo is expected to join both exposures so: average rssi: -50, average distance: 0.11220184543019636, total time exposed: 1650000 (4100000 - 2450000) await infectionExposureController.createAll(infectionExposures); let patientFromDb = await patientRepository.findById(result.id); expect(patientFromDb).to.not.null(); expect(patientFromDb).to.containEql({status: PatientStatus.INFECTION_SUSPECTED}); } }); }); });
the_stack
import { MutableRefObject, RefObject, useMemo, useRef, useState } from "react"; import { Middleware, VirtualElement, arrow, autoUpdate, computePosition, flip, offset, shift, size, } from "@floating-ui/dom"; import { useEvent, useForceUpdate, useSafeLayoutEffect, } from "ariakit-utils/hooks"; import { SetState } from "ariakit-utils/types"; import { DialogState, DialogStateProps, useDialogState, } from "../dialog/dialog-state"; type BasePlacement = "top" | "bottom" | "left" | "right"; type Placement = | BasePlacement | `${BasePlacement}-start` | `${BasePlacement}-end`; type AnchorRect = { x?: number; y?: number; width?: number; height?: number; }; const middlewares = { arrow, flip, offset, shift, size }; function createDOMRect(x = 0, y = 0, width = 0, height = 0) { if (typeof DOMRect === "function") { return new DOMRect(x, y, width, height); } // JSDOM doesn't support DOMRect constructor. const rect = { x, y, width, height, top: y, right: x + width, bottom: y + height, left: x, }; return { ...rect, toJSON: () => rect }; } function getDOMRect(anchorRect?: AnchorRect | null) { if (!anchorRect) return createDOMRect(); const { x, y, width, height } = anchorRect; return createDOMRect(x, y, width, height); } function getAnchorElement( anchorRef: RefObject<HTMLElement | null>, getAnchorRect: (anchor: HTMLElement | null) => AnchorRect | null ) { // https://floating-ui.com/docs/virtual-elements const contextElement = anchorRef.current || undefined; return { contextElement, getBoundingClientRect: () => { const anchor = anchorRef.current; const anchorRect = getAnchorRect(anchor); if (anchorRect || !anchor) { return getDOMRect(anchorRect); } return anchor.getBoundingClientRect(); }, }; } function isValidPlacement(flip: string): flip is Placement { return /^(?:top|bottom|left|right)(?:-(?:start|end))?$/.test(flip); } /** * Provides state for the `Popover` components. * @example * ```jsx * const popover = usePopoverState(); * <PopoverDisclosure state={popover}>Disclosure</PopoverDisclosure> * <Popover state={popover}>Popover</Popover> * ``` */ export function usePopoverState({ placement = "bottom", fixed = false, gutter, flip = true, shift = 0, slide = true, overlap = false, sameWidth = false, fitViewport = false, arrowPadding = 4, overflowPadding = 8, renderCallback, ...props }: PopoverStateProps = {}): PopoverState { const dialog = useDialogState(props); const defaultGetAnchorRect = (anchor?: HTMLElement | null) => anchor?.getBoundingClientRect() || null; const getAnchorRect = useEvent(props.getAnchorRect || defaultGetAnchorRect); const anchorRef = useRef<HTMLElement | null>(null); const popoverRef = useRef<HTMLElement>(null); const arrowRef = useRef<HTMLElement>(null); const [currentPlacement, setCurrentPlacement] = useState(placement); const [rendered, render] = useForceUpdate(); useSafeLayoutEffect(() => { const popover = popoverRef.current; if (!popover) return; const anchor = getAnchorElement(anchorRef, getAnchorRect); const arrow = arrowRef.current; const arrowOffset = (arrow?.clientHeight || 0) / 2; const finalGutter = typeof gutter === "number" ? gutter + arrowOffset : gutter ?? arrowOffset; popover.style.setProperty( "--popover-overflow-padding", `${overflowPadding}px` ); const defaultRenderCallback = () => { const update = async () => { if (!dialog.mounted) return; const middleware: Middleware[] = [ // https://floating-ui.com/docs/offset middlewares.offset(({ placement }) => { // If there's no placement alignment (*-start or *-end), we'll // fallback to the crossAxis offset as it also works for // center-aligned placements. const hasAlignment = !!placement.split("-")[1]; return { crossAxis: !hasAlignment ? shift : undefined, mainAxis: finalGutter, alignmentAxis: shift, }; }), ]; if (flip !== false) { const fallbackPlacements = typeof flip === "string" ? flip.split(" ") : undefined; if ( fallbackPlacements !== undefined && !fallbackPlacements.every(isValidPlacement) ) { throw new Error( "`flip` expects a spaced-delimited list of placements" ); } // https://floating-ui.com/docs/flip middleware.push( middlewares.flip({ padding: overflowPadding, fallbackPlacements: fallbackPlacements, }) ); } if (slide || overlap) { // https://floating-ui.com/docs/shift middleware.push( middlewares.shift({ mainAxis: slide, crossAxis: overlap, padding: overflowPadding, }) ); } // https://floating-ui.com/docs/size middleware.push( middlewares.size({ padding: overflowPadding, apply({ availableWidth, availableHeight, rects }) { const referenceWidth = Math.round(rects.reference.width); popover.style.setProperty( "--popover-anchor-width", `${referenceWidth}px` ); popover.style.setProperty( "--popover-available-width", `${availableWidth}px` ); popover.style.setProperty( "--popover-available-height", `${availableHeight}px` ); if (sameWidth) { popover.style.width = `${referenceWidth}px`; } if (fitViewport) { popover.style.maxWidth = `${availableWidth}px`; popover.style.maxHeight = `${availableHeight}px`; } }, }) ); if (arrow) { // https://floating-ui.com/docs/arrow middleware.push( middlewares.arrow({ element: arrow, padding: arrowPadding }) ); } // https://floating-ui.com/docs/computePosition const pos = await computePosition(anchor, popover, { placement, strategy: fixed ? "fixed" : "absolute", middleware, }); setCurrentPlacement(pos.placement); const x = Math.round(pos.x); const y = Math.round(pos.y); // https://floating-ui.com/docs/misc#subpixel-and-accelerated-positioning Object.assign(popover.style, { position: fixed ? "fixed" : "absolute", top: "0", left: "0", transform: `translate3d(${x}px, ${y}px, 0)`, }); // https://floating-ui.com/docs/arrow#usage if (arrow && pos.middlewareData.arrow) { const { x: arrowX, y: arrowY } = pos.middlewareData.arrow; const dir = pos.placement.split("-")[0] as BasePlacement; Object.assign(arrow.style, { left: arrowX != null ? `${arrowX}px` : "", top: arrowY != null ? `${arrowY}px` : "", [dir]: "100%", }); } }; // autoUpdate does not call update immediately, so for the first update, // we should call the update function ourselves. update(); // https://floating-ui.com/docs/autoUpdate return autoUpdate(anchor, popover, update, { // JSDOM doesn't support ResizeObserver elementResize: typeof ResizeObserver === "function", }); }; if (renderCallback) { return renderCallback({ mounted: dialog.mounted, placement, fixed, gutter: finalGutter, shift, overlap, flip, sameWidth, fitViewport, arrowPadding, overflowPadding, popover, anchor, arrow, setPlacement: setCurrentPlacement, defaultRenderCallback, }); } return defaultRenderCallback(); }, [ rendered, dialog.contentElement, getAnchorRect, gutter, dialog.mounted, shift, overlap, flip, overflowPadding, slide, sameWidth, fitViewport, arrowPadding, placement, fixed, renderCallback, ]); const state = useMemo( () => ({ ...dialog, getAnchorRect, anchorRef, popoverRef, arrowRef, currentPlacement, placement, fixed, gutter, shift, flip, slide, overlap, sameWidth, fitViewport, arrowPadding, overflowPadding, render, renderCallback, }), [ dialog, getAnchorRect, currentPlacement, placement, fixed, gutter, shift, flip, slide, overlap, sameWidth, fitViewport, arrowPadding, overflowPadding, render, renderCallback, ] ); return state; } export type PopoverStateRenderCallbackProps = Pick< PopoverState, | "mounted" | "placement" | "fixed" | "gutter" | "shift" | "overlap" | "flip" | "sameWidth" | "fitViewport" | "arrowPadding" | "overflowPadding" > & { /** * The popover element. */ popover: HTMLElement; /** * The anchor element. */ anchor: VirtualElement; /** * The arrow element. */ arrow?: HTMLElement | null; /** * A method that updates the `currentPlacement` state. */ setPlacement: SetState<Placement>; /** * The default render callback that will be called when the `renderCallback` * prop is not provided. */ defaultRenderCallback: () => () => void; }; export type PopoverState = DialogState & { /** * Function that returns the anchor element's DOMRect. If this is explicitly * passed, it will override the anchor `getBoundingClientRect` method. */ getAnchorRect: (anchor: HTMLElement | null) => AnchorRect | null; /** * The anchor element. */ anchorRef: MutableRefObject<HTMLElement | null>; /** * The popover element that will render the placement attributes. */ popoverRef: RefObject<HTMLElement>; /** * The arrow element. */ arrowRef: RefObject<HTMLElement>; /** * The current temporary placement state of the popover. This may be different * from the the `placement` state if the popover has needed to update its * position on the fly. */ currentPlacement: Placement; /** * The placement of the popover. * @default "bottom" */ placement: Placement; /** * Whether the popover has `position: fixed` or not. * @default false */ fixed: boolean; /** * The distance between the popover and the anchor element. By default, it's 0 * plus half of the arrow offset, if it exists. * @default 0 */ gutter?: number; /** * The skidding of the popover along the anchor element. * @default 0 */ shift: number; /** * Controls the behavior of the popover when it overflows the viewport. * * If a boolean, specifies whether the popover should flip to the opposite side * when it overflows. * * If a string, indicates the preferred fallback placements when it overflows. * The placements must be spaced-delimited, e.g. "top left". * * @example * ```jsx * const popover = usePopoverState({ * placement: "right", * // In case the `right` placement overflows the viewport, * // the placement will fallback to the `bottom` or `top`, * // in that order, depending on where it fits. * flip: "bottom top", * }); * ``` * @default true */ flip: boolean | string; /** * Whether the popover should slide when it overflows. * @default true */ slide: boolean; /** * Whether the popover can overlap the anchor element when it overflows. * @default false */ overlap: boolean; /** * Whether the popover should have the same width as the anchor element. This * will be exposed to CSS as `--popover-anchor-width`. * @default false */ sameWidth: boolean; /** * Whether the popover should fit the viewport. If this is set to true, the * popover wrapper will have `maxWidth` and `maxHeight` set to the viewport * size. This will be exposed to CSS as `--popover-available-width` and * `--popover-available-height`. * @default false */ fitViewport: boolean; /** * The minimum padding between the arrow and the popover corner. * @default 4 */ arrowPadding: number; /** * The minimum padding between the popover and the viewport edge. This will be * exposed to CSS as `--popover-overflow-padding`. * @default 8 */ overflowPadding: number; /** * A function that can be used to recompute the popover styles. This is useful * when the popover anchor changes in a way that affects the popover position. */ render: () => void; /** * A function that will be called when the popover needs to calculate its * styles. It will override the internal behavior. */ renderCallback?: ( props: PopoverStateRenderCallbackProps ) => void | (() => void); }; export type PopoverStateProps = DialogStateProps & Partial< Pick< PopoverState, | "getAnchorRect" | "placement" | "fixed" | "gutter" | "shift" | "flip" | "slide" | "overlap" | "sameWidth" | "fitViewport" | "arrowPadding" | "overflowPadding" | "renderCallback" > >;
the_stack
import validator from '@bahmutov/is-my-json-valid' import debugApi from 'debug' import stringify from 'json-stable-stringify' import get from 'lodash.get' import set from 'lodash.set' import { clone, curry, difference, filter, find, keys, map, mergeAll, mergeDeepLeft, prop, uniq, uniqBy, whereEq, } from 'ramda' import { fill } from './fill' import { CustomFormats, detectors, FormatDefaults, getDefaults, JsonSchemaFormats, } from './formats' import { JsonSchema, ObjectSchema, PlainObject, SchemaCollection, SchemaVersion, } from './objects' import { sanitize } from './sanitize' import { trim } from './trim' import * as utils from './utils' const debug = debugApi('schema-tools') export const getVersionedSchema = (schemas: SchemaCollection) => ( name: string, ) => { name = utils.normalizeName(name) return schemas[name] } const _getObjectSchema = ( schemas: SchemaCollection, schemaName: string, version: SchemaVersion, ): ObjectSchema | undefined => { schemaName = utils.normalizeName(schemaName) const namedSchemas = schemas[schemaName] if (!namedSchemas) { debug('missing schema %s', schemaName) return } return namedSchemas[version] as ObjectSchema } /** * Returns object schema given a name and a version. Curried. * @returns an object or undefined * @example * getObjectSchema(schemas, 'membershipInvitation', '1.0.0') * getObjectSchema(schemas)('membershipInvitation')('1.0.0') */ export const getObjectSchema = curry(_getObjectSchema) const _hasSchema = ( schemas: SchemaCollection, schemaName: string, version: SchemaVersion, ): boolean => Boolean(_getObjectSchema(schemas, schemaName, version)) /** * Returns true if the given schema collection has schema by * name and version. Curried. * @returns `true` if there is a schema with such name and version * @example * getObjectSchema(schemas, 'membershipInvitation', '1.0.0') // true * getObjectSchema(schemas)('fooBarBaz', '1.0.0') // false */ export const hasSchema = curry(_hasSchema) /** * Returns normalized names of all schemas * * @example schemaNames() //> ['membershipInvitation', 'somethingElse', ...] */ export const schemaNames = (schemas: SchemaCollection) => Object.keys(schemas).sort() /** * Returns list of version strings available for given schema name. * * If there is no such schema, returns empty list. * * @param schemaName Schema name to look up */ export const getSchemaVersions = (schemas: SchemaCollection) => ( schemaName: string, ) => { schemaName = utils.normalizeName(schemaName) if (schemas[schemaName]) { return Object.keys(schemas[schemaName]) } return [] } /** * Returns our example for a schema with given version. Curried * @example getExample('membershipInvitation')('1.0.0') * // {id: '...', email: '...', role: '...'} */ export const getExample = curry( (schemas: SchemaCollection, schemaName: string, version: SchemaVersion) => { const o = getObjectSchema(schemas)(schemaName)(version) if (!o) { debug('could not find object schema %s@%s', schemaName, version) return } return o.example }, ) /** * Error returned by the json validation library. * Has an error message for specific property */ type ValidationError = { field: string message: string } const dataHasAdditionalPropertiesValidationError = { field: 'data', message: 'has additional properties', } const findDataHasAdditionalProperties = find( whereEq(dataHasAdditionalPropertiesValidationError), ) const includesDataHasAdditionalPropertiesError = ( errors: ValidationError[], ): boolean => findDataHasAdditionalProperties(errors) !== undefined const errorToString = (error: ValidationError): string => `${error.field} ${error.message}` /** * Flattens validation errors into user-friendlier strings */ const errorsToStrings = (errors: ValidationError[]): string[] => errors.map(errorToString) /** * Validates given object using JSON schema. Returns either 'true' or list of string errors */ export const validateBySchema = ( schema: JsonSchema, formats?: JsonSchemaFormats, greedy: boolean = true, ) => (object: object): true | string[] => { // TODO this could be cached, or even be part of the loaded module // when validating use our additional formats, like "uuid" const validate = validator(schema, { formats, greedy }) if (validate(object)) { return true } const uniqueErrors: ValidationError[] = uniqBy(errorToString, validate.errors) if ( includesDataHasAdditionalPropertiesError(uniqueErrors) && keys(schema.properties).length ) { const hasData: ValidationError = findDataHasAdditionalProperties( uniqueErrors, ) as ValidationError const additionalProperties: string[] = difference( keys(object), keys(schema.properties), ) hasData.message += ': ' + additionalProperties.join(', ') } const errors = uniq(errorsToStrings(uniqueErrors)) return errors } /** * Validates an object against given schema and version * * @param {string} schemaName * @param {object} object * @param {string} version * @returns {(true | string[])} If there are no errors returns true. * If there are any validation errors returns list of strings * */ export const validate = ( schemas: SchemaCollection, formats?: JsonSchemaFormats, greedy: boolean = true, ) => (schemaName: string, version: string) => ( object: object, ): true | string[] => { schemaName = utils.normalizeName(schemaName) const namedSchemas = schemas[schemaName] if (!namedSchemas) { return [`Missing schema ${schemaName}`] } const aSchema = namedSchemas[version] as ObjectSchema if (!aSchema) { return [`Missing schema ${schemaName}@${version}`] } // TODO this could be cached, or even be part of the loaded module // when validating use our additional formats, like "uuid" return validateBySchema(aSchema.schema, formats, greedy)(object) } /** * Error thrown when an object does not pass schema. * * @export * @class SchemaError * @extends {Error} */ export class SchemaError extends Error { /** * List of individual errors * * @type {string[]} * @memberof SchemaError */ errors: string[] /** * Current object being validated * * @type {PlainObject} * @memberof SchemaError */ object: PlainObject /** * Example object from the schema * * @type {PlainObject} * @memberof SchemaError */ example: PlainObject /** * Name of the schema that failed * * @type {string} * @memberof SchemaError */ schemaName: string /** * Version of the schema violated * * @type {string} * @memberof SchemaError */ schemaVersion?: string constructor( message: string, errors: string[], object: PlainObject, example: PlainObject, schemaName: string, schemaVersion?: string, ) { super(message) Object.setPrototypeOf(this, new.target.prototype) this.errors = errors this.object = object this.example = example this.schemaName = schemaName if (schemaVersion) { this.schemaVersion = schemaVersion } } } type ErrorMessageWhiteList = { errors: boolean object: boolean example: boolean } type AssertBySchemaOptions = { greedy: boolean substitutions: string[] omit: Partial<ErrorMessageWhiteList> } const AssertBySchemaDefaults: AssertBySchemaOptions = { greedy: true, substitutions: [], omit: { errors: false, object: false, example: false, }, } export const assertBySchema = ( schema: JsonSchema, example: PlainObject = {}, options?: Partial<AssertBySchemaOptions>, label?: string, formats?: JsonSchemaFormats, schemaVersion?: SchemaVersion, ) => (object: PlainObject) => { const allOptions = mergeDeepLeft( options || AssertBySchemaDefaults, AssertBySchemaDefaults, ) const replace = () => { const cloned = clone(object) allOptions.substitutions.forEach(property => { const value = get(example, property) set(cloned, property, value) }) return cloned } const replaced = allOptions.substitutions.length ? replace() : object const result = validateBySchema(schema, formats, allOptions.greedy)(replaced) if (result === true) { return object } const title = label ? `Schema ${label} violated` : 'Schema violated' const emptyLine = '' let parts = [title] if (!allOptions.omit.errors) { parts = parts.concat([emptyLine, 'Errors:']).concat(result) } if (!allOptions.omit.object) { const objectString = stringify(replaced, { space: ' ' }) parts = parts.concat([emptyLine, 'Current object:', objectString]) } if (!allOptions.omit.example) { const exampleString = stringify(example, { space: ' ' }) parts = parts.concat([ emptyLine, 'Expected object like this:', exampleString, ]) } const message = parts.join('\n') throw new SchemaError( message, result, replaced, example, schema.title, schemaVersion, ) } /** * Validates given object against a schema, throws an error if schema * has been violated. Returns the original object if everything is ok. * * @param name Schema name * @param version Schema version * @param substitutions Replaces specific properties with values from example object * @example getOrganization() * .then(assertSchema('organization', '1.0.0')) * .then(useOrganization) * @example getOrganization() * // returns {id: 'foo', ...} * // but will check {id: '931...', ...} * // where "id" is taken from this schema example object * .then(assertSchema('organization', '1.0.0', ['id'])) * .then(useOrganization) */ export const assertSchema = ( schemas: SchemaCollection, formats?: JsonSchemaFormats, ) => ( name: string, version: string, options?: Partial<AssertBySchemaOptions>, ) => (object: PlainObject) => { const example = getExample(schemas)(name)(version) const schema = getObjectSchema(schemas)(name)(version) if (!schema) { throw new Error(`Could not find schema ${name}@${version}`) } // TODO we can read title and description from the JSON schema itself // so external label would not be necessary const label = `${name}@${version}` return assertBySchema( schema.schema, example, options, label, formats, utils.semverToString(schema.version), )(object) } type BindOptions = { schemas: SchemaCollection formats?: CustomFormats } const mergeSchemas = (schemas: SchemaCollection[]): SchemaCollection => mergeAll(schemas) const mergeFormats = (formats: CustomFormats[]): CustomFormats => mergeAll(formats) const exists = x => Boolean(x) /** * Given schemas and formats creates "mini" API bound to the these schemas. * Can take multiple schemas and merged them all, and merges formats. */ export const bind = (...options: BindOptions[]) => { const allSchemas: SchemaCollection[] = map(prop('schemas'), options) const schemas = mergeSchemas(allSchemas) const allFormats: CustomFormats[] = filter( exists, map(prop('formats'), options as Required<BindOptions>[]), ) const formats = mergeFormats(allFormats) const formatDetectors = detectors(formats) const defaults: FormatDefaults = getDefaults(formats) const api = { assertSchema: assertSchema(schemas, formatDetectors), schemaNames: schemaNames(schemas), getExample: getExample(schemas), sanitize: sanitize(schemas, defaults), validate: validate(schemas), trim: trim(schemas), hasSchema: hasSchema(schemas), fill: fill(schemas), } return api }
the_stack
import * as msRest from "@azure/ms-rest-js"; export const acceptLanguage: msRest.OperationParameter = { parameterPath: "acceptLanguage", mapper: { serializedName: "accept-language", defaultValue: 'en-US', type: { name: "String" } } }; export const accountName: msRest.OperationURLParameter = { parameterPath: "accountName", mapper: { required: true, serializedName: "accountName", defaultValue: '', type: { name: "String" } }, skipEncoding: true }; export const action0: msRest.OperationQueryParameter = { parameterPath: "action", mapper: { required: true, serializedName: "action", type: { name: "Enum", allowedValues: [ "append", "flush", "setProperties", "setAccessControl" ] } } }; export const action1: msRest.OperationQueryParameter = { parameterPath: [ "options", "action" ], mapper: { serializedName: "action", type: { name: "Enum", allowedValues: [ "getAccessControl", "getStatus" ] } } }; export const cacheControl: msRest.OperationParameter = { parameterPath: [ "options", "cacheControl" ], mapper: { serializedName: "Cache-Control", type: { name: "String" } } }; export const close: msRest.OperationQueryParameter = { parameterPath: [ "options", "close" ], mapper: { serializedName: "close", type: { name: "Boolean" } } }; export const contentDisposition: msRest.OperationParameter = { parameterPath: [ "options", "contentDisposition" ], mapper: { serializedName: "Content-Disposition", type: { name: "String" } } }; export const contentEncoding: msRest.OperationParameter = { parameterPath: [ "options", "contentEncoding" ], mapper: { serializedName: "Content-Encoding", type: { name: "String" } } }; export const contentLanguage: msRest.OperationParameter = { parameterPath: [ "options", "contentLanguage" ], mapper: { serializedName: "Content-Language", type: { name: "String" } } }; export const contentLength: msRest.OperationParameter = { parameterPath: [ "options", "contentLength" ], mapper: { serializedName: "Content-Length", constraints: { InclusiveMinimum: 0 }, type: { name: "Number" } } }; export const contentMD5: msRest.OperationParameter = { parameterPath: [ "options", "contentMD5" ], mapper: { serializedName: "Content-MD5", type: { name: "String" } } }; export const continuation: msRest.OperationQueryParameter = { parameterPath: [ "options", "continuation" ], mapper: { serializedName: "continuation", type: { name: "String" } } }; export const directory: msRest.OperationQueryParameter = { parameterPath: [ "options", "directory" ], mapper: { serializedName: "directory", type: { name: "String" } } }; export const dnsSuffix: msRest.OperationURLParameter = { parameterPath: "dnsSuffix", mapper: { required: true, serializedName: "dnsSuffix", defaultValue: 'dfs.core.windows.net', type: { name: "String" } }, skipEncoding: true }; export const filesystem: msRest.OperationURLParameter = { parameterPath: "filesystem", mapper: { required: true, serializedName: "filesystem", constraints: { MaxLength: 63, MinLength: 3, Pattern: /^[$a-z0-9](?!.*--)[-a-z0-9]{1,61}[a-z0-9]$/ }, type: { name: "String" } } }; export const ifMatch: msRest.OperationParameter = { parameterPath: [ "options", "ifMatch" ], mapper: { serializedName: "If-Match", type: { name: "String" } } }; export const ifModifiedSince: msRest.OperationParameter = { parameterPath: [ "options", "ifModifiedSince" ], mapper: { serializedName: "If-Modified-Since", type: { name: "String" } } }; export const ifNoneMatch: msRest.OperationParameter = { parameterPath: [ "options", "ifNoneMatch" ], mapper: { serializedName: "If-None-Match", type: { name: "String" } } }; export const ifUnmodifiedSince: msRest.OperationParameter = { parameterPath: [ "options", "ifUnmodifiedSince" ], mapper: { serializedName: "If-Unmodified-Since", type: { name: "String" } } }; export const maxResults: msRest.OperationQueryParameter = { parameterPath: [ "options", "maxResults" ], mapper: { serializedName: "maxResults", constraints: { InclusiveMinimum: 1 }, type: { name: "Number" } } }; export const mode: msRest.OperationQueryParameter = { parameterPath: [ "options", "mode" ], mapper: { serializedName: "mode", type: { name: "Enum", allowedValues: [ "legacy", "posix" ] } } }; export const path: msRest.OperationURLParameter = { parameterPath: "path", mapper: { required: true, serializedName: "path", type: { name: "String" } } }; export const position: msRest.OperationQueryParameter = { parameterPath: [ "options", "position" ], mapper: { serializedName: "position", type: { name: "Number" } } }; export const prefix: msRest.OperationQueryParameter = { parameterPath: [ "options", "prefix" ], mapper: { serializedName: "prefix", type: { name: "String" } } }; export const range: msRest.OperationParameter = { parameterPath: [ "options", "range" ], mapper: { serializedName: "Range", type: { name: "String" } } }; export const recursive0: msRest.OperationQueryParameter = { parameterPath: "recursive", mapper: { required: true, serializedName: "recursive", type: { name: "Boolean" } } }; export const recursive1: msRest.OperationQueryParameter = { parameterPath: [ "options", "recursive" ], mapper: { serializedName: "recursive", type: { name: "Boolean" } } }; export const resource0: msRest.OperationQueryParameter = { parameterPath: "resource", mapper: { required: true, isConstant: true, serializedName: "resource", defaultValue: 'account', type: { name: "String" } } }; export const resource1: msRest.OperationQueryParameter = { parameterPath: "resource", mapper: { required: true, isConstant: true, serializedName: "resource", defaultValue: 'filesystem', type: { name: "String" } } }; export const resource2: msRest.OperationQueryParameter = { parameterPath: [ "options", "resource" ], mapper: { serializedName: "resource", type: { name: "Enum", allowedValues: [ "directory", "file" ] } } }; export const retainUncommittedData: msRest.OperationQueryParameter = { parameterPath: [ "options", "retainUncommittedData" ], mapper: { serializedName: "retainUncommittedData", type: { name: "Boolean" } } }; export const timeout: msRest.OperationQueryParameter = { parameterPath: [ "options", "timeout" ], mapper: { serializedName: "timeout", constraints: { InclusiveMinimum: 1 }, type: { name: "Number" } } }; export const upn: msRest.OperationQueryParameter = { parameterPath: [ "options", "upn" ], mapper: { serializedName: "upn", type: { name: "Boolean" } } }; export const xMsAcl: msRest.OperationParameter = { parameterPath: [ "options", "xMsAcl" ], mapper: { serializedName: "x-ms-acl", type: { name: "String" } } }; export const xMsCacheControl: msRest.OperationParameter = { parameterPath: [ "options", "xMsCacheControl" ], mapper: { serializedName: "x-ms-cache-control", type: { name: "String" } } }; export const xMsClientRequestId: msRest.OperationParameter = { parameterPath: [ "options", "xMsClientRequestId" ], mapper: { serializedName: "x-ms-client-request-id", constraints: { Pattern: /^[{(]?[0-9a-f]{8}[-]?([0-9a-f]{4}[-]?){3}[0-9a-f]{12}[)}]?$/ }, type: { name: "String" } } }; export const xMsContentDisposition: msRest.OperationParameter = { parameterPath: [ "options", "xMsContentDisposition" ], mapper: { serializedName: "x-ms-content-disposition", type: { name: "String" } } }; export const xMsContentEncoding: msRest.OperationParameter = { parameterPath: [ "options", "xMsContentEncoding" ], mapper: { serializedName: "x-ms-content-encoding", type: { name: "String" } } }; export const xMsContentLanguage: msRest.OperationParameter = { parameterPath: [ "options", "xMsContentLanguage" ], mapper: { serializedName: "x-ms-content-language", type: { name: "String" } } }; export const xMsContentMd5: msRest.OperationParameter = { parameterPath: [ "options", "xMsContentMd5" ], mapper: { serializedName: "x-ms-content-md5", type: { name: "String" } } }; export const xMsContentType: msRest.OperationParameter = { parameterPath: [ "options", "xMsContentType" ], mapper: { serializedName: "x-ms-content-type", type: { name: "String" } } }; export const xMsDate: msRest.OperationParameter = { parameterPath: [ "options", "xMsDate" ], mapper: { serializedName: "x-ms-date", type: { name: "String" } } }; export const xMsGroup: msRest.OperationParameter = { parameterPath: [ "options", "xMsGroup" ], mapper: { serializedName: "x-ms-group", type: { name: "String" } } }; export const xMsLeaseAction: msRest.OperationParameter = { parameterPath: "xMsLeaseAction", mapper: { required: true, serializedName: "x-ms-lease-action", type: { name: "Enum", allowedValues: [ "acquire", "break", "change", "renew", "release" ] } } }; export const xMsLeaseBreakPeriod: msRest.OperationParameter = { parameterPath: [ "options", "xMsLeaseBreakPeriod" ], mapper: { serializedName: "x-ms-lease-break-period", type: { name: "Number" } } }; export const xMsLeaseDuration: msRest.OperationParameter = { parameterPath: [ "options", "xMsLeaseDuration" ], mapper: { serializedName: "x-ms-lease-duration", type: { name: "Number" } } }; export const xMsLeaseId: msRest.OperationParameter = { parameterPath: [ "options", "xMsLeaseId" ], mapper: { serializedName: "x-ms-lease-id", constraints: { Pattern: /^[{(]?[0-9a-f]{8}[-]?([0-9a-f]{4}[-]?){3}[0-9a-f]{12}[)}]?$/ }, type: { name: "String" } } }; export const xMsOwner: msRest.OperationParameter = { parameterPath: [ "options", "xMsOwner" ], mapper: { serializedName: "x-ms-owner", type: { name: "String" } } }; export const xMsPermissions: msRest.OperationParameter = { parameterPath: [ "options", "xMsPermissions" ], mapper: { serializedName: "x-ms-permissions", type: { name: "String" } } }; export const xMsProperties: msRest.OperationParameter = { parameterPath: [ "options", "xMsProperties" ], mapper: { serializedName: "x-ms-properties", type: { name: "String" } } }; export const xMsProposedLeaseId: msRest.OperationParameter = { parameterPath: [ "options", "xMsProposedLeaseId" ], mapper: { serializedName: "x-ms-proposed-lease-id", constraints: { Pattern: /^[{(]?[0-9a-f]{8}[-]?([0-9a-f]{4}[-]?){3}[0-9a-f]{12}[)}]?$/ }, type: { name: "String" } } }; export const xMsRangeGetContentMd5: msRest.OperationParameter = { parameterPath: [ "options", "xMsRangeGetContentMd5" ], mapper: { serializedName: "x-ms-range-get-content-md5", type: { name: "Boolean" } } }; export const xMsRenameSource: msRest.OperationParameter = { parameterPath: [ "options", "xMsRenameSource" ], mapper: { serializedName: "x-ms-rename-source", type: { name: "String" } } }; export const xMsSourceIfMatch: msRest.OperationParameter = { parameterPath: [ "options", "xMsSourceIfMatch" ], mapper: { serializedName: "x-ms-source-if-match", type: { name: "String" } } }; export const xMsSourceIfModifiedSince: msRest.OperationParameter = { parameterPath: [ "options", "xMsSourceIfModifiedSince" ], mapper: { serializedName: "x-ms-source-if-modified-since", type: { name: "String" } } }; export const xMsSourceIfNoneMatch: msRest.OperationParameter = { parameterPath: [ "options", "xMsSourceIfNoneMatch" ], mapper: { serializedName: "x-ms-source-if-none-match", type: { name: "String" } } }; export const xMsSourceIfUnmodifiedSince: msRest.OperationParameter = { parameterPath: [ "options", "xMsSourceIfUnmodifiedSince" ], mapper: { serializedName: "x-ms-source-if-unmodified-since", type: { name: "String" } } }; export const xMsSourceLeaseId: msRest.OperationParameter = { parameterPath: [ "options", "xMsSourceLeaseId" ], mapper: { serializedName: "x-ms-source-lease-id", constraints: { Pattern: /^[{(]?[0-9a-f]{8}[-]?([0-9a-f]{4}[-]?){3}[0-9a-f]{12}[)}]?$/ }, type: { name: "String" } } }; export const xMsUmask: msRest.OperationParameter = { parameterPath: [ "options", "xMsUmask" ], mapper: { serializedName: "x-ms-umask", type: { name: "String" } } }; export const xMsVersion: msRest.OperationParameter = { parameterPath: "xMsVersion", mapper: { serializedName: "x-ms-version", type: { name: "String" } } };
the_stack
import {Class, AnyTiming, Timing} from "@swim/util"; import {Affinity, MemberFastenerClass, Property} from "@swim/component"; import type {AnyLength, Length} from "@swim/math"; import type {AnyColor, Color} from "@swim/style"; import {Look, Mood} from "@swim/theme"; import {ViewRef} from "@swim/view"; import type {GraphicsView} from "@swim/graphics"; import {Controller, TraitViewRef} from "@swim/controller"; import {DataPointView} from "./DataPointView"; import {DataPointLabel, DataPointTrait} from "./DataPointTrait"; import type {DataPointControllerObserver} from "./DataPointControllerObserver"; /** @public */ export class DataPointController<X = unknown, Y = unknown> extends Controller { override readonly observerType?: Class<DataPointControllerObserver<X, Y>>; protected updateLabel(x: X | undefined, y: Y | undefined, dataPointTrait: DataPointTrait<X, Y>): void { const label = dataPointTrait.formatLabel(x, y); if (label !== void 0) { dataPointTrait.label.setValue(label, Affinity.Intrinsic); } } protected setX(x: X, dataPointTrait: DataPointTrait<X, Y>, timing?: AnyTiming | boolean): void { const dataPointView = this.dataPoint.view; if (dataPointView !== null) { if (timing === void 0 || timing === true) { timing = this.dataPointTiming.value; if (timing === true) { timing = dataPointView.getLook(Look.timing, Mood.ambient); } } else { timing = Timing.fromAny(timing); } dataPointView.x.setState(x, timing, Affinity.Intrinsic); } } protected setY(y: Y, dataPointTrait: DataPointTrait<X, Y>, timing?: AnyTiming | boolean): void { const dataPointView = this.dataPoint.view; if (dataPointView !== null) { if (timing === void 0 || timing === true) { timing = this.dataPointTiming.value; if (timing === true) { timing = dataPointView.getLook(Look.timing, Mood.ambient); } } else { timing = Timing.fromAny(timing); } dataPointView.y.setState(y, timing, Affinity.Intrinsic); } } protected setY2(y2: Y | undefined, dataPointTrait: DataPointTrait<X, Y>, timing?: AnyTiming | boolean): void { const dataPointView = this.dataPoint.view; if (dataPointView !== null) { if (timing === void 0 || timing === true) { timing = this.dataPointTiming.value; if (timing === true) { timing = dataPointView.getLook(Look.timing, Mood.ambient); } } else { timing = Timing.fromAny(timing); } dataPointView.y2.setState(y2, timing, Affinity.Intrinsic); } } protected setRadius(radius: AnyLength | null, dataPointTrait: DataPointTrait<X, Y>, timing?: AnyTiming | boolean): void { const dataPointView = this.dataPoint.view; if (dataPointView !== null) { if (timing === void 0 || timing === true) { timing = this.dataPointTiming.value; if (timing === true) { timing = dataPointView.getLook(Look.timing, Mood.ambient); } } else { timing = Timing.fromAny(timing); } dataPointView.radius.setState(radius, timing, Affinity.Intrinsic); } } protected setColor(color: Look<Color> | AnyColor | null, dataPointTrait: DataPointTrait<X, Y>, timing?: AnyTiming | boolean): void { const dataPointView = this.dataPoint.view; if (dataPointView !== null) { if (timing === void 0 || timing === true) { timing = this.dataPointTiming.value; if (timing === true) { timing = dataPointView.getLook(Look.timing, Mood.ambient); } } else { timing = Timing.fromAny(timing); } if (color instanceof Look) { dataPointView.color.setLook(color, timing, Affinity.Intrinsic); } else { dataPointView.color.setState(color, timing, Affinity.Intrinsic); } } } protected setOpacity(opacity: number | undefined, dataPointTrait: DataPointTrait<X, Y>, timing?: AnyTiming | boolean): void { const dataPointView = this.dataPoint.view; if (dataPointView !== null) { if (timing === void 0 || timing === true) { timing = this.dataPointTiming.value; if (timing === true) { timing = dataPointView.getLook(Look.timing, Mood.ambient); } } else { timing = Timing.fromAny(timing); } dataPointView.opacity.setState(opacity, timing, Affinity.Intrinsic); } } protected createLabelView(label: DataPointLabel<X, Y>, dataPointTrait: DataPointTrait<X, Y>): GraphicsView | string | null { if (typeof label === "function") { return label(dataPointTrait); } else { return label; } } protected setLabelView(label: DataPointLabel<X, Y> | null, dataPointTrait: DataPointTrait<X, Y>): void { const dataPointView = this.dataPoint.view; if (dataPointView !== null) { const labelView = label !== null ? this.createLabelView(label, dataPointTrait) : null; dataPointView.label.setView(labelView); } } @Property({type: Timing, inherits: true}) readonly dataPointTiming!: Property<this, Timing | boolean | undefined, AnyTiming>; @TraitViewRef<DataPointController<X, Y>, DataPointTrait<X, Y>, DataPointView<X, Y>>({ traitType: DataPointTrait, observesTrait: true, willAttachTrait(dataPointTrait: DataPointTrait<X, Y>): void { this.owner.callObservers("controllerWillAttachDataPointTrait", dataPointTrait, this.owner); }, didAttachTrait(dataPointTrait: DataPointTrait<X, Y>): void { const dataPointView = this.view; if (dataPointView !== null) { this.owner.setX(dataPointTrait.x.value, dataPointTrait); this.owner.setY(dataPointTrait.y.value, dataPointTrait); this.owner.setY2(dataPointTrait.y2.value, dataPointTrait); this.owner.setRadius(dataPointTrait.radius.value, dataPointTrait); this.owner.setColor(dataPointTrait.color.value, dataPointTrait); this.owner.setOpacity(dataPointTrait.opacity.value, dataPointTrait); this.owner.setLabelView(dataPointTrait.label.value, dataPointTrait); } }, willDetachTrait(dataPointTrait: DataPointTrait<X, Y>): void { const dataPointView = this.view; if (dataPointView !== null) { this.owner.setLabelView(null, dataPointTrait); } }, didDetachTrait(dataPointTrait: DataPointTrait<X, Y>): void { this.owner.callObservers("controllerDidDetachDataPointTrait", dataPointTrait, this.owner); }, traitDidSetDataPointX(newX: X , oldX: X, dataPointTrait: DataPointTrait<X, Y>): void { this.owner.setX(newX, dataPointTrait); }, traitDidSetDataPointY(newY: Y, oldY: Y, dataPointTrait: DataPointTrait<X, Y>): void { this.owner.setY(newY, dataPointTrait); }, traitDidSetDataPointY2(newY2: Y | undefined, oldY2: Y | undefined, dataPointTrait: DataPointTrait<X, Y>): void { this.owner.setY2(newY2, dataPointTrait); }, traitDidSetDataPointRadius(newRadius: Length | null, oldRadius: Length | null, dataPointTrait: DataPointTrait<X, Y>): void { this.owner.setRadius(newRadius, dataPointTrait); }, traitDidSetDataPointColor(newColor: Look<Color> | Color | null, oldColor: Look<Color> | Color | null, dataPointTrait: DataPointTrait<X, Y>): void { this.owner.setColor(newColor, dataPointTrait); }, traitDidSetDataPointOpacity(newOpacity: number | undefined, oldOpacity: number | undefined, dataPointTrait: DataPointTrait<X, Y>): void { this.owner.setOpacity(newOpacity, dataPointTrait); }, traitDidSetDataPointLabel(newLabel: DataPointLabel<X, Y> | null, oldLabel: DataPointLabel<X, Y> | null, dataPointTrait: DataPointTrait<X, Y>): void { this.owner.setLabelView(newLabel, dataPointTrait); }, viewType: DataPointView, observesView: true, willAttachView(dataPointView: DataPointView<X, Y>): void { this.owner.callObservers("controllerWillAttachDataPointView", dataPointView, this.owner); }, didAttachView(dataPointView: DataPointView<X, Y>): void { this.owner.label.setView(dataPointView.label.view); const dataPointTrait = this.trait; if (dataPointTrait !== null) { this.owner.setX(dataPointTrait.x.value, dataPointTrait); this.owner.setY(dataPointTrait.y.value, dataPointTrait); this.owner.setY2(dataPointTrait.y2.value, dataPointTrait); this.owner.setRadius(dataPointTrait.radius.value, dataPointTrait); this.owner.setColor(dataPointTrait.color.value, dataPointTrait); this.owner.setOpacity(dataPointTrait.opacity.value, dataPointTrait); this.owner.setLabelView(dataPointTrait.label.value, dataPointTrait); const x = dataPointView.x.value; const y = dataPointView.y.value; this.owner.updateLabel(x, y, dataPointTrait); } }, willDetachView(dataPointView: DataPointView<X, Y>): void { this.owner.label.setView(null); }, didDetachView(dataPointView: DataPointView<X, Y>): void { this.owner.callObservers("controllerDidDetachDataPointView", dataPointView, this.owner); }, viewWillSetDataPointX(newX: X | undefined, oldX: X | undefined, dataPointView: DataPointView<X, Y>): void { this.owner.callObservers("controllerWillSetDataPointX", newX, oldX, this.owner); }, viewDidSetDataPointX(newX: X | undefined, oldX: X | undefined, dataPointView: DataPointView<X, Y>): void { const dataPointTrait = this.trait; if (dataPointTrait !== null) { const y = dataPointView.y.value; this.owner.updateLabel(newX, y, dataPointTrait); } this.owner.callObservers("controllerDidSetDataPointX", newX, oldX, this.owner); }, viewWillSetDataPointY(newY: Y | undefined, oldY: Y | undefined, dataPointView: DataPointView<X, Y>): void { this.owner.callObservers("controllerWillSetDataPointY", newY, oldY, this.owner); }, viewDidSetDataPointY(newY: Y | undefined, oldY: Y | undefined, dataPointView: DataPointView<X, Y>): void { const dataPointTrait = this.trait; if (dataPointTrait !== null) { const x = dataPointView.x.value; this.owner.updateLabel(x, newY, dataPointTrait); } this.owner.callObservers("controllerDidSetDataPointY", newY, oldY, this.owner); }, viewWillSetDataPointY2(newY2: Y | undefined, oldY2: Y | undefined, dataPointView: DataPointView<X, Y>): void { this.owner.callObservers("controllerWillSetDataPointY2", newY2, oldY2, this.owner); }, viewDidSetDataPointY2(newY2: Y | undefined, oldY2: Y | undefined, dataPointView: DataPointView<X, Y>): void { this.owner.callObservers("controllerDidSetDataPointY2", newY2, oldY2, this.owner); }, viewWillSetDataPointRadius(newRadius: Length | null, oldRadius: Length | null, dataPointView: DataPointView<X, Y>): void { this.owner.callObservers("controllerWillSetDataPointRadius", newRadius, oldRadius, this.owner); }, viewDidSetDataPointRadius(newRadius: Length | null, oldRadius: Length | null, dataPointView: DataPointView<X, Y>): void { this.owner.callObservers("controllerDidSetDataPointRadius", newRadius, oldRadius, this.owner); }, viewWillSetDataPointColor(newColor: Color | null, oldColor: Color | null, dataPointView: DataPointView<X, Y>): void { this.owner.callObservers("controllerWillSetDataPointColor", newColor, oldColor, this.owner); }, viewDidSetDataPointColor(newColor: Color | null, oldColor: Color | null, dataPointView: DataPointView<X, Y>): void { this.owner.callObservers("controllerDidSetDataPointColor", newColor, oldColor, this.owner); }, viewWillSetDataPointOpacity(newOpacity: number | undefined, oldOpacity: number | undefined, dataPointView: DataPointView<X, Y>): void { this.owner.callObservers("controllerWillSetDataPointOpacity", newOpacity, oldOpacity, this.owner); }, viewDidSetDataPointOpacity(newOpacity: number | undefined, oldOpacity: number | undefined, dataPointView: DataPointView<X, Y>): void { this.owner.callObservers("controllerDidSetDataPointOpacity", newOpacity, oldOpacity, this.owner); }, viewWillAttachDataPointLabel(labelView: GraphicsView): void { this.owner.label.setView(labelView); }, viewDidDetachDataPointLabel(labelView: GraphicsView): void { this.owner.label.setView(null); }, createView(): DataPointView<X, Y> { const dataPointView = new DataPointView<X, Y>(); const dataPointTrait = this.trait; if (dataPointTrait !== null) { dataPointView.x.setState(dataPointTrait.x.value, Affinity.Intrinsic); dataPointView.y.setState(dataPointTrait.y.value, Affinity.Intrinsic); dataPointView.y2.setState(dataPointTrait.y2.value, Affinity.Intrinsic); dataPointView.radius.setState(dataPointTrait.radius.value, Affinity.Intrinsic); } return dataPointView; }, }) readonly dataPoint!: TraitViewRef<this, DataPointTrait<X, Y>, DataPointView<X, Y>>; static readonly dataPoint: MemberFastenerClass<DataPointController, "dataPoint">; @ViewRef<DataPointController<X, Y>, GraphicsView>({ key: true, willAttachView(labelView: GraphicsView): void { this.owner.callObservers("controllerWillAttachDataPointLabelView", labelView, this.owner); }, didDetachView(labelView: GraphicsView): void { this.owner.callObservers("controllerDidDetachDataPointLabelView", labelView, this.owner); }, }) readonly label!: ViewRef<this, GraphicsView>; static readonly label: MemberFastenerClass<DataPointController, "label">; }
the_stack